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