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