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