1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * linux/mm/compaction.c
4  *
5  * Memory compaction for the reduction of external fragmentation. Note that
6  * this heavily depends upon page migration to do all the real heavy
7  * lifting
8  *
9  * Copyright IBM Corp. 2007-2010 Mel Gorman <mel@csn.ul.ie>
10  */
11 #include <linux/cpu.h>
12 #include <linux/swap.h>
13 #include <linux/migrate.h>
14 #include <linux/compaction.h>
15 #include <linux/mm_inline.h>
16 #include <linux/sched/signal.h>
17 #include <linux/backing-dev.h>
18 #include <linux/sysctl.h>
19 #include <linux/sysfs.h>
20 #include <linux/page-isolation.h>
21 #include <linux/kasan.h>
22 #include <linux/kthread.h>
23 #include <linux/freezer.h>
24 #include <linux/page_owner.h>
25 #include <linux/psi.h>
26 #include <linux/cpuset.h>
27 #include "internal.h"
28 
29 #ifdef CONFIG_COMPACTION
30 /*
31  * Fragmentation score check interval for proactive compaction purposes.
32  */
33 #define HPAGE_FRAG_CHECK_INTERVAL_MSEC	(500)
34 
count_compact_event(enum vm_event_item item)35 static inline void count_compact_event(enum vm_event_item item)
36 {
37 	count_vm_event(item);
38 }
39 
count_compact_events(enum vm_event_item item,long delta)40 static inline void count_compact_events(enum vm_event_item item, long delta)
41 {
42 	count_vm_events(item, delta);
43 }
44 
45 /*
46  * order == -1 is expected when compacting proactively via
47  * 1. /proc/sys/vm/compact_memory
48  * 2. /sys/devices/system/node/nodex/compact
49  * 3. /proc/sys/vm/compaction_proactiveness
50  */
is_via_compact_memory(int order)51 static inline bool is_via_compact_memory(int order)
52 {
53 	return order == -1;
54 }
55 
56 #else
57 #define count_compact_event(item) do { } while (0)
58 #define count_compact_events(item, delta) do { } while (0)
is_via_compact_memory(int order)59 static inline bool is_via_compact_memory(int order) { return false; }
60 #endif
61 
62 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
63 
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/compaction.h>
66 #undef CREATE_TRACE_POINTS
67 
68 #include <trace/hooks/vmscan.h>
69 #include <trace/hooks/compaction.h>
70 #include <trace/hooks/mm.h>
71 
72 #undef CREATE_TRACE_POINTS
73 #ifndef __GENKSYMS__
74 #include <trace/hooks/mm.h>
75 #endif
76 
77 #define block_start_pfn(pfn, order)	round_down(pfn, 1UL << (order))
78 #define block_end_pfn(pfn, order)	ALIGN((pfn) + 1, 1UL << (order))
79 
80 /*
81  * Page order with-respect-to which proactive compaction
82  * calculates external fragmentation, which is used as
83  * the "fragmentation score" of a node/zone.
84  */
85 #if defined CONFIG_TRANSPARENT_HUGEPAGE
86 #define COMPACTION_HPAGE_ORDER	HPAGE_PMD_ORDER
87 #elif defined CONFIG_HUGETLBFS
88 #define COMPACTION_HPAGE_ORDER	HUGETLB_PAGE_ORDER
89 #else
90 #define COMPACTION_HPAGE_ORDER	(PMD_SHIFT - PAGE_SHIFT)
91 #endif
92 
mark_allocated_noprof(struct page * page,unsigned int order,gfp_t gfp_flags)93 static struct page *mark_allocated_noprof(struct page *page, unsigned int order, gfp_t gfp_flags)
94 {
95 	post_alloc_hook(page, order, __GFP_MOVABLE);
96 	return page;
97 }
98 #define mark_allocated(...)	alloc_hooks(mark_allocated_noprof(__VA_ARGS__))
99 
release_free_list(struct list_head * freepages)100 static unsigned long release_free_list(struct list_head *freepages)
101 {
102 	int order;
103 	unsigned long high_pfn = 0;
104 
105 	for (order = 0; order < NR_PAGE_ORDERS; order++) {
106 		struct page *page, *next;
107 
108 		list_for_each_entry_safe(page, next, &freepages[order], lru) {
109 			unsigned long pfn = page_to_pfn(page);
110 
111 			list_del(&page->lru);
112 			/*
113 			 * Convert free pages into post allocation pages, so
114 			 * that we can free them via __free_page.
115 			 */
116 			mark_allocated(page, order, __GFP_MOVABLE);
117 			__free_pages(page, order);
118 			if (pfn > high_pfn)
119 				high_pfn = pfn;
120 		}
121 	}
122 	return high_pfn;
123 }
124 
125 #ifdef CONFIG_COMPACTION
PageMovable(struct page * page)126 bool PageMovable(struct page *page)
127 {
128 	const struct movable_operations *mops;
129 
130 	VM_BUG_ON_PAGE(!PageLocked(page), page);
131 	if (!__PageMovable(page))
132 		return false;
133 
134 	mops = page_movable_ops(page);
135 	if (mops)
136 		return true;
137 
138 	return false;
139 }
140 
__SetPageMovable(struct page * page,const struct movable_operations * mops)141 void __SetPageMovable(struct page *page, const struct movable_operations *mops)
142 {
143 	VM_BUG_ON_PAGE(!PageLocked(page), page);
144 	VM_BUG_ON_PAGE((unsigned long)mops & PAGE_MAPPING_MOVABLE, page);
145 	page->mapping = (void *)((unsigned long)mops | PAGE_MAPPING_MOVABLE);
146 }
147 EXPORT_SYMBOL(__SetPageMovable);
148 
__ClearPageMovable(struct page * page)149 void __ClearPageMovable(struct page *page)
150 {
151 	VM_BUG_ON_PAGE(!PageMovable(page), page);
152 	/*
153 	 * This page still has the type of a movable page, but it's
154 	 * actually not movable any more.
155 	 */
156 	page->mapping = (void *)PAGE_MAPPING_MOVABLE;
157 }
158 EXPORT_SYMBOL(__ClearPageMovable);
159 
160 /* Do not skip compaction more than 64 times */
161 #define COMPACT_MAX_DEFER_SHIFT 6
162 
163 /*
164  * Compaction is deferred when compaction fails to result in a page
165  * allocation success. 1 << compact_defer_shift, compactions are skipped up
166  * to a limit of 1 << COMPACT_MAX_DEFER_SHIFT
167  */
defer_compaction(struct zone * zone,int order)168 static void defer_compaction(struct zone *zone, int order)
169 {
170 	zone->compact_considered = 0;
171 	zone->compact_defer_shift++;
172 
173 	if (order < zone->compact_order_failed)
174 		zone->compact_order_failed = order;
175 
176 	if (zone->compact_defer_shift > COMPACT_MAX_DEFER_SHIFT)
177 		zone->compact_defer_shift = COMPACT_MAX_DEFER_SHIFT;
178 
179 	trace_mm_compaction_defer_compaction(zone, order);
180 }
181 
182 /* Returns true if compaction should be skipped this time */
compaction_deferred(struct zone * zone,int order)183 static bool compaction_deferred(struct zone *zone, int order)
184 {
185 	unsigned long defer_limit = 1UL << zone->compact_defer_shift;
186 
187 	if (order < zone->compact_order_failed)
188 		return false;
189 
190 	/* Avoid possible overflow */
191 	if (++zone->compact_considered >= defer_limit) {
192 		zone->compact_considered = defer_limit;
193 		return false;
194 	}
195 
196 	trace_mm_compaction_deferred(zone, order);
197 
198 	return true;
199 }
200 
201 /*
202  * Update defer tracking counters after successful compaction of given order,
203  * which means an allocation either succeeded (alloc_success == true) or is
204  * expected to succeed.
205  */
compaction_defer_reset(struct zone * zone,int order,bool alloc_success)206 void compaction_defer_reset(struct zone *zone, int order,
207 		bool alloc_success)
208 {
209 	if (alloc_success) {
210 		zone->compact_considered = 0;
211 		zone->compact_defer_shift = 0;
212 	}
213 	if (order >= zone->compact_order_failed)
214 		zone->compact_order_failed = order + 1;
215 
216 	trace_mm_compaction_defer_reset(zone, order);
217 }
218 
219 /* Returns true if restarting compaction after many failures */
compaction_restarting(struct zone * zone,int order)220 static bool compaction_restarting(struct zone *zone, int order)
221 {
222 	if (order < zone->compact_order_failed)
223 		return false;
224 
225 	return zone->compact_defer_shift == COMPACT_MAX_DEFER_SHIFT &&
226 		zone->compact_considered >= 1UL << zone->compact_defer_shift;
227 }
228 
229 /* Returns true if the pageblock should be scanned for pages to isolate. */
isolation_suitable(struct compact_control * cc,struct page * page)230 static inline bool isolation_suitable(struct compact_control *cc,
231 					struct page *page)
232 {
233 	if (cc->ignore_skip_hint)
234 		return true;
235 
236 	return !get_pageblock_skip(page);
237 }
238 
reset_cached_positions(struct zone * zone)239 static void reset_cached_positions(struct zone *zone)
240 {
241 	zone->compact_cached_migrate_pfn[0] = zone->zone_start_pfn;
242 	zone->compact_cached_migrate_pfn[1] = zone->zone_start_pfn;
243 	zone->compact_cached_free_pfn =
244 				pageblock_start_pfn(zone_end_pfn(zone) - 1);
245 }
246 
247 #ifdef CONFIG_SPARSEMEM
248 /*
249  * If the PFN falls into an offline section, return the start PFN of the
250  * next online section. If the PFN falls into an online section or if
251  * there is no next online section, return 0.
252  */
skip_offline_sections(unsigned long start_pfn)253 static unsigned long skip_offline_sections(unsigned long start_pfn)
254 {
255 	unsigned long start_nr = pfn_to_section_nr(start_pfn);
256 
257 	if (online_section_nr(start_nr))
258 		return 0;
259 
260 	while (++start_nr <= __highest_present_section_nr) {
261 		if (online_section_nr(start_nr))
262 			return section_nr_to_pfn(start_nr);
263 	}
264 
265 	return 0;
266 }
267 
268 /*
269  * If the PFN falls into an offline section, return the end PFN of the
270  * next online section in reverse. If the PFN falls into an online section
271  * or if there is no next online section in reverse, return 0.
272  */
skip_offline_sections_reverse(unsigned long start_pfn)273 static unsigned long skip_offline_sections_reverse(unsigned long start_pfn)
274 {
275 	unsigned long start_nr = pfn_to_section_nr(start_pfn);
276 
277 	if (!start_nr || online_section_nr(start_nr))
278 		return 0;
279 
280 	while (start_nr-- > 0) {
281 		if (online_section_nr(start_nr))
282 			return section_nr_to_pfn(start_nr) + PAGES_PER_SECTION;
283 	}
284 
285 	return 0;
286 }
287 #else
skip_offline_sections(unsigned long start_pfn)288 static unsigned long skip_offline_sections(unsigned long start_pfn)
289 {
290 	return 0;
291 }
292 
skip_offline_sections_reverse(unsigned long start_pfn)293 static unsigned long skip_offline_sections_reverse(unsigned long start_pfn)
294 {
295 	return 0;
296 }
297 #endif
298 
299 /*
300  * Compound pages of >= pageblock_order should consistently be skipped until
301  * released. It is always pointless to compact pages of such order (if they are
302  * migratable), and the pageblocks they occupy cannot contain any free pages.
303  */
pageblock_skip_persistent(struct page * page)304 static bool pageblock_skip_persistent(struct page *page)
305 {
306 	if (!PageCompound(page))
307 		return false;
308 
309 	page = compound_head(page);
310 
311 	if (compound_order(page) >= pageblock_order)
312 		return true;
313 
314 	return false;
315 }
316 
317 static bool
__reset_isolation_pfn(struct zone * zone,unsigned long pfn,bool check_source,bool check_target)318 __reset_isolation_pfn(struct zone *zone, unsigned long pfn, bool check_source,
319 							bool check_target)
320 {
321 	struct page *page = pfn_to_online_page(pfn);
322 	struct page *block_page;
323 	struct page *end_page;
324 	unsigned long block_pfn;
325 
326 	if (!page)
327 		return false;
328 	if (zone != page_zone(page))
329 		return false;
330 	if (pageblock_skip_persistent(page))
331 		return false;
332 
333 	/*
334 	 * If skip is already cleared do no further checking once the
335 	 * restart points have been set.
336 	 */
337 	if (check_source && check_target && !get_pageblock_skip(page))
338 		return true;
339 
340 	/*
341 	 * If clearing skip for the target scanner, do not select a
342 	 * non-movable pageblock as the starting point.
343 	 */
344 	if (!check_source && check_target &&
345 	    get_pageblock_migratetype(page) != MIGRATE_MOVABLE)
346 		return false;
347 
348 	/* Ensure the start of the pageblock or zone is online and valid */
349 	block_pfn = pageblock_start_pfn(pfn);
350 	block_pfn = max(block_pfn, zone->zone_start_pfn);
351 	block_page = pfn_to_online_page(block_pfn);
352 	if (block_page) {
353 		page = block_page;
354 		pfn = block_pfn;
355 	}
356 
357 	/* Ensure the end of the pageblock or zone is online and valid */
358 	block_pfn = pageblock_end_pfn(pfn) - 1;
359 	block_pfn = min(block_pfn, zone_end_pfn(zone) - 1);
360 	end_page = pfn_to_online_page(block_pfn);
361 	if (!end_page)
362 		return false;
363 
364 	/*
365 	 * Only clear the hint if a sample indicates there is either a
366 	 * free page or an LRU page in the block. One or other condition
367 	 * is necessary for the block to be a migration source/target.
368 	 */
369 	do {
370 		if (check_source && PageLRU(page)) {
371 			clear_pageblock_skip(page);
372 			return true;
373 		}
374 
375 		if (check_target && PageBuddy(page)) {
376 			clear_pageblock_skip(page);
377 			return true;
378 		}
379 
380 		page += (1 << PAGE_ALLOC_COSTLY_ORDER);
381 	} while (page <= end_page);
382 
383 	return false;
384 }
385 
386 /*
387  * This function is called to clear all cached information on pageblocks that
388  * should be skipped for page isolation when the migrate and free page scanner
389  * meet.
390  */
__reset_isolation_suitable(struct zone * zone)391 static void __reset_isolation_suitable(struct zone *zone)
392 {
393 	unsigned long migrate_pfn = zone->zone_start_pfn;
394 	unsigned long free_pfn = zone_end_pfn(zone) - 1;
395 	unsigned long reset_migrate = free_pfn;
396 	unsigned long reset_free = migrate_pfn;
397 	bool source_set = false;
398 	bool free_set = false;
399 
400 	/* Only flush if a full compaction finished recently */
401 	if (!zone->compact_blockskip_flush)
402 		return;
403 
404 	zone->compact_blockskip_flush = false;
405 
406 	/*
407 	 * Walk the zone and update pageblock skip information. Source looks
408 	 * for PageLRU while target looks for PageBuddy. When the scanner
409 	 * is found, both PageBuddy and PageLRU are checked as the pageblock
410 	 * is suitable as both source and target.
411 	 */
412 	for (; migrate_pfn < free_pfn; migrate_pfn += pageblock_nr_pages,
413 					free_pfn -= pageblock_nr_pages) {
414 		cond_resched();
415 
416 		/* Update the migrate PFN */
417 		if (__reset_isolation_pfn(zone, migrate_pfn, true, source_set) &&
418 		    migrate_pfn < reset_migrate) {
419 			source_set = true;
420 			reset_migrate = migrate_pfn;
421 			zone->compact_init_migrate_pfn = reset_migrate;
422 			zone->compact_cached_migrate_pfn[0] = reset_migrate;
423 			zone->compact_cached_migrate_pfn[1] = reset_migrate;
424 		}
425 
426 		/* Update the free PFN */
427 		if (__reset_isolation_pfn(zone, free_pfn, free_set, true) &&
428 		    free_pfn > reset_free) {
429 			free_set = true;
430 			reset_free = free_pfn;
431 			zone->compact_init_free_pfn = reset_free;
432 			zone->compact_cached_free_pfn = reset_free;
433 		}
434 	}
435 
436 	/* Leave no distance if no suitable block was reset */
437 	if (reset_migrate >= reset_free) {
438 		zone->compact_cached_migrate_pfn[0] = migrate_pfn;
439 		zone->compact_cached_migrate_pfn[1] = migrate_pfn;
440 		zone->compact_cached_free_pfn = free_pfn;
441 	}
442 }
443 
reset_isolation_suitable(pg_data_t * pgdat)444 void reset_isolation_suitable(pg_data_t *pgdat)
445 {
446 	int zoneid;
447 
448 	for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
449 		struct zone *zone = &pgdat->node_zones[zoneid];
450 		if (!populated_zone(zone))
451 			continue;
452 
453 		__reset_isolation_suitable(zone);
454 	}
455 }
456 
457 /*
458  * Sets the pageblock skip bit if it was clear. Note that this is a hint as
459  * locks are not required for read/writers. Returns true if it was already set.
460  */
test_and_set_skip(struct compact_control * cc,struct page * page)461 static bool test_and_set_skip(struct compact_control *cc, struct page *page)
462 {
463 	bool skip;
464 
465 	/* Do not update if skip hint is being ignored */
466 	if (cc->ignore_skip_hint)
467 		return false;
468 
469 	skip = get_pageblock_skip(page);
470 	if (!skip && !cc->no_set_skip_hint)
471 		set_pageblock_skip(page);
472 
473 	return skip;
474 }
475 
update_cached_migrate(struct compact_control * cc,unsigned long pfn)476 static void update_cached_migrate(struct compact_control *cc, unsigned long pfn)
477 {
478 	struct zone *zone = cc->zone;
479 
480 	/* Set for isolation rather than compaction */
481 	if (cc->no_set_skip_hint)
482 		return;
483 
484 	pfn = pageblock_end_pfn(pfn);
485 
486 	/* Update where async and sync compaction should restart */
487 	if (pfn > zone->compact_cached_migrate_pfn[0])
488 		zone->compact_cached_migrate_pfn[0] = pfn;
489 	if (cc->mode != MIGRATE_ASYNC &&
490 	    pfn > zone->compact_cached_migrate_pfn[1])
491 		zone->compact_cached_migrate_pfn[1] = pfn;
492 }
493 
494 /*
495  * If no pages were isolated then mark this pageblock to be skipped in the
496  * future. The information is later cleared by __reset_isolation_suitable().
497  */
update_pageblock_skip(struct compact_control * cc,struct page * page,unsigned long pfn)498 static void update_pageblock_skip(struct compact_control *cc,
499 			struct page *page, unsigned long pfn)
500 {
501 	struct zone *zone = cc->zone;
502 
503 	if (cc->no_set_skip_hint)
504 		return;
505 
506 	set_pageblock_skip(page);
507 
508 	if (pfn < zone->compact_cached_free_pfn)
509 		zone->compact_cached_free_pfn = pfn;
510 }
511 #else
isolation_suitable(struct compact_control * cc,struct page * page)512 static inline bool isolation_suitable(struct compact_control *cc,
513 					struct page *page)
514 {
515 	return true;
516 }
517 
pageblock_skip_persistent(struct page * page)518 static inline bool pageblock_skip_persistent(struct page *page)
519 {
520 	return false;
521 }
522 
update_pageblock_skip(struct compact_control * cc,struct page * page,unsigned long pfn)523 static inline void update_pageblock_skip(struct compact_control *cc,
524 			struct page *page, unsigned long pfn)
525 {
526 }
527 
update_cached_migrate(struct compact_control * cc,unsigned long pfn)528 static void update_cached_migrate(struct compact_control *cc, unsigned long pfn)
529 {
530 }
531 
test_and_set_skip(struct compact_control * cc,struct page * page)532 static bool test_and_set_skip(struct compact_control *cc, struct page *page)
533 {
534 	return false;
535 }
536 #endif /* CONFIG_COMPACTION */
537 
538 /*
539  * Compaction requires the taking of some coarse locks that are potentially
540  * very heavily contended. For async compaction, trylock and record if the
541  * lock is contended. The lock will still be acquired but compaction will
542  * abort when the current block is finished regardless of success rate.
543  * Sync compaction acquires the lock.
544  *
545  * Always returns true which makes it easier to track lock state in callers.
546  */
compact_lock_irqsave(spinlock_t * lock,unsigned long * flags,struct compact_control * cc)547 static bool compact_lock_irqsave(spinlock_t *lock, unsigned long *flags,
548 						struct compact_control *cc)
549 	__acquires(lock)
550 {
551 	/* Track if the lock is contended in async mode */
552 	if (cc->mode == MIGRATE_ASYNC && !cc->contended) {
553 		if (spin_trylock_irqsave(lock, *flags))
554 			return true;
555 
556 		cc->contended = true;
557 	}
558 
559 	spin_lock_irqsave(lock, *flags);
560 	return true;
561 }
562 
563 /*
564  * Compaction requires the taking of some coarse locks that are potentially
565  * very heavily contended. The lock should be periodically unlocked to avoid
566  * having disabled IRQs for a long time, even when there is nobody waiting on
567  * the lock. It might also be that allowing the IRQs will result in
568  * need_resched() becoming true. If scheduling is needed, compaction schedules.
569  * Either compaction type will also abort if a fatal signal is pending.
570  * In either case if the lock was locked, it is dropped and not regained.
571  *
572  * Returns true if compaction should abort due to fatal signal pending.
573  * Returns false when compaction can continue.
574  */
compact_unlock_should_abort(spinlock_t * lock,unsigned long flags,bool * locked,struct compact_control * cc)575 static bool compact_unlock_should_abort(spinlock_t *lock,
576 		unsigned long flags, bool *locked, struct compact_control *cc)
577 {
578 	if (*locked) {
579 		spin_unlock_irqrestore(lock, flags);
580 		*locked = false;
581 	}
582 
583 	if (fatal_signal_pending(current)) {
584 		cc->contended = true;
585 		return true;
586 	}
587 
588 	cond_resched();
589 
590 	return false;
591 }
592 
593 /*
594  * Isolate free pages onto a private freelist. If @strict is true, will abort
595  * returning 0 on any invalid PFNs or non-free pages inside of the pageblock
596  * (even though it may still end up isolating some pages).
597  */
isolate_freepages_block(struct compact_control * cc,unsigned long * start_pfn,unsigned long end_pfn,struct list_head * freelist,unsigned int stride,bool strict)598 static unsigned long isolate_freepages_block(struct compact_control *cc,
599 				unsigned long *start_pfn,
600 				unsigned long end_pfn,
601 				struct list_head *freelist,
602 				unsigned int stride,
603 				bool strict)
604 {
605 	int nr_scanned = 0, total_isolated = 0;
606 	struct page *page;
607 	unsigned long flags = 0;
608 	bool locked = false;
609 	unsigned long blockpfn = *start_pfn;
610 	unsigned int order;
611 
612 	/* Strict mode is for isolation, speed is secondary */
613 	if (strict)
614 		stride = 1;
615 
616 	page = pfn_to_page(blockpfn);
617 
618 	/* Isolate free pages. */
619 	for (; blockpfn < end_pfn; blockpfn += stride, page += stride) {
620 		int isolated;
621 
622 		/*
623 		 * Periodically drop the lock (if held) regardless of its
624 		 * contention, to give chance to IRQs. Abort if fatal signal
625 		 * pending.
626 		 */
627 		if (!(blockpfn % COMPACT_CLUSTER_MAX)
628 		    && compact_unlock_should_abort(&cc->zone->lock, flags,
629 								&locked, cc))
630 			break;
631 
632 		nr_scanned++;
633 
634 		/*
635 		 * For compound pages such as THP and hugetlbfs, we can save
636 		 * potentially a lot of iterations if we skip them at once.
637 		 * The check is racy, but we can consider only valid values
638 		 * and the only danger is skipping too much.
639 		 */
640 		if (PageCompound(page)) {
641 			const unsigned int order = compound_order(page);
642 
643 			if ((order <= MAX_PAGE_ORDER) &&
644 			    (blockpfn + (1UL << order) <= end_pfn)) {
645 				blockpfn += (1UL << order) - 1;
646 				page += (1UL << order) - 1;
647 				nr_scanned += (1UL << order) - 1;
648 			}
649 
650 			goto isolate_fail;
651 		}
652 
653 		if (!PageBuddy(page))
654 			goto isolate_fail;
655 
656 		/* If we already hold the lock, we can skip some rechecking. */
657 		if (!locked) {
658 			locked = compact_lock_irqsave(&cc->zone->lock,
659 								&flags, cc);
660 
661 			/* Recheck this is a buddy page under lock */
662 			if (!PageBuddy(page))
663 				goto isolate_fail;
664 		}
665 
666 		/* Found a free page, will break it into order-0 pages */
667 		order = buddy_order(page);
668 		isolated = __isolate_free_page(page, order);
669 		if (!isolated)
670 			break;
671 		set_page_private(page, order);
672 
673 		nr_scanned += isolated - 1;
674 		total_isolated += isolated;
675 		cc->nr_freepages += isolated;
676 		list_add_tail(&page->lru, &freelist[order]);
677 
678 		if (!strict && cc->nr_migratepages <= cc->nr_freepages) {
679 			blockpfn += isolated;
680 			break;
681 		}
682 		/* Advance to the end of split page */
683 		blockpfn += isolated - 1;
684 		page += isolated - 1;
685 		continue;
686 
687 isolate_fail:
688 		if (strict)
689 			break;
690 
691 	}
692 
693 	if (locked)
694 		spin_unlock_irqrestore(&cc->zone->lock, flags);
695 
696 	/*
697 	 * Be careful to not go outside of the pageblock.
698 	 */
699 	if (unlikely(blockpfn > end_pfn))
700 		blockpfn = end_pfn;
701 
702 	trace_mm_compaction_isolate_freepages(*start_pfn, blockpfn,
703 					nr_scanned, total_isolated);
704 
705 	/* Record how far we have got within the block */
706 	*start_pfn = blockpfn;
707 
708 	/*
709 	 * If strict isolation is requested by CMA then check that all the
710 	 * pages requested were isolated. If there were any failures, 0 is
711 	 * returned and CMA will fail.
712 	 */
713 	if (strict && blockpfn < end_pfn)
714 		total_isolated = 0;
715 
716 	cc->total_free_scanned += nr_scanned;
717 	if (total_isolated)
718 		count_compact_events(COMPACTISOLATED, total_isolated);
719 	return total_isolated;
720 }
721 
722 /**
723  * isolate_freepages_range() - isolate free pages.
724  * @cc:        Compaction control structure.
725  * @start_pfn: The first PFN to start isolating.
726  * @end_pfn:   The one-past-last PFN.
727  *
728  * Non-free pages, invalid PFNs, or zone boundaries within the
729  * [start_pfn, end_pfn) range are considered errors, cause function to
730  * undo its actions and return zero. cc->freepages[] are empty.
731  *
732  * Otherwise, function returns one-past-the-last PFN of isolated page
733  * (which may be greater then end_pfn if end fell in a middle of
734  * a free page). cc->freepages[] contain free pages isolated.
735  */
736 unsigned long
isolate_freepages_range(struct compact_control * cc,unsigned long start_pfn,unsigned long end_pfn)737 isolate_freepages_range(struct compact_control *cc,
738 			unsigned long start_pfn, unsigned long end_pfn)
739 {
740 	unsigned long isolated, pfn, block_start_pfn, block_end_pfn;
741 	int order;
742 
743 	for (order = 0; order < NR_PAGE_ORDERS; order++)
744 		INIT_LIST_HEAD(&cc->freepages[order]);
745 
746 	pfn = start_pfn;
747 	block_start_pfn = pageblock_start_pfn(pfn);
748 	if (block_start_pfn < cc->zone->zone_start_pfn)
749 		block_start_pfn = cc->zone->zone_start_pfn;
750 	block_end_pfn = pageblock_end_pfn(pfn);
751 
752 	for (; pfn < end_pfn; pfn += isolated,
753 				block_start_pfn = block_end_pfn,
754 				block_end_pfn += pageblock_nr_pages) {
755 		/* Protect pfn from changing by isolate_freepages_block */
756 		unsigned long isolate_start_pfn = pfn;
757 
758 		/*
759 		 * pfn could pass the block_end_pfn if isolated freepage
760 		 * is more than pageblock order. In this case, we adjust
761 		 * scanning range to right one.
762 		 */
763 		if (pfn >= block_end_pfn) {
764 			block_start_pfn = pageblock_start_pfn(pfn);
765 			block_end_pfn = pageblock_end_pfn(pfn);
766 		}
767 
768 		block_end_pfn = min(block_end_pfn, end_pfn);
769 
770 		if (!pageblock_pfn_to_page(block_start_pfn,
771 					block_end_pfn, cc->zone))
772 			break;
773 
774 		isolated = isolate_freepages_block(cc, &isolate_start_pfn,
775 					block_end_pfn, cc->freepages, 0, true);
776 
777 		/*
778 		 * In strict mode, isolate_freepages_block() returns 0 if
779 		 * there are any holes in the block (ie. invalid PFNs or
780 		 * non-free pages).
781 		 */
782 		if (!isolated)
783 			break;
784 
785 		/*
786 		 * If we managed to isolate pages, it is always (1 << n) *
787 		 * pageblock_nr_pages for some non-negative n.  (Max order
788 		 * page may span two pageblocks).
789 		 */
790 	}
791 
792 	if (pfn < end_pfn) {
793 		/* Loop terminated early, cleanup. */
794 		release_free_list(cc->freepages);
795 		return 0;
796 	}
797 
798 	/* We don't use freelists for anything. */
799 	return pfn;
800 }
801 
802 /* Similar to reclaim, but different enough that they don't share logic */
too_many_isolated(struct compact_control * cc)803 static bool too_many_isolated(struct compact_control *cc)
804 {
805 	pg_data_t *pgdat = cc->zone->zone_pgdat;
806 	bool too_many;
807 
808 	unsigned long active, inactive, isolated;
809 
810 	inactive = node_page_state(pgdat, NR_INACTIVE_FILE) +
811 			node_page_state(pgdat, NR_INACTIVE_ANON);
812 	active = node_page_state(pgdat, NR_ACTIVE_FILE) +
813 			node_page_state(pgdat, NR_ACTIVE_ANON);
814 	isolated = node_page_state(pgdat, NR_ISOLATED_FILE) +
815 			node_page_state(pgdat, NR_ISOLATED_ANON);
816 
817 	/*
818 	 * Allow GFP_NOFS to isolate past the limit set for regular
819 	 * compaction runs. This prevents an ABBA deadlock when other
820 	 * compactors have already isolated to the limit, but are
821 	 * blocked on filesystem locks held by the GFP_NOFS thread.
822 	 */
823 	if (cc->gfp_mask & __GFP_FS) {
824 		inactive >>= 3;
825 		active >>= 3;
826 	}
827 
828 	too_many = isolated > (inactive + active) / 2;
829 	if (!too_many)
830 		wake_throttle_isolated(pgdat);
831 
832 	return too_many;
833 }
834 
835 /**
836  * skip_isolation_on_order() - determine when to skip folio isolation based on
837  *			       folio order and compaction target order
838  * @order:		to-be-isolated folio order
839  * @target_order:	compaction target order
840  *
841  * This avoids unnecessary folio isolations during compaction.
842  */
skip_isolation_on_order(int order,int target_order)843 static bool skip_isolation_on_order(int order, int target_order)
844 {
845 	/*
846 	 * Unless we are performing global compaction (i.e.,
847 	 * is_via_compact_memory), skip any folios that are larger than the
848 	 * target order: we wouldn't be here if we'd have a free folio with
849 	 * the desired target_order, so migrating this folio would likely fail
850 	 * later.
851 	 */
852 	if (!is_via_compact_memory(target_order) && order >= target_order)
853 		return true;
854 	/*
855 	 * We limit memory compaction to pageblocks and won't try
856 	 * creating free blocks of memory that are larger than that.
857 	 */
858 	return order >= pageblock_order;
859 }
860 
861 /**
862  * isolate_migratepages_block() - isolate all migrate-able pages within
863  *				  a single pageblock
864  * @cc:		Compaction control structure.
865  * @low_pfn:	The first PFN to isolate
866  * @end_pfn:	The one-past-the-last PFN to isolate, within same pageblock
867  * @mode:	Isolation mode to be used.
868  *
869  * Isolate all pages that can be migrated from the range specified by
870  * [low_pfn, end_pfn). The range is expected to be within same pageblock.
871  * Returns errno, like -EAGAIN or -EINTR in case e.g signal pending or congestion,
872  * -ENOMEM in case we could not allocate a page, or 0.
873  * cc->migrate_pfn will contain the next pfn to scan.
874  *
875  * The pages are isolated on cc->migratepages list (not required to be empty),
876  * and cc->nr_migratepages is updated accordingly.
877  */
878 static int
isolate_migratepages_block(struct compact_control * cc,unsigned long low_pfn,unsigned long end_pfn,isolate_mode_t mode)879 isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
880 			unsigned long end_pfn, isolate_mode_t mode)
881 {
882 	pg_data_t *pgdat = cc->zone->zone_pgdat;
883 	unsigned long nr_scanned = 0, nr_isolated = 0;
884 	struct lruvec *lruvec;
885 	unsigned long flags = 0;
886 	struct lruvec *locked = NULL;
887 	struct folio *folio = NULL;
888 	struct page *page = NULL, *valid_page = NULL;
889 	struct address_space *mapping;
890 	unsigned long start_pfn = low_pfn;
891 	bool skip_on_failure = false;
892 	unsigned long next_skip_pfn = 0;
893 	bool skip_updated = false;
894 	int ret = 0;
895 
896 	cc->migrate_pfn = low_pfn;
897 
898 	/*
899 	 * Ensure that there are not too many pages isolated from the LRU
900 	 * list by either parallel reclaimers or compaction. If there are,
901 	 * delay for some time until fewer pages are isolated
902 	 */
903 	while (unlikely(too_many_isolated(cc))) {
904 		/* stop isolation if there are still pages not migrated */
905 		if (cc->nr_migratepages)
906 			return -EAGAIN;
907 
908 		/* async migration should just abort */
909 		if (cc->mode == MIGRATE_ASYNC)
910 			return -EAGAIN;
911 
912 		reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
913 
914 		if (fatal_signal_pending(current))
915 			return -EINTR;
916 	}
917 
918 	cond_resched();
919 
920 	if (cc->direct_compaction && (cc->mode == MIGRATE_ASYNC)) {
921 		skip_on_failure = true;
922 		next_skip_pfn = block_end_pfn(low_pfn, cc->order);
923 	}
924 
925 	/* Time to isolate some pages for migration */
926 	for (; low_pfn < end_pfn; low_pfn++) {
927 		bool is_dirty, is_unevictable;
928 
929 		if (skip_on_failure && low_pfn >= next_skip_pfn) {
930 			/*
931 			 * We have isolated all migration candidates in the
932 			 * previous order-aligned block, and did not skip it due
933 			 * to failure. We should migrate the pages now and
934 			 * hopefully succeed compaction.
935 			 */
936 			if (nr_isolated)
937 				break;
938 
939 			/*
940 			 * We failed to isolate in the previous order-aligned
941 			 * block. Set the new boundary to the end of the
942 			 * current block. Note we can't simply increase
943 			 * next_skip_pfn by 1 << order, as low_pfn might have
944 			 * been incremented by a higher number due to skipping
945 			 * a compound or a high-order buddy page in the
946 			 * previous loop iteration.
947 			 */
948 			next_skip_pfn = block_end_pfn(low_pfn, cc->order);
949 		}
950 
951 		/*
952 		 * Periodically drop the lock (if held) regardless of its
953 		 * contention, to give chance to IRQs. Abort completely if
954 		 * a fatal signal is pending.
955 		 */
956 		if (!(low_pfn % COMPACT_CLUSTER_MAX)) {
957 			if (locked) {
958 				unlock_page_lruvec_irqrestore(locked, flags);
959 				locked = NULL;
960 			}
961 
962 			if (fatal_signal_pending(current)) {
963 				cc->contended = true;
964 				ret = -EINTR;
965 
966 				goto fatal_pending;
967 			}
968 
969 			cond_resched();
970 		}
971 
972 		nr_scanned++;
973 
974 		page = pfn_to_page(low_pfn);
975 
976 		/*
977 		 * Check if the pageblock has already been marked skipped.
978 		 * Only the first PFN is checked as the caller isolates
979 		 * COMPACT_CLUSTER_MAX at a time so the second call must
980 		 * not falsely conclude that the block should be skipped.
981 		 */
982 		if (!valid_page && (pageblock_aligned(low_pfn) ||
983 				    low_pfn == cc->zone->zone_start_pfn)) {
984 			if (!isolation_suitable(cc, page)) {
985 				low_pfn = end_pfn;
986 				folio = NULL;
987 				goto isolate_abort;
988 			}
989 			valid_page = page;
990 		}
991 
992 		if (PageHuge(page)) {
993 			const unsigned int order = compound_order(page);
994 			/*
995 			 * skip hugetlbfs if we are not compacting for pages
996 			 * bigger than its order. THPs and other compound pages
997 			 * are handled below.
998 			 */
999 			if (!cc->alloc_contig) {
1000 
1001 				if (order <= MAX_PAGE_ORDER) {
1002 					low_pfn += (1UL << order) - 1;
1003 					nr_scanned += (1UL << order) - 1;
1004 				}
1005 				goto isolate_fail;
1006 			}
1007 			/* for alloc_contig case */
1008 			if (locked) {
1009 				unlock_page_lruvec_irqrestore(locked, flags);
1010 				locked = NULL;
1011 			}
1012 
1013 			ret = isolate_or_dissolve_huge_page(page, &cc->migratepages);
1014 
1015 			/*
1016 			 * Fail isolation in case isolate_or_dissolve_huge_page()
1017 			 * reports an error. In case of -ENOMEM, abort right away.
1018 			 */
1019 			if (ret < 0) {
1020 				 /* Do not report -EBUSY down the chain */
1021 				if (ret == -EBUSY)
1022 					ret = 0;
1023 				low_pfn += (1UL << order) - 1;
1024 				nr_scanned += (1UL << order) - 1;
1025 				goto isolate_fail;
1026 			}
1027 
1028 			if (PageHuge(page)) {
1029 				/*
1030 				 * Hugepage was successfully isolated and placed
1031 				 * on the cc->migratepages list.
1032 				 */
1033 				folio = page_folio(page);
1034 				low_pfn += folio_nr_pages(folio) - 1;
1035 				goto isolate_success_no_list;
1036 			}
1037 
1038 			/*
1039 			 * Ok, the hugepage was dissolved. Now these pages are
1040 			 * Buddy and cannot be re-allocated because they are
1041 			 * isolated. Fall-through as the check below handles
1042 			 * Buddy pages.
1043 			 */
1044 		}
1045 
1046 		/*
1047 		 * Skip if free. We read page order here without zone lock
1048 		 * which is generally unsafe, but the race window is small and
1049 		 * the worst thing that can happen is that we skip some
1050 		 * potential isolation targets.
1051 		 */
1052 		if (PageBuddy(page)) {
1053 			unsigned long freepage_order = buddy_order_unsafe(page);
1054 
1055 			/*
1056 			 * Without lock, we cannot be sure that what we got is
1057 			 * a valid page order. Consider only values in the
1058 			 * valid order range to prevent low_pfn overflow.
1059 			 */
1060 			if (freepage_order > 0 && freepage_order <= MAX_PAGE_ORDER) {
1061 				low_pfn += (1UL << freepage_order) - 1;
1062 				nr_scanned += (1UL << freepage_order) - 1;
1063 			}
1064 			continue;
1065 		}
1066 
1067 		/*
1068 		 * Regardless of being on LRU, compound pages such as THP
1069 		 * (hugetlbfs is handled above) are not to be compacted unless
1070 		 * we are attempting an allocation larger than the compound
1071 		 * page size. We can potentially save a lot of iterations if we
1072 		 * skip them at once. The check is racy, but we can consider
1073 		 * only valid values and the only danger is skipping too much.
1074 		 */
1075 		if (PageCompound(page) && !cc->alloc_contig) {
1076 			const unsigned int order = compound_order(page);
1077 
1078 			/* Skip based on page order and compaction target order. */
1079 			if (skip_isolation_on_order(order, cc->order)) {
1080 				if (order <= MAX_PAGE_ORDER) {
1081 					low_pfn += (1UL << order) - 1;
1082 					nr_scanned += (1UL << order) - 1;
1083 				}
1084 				goto isolate_fail;
1085 			}
1086 		}
1087 
1088 		/*
1089 		 * Check may be lockless but that's ok as we recheck later.
1090 		 * It's possible to migrate LRU and non-lru movable pages.
1091 		 * Skip any other type of page
1092 		 */
1093 		if (!PageLRU(page)) {
1094 			/*
1095 			 * __PageMovable can return false positive so we need
1096 			 * to verify it under page_lock.
1097 			 */
1098 			if (unlikely(__PageMovable(page)) &&
1099 					!PageIsolated(page)) {
1100 				if (locked) {
1101 					unlock_page_lruvec_irqrestore(locked, flags);
1102 					locked = NULL;
1103 				}
1104 
1105 				if (isolate_movable_page(page, mode)) {
1106 					folio = page_folio(page);
1107 					goto isolate_success;
1108 				}
1109 			}
1110 
1111 			goto isolate_fail;
1112 		}
1113 
1114 		/*
1115 		 * Be careful not to clear PageLRU until after we're
1116 		 * sure the page is not being freed elsewhere -- the
1117 		 * page release code relies on it.
1118 		 */
1119 		folio = folio_get_nontail_page(page);
1120 		if (unlikely(!folio))
1121 			goto isolate_fail;
1122 
1123 		/*
1124 		 * Migration will fail if an anonymous page is pinned in memory,
1125 		 * so avoid taking lru_lock and isolating it unnecessarily in an
1126 		 * admittedly racy check.
1127 		 */
1128 		mapping = folio_mapping(folio);
1129 		if (!mapping && (folio_ref_count(folio) - 1) > folio_mapcount(folio))
1130 			goto isolate_fail_put;
1131 
1132 		/*
1133 		 * Only allow to migrate anonymous pages in GFP_NOFS context
1134 		 * because those do not depend on fs locks.
1135 		 */
1136 		if (!(cc->gfp_mask & __GFP_FS) && mapping)
1137 			goto isolate_fail_put;
1138 
1139 		/* Only take pages on LRU: a check now makes later tests safe */
1140 		if (!folio_test_lru(folio))
1141 			goto isolate_fail_put;
1142 
1143 		is_unevictable = folio_test_unevictable(folio);
1144 
1145 		/* Compaction might skip unevictable pages but CMA takes them */
1146 		if (!(mode & ISOLATE_UNEVICTABLE) && is_unevictable)
1147 			goto isolate_fail_put;
1148 
1149 		/*
1150 		 * To minimise LRU disruption, the caller can indicate with
1151 		 * ISOLATE_ASYNC_MIGRATE that it only wants to isolate pages
1152 		 * it will be able to migrate without blocking - clean pages
1153 		 * for the most part.  PageWriteback would require blocking.
1154 		 */
1155 		if ((mode & ISOLATE_ASYNC_MIGRATE) && folio_test_writeback(folio))
1156 			goto isolate_fail_put;
1157 
1158 		is_dirty = folio_test_dirty(folio);
1159 
1160 		if (((mode & ISOLATE_ASYNC_MIGRATE) && is_dirty) ||
1161 		    (mapping && is_unevictable)) {
1162 			bool migrate_dirty = true;
1163 			bool is_inaccessible;
1164 
1165 			/*
1166 			 * Only folios without mappings or that have
1167 			 * a ->migrate_folio callback are possible to migrate
1168 			 * without blocking.
1169 			 *
1170 			 * Folios from inaccessible mappings are not migratable.
1171 			 *
1172 			 * However, we can be racing with truncation, which can
1173 			 * free the mapping that we need to check. Truncation
1174 			 * holds the folio lock until after the folio is removed
1175 			 * from the page so holding it ourselves is sufficient.
1176 			 *
1177 			 * To avoid locking the folio just to check inaccessible,
1178 			 * assume every inaccessible folio is also unevictable,
1179 			 * which is a cheaper test.  If our assumption goes
1180 			 * wrong, it's not a correctness bug, just potentially
1181 			 * wasted cycles.
1182 			 */
1183 			if (!folio_trylock(folio))
1184 				goto isolate_fail_put;
1185 
1186 			mapping = folio_mapping(folio);
1187 			if ((mode & ISOLATE_ASYNC_MIGRATE) && is_dirty) {
1188 				migrate_dirty = !mapping ||
1189 						mapping->a_ops->migrate_folio;
1190 			}
1191 			is_inaccessible = mapping && mapping_inaccessible(mapping);
1192 			folio_unlock(folio);
1193 			if (!migrate_dirty || is_inaccessible)
1194 				goto isolate_fail_put;
1195 		}
1196 
1197 		/* Try isolate the folio */
1198 		if (!folio_test_clear_lru(folio))
1199 			goto isolate_fail_put;
1200 
1201 		lruvec = folio_lruvec(folio);
1202 
1203 		/* If we already hold the lock, we can skip some rechecking */
1204 		if (lruvec != locked) {
1205 			if (locked)
1206 				unlock_page_lruvec_irqrestore(locked, flags);
1207 
1208 			compact_lock_irqsave(&lruvec->lru_lock, &flags, cc);
1209 			locked = lruvec;
1210 
1211 			lruvec_memcg_debug(lruvec, folio);
1212 
1213 			/*
1214 			 * Try get exclusive access under lock. If marked for
1215 			 * skip, the scan is aborted unless the current context
1216 			 * is a rescan to reach the end of the pageblock.
1217 			 */
1218 			if (!skip_updated && valid_page) {
1219 				skip_updated = true;
1220 				if (test_and_set_skip(cc, valid_page) &&
1221 				    !cc->finish_pageblock) {
1222 					low_pfn = end_pfn;
1223 					goto isolate_abort;
1224 				}
1225 			}
1226 
1227 			/*
1228 			 * Check LRU folio order under the lock
1229 			 */
1230 			if (unlikely(skip_isolation_on_order(folio_order(folio),
1231 							     cc->order) &&
1232 				     !cc->alloc_contig)) {
1233 				low_pfn += folio_nr_pages(folio) - 1;
1234 				nr_scanned += folio_nr_pages(folio) - 1;
1235 				folio_set_lru(folio);
1236 				goto isolate_fail_put;
1237 			}
1238 		}
1239 
1240 		/* The folio is taken off the LRU */
1241 		if (folio_test_large(folio))
1242 			low_pfn += folio_nr_pages(folio) - 1;
1243 
1244 		/* Successfully isolated */
1245 		lruvec_del_folio(lruvec, folio);
1246 		node_stat_mod_folio(folio,
1247 				NR_ISOLATED_ANON + folio_is_file_lru(folio),
1248 				folio_nr_pages(folio));
1249 
1250 isolate_success:
1251 		list_add(&folio->lru, &cc->migratepages);
1252 isolate_success_no_list:
1253 		cc->nr_migratepages += folio_nr_pages(folio);
1254 		nr_isolated += folio_nr_pages(folio);
1255 		nr_scanned += folio_nr_pages(folio) - 1;
1256 
1257 		/*
1258 		 * Avoid isolating too much unless this block is being
1259 		 * fully scanned (e.g. dirty/writeback pages, parallel allocation)
1260 		 * or a lock is contended. For contention, isolate quickly to
1261 		 * potentially remove one source of contention.
1262 		 */
1263 		if (cc->nr_migratepages >= COMPACT_CLUSTER_MAX &&
1264 		    !cc->finish_pageblock && !cc->contended) {
1265 			++low_pfn;
1266 			break;
1267 		}
1268 
1269 		continue;
1270 
1271 isolate_fail_put:
1272 		/* Avoid potential deadlock in freeing page under lru_lock */
1273 		if (locked) {
1274 			unlock_page_lruvec_irqrestore(locked, flags);
1275 			locked = NULL;
1276 		}
1277 		folio_put(folio);
1278 
1279 isolate_fail:
1280 		if (!skip_on_failure && ret != -ENOMEM)
1281 			continue;
1282 
1283 		/*
1284 		 * We have isolated some pages, but then failed. Release them
1285 		 * instead of migrating, as we cannot form the cc->order buddy
1286 		 * page anyway.
1287 		 */
1288 		if (nr_isolated) {
1289 			if (locked) {
1290 				unlock_page_lruvec_irqrestore(locked, flags);
1291 				locked = NULL;
1292 			}
1293 			putback_movable_pages(&cc->migratepages);
1294 			cc->nr_migratepages = 0;
1295 			nr_isolated = 0;
1296 		}
1297 
1298 		if (low_pfn < next_skip_pfn) {
1299 			low_pfn = next_skip_pfn - 1;
1300 			/*
1301 			 * The check near the loop beginning would have updated
1302 			 * next_skip_pfn too, but this is a bit simpler.
1303 			 */
1304 			next_skip_pfn += 1UL << cc->order;
1305 		}
1306 
1307 		if (ret == -ENOMEM)
1308 			break;
1309 	}
1310 
1311 	/*
1312 	 * The PageBuddy() check could have potentially brought us outside
1313 	 * the range to be scanned.
1314 	 */
1315 	if (unlikely(low_pfn > end_pfn))
1316 		low_pfn = end_pfn;
1317 
1318 	folio = NULL;
1319 
1320 isolate_abort:
1321 	if (locked)
1322 		unlock_page_lruvec_irqrestore(locked, flags);
1323 	if (folio) {
1324 		folio_set_lru(folio);
1325 		folio_put(folio);
1326 	}
1327 
1328 	/*
1329 	 * Update the cached scanner pfn once the pageblock has been scanned.
1330 	 * Pages will either be migrated in which case there is no point
1331 	 * scanning in the near future or migration failed in which case the
1332 	 * failure reason may persist. The block is marked for skipping if
1333 	 * there were no pages isolated in the block or if the block is
1334 	 * rescanned twice in a row.
1335 	 */
1336 	if (low_pfn == end_pfn && (!nr_isolated || cc->finish_pageblock)) {
1337 		if (!cc->no_set_skip_hint && valid_page && !skip_updated)
1338 			set_pageblock_skip(valid_page);
1339 		update_cached_migrate(cc, low_pfn);
1340 	}
1341 
1342 	trace_mm_compaction_isolate_migratepages(start_pfn, low_pfn,
1343 						nr_scanned, nr_isolated);
1344 
1345 fatal_pending:
1346 	cc->total_migrate_scanned += nr_scanned;
1347 	if (nr_isolated)
1348 		count_compact_events(COMPACTISOLATED, nr_isolated);
1349 
1350 	cc->migrate_pfn = low_pfn;
1351 
1352 	return ret;
1353 }
1354 
1355 /**
1356  * isolate_migratepages_range() - isolate migrate-able pages in a PFN range
1357  * @cc:        Compaction control structure.
1358  * @start_pfn: The first PFN to start isolating.
1359  * @end_pfn:   The one-past-last PFN.
1360  *
1361  * Returns -EAGAIN when contented, -EINTR in case of a signal pending, -ENOMEM
1362  * in case we could not allocate a page, or 0.
1363  */
1364 int
isolate_migratepages_range(struct compact_control * cc,unsigned long start_pfn,unsigned long end_pfn)1365 isolate_migratepages_range(struct compact_control *cc, unsigned long start_pfn,
1366 							unsigned long end_pfn)
1367 {
1368 	unsigned long pfn, block_start_pfn, block_end_pfn;
1369 	int ret = 0;
1370 
1371 	/* Scan block by block. First and last block may be incomplete */
1372 	pfn = start_pfn;
1373 	block_start_pfn = pageblock_start_pfn(pfn);
1374 	if (block_start_pfn < cc->zone->zone_start_pfn)
1375 		block_start_pfn = cc->zone->zone_start_pfn;
1376 	block_end_pfn = pageblock_end_pfn(pfn);
1377 
1378 	for (; pfn < end_pfn; pfn = block_end_pfn,
1379 				block_start_pfn = block_end_pfn,
1380 				block_end_pfn += pageblock_nr_pages) {
1381 
1382 		block_end_pfn = min(block_end_pfn, end_pfn);
1383 
1384 		if (!pageblock_pfn_to_page(block_start_pfn,
1385 					block_end_pfn, cc->zone))
1386 			continue;
1387 
1388 		ret = isolate_migratepages_block(cc, pfn, block_end_pfn,
1389 						 ISOLATE_UNEVICTABLE);
1390 
1391 		if (ret)
1392 			break;
1393 
1394 		if (cc->nr_migratepages >= COMPACT_CLUSTER_MAX)
1395 			break;
1396 	}
1397 
1398 	return ret;
1399 }
1400 
1401 #endif /* CONFIG_COMPACTION || CONFIG_CMA */
1402 #include <trace/hooks/mm.h>
1403 #ifdef CONFIG_COMPACTION
1404 
suitable_migration_source(struct compact_control * cc,struct page * page)1405 static bool suitable_migration_source(struct compact_control *cc,
1406 							struct page *page)
1407 {
1408 	int block_mt;
1409 
1410 	if (pageblock_skip_persistent(page))
1411 		return false;
1412 
1413 	if ((cc->mode != MIGRATE_ASYNC) || !cc->direct_compaction)
1414 		return true;
1415 
1416 	block_mt = get_pageblock_migratetype(page);
1417 
1418 	if (cc->migratetype == MIGRATE_MOVABLE)
1419 		return is_migrate_movable(block_mt);
1420 	else
1421 		return block_mt == cc->migratetype;
1422 }
1423 
1424 /* Returns true if the page is within a block suitable for migration to */
suitable_migration_target(struct compact_control * cc,struct page * page)1425 static bool suitable_migration_target(struct compact_control *cc,
1426 							struct page *page)
1427 {
1428 	bool bypass = false;
1429 
1430 	/* If the page is a large free page, then disallow migration */
1431 	if (PageBuddy(page)) {
1432 		int order = cc->order > 0 ? cc->order : pageblock_order;
1433 
1434 		/*
1435 		 * We are checking page_order without zone->lock taken. But
1436 		 * the only small danger is that we skip a potentially suitable
1437 		 * pageblock, so it's not worth to check order for valid range.
1438 		 */
1439 		if (buddy_order_unsafe(page) >= order)
1440 			return false;
1441 	}
1442 
1443 	trace_android_vh_migration_target_bypass(page, &bypass);
1444 	if (bypass)
1445 		return false;
1446 
1447 	if (cc->ignore_block_suitable)
1448 		return true;
1449 
1450 	/* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */
1451 	if (is_migrate_movable(get_pageblock_migratetype(page)))
1452 		return true;
1453 
1454 	/* Otherwise skip the block */
1455 	return false;
1456 }
1457 
1458 static inline unsigned int
freelist_scan_limit(struct compact_control * cc)1459 freelist_scan_limit(struct compact_control *cc)
1460 {
1461 	unsigned short shift = BITS_PER_LONG - 1;
1462 
1463 	return (COMPACT_CLUSTER_MAX >> min(shift, cc->fast_search_fail)) + 1;
1464 }
1465 
1466 /*
1467  * Test whether the free scanner has reached the same or lower pageblock than
1468  * the migration scanner, and compaction should thus terminate.
1469  */
compact_scanners_met(struct compact_control * cc)1470 static inline bool compact_scanners_met(struct compact_control *cc)
1471 {
1472 	return (cc->free_pfn >> pageblock_order)
1473 		<= (cc->migrate_pfn >> pageblock_order);
1474 }
1475 
1476 /*
1477  * Used when scanning for a suitable migration target which scans freelists
1478  * in reverse. Reorders the list such as the unscanned pages are scanned
1479  * first on the next iteration of the free scanner
1480  */
1481 static void
move_freelist_head(struct list_head * freelist,struct page * freepage)1482 move_freelist_head(struct list_head *freelist, struct page *freepage)
1483 {
1484 	LIST_HEAD(sublist);
1485 
1486 	if (!list_is_first(&freepage->buddy_list, freelist)) {
1487 		list_cut_before(&sublist, freelist, &freepage->buddy_list);
1488 		list_splice_tail(&sublist, freelist);
1489 	}
1490 }
1491 
1492 /*
1493  * Similar to move_freelist_head except used by the migration scanner
1494  * when scanning forward. It's possible for these list operations to
1495  * move against each other if they search the free list exactly in
1496  * lockstep.
1497  */
1498 static void
move_freelist_tail(struct list_head * freelist,struct page * freepage)1499 move_freelist_tail(struct list_head *freelist, struct page *freepage)
1500 {
1501 	LIST_HEAD(sublist);
1502 
1503 	if (!list_is_last(&freepage->buddy_list, freelist)) {
1504 		list_cut_position(&sublist, freelist, &freepage->buddy_list);
1505 		list_splice_tail(&sublist, freelist);
1506 	}
1507 }
1508 
1509 static void
fast_isolate_around(struct compact_control * cc,unsigned long pfn)1510 fast_isolate_around(struct compact_control *cc, unsigned long pfn)
1511 {
1512 	unsigned long start_pfn, end_pfn;
1513 	struct page *page;
1514 	bool bypass = false;
1515 
1516 	/* Do not search around if there are enough pages already */
1517 	if (cc->nr_freepages >= cc->nr_migratepages)
1518 		return;
1519 
1520 	/* Minimise scanning during async compaction */
1521 	if (cc->direct_compaction && cc->mode == MIGRATE_ASYNC)
1522 		return;
1523 
1524 	/* Pageblock boundaries */
1525 	start_pfn = max(pageblock_start_pfn(pfn), cc->zone->zone_start_pfn);
1526 	end_pfn = min(pageblock_end_pfn(pfn), zone_end_pfn(cc->zone));
1527 
1528 	page = pageblock_pfn_to_page(start_pfn, end_pfn, cc->zone);
1529 	if (!page)
1530 		return;
1531 
1532 	trace_android_vh_migration_target_bypass(page, &bypass);
1533 	if (bypass)
1534 		return;
1535 
1536 	isolate_freepages_block(cc, &start_pfn, end_pfn, cc->freepages, 1, false);
1537 
1538 	/* Skip this pageblock in the future as it's full or nearly full */
1539 	if (start_pfn == end_pfn && !cc->no_set_skip_hint)
1540 		set_pageblock_skip(page);
1541 }
1542 
1543 /* Search orders in round-robin fashion */
next_search_order(struct compact_control * cc,int order)1544 static int next_search_order(struct compact_control *cc, int order)
1545 {
1546 	order--;
1547 	if (order < 0)
1548 		order = cc->order - 1;
1549 
1550 	/* Search wrapped around? */
1551 	if (order == cc->search_order) {
1552 		cc->search_order--;
1553 		if (cc->search_order < 0)
1554 			cc->search_order = cc->order - 1;
1555 		return -1;
1556 	}
1557 
1558 	return order;
1559 }
1560 
fast_isolate_freepages(struct compact_control * cc)1561 static void fast_isolate_freepages(struct compact_control *cc)
1562 {
1563 	unsigned int limit = max(1U, freelist_scan_limit(cc) >> 1);
1564 	unsigned int nr_scanned = 0, total_isolated = 0;
1565 	unsigned long low_pfn, min_pfn, highest = 0;
1566 	unsigned long nr_isolated = 0;
1567 	unsigned long distance;
1568 	struct page *page = NULL;
1569 	bool scan_start = false;
1570 	int order;
1571 
1572 	/* Full compaction passes in a negative order */
1573 	if (cc->order <= 0)
1574 		return;
1575 
1576 	/*
1577 	 * If starting the scan, use a deeper search and use the highest
1578 	 * PFN found if a suitable one is not found.
1579 	 */
1580 	if (cc->free_pfn >= cc->zone->compact_init_free_pfn) {
1581 		limit = pageblock_nr_pages >> 1;
1582 		scan_start = true;
1583 	}
1584 
1585 	/*
1586 	 * Preferred point is in the top quarter of the scan space but take
1587 	 * a pfn from the top half if the search is problematic.
1588 	 */
1589 	distance = (cc->free_pfn - cc->migrate_pfn);
1590 	low_pfn = pageblock_start_pfn(cc->free_pfn - (distance >> 2));
1591 	min_pfn = pageblock_start_pfn(cc->free_pfn - (distance >> 1));
1592 
1593 	if (WARN_ON_ONCE(min_pfn > low_pfn))
1594 		low_pfn = min_pfn;
1595 
1596 	/*
1597 	 * Search starts from the last successful isolation order or the next
1598 	 * order to search after a previous failure
1599 	 */
1600 	cc->search_order = min_t(unsigned int, cc->order - 1, cc->search_order);
1601 
1602 	for (order = cc->search_order;
1603 	     !page && order >= 0;
1604 	     order = next_search_order(cc, order)) {
1605 		struct free_area *area = &cc->zone->free_area[order];
1606 		struct list_head *freelist;
1607 		struct page *freepage;
1608 		unsigned long flags;
1609 		unsigned int order_scanned = 0;
1610 		unsigned long high_pfn = 0;
1611 
1612 		if (!area->nr_free)
1613 			continue;
1614 
1615 		spin_lock_irqsave(&cc->zone->lock, flags);
1616 		freelist = &area->free_list[MIGRATE_MOVABLE];
1617 		list_for_each_entry_reverse(freepage, freelist, buddy_list) {
1618 			unsigned long pfn;
1619 
1620 			order_scanned++;
1621 			nr_scanned++;
1622 			pfn = page_to_pfn(freepage);
1623 
1624 			if (pfn >= highest)
1625 				highest = max(pageblock_start_pfn(pfn),
1626 					      cc->zone->zone_start_pfn);
1627 
1628 			if (pfn >= low_pfn) {
1629 				cc->fast_search_fail = 0;
1630 				cc->search_order = order;
1631 				page = freepage;
1632 				break;
1633 			}
1634 
1635 			if (pfn >= min_pfn && pfn > high_pfn) {
1636 				high_pfn = pfn;
1637 
1638 				/* Shorten the scan if a candidate is found */
1639 				limit >>= 1;
1640 			}
1641 
1642 			if (order_scanned >= limit)
1643 				break;
1644 		}
1645 
1646 		/* Use a maximum candidate pfn if a preferred one was not found */
1647 		if (!page && high_pfn) {
1648 			page = pfn_to_page(high_pfn);
1649 
1650 			/* Update freepage for the list reorder below */
1651 			freepage = page;
1652 		}
1653 
1654 		/* Reorder to so a future search skips recent pages */
1655 		move_freelist_head(freelist, freepage);
1656 
1657 		/* Isolate the page if available */
1658 		if (page) {
1659 			if (__isolate_free_page(page, order)) {
1660 				set_page_private(page, order);
1661 				nr_isolated = 1 << order;
1662 				nr_scanned += nr_isolated - 1;
1663 				total_isolated += nr_isolated;
1664 				cc->nr_freepages += nr_isolated;
1665 				list_add_tail(&page->lru, &cc->freepages[order]);
1666 				count_compact_events(COMPACTISOLATED, nr_isolated);
1667 			} else {
1668 				/* If isolation fails, abort the search */
1669 				order = cc->search_order + 1;
1670 				page = NULL;
1671 			}
1672 		}
1673 
1674 		spin_unlock_irqrestore(&cc->zone->lock, flags);
1675 
1676 		/* Skip fast search if enough freepages isolated */
1677 		if (cc->nr_freepages >= cc->nr_migratepages)
1678 			break;
1679 
1680 		/*
1681 		 * Smaller scan on next order so the total scan is related
1682 		 * to freelist_scan_limit.
1683 		 */
1684 		if (order_scanned >= limit)
1685 			limit = max(1U, limit >> 1);
1686 	}
1687 
1688 	trace_mm_compaction_fast_isolate_freepages(min_pfn, cc->free_pfn,
1689 						   nr_scanned, total_isolated);
1690 
1691 	if (!page) {
1692 		cc->fast_search_fail++;
1693 		if (scan_start) {
1694 			/*
1695 			 * Use the highest PFN found above min. If one was
1696 			 * not found, be pessimistic for direct compaction
1697 			 * and use the min mark.
1698 			 */
1699 			if (highest >= min_pfn) {
1700 				page = pfn_to_page(highest);
1701 				cc->free_pfn = highest;
1702 			} else {
1703 				if (cc->direct_compaction && pfn_valid(min_pfn)) {
1704 					page = pageblock_pfn_to_page(min_pfn,
1705 						min(pageblock_end_pfn(min_pfn),
1706 						    zone_end_pfn(cc->zone)),
1707 						cc->zone);
1708 					if (page && !suitable_migration_target(cc, page))
1709 						page = NULL;
1710 
1711 					cc->free_pfn = min_pfn;
1712 				}
1713 			}
1714 		}
1715 	}
1716 
1717 	if (highest && highest >= cc->zone->compact_cached_free_pfn) {
1718 		highest -= pageblock_nr_pages;
1719 		cc->zone->compact_cached_free_pfn = highest;
1720 	}
1721 
1722 	cc->total_free_scanned += nr_scanned;
1723 	if (!page)
1724 		return;
1725 
1726 	low_pfn = page_to_pfn(page);
1727 	fast_isolate_around(cc, low_pfn);
1728 }
1729 
1730 /*
1731  * Based on information in the current compact_control, find blocks
1732  * suitable for isolating free pages from and then isolate them.
1733  */
isolate_freepages(struct compact_control * cc)1734 static void isolate_freepages(struct compact_control *cc)
1735 {
1736 	struct zone *zone = cc->zone;
1737 	struct page *page;
1738 	unsigned long block_start_pfn;	/* start of current pageblock */
1739 	unsigned long isolate_start_pfn; /* exact pfn we start at */
1740 	unsigned long block_end_pfn;	/* end of current pageblock */
1741 	unsigned long low_pfn;	     /* lowest pfn scanner is able to scan */
1742 	unsigned int stride;
1743 	bool bypass = false;
1744 
1745 	/* Try a small search of the free lists for a candidate */
1746 	fast_isolate_freepages(cc);
1747 	if (cc->nr_freepages)
1748 		return;
1749 
1750 	/*
1751 	 * Initialise the free scanner. The starting point is where we last
1752 	 * successfully isolated from, zone-cached value, or the end of the
1753 	 * zone when isolating for the first time. For looping we also need
1754 	 * this pfn aligned down to the pageblock boundary, because we do
1755 	 * block_start_pfn -= pageblock_nr_pages in the for loop.
1756 	 * For ending point, take care when isolating in last pageblock of a
1757 	 * zone which ends in the middle of a pageblock.
1758 	 * The low boundary is the end of the pageblock the migration scanner
1759 	 * is using.
1760 	 */
1761 	isolate_start_pfn = cc->free_pfn;
1762 	block_start_pfn = pageblock_start_pfn(isolate_start_pfn);
1763 	block_end_pfn = min(block_start_pfn + pageblock_nr_pages,
1764 						zone_end_pfn(zone));
1765 	low_pfn = pageblock_end_pfn(cc->migrate_pfn);
1766 	stride = cc->mode == MIGRATE_ASYNC ? COMPACT_CLUSTER_MAX : 1;
1767 
1768 	/*
1769 	 * Isolate free pages until enough are available to migrate the
1770 	 * pages on cc->migratepages. We stop searching if the migrate
1771 	 * and free page scanners meet or enough free pages are isolated.
1772 	 */
1773 	for (; block_start_pfn >= low_pfn;
1774 				block_end_pfn = block_start_pfn,
1775 				block_start_pfn -= pageblock_nr_pages,
1776 				isolate_start_pfn = block_start_pfn) {
1777 		unsigned long nr_isolated;
1778 
1779 		/*
1780 		 * This can iterate a massively long zone without finding any
1781 		 * suitable migration targets, so periodically check resched.
1782 		 */
1783 		if (!(block_start_pfn % (COMPACT_CLUSTER_MAX * pageblock_nr_pages)))
1784 			cond_resched();
1785 
1786 		page = pageblock_pfn_to_page(block_start_pfn, block_end_pfn,
1787 									zone);
1788 		if (!page) {
1789 			unsigned long next_pfn;
1790 
1791 			next_pfn = skip_offline_sections_reverse(block_start_pfn);
1792 			if (next_pfn)
1793 				block_start_pfn = max(next_pfn, low_pfn);
1794 
1795 			continue;
1796 		}
1797 
1798 		/* Check the block is suitable for migration */
1799 		if (!suitable_migration_target(cc, page))
1800 			continue;
1801 
1802 		/* If isolation recently failed, do not retry */
1803 		if (!isolation_suitable(cc, page))
1804 			continue;
1805 
1806 		trace_android_vh_isolate_freepages(cc, page, &bypass);
1807 		if (bypass)
1808 			continue;
1809 
1810 		/* Found a block suitable for isolating free pages from. */
1811 		nr_isolated = isolate_freepages_block(cc, &isolate_start_pfn,
1812 					block_end_pfn, cc->freepages, stride, false);
1813 
1814 		/* Update the skip hint if the full pageblock was scanned */
1815 		if (isolate_start_pfn == block_end_pfn)
1816 			update_pageblock_skip(cc, page, block_start_pfn -
1817 					      pageblock_nr_pages);
1818 
1819 		/* Are enough freepages isolated? */
1820 		if (cc->nr_freepages >= cc->nr_migratepages) {
1821 			if (isolate_start_pfn >= block_end_pfn) {
1822 				/*
1823 				 * Restart at previous pageblock if more
1824 				 * freepages can be isolated next time.
1825 				 */
1826 				isolate_start_pfn =
1827 					block_start_pfn - pageblock_nr_pages;
1828 			}
1829 			break;
1830 		} else if (isolate_start_pfn < block_end_pfn) {
1831 			/*
1832 			 * If isolation failed early, do not continue
1833 			 * needlessly.
1834 			 */
1835 			break;
1836 		}
1837 
1838 		/* Adjust stride depending on isolation */
1839 		if (nr_isolated) {
1840 			stride = 1;
1841 			continue;
1842 		}
1843 		stride = min_t(unsigned int, COMPACT_CLUSTER_MAX, stride << 1);
1844 	}
1845 
1846 	/*
1847 	 * Record where the free scanner will restart next time. Either we
1848 	 * broke from the loop and set isolate_start_pfn based on the last
1849 	 * call to isolate_freepages_block(), or we met the migration scanner
1850 	 * and the loop terminated due to isolate_start_pfn < low_pfn
1851 	 */
1852 	cc->free_pfn = isolate_start_pfn;
1853 }
1854 
1855 /*
1856  * This is a migrate-callback that "allocates" freepages by taking pages
1857  * from the isolated freelists in the block we are migrating to.
1858  */
compaction_alloc_noprof(struct folio * src,unsigned long data)1859 static struct folio *compaction_alloc_noprof(struct folio *src, unsigned long data)
1860 {
1861 	struct compact_control *cc = (struct compact_control *)data;
1862 	struct folio *dst;
1863 	int order = folio_order(src);
1864 	bool has_isolated_pages = false;
1865 	int start_order;
1866 	struct page *freepage;
1867 	unsigned long size;
1868 
1869 again:
1870 	for (start_order = order; start_order < NR_PAGE_ORDERS; start_order++)
1871 		if (!list_empty(&cc->freepages[start_order]))
1872 			break;
1873 
1874 	/* no free pages in the list */
1875 	if (start_order == NR_PAGE_ORDERS) {
1876 		if (has_isolated_pages)
1877 			return NULL;
1878 		isolate_freepages(cc);
1879 		has_isolated_pages = true;
1880 		goto again;
1881 	}
1882 
1883 	freepage = list_first_entry(&cc->freepages[start_order], struct page,
1884 				lru);
1885 	size = 1 << start_order;
1886 
1887 	list_del(&freepage->lru);
1888 
1889 	while (start_order > order) {
1890 		start_order--;
1891 		size >>= 1;
1892 
1893 		list_add(&freepage[size].lru, &cc->freepages[start_order]);
1894 		set_page_private(&freepage[size], start_order);
1895 	}
1896 	dst = (struct folio *)freepage;
1897 
1898 	post_alloc_hook(&dst->page, order, __GFP_MOVABLE);
1899 	if (order)
1900 		prep_compound_page(&dst->page, order);
1901 	cc->nr_freepages -= 1 << order;
1902 	cc->nr_migratepages -= 1 << order;
1903 	return page_rmappable_folio(&dst->page);
1904 }
1905 
compaction_alloc(struct folio * src,unsigned long data)1906 static struct folio *compaction_alloc(struct folio *src, unsigned long data)
1907 {
1908 	return alloc_hooks(compaction_alloc_noprof(src, data));
1909 }
1910 
1911 /*
1912  * This is a migrate-callback that "frees" freepages back to the isolated
1913  * freelist.  All pages on the freelist are from the same zone, so there is no
1914  * special handling needed for NUMA.
1915  */
compaction_free(struct folio * dst,unsigned long data)1916 static void compaction_free(struct folio *dst, unsigned long data)
1917 {
1918 	struct compact_control *cc = (struct compact_control *)data;
1919 	int order = folio_order(dst);
1920 	struct page *page = &dst->page;
1921 
1922 	if (folio_put_testzero(dst)) {
1923 		free_pages_prepare(page, order);
1924 		list_add(&dst->lru, &cc->freepages[order]);
1925 		cc->nr_freepages += 1 << order;
1926 	}
1927 	cc->nr_migratepages += 1 << order;
1928 	/*
1929 	 * someone else has referenced the page, we cannot take it back to our
1930 	 * free list.
1931 	 */
1932 }
1933 
1934 /* possible outcome of isolate_migratepages */
1935 typedef enum {
1936 	ISOLATE_ABORT,		/* Abort compaction now */
1937 	ISOLATE_NONE,		/* No pages isolated, continue scanning */
1938 	ISOLATE_SUCCESS,	/* Pages isolated, migrate */
1939 } isolate_migrate_t;
1940 
1941 /*
1942  * Allow userspace to control policy on scanning the unevictable LRU for
1943  * compactable pages.
1944  */
1945 static int sysctl_compact_unevictable_allowed __read_mostly = CONFIG_COMPACT_UNEVICTABLE_DEFAULT;
1946 /*
1947  * Tunable for proactive compaction. It determines how
1948  * aggressively the kernel should compact memory in the
1949  * background. It takes values in the range [0, 100].
1950  */
1951 static unsigned int __read_mostly sysctl_compaction_proactiveness = 20;
1952 static int sysctl_extfrag_threshold = 500;
1953 static int __read_mostly sysctl_compact_memory;
1954 
1955 static inline void
update_fast_start_pfn(struct compact_control * cc,unsigned long pfn)1956 update_fast_start_pfn(struct compact_control *cc, unsigned long pfn)
1957 {
1958 	if (cc->fast_start_pfn == ULONG_MAX)
1959 		return;
1960 
1961 	if (!cc->fast_start_pfn)
1962 		cc->fast_start_pfn = pfn;
1963 
1964 	cc->fast_start_pfn = min(cc->fast_start_pfn, pfn);
1965 }
1966 
1967 static inline unsigned long
reinit_migrate_pfn(struct compact_control * cc)1968 reinit_migrate_pfn(struct compact_control *cc)
1969 {
1970 	if (!cc->fast_start_pfn || cc->fast_start_pfn == ULONG_MAX)
1971 		return cc->migrate_pfn;
1972 
1973 	cc->migrate_pfn = cc->fast_start_pfn;
1974 	cc->fast_start_pfn = ULONG_MAX;
1975 
1976 	return cc->migrate_pfn;
1977 }
1978 
1979 /*
1980  * Briefly search the free lists for a migration source that already has
1981  * some free pages to reduce the number of pages that need migration
1982  * before a pageblock is free.
1983  */
fast_find_migrateblock(struct compact_control * cc)1984 static unsigned long fast_find_migrateblock(struct compact_control *cc)
1985 {
1986 	unsigned int limit = freelist_scan_limit(cc);
1987 	unsigned int nr_scanned = 0;
1988 	unsigned long distance;
1989 	unsigned long pfn = cc->migrate_pfn;
1990 	unsigned long high_pfn;
1991 	int order;
1992 	bool found_block = false;
1993 
1994 	/* Skip hints are relied on to avoid repeats on the fast search */
1995 	if (cc->ignore_skip_hint)
1996 		return pfn;
1997 
1998 	/*
1999 	 * If the pageblock should be finished then do not select a different
2000 	 * pageblock.
2001 	 */
2002 	if (cc->finish_pageblock)
2003 		return pfn;
2004 
2005 	/*
2006 	 * If the migrate_pfn is not at the start of a zone or the start
2007 	 * of a pageblock then assume this is a continuation of a previous
2008 	 * scan restarted due to COMPACT_CLUSTER_MAX.
2009 	 */
2010 	if (pfn != cc->zone->zone_start_pfn && pfn != pageblock_start_pfn(pfn))
2011 		return pfn;
2012 
2013 	/*
2014 	 * For smaller orders, just linearly scan as the number of pages
2015 	 * to migrate should be relatively small and does not necessarily
2016 	 * justify freeing up a large block for a small allocation.
2017 	 */
2018 	if (cc->order <= PAGE_ALLOC_COSTLY_ORDER)
2019 		return pfn;
2020 
2021 	/*
2022 	 * Only allow kcompactd and direct requests for movable pages to
2023 	 * quickly clear out a MOVABLE pageblock for allocation. This
2024 	 * reduces the risk that a large movable pageblock is freed for
2025 	 * an unmovable/reclaimable small allocation.
2026 	 */
2027 	if (cc->direct_compaction && cc->migratetype != MIGRATE_MOVABLE)
2028 		return pfn;
2029 
2030 	/*
2031 	 * When starting the migration scanner, pick any pageblock within the
2032 	 * first half of the search space. Otherwise try and pick a pageblock
2033 	 * within the first eighth to reduce the chances that a migration
2034 	 * target later becomes a source.
2035 	 */
2036 	distance = (cc->free_pfn - cc->migrate_pfn) >> 1;
2037 	if (cc->migrate_pfn != cc->zone->zone_start_pfn)
2038 		distance >>= 2;
2039 	high_pfn = pageblock_start_pfn(cc->migrate_pfn + distance);
2040 
2041 	for (order = cc->order - 1;
2042 	     order >= PAGE_ALLOC_COSTLY_ORDER && !found_block && nr_scanned < limit;
2043 	     order--) {
2044 		struct free_area *area = &cc->zone->free_area[order];
2045 		struct list_head *freelist;
2046 		unsigned long flags;
2047 		struct page *freepage;
2048 
2049 		if (!area->nr_free)
2050 			continue;
2051 
2052 		spin_lock_irqsave(&cc->zone->lock, flags);
2053 		freelist = &area->free_list[MIGRATE_MOVABLE];
2054 		list_for_each_entry(freepage, freelist, buddy_list) {
2055 			unsigned long free_pfn;
2056 
2057 			if (nr_scanned++ >= limit) {
2058 				move_freelist_tail(freelist, freepage);
2059 				break;
2060 			}
2061 
2062 			free_pfn = page_to_pfn(freepage);
2063 			if (free_pfn < high_pfn) {
2064 				/*
2065 				 * Avoid if skipped recently. Ideally it would
2066 				 * move to the tail but even safe iteration of
2067 				 * the list assumes an entry is deleted, not
2068 				 * reordered.
2069 				 */
2070 				if (get_pageblock_skip(freepage))
2071 					continue;
2072 
2073 				/* Reorder to so a future search skips recent pages */
2074 				move_freelist_tail(freelist, freepage);
2075 
2076 				update_fast_start_pfn(cc, free_pfn);
2077 				pfn = pageblock_start_pfn(free_pfn);
2078 				if (pfn < cc->zone->zone_start_pfn)
2079 					pfn = cc->zone->zone_start_pfn;
2080 				cc->fast_search_fail = 0;
2081 				found_block = true;
2082 				break;
2083 			}
2084 		}
2085 		spin_unlock_irqrestore(&cc->zone->lock, flags);
2086 	}
2087 
2088 	cc->total_migrate_scanned += nr_scanned;
2089 
2090 	/*
2091 	 * If fast scanning failed then use a cached entry for a page block
2092 	 * that had free pages as the basis for starting a linear scan.
2093 	 */
2094 	if (!found_block) {
2095 		cc->fast_search_fail++;
2096 		pfn = reinit_migrate_pfn(cc);
2097 	}
2098 	return pfn;
2099 }
2100 
2101 /*
2102  * Isolate all pages that can be migrated from the first suitable block,
2103  * starting at the block pointed to by the migrate scanner pfn within
2104  * compact_control.
2105  */
isolate_migratepages(struct compact_control * cc)2106 static isolate_migrate_t isolate_migratepages(struct compact_control *cc)
2107 {
2108 	unsigned long block_start_pfn;
2109 	unsigned long block_end_pfn;
2110 	unsigned long low_pfn;
2111 	struct page *page;
2112 	const isolate_mode_t isolate_mode =
2113 		(sysctl_compact_unevictable_allowed ? ISOLATE_UNEVICTABLE : 0) |
2114 		(cc->mode != MIGRATE_SYNC ? ISOLATE_ASYNC_MIGRATE : 0);
2115 	bool fast_find_block;
2116 
2117 	/*
2118 	 * Start at where we last stopped, or beginning of the zone as
2119 	 * initialized by compact_zone(). The first failure will use
2120 	 * the lowest PFN as the starting point for linear scanning.
2121 	 */
2122 	low_pfn = fast_find_migrateblock(cc);
2123 	block_start_pfn = pageblock_start_pfn(low_pfn);
2124 	if (block_start_pfn < cc->zone->zone_start_pfn)
2125 		block_start_pfn = cc->zone->zone_start_pfn;
2126 
2127 	/*
2128 	 * fast_find_migrateblock() has already ensured the pageblock is not
2129 	 * set with a skipped flag, so to avoid the isolation_suitable check
2130 	 * below again, check whether the fast search was successful.
2131 	 */
2132 	fast_find_block = low_pfn != cc->migrate_pfn && !cc->fast_search_fail;
2133 
2134 	/* Only scan within a pageblock boundary */
2135 	block_end_pfn = pageblock_end_pfn(low_pfn);
2136 
2137 	/*
2138 	 * Iterate over whole pageblocks until we find the first suitable.
2139 	 * Do not cross the free scanner.
2140 	 */
2141 	for (; block_end_pfn <= cc->free_pfn;
2142 			fast_find_block = false,
2143 			cc->migrate_pfn = low_pfn = block_end_pfn,
2144 			block_start_pfn = block_end_pfn,
2145 			block_end_pfn += pageblock_nr_pages) {
2146 
2147 		/*
2148 		 * This can potentially iterate a massively long zone with
2149 		 * many pageblocks unsuitable, so periodically check if we
2150 		 * need to schedule.
2151 		 */
2152 		if (!(low_pfn % (COMPACT_CLUSTER_MAX * pageblock_nr_pages)))
2153 			cond_resched();
2154 
2155 		page = pageblock_pfn_to_page(block_start_pfn,
2156 						block_end_pfn, cc->zone);
2157 		if (!page) {
2158 			unsigned long next_pfn;
2159 
2160 			next_pfn = skip_offline_sections(block_start_pfn);
2161 			if (next_pfn)
2162 				block_end_pfn = min(next_pfn, cc->free_pfn);
2163 			continue;
2164 		}
2165 
2166 		/*
2167 		 * If isolation recently failed, do not retry. Only check the
2168 		 * pageblock once. COMPACT_CLUSTER_MAX causes a pageblock
2169 		 * to be visited multiple times. Assume skip was checked
2170 		 * before making it "skip" so other compaction instances do
2171 		 * not scan the same block.
2172 		 */
2173 		if ((pageblock_aligned(low_pfn) ||
2174 		     low_pfn == cc->zone->zone_start_pfn) &&
2175 		    !fast_find_block && !isolation_suitable(cc, page))
2176 			continue;
2177 
2178 		/*
2179 		 * For async direct compaction, only scan the pageblocks of the
2180 		 * same migratetype without huge pages. Async direct compaction
2181 		 * is optimistic to see if the minimum amount of work satisfies
2182 		 * the allocation. The cached PFN is updated as it's possible
2183 		 * that all remaining blocks between source and target are
2184 		 * unsuitable and the compaction scanners fail to meet.
2185 		 */
2186 		if (!suitable_migration_source(cc, page)) {
2187 			update_cached_migrate(cc, block_end_pfn);
2188 			continue;
2189 		}
2190 
2191 		/* Perform the isolation */
2192 		if (isolate_migratepages_block(cc, low_pfn, block_end_pfn,
2193 						isolate_mode))
2194 			return ISOLATE_ABORT;
2195 
2196 		/*
2197 		 * Either we isolated something and proceed with migration. Or
2198 		 * we failed and compact_zone should decide if we should
2199 		 * continue or not.
2200 		 */
2201 		break;
2202 	}
2203 
2204 	return cc->nr_migratepages ? ISOLATE_SUCCESS : ISOLATE_NONE;
2205 }
2206 
2207 /*
2208  * Determine whether kswapd is (or recently was!) running on this node.
2209  *
2210  * pgdat_kswapd_lock() pins pgdat->kswapd, so a concurrent kswapd_stop() can't
2211  * zero it.
2212  */
kswapd_is_running(pg_data_t * pgdat)2213 static bool kswapd_is_running(pg_data_t *pgdat)
2214 {
2215 	bool running;
2216 
2217 	pgdat_kswapd_lock(pgdat);
2218 	running = pgdat->kswapd && task_is_running(pgdat->kswapd);
2219 	pgdat_kswapd_unlock(pgdat);
2220 
2221 	return running;
2222 }
2223 
2224 /*
2225  * A zone's fragmentation score is the external fragmentation wrt to the
2226  * COMPACTION_HPAGE_ORDER. It returns a value in the range [0, 100].
2227  */
fragmentation_score_zone(struct zone * zone)2228 static unsigned int fragmentation_score_zone(struct zone *zone)
2229 {
2230 	return extfrag_for_order(zone, COMPACTION_HPAGE_ORDER);
2231 }
2232 
2233 /*
2234  * A weighted zone's fragmentation score is the external fragmentation
2235  * wrt to the COMPACTION_HPAGE_ORDER scaled by the zone's size. It
2236  * returns a value in the range [0, 100].
2237  *
2238  * The scaling factor ensures that proactive compaction focuses on larger
2239  * zones like ZONE_NORMAL, rather than smaller, specialized zones like
2240  * ZONE_DMA32. For smaller zones, the score value remains close to zero,
2241  * and thus never exceeds the high threshold for proactive compaction.
2242  */
fragmentation_score_zone_weighted(struct zone * zone)2243 static unsigned int fragmentation_score_zone_weighted(struct zone *zone)
2244 {
2245 	unsigned long score;
2246 
2247 	score = zone->present_pages * fragmentation_score_zone(zone);
2248 	return div64_ul(score, zone->zone_pgdat->node_present_pages + 1);
2249 }
2250 
2251 /*
2252  * The per-node proactive (background) compaction process is started by its
2253  * corresponding kcompactd thread when the node's fragmentation score
2254  * exceeds the high threshold. The compaction process remains active till
2255  * the node's score falls below the low threshold, or one of the back-off
2256  * conditions is met.
2257  */
fragmentation_score_node(pg_data_t * pgdat)2258 static unsigned int fragmentation_score_node(pg_data_t *pgdat)
2259 {
2260 	unsigned int score = 0;
2261 	int zoneid;
2262 
2263 	for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
2264 		struct zone *zone;
2265 
2266 		zone = &pgdat->node_zones[zoneid];
2267 		if (!populated_zone(zone))
2268 			continue;
2269 		score += fragmentation_score_zone_weighted(zone);
2270 	}
2271 
2272 	return score;
2273 }
2274 
fragmentation_score_wmark(bool low)2275 static unsigned int fragmentation_score_wmark(bool low)
2276 {
2277 	unsigned int wmark_low;
2278 
2279 	/*
2280 	 * Cap the low watermark to avoid excessive compaction
2281 	 * activity in case a user sets the proactiveness tunable
2282 	 * close to 100 (maximum).
2283 	 */
2284 	wmark_low = max(100U - sysctl_compaction_proactiveness, 5U);
2285 	return low ? wmark_low : min(wmark_low + 10, 100U);
2286 }
2287 
should_proactive_compact_node(pg_data_t * pgdat)2288 static bool should_proactive_compact_node(pg_data_t *pgdat)
2289 {
2290 	int wmark_high;
2291 
2292 	if (!sysctl_compaction_proactiveness || kswapd_is_running(pgdat))
2293 		return false;
2294 
2295 	wmark_high = fragmentation_score_wmark(false);
2296 	trace_android_vh_proactive_compact_wmark_high(&wmark_high);
2297 	return fragmentation_score_node(pgdat) > wmark_high;
2298 }
2299 
__compact_finished(struct compact_control * cc)2300 static enum compact_result __compact_finished(struct compact_control *cc)
2301 {
2302 	unsigned int order;
2303 	const int migratetype = cc->migratetype;
2304 	int ret;
2305 	bool abort_compact = false;
2306 
2307 	/* Compaction run completes if the migrate and free scanner meet */
2308 	if (compact_scanners_met(cc)) {
2309 		/* Let the next compaction start anew. */
2310 		reset_cached_positions(cc->zone);
2311 
2312 		/*
2313 		 * Mark that the PG_migrate_skip information should be cleared
2314 		 * by kswapd when it goes to sleep. kcompactd does not set the
2315 		 * flag itself as the decision to be clear should be directly
2316 		 * based on an allocation request.
2317 		 */
2318 		if (cc->direct_compaction)
2319 			cc->zone->compact_blockskip_flush = true;
2320 
2321 		if (cc->whole_zone)
2322 			return COMPACT_COMPLETE;
2323 		else
2324 			return COMPACT_PARTIAL_SKIPPED;
2325 	}
2326 
2327 	if (cc->proactive_compaction) {
2328 		int score, wmark_low;
2329 		pg_data_t *pgdat;
2330 
2331 		pgdat = cc->zone->zone_pgdat;
2332 		if (kswapd_is_running(pgdat))
2333 			return COMPACT_PARTIAL_SKIPPED;
2334 
2335 		score = fragmentation_score_zone(cc->zone);
2336 		wmark_low = fragmentation_score_wmark(true);
2337 
2338 		if (score > wmark_low)
2339 			ret = COMPACT_CONTINUE;
2340 		else
2341 			ret = COMPACT_SUCCESS;
2342 
2343 		goto out;
2344 	}
2345 
2346 	if (is_via_compact_memory(cc->order))
2347 		return COMPACT_CONTINUE;
2348 
2349 	/*
2350 	 * Always finish scanning a pageblock to reduce the possibility of
2351 	 * fallbacks in the future. This is particularly important when
2352 	 * migration source is unmovable/reclaimable but it's not worth
2353 	 * special casing.
2354 	 */
2355 	if (!pageblock_aligned(cc->migrate_pfn))
2356 		return COMPACT_CONTINUE;
2357 
2358 	/* Direct compactor: Is a suitable page free? */
2359 	ret = COMPACT_NO_SUITABLE_PAGE;
2360 	for (order = cc->order; order < NR_PAGE_ORDERS; order++) {
2361 		struct free_area *area = &cc->zone->free_area[order];
2362 
2363 		/* Job done if page is free of the right migratetype */
2364 		if (!free_area_empty(area, migratetype))
2365 			return COMPACT_SUCCESS;
2366 
2367 #ifdef CONFIG_CMA
2368 		/* MIGRATE_MOVABLE can fallback on MIGRATE_CMA */
2369 		if (migratetype == MIGRATE_MOVABLE &&
2370 			!free_area_empty(area, MIGRATE_CMA))
2371 			return COMPACT_SUCCESS;
2372 #endif
2373 		/*
2374 		 * Job done if allocation would steal freepages from
2375 		 * other migratetype buddy lists.
2376 		 */
2377 		if (find_suitable_fallback(area, order, migratetype, true) >= 0)
2378 			/*
2379 			 * Movable pages are OK in any pageblock. If we are
2380 			 * stealing for a non-movable allocation, make sure
2381 			 * we finish compacting the current pageblock first
2382 			 * (which is assured by the above migrate_pfn align
2383 			 * check) so it is as free as possible and we won't
2384 			 * have to steal another one soon.
2385 			 */
2386 			return COMPACT_SUCCESS;
2387 	}
2388 
2389 out:
2390 	trace_android_vh_compact_finished(&abort_compact);
2391 	if (cc->contended || fatal_signal_pending(current) || abort_compact)
2392 		ret = COMPACT_CONTENDED;
2393 
2394 	return ret;
2395 }
2396 
compact_finished(struct compact_control * cc)2397 static enum compact_result compact_finished(struct compact_control *cc)
2398 {
2399 	int ret;
2400 
2401 	ret = __compact_finished(cc);
2402 	trace_mm_compaction_finished(cc->zone, cc->order, ret);
2403 	if (ret == COMPACT_NO_SUITABLE_PAGE)
2404 		ret = COMPACT_CONTINUE;
2405 
2406 	return ret;
2407 }
2408 
__compaction_suitable(struct zone * zone,int order,int highest_zoneidx,unsigned long wmark_target)2409 static bool __compaction_suitable(struct zone *zone, int order,
2410 				  int highest_zoneidx,
2411 				  unsigned long wmark_target)
2412 {
2413 	unsigned long watermark;
2414 	/*
2415 	 * Watermarks for order-0 must be met for compaction to be able to
2416 	 * isolate free pages for migration targets. This means that the
2417 	 * watermark and alloc_flags have to match, or be more pessimistic than
2418 	 * the check in __isolate_free_page(). We don't use the direct
2419 	 * compactor's alloc_flags, as they are not relevant for freepage
2420 	 * isolation. We however do use the direct compactor's highest_zoneidx
2421 	 * to skip over zones where lowmem reserves would prevent allocation
2422 	 * even if compaction succeeds.
2423 	 * For costly orders, we require low watermark instead of min for
2424 	 * compaction to proceed to increase its chances.
2425 	 * ALLOC_CMA is used, as pages in CMA pageblocks are considered
2426 	 * suitable migration targets
2427 	 */
2428 	watermark = (order > PAGE_ALLOC_COSTLY_ORDER) ?
2429 				low_wmark_pages(zone) : min_wmark_pages(zone);
2430 	watermark += compact_gap(order);
2431 	return __zone_watermark_ok(zone, 0, watermark, highest_zoneidx,
2432 				   ALLOC_CMA, wmark_target);
2433 }
2434 
2435 /*
2436  * compaction_suitable: Is this suitable to run compaction on this zone now?
2437  */
compaction_suitable(struct zone * zone,int order,int highest_zoneidx)2438 bool compaction_suitable(struct zone *zone, int order, int highest_zoneidx)
2439 {
2440 	enum compact_result compact_result;
2441 	bool suitable;
2442 
2443 	suitable = __compaction_suitable(zone, order, highest_zoneidx,
2444 					 zone_page_state(zone, NR_FREE_PAGES));
2445 	/*
2446 	 * fragmentation index determines if allocation failures are due to
2447 	 * low memory or external fragmentation
2448 	 *
2449 	 * index of -1000 would imply allocations might succeed depending on
2450 	 * watermarks, but we already failed the high-order watermark check
2451 	 * index towards 0 implies failure is due to lack of memory
2452 	 * index towards 1000 implies failure is due to fragmentation
2453 	 *
2454 	 * Only compact if a failure would be due to fragmentation. Also
2455 	 * ignore fragindex for non-costly orders where the alternative to
2456 	 * a successful reclaim/compaction is OOM. Fragindex and the
2457 	 * vm.extfrag_threshold sysctl is meant as a heuristic to prevent
2458 	 * excessive compaction for costly orders, but it should not be at the
2459 	 * expense of system stability.
2460 	 */
2461 	if (suitable) {
2462 		compact_result = COMPACT_CONTINUE;
2463 		if (order > PAGE_ALLOC_COSTLY_ORDER) {
2464 			int fragindex = fragmentation_index(zone, order);
2465 
2466 			if (fragindex >= 0 &&
2467 			    fragindex <= sysctl_extfrag_threshold) {
2468 				suitable = false;
2469 				compact_result = COMPACT_NOT_SUITABLE_ZONE;
2470 			}
2471 		}
2472 	} else {
2473 		compact_result = COMPACT_SKIPPED;
2474 	}
2475 
2476 	trace_mm_compaction_suitable(zone, order, compact_result);
2477 
2478 	return suitable;
2479 }
2480 
compaction_zonelist_suitable(struct alloc_context * ac,int order,int alloc_flags)2481 bool compaction_zonelist_suitable(struct alloc_context *ac, int order,
2482 		int alloc_flags)
2483 {
2484 	struct zone *zone;
2485 	struct zoneref *z;
2486 
2487 	/*
2488 	 * Make sure at least one zone would pass __compaction_suitable if we continue
2489 	 * retrying the reclaim.
2490 	 */
2491 	for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
2492 				ac->highest_zoneidx, ac->nodemask) {
2493 		unsigned long available;
2494 
2495 		/*
2496 		 * Do not consider all the reclaimable memory because we do not
2497 		 * want to trash just for a single high order allocation which
2498 		 * is even not guaranteed to appear even if __compaction_suitable
2499 		 * is happy about the watermark check.
2500 		 */
2501 		available = zone_reclaimable_pages(zone) / order;
2502 		available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
2503 		if (__compaction_suitable(zone, order, ac->highest_zoneidx,
2504 					  available))
2505 			return true;
2506 	}
2507 
2508 	return false;
2509 }
2510 
2511 /*
2512  * Should we do compaction for target allocation order.
2513  * Return COMPACT_SUCCESS if allocation for target order can be already
2514  * satisfied
2515  * Return COMPACT_SKIPPED if compaction for target order is likely to fail
2516  * Return COMPACT_CONTINUE if compaction for target order should be ran
2517  */
2518 static enum compact_result
compaction_suit_allocation_order(struct zone * zone,unsigned int order,int highest_zoneidx,unsigned int alloc_flags)2519 compaction_suit_allocation_order(struct zone *zone, unsigned int order,
2520 				 int highest_zoneidx, unsigned int alloc_flags)
2521 {
2522 	unsigned long watermark;
2523 
2524 	watermark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
2525 	if (zone_watermark_ok(zone, order, watermark, highest_zoneidx,
2526 			      alloc_flags))
2527 		return COMPACT_SUCCESS;
2528 
2529 	if (!compaction_suitable(zone, order, highest_zoneidx))
2530 		return COMPACT_SKIPPED;
2531 
2532 	return COMPACT_CONTINUE;
2533 }
2534 
2535 static enum compact_result
compact_zone(struct compact_control * cc,struct capture_control * capc)2536 compact_zone(struct compact_control *cc, struct capture_control *capc)
2537 {
2538 	enum compact_result ret;
2539 	unsigned long start_pfn = cc->zone->zone_start_pfn;
2540 	unsigned long end_pfn = zone_end_pfn(cc->zone);
2541 	unsigned long last_migrated_pfn;
2542 	const bool sync = cc->mode != MIGRATE_ASYNC;
2543 	bool update_cached;
2544 	unsigned int nr_succeeded = 0, nr_migratepages;
2545 	int order;
2546 	long vendor_ret;
2547 
2548 	/*
2549 	 * These counters track activities during zone compaction.  Initialize
2550 	 * them before compacting a new zone.
2551 	 */
2552 	cc->total_migrate_scanned = 0;
2553 	cc->total_free_scanned = 0;
2554 	cc->nr_migratepages = 0;
2555 	cc->nr_freepages = 0;
2556 	for (order = 0; order < NR_PAGE_ORDERS; order++)
2557 		INIT_LIST_HEAD(&cc->freepages[order]);
2558 	INIT_LIST_HEAD(&cc->migratepages);
2559 
2560 	cc->migratetype = gfp_migratetype(cc->gfp_mask);
2561 
2562 	if (!is_via_compact_memory(cc->order)) {
2563 		ret = compaction_suit_allocation_order(cc->zone, cc->order,
2564 						       cc->highest_zoneidx,
2565 						       cc->alloc_flags);
2566 		if (ret != COMPACT_CONTINUE)
2567 			return ret;
2568 	}
2569 
2570 	/*
2571 	 * Clear pageblock skip if there were failures recently and compaction
2572 	 * is about to be retried after being deferred.
2573 	 */
2574 	if (compaction_restarting(cc->zone, cc->order))
2575 		__reset_isolation_suitable(cc->zone);
2576 
2577 	/*
2578 	 * Setup to move all movable pages to the end of the zone. Used cached
2579 	 * information on where the scanners should start (unless we explicitly
2580 	 * want to compact the whole zone), but check that it is initialised
2581 	 * by ensuring the values are within zone boundaries.
2582 	 */
2583 	cc->fast_start_pfn = 0;
2584 	if (cc->whole_zone) {
2585 		cc->migrate_pfn = start_pfn;
2586 		cc->free_pfn = pageblock_start_pfn(end_pfn - 1);
2587 	} else {
2588 		cc->migrate_pfn = cc->zone->compact_cached_migrate_pfn[sync];
2589 		cc->free_pfn = cc->zone->compact_cached_free_pfn;
2590 		if (cc->free_pfn < start_pfn || cc->free_pfn >= end_pfn) {
2591 			cc->free_pfn = pageblock_start_pfn(end_pfn - 1);
2592 			cc->zone->compact_cached_free_pfn = cc->free_pfn;
2593 		}
2594 		if (cc->migrate_pfn < start_pfn || cc->migrate_pfn >= end_pfn) {
2595 			cc->migrate_pfn = start_pfn;
2596 			cc->zone->compact_cached_migrate_pfn[0] = cc->migrate_pfn;
2597 			cc->zone->compact_cached_migrate_pfn[1] = cc->migrate_pfn;
2598 		}
2599 
2600 		if (cc->migrate_pfn <= cc->zone->compact_init_migrate_pfn)
2601 			cc->whole_zone = true;
2602 	}
2603 
2604 	last_migrated_pfn = 0;
2605 
2606 	/*
2607 	 * Migrate has separate cached PFNs for ASYNC and SYNC* migration on
2608 	 * the basis that some migrations will fail in ASYNC mode. However,
2609 	 * if the cached PFNs match and pageblocks are skipped due to having
2610 	 * no isolation candidates, then the sync state does not matter.
2611 	 * Until a pageblock with isolation candidates is found, keep the
2612 	 * cached PFNs in sync to avoid revisiting the same blocks.
2613 	 */
2614 	update_cached = !sync &&
2615 		cc->zone->compact_cached_migrate_pfn[0] == cc->zone->compact_cached_migrate_pfn[1];
2616 
2617 	trace_mm_compaction_begin(cc, start_pfn, end_pfn, sync);
2618 	trace_android_vh_mm_compaction_begin(cc, &vendor_ret);
2619 
2620 	/* lru_add_drain_all could be expensive with involving other CPUs */
2621 	lru_add_drain();
2622 
2623 	while ((ret = compact_finished(cc)) == COMPACT_CONTINUE) {
2624 		int err;
2625 		unsigned long iteration_start_pfn = cc->migrate_pfn;
2626 
2627 		/*
2628 		 * Avoid multiple rescans of the same pageblock which can
2629 		 * happen if a page cannot be isolated (dirty/writeback in
2630 		 * async mode) or if the migrated pages are being allocated
2631 		 * before the pageblock is cleared.  The first rescan will
2632 		 * capture the entire pageblock for migration. If it fails,
2633 		 * it'll be marked skip and scanning will proceed as normal.
2634 		 */
2635 		cc->finish_pageblock = false;
2636 		if (pageblock_start_pfn(last_migrated_pfn) ==
2637 		    pageblock_start_pfn(iteration_start_pfn)) {
2638 			cc->finish_pageblock = true;
2639 		}
2640 
2641 rescan:
2642 		switch (isolate_migratepages(cc)) {
2643 		case ISOLATE_ABORT:
2644 			ret = COMPACT_CONTENDED;
2645 			putback_movable_pages(&cc->migratepages);
2646 			cc->nr_migratepages = 0;
2647 			goto out;
2648 		case ISOLATE_NONE:
2649 			if (update_cached) {
2650 				cc->zone->compact_cached_migrate_pfn[1] =
2651 					cc->zone->compact_cached_migrate_pfn[0];
2652 			}
2653 
2654 			/*
2655 			 * We haven't isolated and migrated anything, but
2656 			 * there might still be unflushed migrations from
2657 			 * previous cc->order aligned block.
2658 			 */
2659 			goto check_drain;
2660 		case ISOLATE_SUCCESS:
2661 			update_cached = false;
2662 			last_migrated_pfn = max(cc->zone->zone_start_pfn,
2663 				pageblock_start_pfn(cc->migrate_pfn - 1));
2664 		}
2665 
2666 		/*
2667 		 * Record the number of pages to migrate since the
2668 		 * compaction_alloc/free() will update cc->nr_migratepages
2669 		 * properly.
2670 		 */
2671 		nr_migratepages = cc->nr_migratepages;
2672 		err = migrate_pages(&cc->migratepages, compaction_alloc,
2673 				compaction_free, (unsigned long)cc, cc->mode,
2674 				MR_COMPACTION, &nr_succeeded);
2675 
2676 		trace_mm_compaction_migratepages(nr_migratepages, nr_succeeded);
2677 
2678 		/* All pages were either migrated or will be released */
2679 		cc->nr_migratepages = 0;
2680 		if (err) {
2681 			putback_movable_pages(&cc->migratepages);
2682 			/*
2683 			 * migrate_pages() may return -ENOMEM when scanners meet
2684 			 * and we want compact_finished() to detect it
2685 			 */
2686 			if (err == -ENOMEM && !compact_scanners_met(cc)) {
2687 				ret = COMPACT_CONTENDED;
2688 				goto out;
2689 			}
2690 			/*
2691 			 * If an ASYNC or SYNC_LIGHT fails to migrate a page
2692 			 * within the pageblock_order-aligned block and
2693 			 * fast_find_migrateblock may be used then scan the
2694 			 * remainder of the pageblock. This will mark the
2695 			 * pageblock "skip" to avoid rescanning in the near
2696 			 * future. This will isolate more pages than necessary
2697 			 * for the request but avoid loops due to
2698 			 * fast_find_migrateblock revisiting blocks that were
2699 			 * recently partially scanned.
2700 			 */
2701 			if (!pageblock_aligned(cc->migrate_pfn) &&
2702 			    !cc->ignore_skip_hint && !cc->finish_pageblock &&
2703 			    (cc->mode < MIGRATE_SYNC)) {
2704 				cc->finish_pageblock = true;
2705 
2706 				/*
2707 				 * Draining pcplists does not help THP if
2708 				 * any page failed to migrate. Even after
2709 				 * drain, the pageblock will not be free.
2710 				 */
2711 				if (cc->order == COMPACTION_HPAGE_ORDER)
2712 					last_migrated_pfn = 0;
2713 
2714 				goto rescan;
2715 			}
2716 		}
2717 
2718 		/* Stop if a page has been captured */
2719 		if (capc && capc->page) {
2720 			ret = COMPACT_SUCCESS;
2721 			break;
2722 		}
2723 
2724 check_drain:
2725 		/*
2726 		 * Has the migration scanner moved away from the previous
2727 		 * cc->order aligned block where we migrated from? If yes,
2728 		 * flush the pages that were freed, so that they can merge and
2729 		 * compact_finished() can detect immediately if allocation
2730 		 * would succeed.
2731 		 */
2732 		if (cc->order > 0 && last_migrated_pfn) {
2733 			unsigned long current_block_start =
2734 				block_start_pfn(cc->migrate_pfn, cc->order);
2735 
2736 			if (last_migrated_pfn < current_block_start) {
2737 				lru_add_drain_cpu_zone(cc->zone);
2738 				/* No more flushing until we migrate again */
2739 				last_migrated_pfn = 0;
2740 			}
2741 		}
2742 	}
2743 
2744 out:
2745 	/*
2746 	 * Release free pages and update where the free scanner should restart,
2747 	 * so we don't leave any returned pages behind in the next attempt.
2748 	 */
2749 	if (cc->nr_freepages > 0) {
2750 		unsigned long free_pfn = release_free_list(cc->freepages);
2751 
2752 		cc->nr_freepages = 0;
2753 		VM_BUG_ON(free_pfn == 0);
2754 		/* The cached pfn is always the first in a pageblock */
2755 		free_pfn = pageblock_start_pfn(free_pfn);
2756 		/*
2757 		 * Only go back, not forward. The cached pfn might have been
2758 		 * already reset to zone end in compact_finished()
2759 		 */
2760 		if (free_pfn > cc->zone->compact_cached_free_pfn)
2761 			cc->zone->compact_cached_free_pfn = free_pfn;
2762 	}
2763 
2764 	count_compact_events(COMPACTMIGRATE_SCANNED, cc->total_migrate_scanned);
2765 	count_compact_events(COMPACTFREE_SCANNED, cc->total_free_scanned);
2766 
2767 	trace_android_vh_mm_compaction_end(cc, vendor_ret);
2768 	trace_mm_compaction_end(cc, start_pfn, end_pfn, sync, ret);
2769 
2770 	VM_BUG_ON(!list_empty(&cc->migratepages));
2771 
2772 	return ret;
2773 }
2774 
compact_zone_order(struct zone * zone,int order,gfp_t gfp_mask,enum compact_priority prio,unsigned int alloc_flags,int highest_zoneidx,struct page ** capture)2775 static enum compact_result compact_zone_order(struct zone *zone, int order,
2776 		gfp_t gfp_mask, enum compact_priority prio,
2777 		unsigned int alloc_flags, int highest_zoneidx,
2778 		struct page **capture)
2779 {
2780 	enum compact_result ret;
2781 	struct compact_control cc = {
2782 		.order = order,
2783 		.search_order = order,
2784 		.gfp_mask = gfp_mask,
2785 		.zone = zone,
2786 		.mode = (prio == COMPACT_PRIO_ASYNC) ?
2787 					MIGRATE_ASYNC :	MIGRATE_SYNC_LIGHT,
2788 		.alloc_flags = alloc_flags,
2789 		.highest_zoneidx = highest_zoneidx,
2790 		.direct_compaction = true,
2791 		.whole_zone = (prio == MIN_COMPACT_PRIORITY),
2792 		.ignore_skip_hint = (prio == MIN_COMPACT_PRIORITY),
2793 		.ignore_block_suitable = (prio == MIN_COMPACT_PRIORITY)
2794 	};
2795 	struct capture_control capc = {
2796 		.cc = &cc,
2797 		.page = NULL,
2798 	};
2799 
2800 	/*
2801 	 * Make sure the structs are really initialized before we expose the
2802 	 * capture control, in case we are interrupted and the interrupt handler
2803 	 * frees a page.
2804 	 */
2805 	barrier();
2806 	WRITE_ONCE(current->capture_control, &capc);
2807 
2808 	ret = compact_zone(&cc, &capc);
2809 
2810 	/*
2811 	 * Make sure we hide capture control first before we read the captured
2812 	 * page pointer, otherwise an interrupt could free and capture a page
2813 	 * and we would leak it.
2814 	 */
2815 	WRITE_ONCE(current->capture_control, NULL);
2816 	*capture = READ_ONCE(capc.page);
2817 	/*
2818 	 * Technically, it is also possible that compaction is skipped but
2819 	 * the page is still captured out of luck(IRQ came and freed the page).
2820 	 * Returning COMPACT_SUCCESS in such cases helps in properly accounting
2821 	 * the COMPACT[STALL|FAIL] when compaction is skipped.
2822 	 */
2823 	if (*capture)
2824 		ret = COMPACT_SUCCESS;
2825 
2826 	return ret;
2827 }
2828 
2829 /**
2830  * try_to_compact_pages - Direct compact to satisfy a high-order allocation
2831  * @gfp_mask: The GFP mask of the current allocation
2832  * @order: The order of the current allocation
2833  * @alloc_flags: The allocation flags of the current allocation
2834  * @ac: The context of current allocation
2835  * @prio: Determines how hard direct compaction should try to succeed
2836  * @capture: Pointer to free page created by compaction will be stored here
2837  *
2838  * This is the main entry point for direct page compaction.
2839  */
try_to_compact_pages(gfp_t gfp_mask,unsigned int order,unsigned int alloc_flags,const struct alloc_context * ac,enum compact_priority prio,struct page ** capture)2840 enum compact_result try_to_compact_pages(gfp_t gfp_mask, unsigned int order,
2841 		unsigned int alloc_flags, const struct alloc_context *ac,
2842 		enum compact_priority prio, struct page **capture)
2843 {
2844 	struct zoneref *z;
2845 	struct zone *zone;
2846 	enum compact_result rc = COMPACT_SKIPPED;
2847 
2848 	if (!gfp_compaction_allowed(gfp_mask))
2849 		return COMPACT_SKIPPED;
2850 
2851 	trace_mm_compaction_try_to_compact_pages(order, gfp_mask, prio);
2852 
2853 	/* Compact each zone in the list */
2854 	for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
2855 					ac->highest_zoneidx, ac->nodemask) {
2856 		enum compact_result status;
2857 		bool can_compact = true;
2858 
2859 		trace_android_vh_mm_customize_zone_can_compact(zone, &can_compact);
2860 		if (!can_compact)
2861 			continue;
2862 
2863 		if (cpusets_enabled() &&
2864 			(alloc_flags & ALLOC_CPUSET) &&
2865 			!__cpuset_zone_allowed(zone, gfp_mask))
2866 				continue;
2867 
2868 		if (prio > MIN_COMPACT_PRIORITY
2869 					&& compaction_deferred(zone, order)) {
2870 			rc = max_t(enum compact_result, COMPACT_DEFERRED, rc);
2871 			continue;
2872 		}
2873 
2874 		status = compact_zone_order(zone, order, gfp_mask, prio,
2875 				alloc_flags, ac->highest_zoneidx, capture);
2876 		rc = max(status, rc);
2877 
2878 		/* The allocation should succeed, stop compacting */
2879 		if (status == COMPACT_SUCCESS) {
2880 			/*
2881 			 * We think the allocation will succeed in this zone,
2882 			 * but it is not certain, hence the false. The caller
2883 			 * will repeat this with true if allocation indeed
2884 			 * succeeds in this zone.
2885 			 */
2886 			compaction_defer_reset(zone, order, false);
2887 
2888 			break;
2889 		}
2890 
2891 		if (prio != COMPACT_PRIO_ASYNC && (status == COMPACT_COMPLETE ||
2892 					status == COMPACT_PARTIAL_SKIPPED))
2893 			/*
2894 			 * We think that allocation won't succeed in this zone
2895 			 * so we defer compaction there. If it ends up
2896 			 * succeeding after all, it will be reset.
2897 			 */
2898 			defer_compaction(zone, order);
2899 
2900 		/*
2901 		 * We might have stopped compacting due to need_resched() in
2902 		 * async compaction, or due to a fatal signal detected. In that
2903 		 * case do not try further zones
2904 		 */
2905 		if ((prio == COMPACT_PRIO_ASYNC && need_resched())
2906 					|| fatal_signal_pending(current))
2907 			break;
2908 	}
2909 	trace_android_vh_compaction_try_to_compact_exit(&rc);
2910 	return rc;
2911 }
2912 
2913 /* Compact all zones within a node with MIGRATE_ASYNC */
compact_node_async(int nid)2914 void compact_node_async(int nid)
2915 {
2916 	pg_data_t *pgdat = NODE_DATA(nid);
2917 	int zoneid;
2918 	struct zone *zone;
2919 	struct compact_control cc = {
2920 		.order = -1,
2921 		.mode = MIGRATE_ASYNC,
2922 		.ignore_skip_hint = true,
2923 		.whole_zone = true,
2924 		.gfp_mask = GFP_KERNEL,
2925 		.proactive_compaction = false,
2926 	};
2927 
2928 	for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
2929 		bool can_compact = true;
2930 
2931 		zone = &pgdat->node_zones[zoneid];
2932 		if (!populated_zone(zone))
2933 			continue;
2934 
2935 		trace_android_vh_mm_customize_zone_can_compact(zone, &can_compact);
2936 		if (!can_compact)
2937 			continue;
2938 
2939 		if (fatal_signal_pending(current))
2940 			break;
2941 
2942 		cc.zone = zone;
2943 
2944 		compact_zone(&cc, NULL);
2945 	}
2946 }
2947 EXPORT_SYMBOL_GPL(compact_node_async);
2948 
2949 /*
2950  * compact_node() - compact all zones within a node
2951  * @pgdat: The node page data
2952  * @proactive: Whether the compaction is proactive
2953  *
2954  * For proactive compaction, compact till each zone's fragmentation score
2955  * reaches within proactive compaction thresholds (as determined by the
2956  * proactiveness tunable), it is possible that the function returns before
2957  * reaching score targets due to various back-off conditions, such as,
2958  * contention on per-node or per-zone locks.
2959  */
compact_node(pg_data_t * pgdat,bool proactive)2960 static int compact_node(pg_data_t *pgdat, bool proactive)
2961 {
2962 	int zoneid;
2963 	struct zone *zone;
2964 	struct compact_control cc = {
2965 		.order = -1,
2966 		.mode = proactive ? MIGRATE_SYNC_LIGHT : MIGRATE_SYNC,
2967 		.ignore_skip_hint = true,
2968 		.whole_zone = true,
2969 		.gfp_mask = GFP_KERNEL,
2970 		.proactive_compaction = proactive,
2971 	};
2972 
2973 	for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
2974 		bool can_compact = true;
2975 
2976 		zone = &pgdat->node_zones[zoneid];
2977 		if (!populated_zone(zone))
2978 			continue;
2979 
2980 		trace_android_vh_mm_customize_zone_can_compact(zone, &can_compact);
2981 		if (!can_compact)
2982 			continue;
2983 
2984 		if (fatal_signal_pending(current))
2985 			return -EINTR;
2986 
2987 		cc.zone = zone;
2988 
2989 		compact_zone(&cc, NULL);
2990 
2991 		if (proactive) {
2992 			count_compact_events(KCOMPACTD_MIGRATE_SCANNED,
2993 					     cc.total_migrate_scanned);
2994 			count_compact_events(KCOMPACTD_FREE_SCANNED,
2995 					     cc.total_free_scanned);
2996 		}
2997 	}
2998 
2999 	return 0;
3000 }
3001 
3002 /* Compact all zones of all nodes in the system */
compact_nodes(void)3003 static int compact_nodes(void)
3004 {
3005 	int ret, nid;
3006 
3007 	/* Flush pending updates to the LRU lists */
3008 	lru_add_drain_all();
3009 
3010 	for_each_online_node(nid) {
3011 		ret = compact_node(NODE_DATA(nid), false);
3012 		if (ret)
3013 			return ret;
3014 	}
3015 
3016 	return 0;
3017 }
3018 
compaction_proactiveness_sysctl_handler(const struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)3019 static int compaction_proactiveness_sysctl_handler(const struct ctl_table *table, int write,
3020 		void *buffer, size_t *length, loff_t *ppos)
3021 {
3022 	int rc, nid;
3023 
3024 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
3025 	if (rc)
3026 		return rc;
3027 
3028 	if (write && sysctl_compaction_proactiveness) {
3029 		for_each_online_node(nid) {
3030 			pg_data_t *pgdat = NODE_DATA(nid);
3031 
3032 			if (pgdat->proactive_compact_trigger)
3033 				continue;
3034 
3035 			pgdat->proactive_compact_trigger = true;
3036 			trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, -1,
3037 							     pgdat->nr_zones - 1);
3038 			wake_up_interruptible(&pgdat->kcompactd_wait);
3039 		}
3040 	}
3041 
3042 	return 0;
3043 }
3044 
3045 /*
3046  * This is the entry point for compacting all nodes via
3047  * /proc/sys/vm/compact_memory
3048  */
sysctl_compaction_handler(const struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)3049 static int sysctl_compaction_handler(const struct ctl_table *table, int write,
3050 			void *buffer, size_t *length, loff_t *ppos)
3051 {
3052 	int ret;
3053 
3054 	ret = proc_dointvec(table, write, buffer, length, ppos);
3055 	if (ret)
3056 		return ret;
3057 
3058 	if (sysctl_compact_memory != 1)
3059 		return -EINVAL;
3060 
3061 	if (write)
3062 		ret = compact_nodes();
3063 
3064 	return ret;
3065 }
3066 
3067 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
compact_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)3068 static ssize_t compact_store(struct device *dev,
3069 			     struct device_attribute *attr,
3070 			     const char *buf, size_t count)
3071 {
3072 	int nid = dev->id;
3073 
3074 	if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
3075 		/* Flush pending updates to the LRU lists */
3076 		lru_add_drain_all();
3077 
3078 		compact_node(NODE_DATA(nid), false);
3079 	}
3080 
3081 	return count;
3082 }
3083 static DEVICE_ATTR_WO(compact);
3084 
compaction_register_node(struct node * node)3085 int compaction_register_node(struct node *node)
3086 {
3087 	return device_create_file(&node->dev, &dev_attr_compact);
3088 }
3089 
compaction_unregister_node(struct node * node)3090 void compaction_unregister_node(struct node *node)
3091 {
3092 	device_remove_file(&node->dev, &dev_attr_compact);
3093 }
3094 #endif /* CONFIG_SYSFS && CONFIG_NUMA */
3095 
kcompactd_work_requested(pg_data_t * pgdat)3096 static inline bool kcompactd_work_requested(pg_data_t *pgdat)
3097 {
3098 	return pgdat->kcompactd_max_order > 0 || kthread_should_stop() ||
3099 		pgdat->proactive_compact_trigger;
3100 }
3101 
kcompactd_node_suitable(pg_data_t * pgdat)3102 static bool kcompactd_node_suitable(pg_data_t *pgdat)
3103 {
3104 	int zoneid;
3105 	struct zone *zone;
3106 	enum zone_type highest_zoneidx = pgdat->kcompactd_highest_zoneidx;
3107 	enum compact_result ret;
3108 
3109 	for (zoneid = 0; zoneid <= highest_zoneidx; zoneid++) {
3110 		bool can_compact = true;
3111 		zone = &pgdat->node_zones[zoneid];
3112 
3113 		if (!populated_zone(zone))
3114 			continue;
3115 
3116 		trace_android_vh_mm_customize_zone_can_compact(zone, &can_compact);
3117 		if (!can_compact)
3118 			continue;
3119 
3120 		ret = compaction_suit_allocation_order(zone,
3121 				pgdat->kcompactd_max_order,
3122 				highest_zoneidx, ALLOC_WMARK_MIN);
3123 		if (ret == COMPACT_CONTINUE)
3124 			return true;
3125 	}
3126 
3127 	return false;
3128 }
3129 
kcompactd_do_work(pg_data_t * pgdat)3130 static void kcompactd_do_work(pg_data_t *pgdat)
3131 {
3132 	/*
3133 	 * With no special task, compact all zones so that a page of requested
3134 	 * order is allocatable.
3135 	 */
3136 	int zoneid;
3137 	struct zone *zone;
3138 	struct compact_control cc = {
3139 		.order = pgdat->kcompactd_max_order,
3140 		.search_order = pgdat->kcompactd_max_order,
3141 		.highest_zoneidx = pgdat->kcompactd_highest_zoneidx,
3142 		.mode = MIGRATE_SYNC_LIGHT,
3143 		.ignore_skip_hint = false,
3144 		.gfp_mask = GFP_KERNEL,
3145 	};
3146 	enum compact_result ret;
3147 
3148 	trace_mm_compaction_kcompactd_wake(pgdat->node_id, cc.order,
3149 							cc.highest_zoneidx);
3150 	count_compact_event(KCOMPACTD_WAKE);
3151 
3152 	for (zoneid = 0; zoneid <= cc.highest_zoneidx; zoneid++) {
3153 		int status;
3154 		bool can_compact = true;
3155 
3156 		zone = &pgdat->node_zones[zoneid];
3157 		if (!populated_zone(zone))
3158 			continue;
3159 
3160 		trace_android_vh_mm_customize_zone_can_compact(zone, &can_compact);
3161 		if (!can_compact)
3162 			continue;
3163 
3164 		if (compaction_deferred(zone, cc.order))
3165 			continue;
3166 
3167 		ret = compaction_suit_allocation_order(zone,
3168 				cc.order, zoneid, ALLOC_WMARK_MIN);
3169 		if (ret != COMPACT_CONTINUE)
3170 			continue;
3171 
3172 		if (kthread_should_stop())
3173 			return;
3174 
3175 		cc.zone = zone;
3176 		status = compact_zone(&cc, NULL);
3177 
3178 		if (status == COMPACT_SUCCESS) {
3179 			compaction_defer_reset(zone, cc.order, false);
3180 		} else if (status == COMPACT_PARTIAL_SKIPPED || status == COMPACT_COMPLETE) {
3181 			/*
3182 			 * Buddy pages may become stranded on pcps that could
3183 			 * otherwise coalesce on the zone's free area for
3184 			 * order >= cc.order.  This is ratelimited by the
3185 			 * upcoming deferral.
3186 			 */
3187 			drain_all_pages(zone);
3188 
3189 			/*
3190 			 * We use sync migration mode here, so we defer like
3191 			 * sync direct compaction does.
3192 			 */
3193 			defer_compaction(zone, cc.order);
3194 		}
3195 
3196 		count_compact_events(KCOMPACTD_MIGRATE_SCANNED,
3197 				     cc.total_migrate_scanned);
3198 		count_compact_events(KCOMPACTD_FREE_SCANNED,
3199 				     cc.total_free_scanned);
3200 	}
3201 	trace_android_vh_compaction_exit(pgdat->node_id, cc.order, cc.highest_zoneidx);
3202 
3203 	/*
3204 	 * Regardless of success, we are done until woken up next. But remember
3205 	 * the requested order/highest_zoneidx in case it was higher/tighter
3206 	 * than our current ones
3207 	 */
3208 	if (pgdat->kcompactd_max_order <= cc.order)
3209 		pgdat->kcompactd_max_order = 0;
3210 	if (pgdat->kcompactd_highest_zoneidx >= cc.highest_zoneidx)
3211 		pgdat->kcompactd_highest_zoneidx = pgdat->nr_zones - 1;
3212 }
3213 
wakeup_kcompactd(pg_data_t * pgdat,int order,int highest_zoneidx)3214 void wakeup_kcompactd(pg_data_t *pgdat, int order, int highest_zoneidx)
3215 {
3216 	if (!order)
3217 		return;
3218 
3219 	if (pgdat->kcompactd_max_order < order)
3220 		pgdat->kcompactd_max_order = order;
3221 
3222 	if (pgdat->kcompactd_highest_zoneidx > highest_zoneidx)
3223 		pgdat->kcompactd_highest_zoneidx = highest_zoneidx;
3224 
3225 	/*
3226 	 * Pairs with implicit barrier in wait_event_freezable()
3227 	 * such that wakeups are not missed.
3228 	 */
3229 	if (!wq_has_sleeper(&pgdat->kcompactd_wait))
3230 		return;
3231 
3232 	if (!kcompactd_node_suitable(pgdat))
3233 		return;
3234 
3235 	trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, order,
3236 							highest_zoneidx);
3237 	wake_up_interruptible(&pgdat->kcompactd_wait);
3238 }
3239 
3240 /*
3241  * The background compaction daemon, started as a kernel thread
3242  * from the init process.
3243  */
kcompactd(void * p)3244 static int kcompactd(void *p)
3245 {
3246 	pg_data_t *pgdat = (pg_data_t *)p;
3247 	struct task_struct *tsk = current;
3248 	long default_timeout = msecs_to_jiffies(HPAGE_FRAG_CHECK_INTERVAL_MSEC);
3249 	long timeout = default_timeout;
3250 	bool bypass = false;
3251 
3252 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
3253 
3254 	if (!cpumask_empty(cpumask))
3255 		set_cpus_allowed_ptr(tsk, cpumask);
3256 
3257 	current->flags |= PF_KCOMPACTD;
3258 	set_freezable();
3259 
3260 	pgdat->kcompactd_max_order = 0;
3261 	pgdat->kcompactd_highest_zoneidx = pgdat->nr_zones - 1;
3262 
3263 	while (!kthread_should_stop()) {
3264 		unsigned long pflags;
3265 
3266 		/*
3267 		 * Avoid the unnecessary wakeup for proactive compaction
3268 		 * when it is disabled.
3269 		 */
3270 		if (!sysctl_compaction_proactiveness)
3271 			timeout = MAX_SCHEDULE_TIMEOUT;
3272 		trace_mm_compaction_kcompactd_sleep(pgdat->node_id);
3273 		if (wait_event_freezable_timeout(pgdat->kcompactd_wait,
3274 			kcompactd_work_requested(pgdat), timeout) &&
3275 			!pgdat->proactive_compact_trigger) {
3276 
3277 			trace_android_vh_async_psi_bypass(&bypass);
3278 			if (!bypass)
3279 				psi_memstall_enter(&pflags);
3280 			kcompactd_do_work(pgdat);
3281 			if (!bypass)
3282 				psi_memstall_leave(&pflags);
3283 			/*
3284 			 * Reset the timeout value. The defer timeout from
3285 			 * proactive compaction is lost here but that is fine
3286 			 * as the condition of the zone changing substantionally
3287 			 * then carrying on with the previous defer interval is
3288 			 * not useful.
3289 			 */
3290 			timeout = default_timeout;
3291 			continue;
3292 		}
3293 
3294 		/*
3295 		 * Start the proactive work with default timeout. Based
3296 		 * on the fragmentation score, this timeout is updated.
3297 		 */
3298 		timeout = default_timeout;
3299 		if (should_proactive_compact_node(pgdat)) {
3300 			unsigned int prev_score, score;
3301 
3302 			prev_score = fragmentation_score_node(pgdat);
3303 			compact_node(pgdat, true);
3304 			score = fragmentation_score_node(pgdat);
3305 			/*
3306 			 * Defer proactive compaction if the fragmentation
3307 			 * score did not go down i.e. no progress made.
3308 			 */
3309 			if (unlikely(score >= prev_score))
3310 				timeout =
3311 				   default_timeout << COMPACT_MAX_DEFER_SHIFT;
3312 		}
3313 		if (unlikely(pgdat->proactive_compact_trigger))
3314 			pgdat->proactive_compact_trigger = false;
3315 	}
3316 
3317 	current->flags &= ~PF_KCOMPACTD;
3318 
3319 	return 0;
3320 }
3321 
3322 /*
3323  * This kcompactd start function will be called by init and node-hot-add.
3324  * On node-hot-add, kcompactd will moved to proper cpus if cpus are hot-added.
3325  */
kcompactd_run(int nid)3326 void __meminit kcompactd_run(int nid)
3327 {
3328 	pg_data_t *pgdat = NODE_DATA(nid);
3329 
3330 	if (pgdat->kcompactd)
3331 		return;
3332 
3333 	pgdat->kcompactd = kthread_run(kcompactd, pgdat, "kcompactd%d", nid);
3334 	if (IS_ERR(pgdat->kcompactd)) {
3335 		pr_err("Failed to start kcompactd on node %d\n", nid);
3336 		pgdat->kcompactd = NULL;
3337 	}
3338 }
3339 
3340 /*
3341  * Called by memory hotplug when all memory in a node is offlined. Caller must
3342  * be holding mem_hotplug_begin/done().
3343  */
kcompactd_stop(int nid)3344 void __meminit kcompactd_stop(int nid)
3345 {
3346 	struct task_struct *kcompactd = NODE_DATA(nid)->kcompactd;
3347 
3348 	if (kcompactd) {
3349 		kthread_stop(kcompactd);
3350 		NODE_DATA(nid)->kcompactd = NULL;
3351 	}
3352 }
3353 
3354 /*
3355  * It's optimal to keep kcompactd on the same CPUs as their memory, but
3356  * not required for correctness. So if the last cpu in a node goes
3357  * away, we get changed to run anywhere: as the first one comes back,
3358  * restore their cpu bindings.
3359  */
kcompactd_cpu_online(unsigned int cpu)3360 static int kcompactd_cpu_online(unsigned int cpu)
3361 {
3362 	int nid;
3363 
3364 	for_each_node_state(nid, N_MEMORY) {
3365 		pg_data_t *pgdat = NODE_DATA(nid);
3366 		const struct cpumask *mask;
3367 
3368 		mask = cpumask_of_node(pgdat->node_id);
3369 
3370 		if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
3371 			/* One of our CPUs online: restore mask */
3372 			if (pgdat->kcompactd)
3373 				set_cpus_allowed_ptr(pgdat->kcompactd, mask);
3374 	}
3375 	trace_android_vh_mm_kcompactd_cpu_online(cpu);
3376 	return 0;
3377 }
3378 
proc_dointvec_minmax_warn_RT_change(const struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)3379 static int proc_dointvec_minmax_warn_RT_change(const struct ctl_table *table,
3380 		int write, void *buffer, size_t *lenp, loff_t *ppos)
3381 {
3382 	int ret, old;
3383 
3384 	if (!IS_ENABLED(CONFIG_PREEMPT_RT) || !write)
3385 		return proc_dointvec_minmax(table, write, buffer, lenp, ppos);
3386 
3387 	old = *(int *)table->data;
3388 	ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
3389 	if (ret)
3390 		return ret;
3391 	if (old != *(int *)table->data)
3392 		pr_warn_once("sysctl attribute %s changed by %s[%d]\n",
3393 			     table->procname, current->comm,
3394 			     task_pid_nr(current));
3395 	return ret;
3396 }
3397 
3398 static struct ctl_table vm_compaction[] = {
3399 	{
3400 		.procname	= "compact_memory",
3401 		.data		= &sysctl_compact_memory,
3402 		.maxlen		= sizeof(int),
3403 		.mode		= 0200,
3404 		.proc_handler	= sysctl_compaction_handler,
3405 	},
3406 	{
3407 		.procname	= "compaction_proactiveness",
3408 		.data		= &sysctl_compaction_proactiveness,
3409 		.maxlen		= sizeof(sysctl_compaction_proactiveness),
3410 		.mode		= 0644,
3411 		.proc_handler	= compaction_proactiveness_sysctl_handler,
3412 		.extra1		= SYSCTL_ZERO,
3413 		.extra2		= SYSCTL_ONE_HUNDRED,
3414 	},
3415 	{
3416 		.procname	= "extfrag_threshold",
3417 		.data		= &sysctl_extfrag_threshold,
3418 		.maxlen		= sizeof(int),
3419 		.mode		= 0644,
3420 		.proc_handler	= proc_dointvec_minmax,
3421 		.extra1		= SYSCTL_ZERO,
3422 		.extra2		= SYSCTL_ONE_THOUSAND,
3423 	},
3424 	{
3425 		.procname	= "compact_unevictable_allowed",
3426 		.data		= &sysctl_compact_unevictable_allowed,
3427 		.maxlen		= sizeof(int),
3428 		.mode		= 0644,
3429 		.proc_handler	= proc_dointvec_minmax_warn_RT_change,
3430 		.extra1		= SYSCTL_ZERO,
3431 		.extra2		= SYSCTL_ONE,
3432 	},
3433 };
3434 
kcompactd_init(void)3435 static int __init kcompactd_init(void)
3436 {
3437 	int nid;
3438 	int ret;
3439 
3440 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
3441 					"mm/compaction:online",
3442 					kcompactd_cpu_online, NULL);
3443 	if (ret < 0) {
3444 		pr_err("kcompactd: failed to register hotplug callbacks.\n");
3445 		return ret;
3446 	}
3447 
3448 	for_each_node_state(nid, N_MEMORY)
3449 		kcompactd_run(nid);
3450 	register_sysctl_init("vm", vm_compaction);
3451 	return 0;
3452 }
3453 subsys_initcall(kcompactd_init)
3454 
3455 #endif /* CONFIG_COMPACTION */
3456