xref: /linux/mm/compaction.c (revision 4fbbb3fde3c69879ceebb33a8edd9d867008728b)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
2748446bbSMel Gorman /*
3748446bbSMel Gorman  * linux/mm/compaction.c
4748446bbSMel Gorman  *
5748446bbSMel Gorman  * Memory compaction for the reduction of external fragmentation. Note that
6748446bbSMel Gorman  * this heavily depends upon page migration to do all the real heavy
7748446bbSMel Gorman  * lifting
8748446bbSMel Gorman  *
9748446bbSMel Gorman  * Copyright IBM Corp. 2007-2010 Mel Gorman <mel@csn.ul.ie>
10748446bbSMel Gorman  */
11698b1b30SVlastimil Babka #include <linux/cpu.h>
12748446bbSMel Gorman #include <linux/swap.h>
13748446bbSMel Gorman #include <linux/migrate.h>
14748446bbSMel Gorman #include <linux/compaction.h>
15748446bbSMel Gorman #include <linux/mm_inline.h>
16174cd4b1SIngo Molnar #include <linux/sched/signal.h>
17748446bbSMel Gorman #include <linux/backing-dev.h>
1876ab0f53SMel Gorman #include <linux/sysctl.h>
19ed4a6d7fSMel Gorman #include <linux/sysfs.h>
20194159fbSMinchan Kim #include <linux/page-isolation.h>
21b8c73fc2SAndrey Ryabinin #include <linux/kasan.h>
22698b1b30SVlastimil Babka #include <linux/kthread.h>
23698b1b30SVlastimil Babka #include <linux/freezer.h>
2483358eceSJoonsoo Kim #include <linux/page_owner.h>
25eb414681SJohannes Weiner #include <linux/psi.h>
26748446bbSMel Gorman #include "internal.h"
27748446bbSMel Gorman 
28010fc29aSMinchan Kim #ifdef CONFIG_COMPACTION
2931ca72faSCharan Teja Kalla /*
3031ca72faSCharan Teja Kalla  * Fragmentation score check interval for proactive compaction purposes.
3131ca72faSCharan Teja Kalla  */
3231ca72faSCharan Teja Kalla #define HPAGE_FRAG_CHECK_INTERVAL_MSEC	(500)
3331ca72faSCharan Teja Kalla 
34010fc29aSMinchan Kim static inline void count_compact_event(enum vm_event_item item)
35010fc29aSMinchan Kim {
36010fc29aSMinchan Kim 	count_vm_event(item);
37010fc29aSMinchan Kim }
38010fc29aSMinchan Kim 
39010fc29aSMinchan Kim static inline void count_compact_events(enum vm_event_item item, long delta)
40010fc29aSMinchan Kim {
41010fc29aSMinchan Kim 	count_vm_events(item, delta);
42010fc29aSMinchan Kim }
43010fc29aSMinchan Kim #else
44010fc29aSMinchan Kim #define count_compact_event(item) do { } while (0)
45010fc29aSMinchan Kim #define count_compact_events(item, delta) do { } while (0)
46010fc29aSMinchan Kim #endif
47010fc29aSMinchan Kim 
48ff9543fdSMichal Nazarewicz #if defined CONFIG_COMPACTION || defined CONFIG_CMA
49ff9543fdSMichal Nazarewicz 
50b7aba698SMel Gorman #define CREATE_TRACE_POINTS
51b7aba698SMel Gorman #include <trace/events/compaction.h>
52b7aba698SMel Gorman 
5306b6640aSVlastimil Babka #define block_start_pfn(pfn, order)	round_down(pfn, 1UL << (order))
5406b6640aSVlastimil Babka #define block_end_pfn(pfn, order)	ALIGN((pfn) + 1, 1UL << (order))
5506b6640aSVlastimil Babka 
56facdaa91SNitin Gupta /*
57facdaa91SNitin Gupta  * Page order with-respect-to which proactive compaction
58facdaa91SNitin Gupta  * calculates external fragmentation, which is used as
59facdaa91SNitin Gupta  * the "fragmentation score" of a node/zone.
60facdaa91SNitin Gupta  */
61facdaa91SNitin Gupta #if defined CONFIG_TRANSPARENT_HUGEPAGE
62facdaa91SNitin Gupta #define COMPACTION_HPAGE_ORDER	HPAGE_PMD_ORDER
6325788738SNitin Gupta #elif defined CONFIG_HUGETLBFS
64facdaa91SNitin Gupta #define COMPACTION_HPAGE_ORDER	HUGETLB_PAGE_ORDER
65facdaa91SNitin Gupta #else
66facdaa91SNitin Gupta #define COMPACTION_HPAGE_ORDER	(PMD_SHIFT - PAGE_SHIFT)
67facdaa91SNitin Gupta #endif
68facdaa91SNitin Gupta 
69748446bbSMel Gorman static unsigned long release_freepages(struct list_head *freelist)
70748446bbSMel Gorman {
71748446bbSMel Gorman 	struct page *page, *next;
726bace090SVlastimil Babka 	unsigned long high_pfn = 0;
73748446bbSMel Gorman 
74748446bbSMel Gorman 	list_for_each_entry_safe(page, next, freelist, lru) {
756bace090SVlastimil Babka 		unsigned long pfn = page_to_pfn(page);
76748446bbSMel Gorman 		list_del(&page->lru);
77748446bbSMel Gorman 		__free_page(page);
786bace090SVlastimil Babka 		if (pfn > high_pfn)
796bace090SVlastimil Babka 			high_pfn = pfn;
80748446bbSMel Gorman 	}
81748446bbSMel Gorman 
826bace090SVlastimil Babka 	return high_pfn;
83748446bbSMel Gorman }
84748446bbSMel Gorman 
854469ab98SMel Gorman static void split_map_pages(struct list_head *list)
86ff9543fdSMichal Nazarewicz {
8766c64223SJoonsoo Kim 	unsigned int i, order, nr_pages;
8866c64223SJoonsoo Kim 	struct page *page, *next;
8966c64223SJoonsoo Kim 	LIST_HEAD(tmp_list);
90ff9543fdSMichal Nazarewicz 
9166c64223SJoonsoo Kim 	list_for_each_entry_safe(page, next, list, lru) {
9266c64223SJoonsoo Kim 		list_del(&page->lru);
9366c64223SJoonsoo Kim 
9466c64223SJoonsoo Kim 		order = page_private(page);
9566c64223SJoonsoo Kim 		nr_pages = 1 << order;
9666c64223SJoonsoo Kim 
9746f24fd8SJoonsoo Kim 		post_alloc_hook(page, order, __GFP_MOVABLE);
9866c64223SJoonsoo Kim 		if (order)
9966c64223SJoonsoo Kim 			split_page(page, order);
10066c64223SJoonsoo Kim 
10166c64223SJoonsoo Kim 		for (i = 0; i < nr_pages; i++) {
10266c64223SJoonsoo Kim 			list_add(&page->lru, &tmp_list);
10366c64223SJoonsoo Kim 			page++;
104ff9543fdSMichal Nazarewicz 		}
105ff9543fdSMichal Nazarewicz 	}
106ff9543fdSMichal Nazarewicz 
10766c64223SJoonsoo Kim 	list_splice(&tmp_list, list);
10866c64223SJoonsoo Kim }
10966c64223SJoonsoo Kim 
110bb13ffebSMel Gorman #ifdef CONFIG_COMPACTION
11168f2736aSMatthew Wilcox (Oracle) bool PageMovable(struct page *page)
112bda807d4SMinchan Kim {
11368f2736aSMatthew Wilcox (Oracle) 	const struct movable_operations *mops;
114bda807d4SMinchan Kim 
115bda807d4SMinchan Kim 	VM_BUG_ON_PAGE(!PageLocked(page), page);
116bda807d4SMinchan Kim 	if (!__PageMovable(page))
11768f2736aSMatthew Wilcox (Oracle) 		return false;
118bda807d4SMinchan Kim 
11968f2736aSMatthew Wilcox (Oracle) 	mops = page_movable_ops(page);
12068f2736aSMatthew Wilcox (Oracle) 	if (mops)
12168f2736aSMatthew Wilcox (Oracle) 		return true;
122bda807d4SMinchan Kim 
12368f2736aSMatthew Wilcox (Oracle) 	return false;
124bda807d4SMinchan Kim }
125bda807d4SMinchan Kim 
12668f2736aSMatthew Wilcox (Oracle) void __SetPageMovable(struct page *page, const struct movable_operations *mops)
127bda807d4SMinchan Kim {
128bda807d4SMinchan Kim 	VM_BUG_ON_PAGE(!PageLocked(page), page);
12968f2736aSMatthew Wilcox (Oracle) 	VM_BUG_ON_PAGE((unsigned long)mops & PAGE_MAPPING_MOVABLE, page);
13068f2736aSMatthew Wilcox (Oracle) 	page->mapping = (void *)((unsigned long)mops | PAGE_MAPPING_MOVABLE);
131bda807d4SMinchan Kim }
132bda807d4SMinchan Kim EXPORT_SYMBOL(__SetPageMovable);
133bda807d4SMinchan Kim 
134bda807d4SMinchan Kim void __ClearPageMovable(struct page *page)
135bda807d4SMinchan Kim {
136bda807d4SMinchan Kim 	VM_BUG_ON_PAGE(!PageMovable(page), page);
137bda807d4SMinchan Kim 	/*
13868f2736aSMatthew Wilcox (Oracle) 	 * This page still has the type of a movable page, but it's
13968f2736aSMatthew Wilcox (Oracle) 	 * actually not movable any more.
140bda807d4SMinchan Kim 	 */
14168f2736aSMatthew Wilcox (Oracle) 	page->mapping = (void *)PAGE_MAPPING_MOVABLE;
142bda807d4SMinchan Kim }
143bda807d4SMinchan Kim EXPORT_SYMBOL(__ClearPageMovable);
144bda807d4SMinchan Kim 
14524e2716fSJoonsoo Kim /* Do not skip compaction more than 64 times */
14624e2716fSJoonsoo Kim #define COMPACT_MAX_DEFER_SHIFT 6
14724e2716fSJoonsoo Kim 
14824e2716fSJoonsoo Kim /*
14924e2716fSJoonsoo Kim  * Compaction is deferred when compaction fails to result in a page
150860b3272SAlex Shi  * allocation success. 1 << compact_defer_shift, compactions are skipped up
15124e2716fSJoonsoo Kim  * to a limit of 1 << COMPACT_MAX_DEFER_SHIFT
15224e2716fSJoonsoo Kim  */
1532271b016SHui Su static void defer_compaction(struct zone *zone, int order)
15424e2716fSJoonsoo Kim {
15524e2716fSJoonsoo Kim 	zone->compact_considered = 0;
15624e2716fSJoonsoo Kim 	zone->compact_defer_shift++;
15724e2716fSJoonsoo Kim 
15824e2716fSJoonsoo Kim 	if (order < zone->compact_order_failed)
15924e2716fSJoonsoo Kim 		zone->compact_order_failed = order;
16024e2716fSJoonsoo Kim 
16124e2716fSJoonsoo Kim 	if (zone->compact_defer_shift > COMPACT_MAX_DEFER_SHIFT)
16224e2716fSJoonsoo Kim 		zone->compact_defer_shift = COMPACT_MAX_DEFER_SHIFT;
16324e2716fSJoonsoo Kim 
16424e2716fSJoonsoo Kim 	trace_mm_compaction_defer_compaction(zone, order);
16524e2716fSJoonsoo Kim }
16624e2716fSJoonsoo Kim 
16724e2716fSJoonsoo Kim /* Returns true if compaction should be skipped this time */
1682271b016SHui Su static bool compaction_deferred(struct zone *zone, int order)
16924e2716fSJoonsoo Kim {
17024e2716fSJoonsoo Kim 	unsigned long defer_limit = 1UL << zone->compact_defer_shift;
17124e2716fSJoonsoo Kim 
17224e2716fSJoonsoo Kim 	if (order < zone->compact_order_failed)
17324e2716fSJoonsoo Kim 		return false;
17424e2716fSJoonsoo Kim 
17524e2716fSJoonsoo Kim 	/* Avoid possible overflow */
17662b35fe0SMateusz Nosek 	if (++zone->compact_considered >= defer_limit) {
17724e2716fSJoonsoo Kim 		zone->compact_considered = defer_limit;
17824e2716fSJoonsoo Kim 		return false;
17962b35fe0SMateusz Nosek 	}
18024e2716fSJoonsoo Kim 
18124e2716fSJoonsoo Kim 	trace_mm_compaction_deferred(zone, order);
18224e2716fSJoonsoo Kim 
18324e2716fSJoonsoo Kim 	return true;
18424e2716fSJoonsoo Kim }
18524e2716fSJoonsoo Kim 
18624e2716fSJoonsoo Kim /*
18724e2716fSJoonsoo Kim  * Update defer tracking counters after successful compaction of given order,
18824e2716fSJoonsoo Kim  * which means an allocation either succeeded (alloc_success == true) or is
18924e2716fSJoonsoo Kim  * expected to succeed.
19024e2716fSJoonsoo Kim  */
19124e2716fSJoonsoo Kim void compaction_defer_reset(struct zone *zone, int order,
19224e2716fSJoonsoo Kim 		bool alloc_success)
19324e2716fSJoonsoo Kim {
19424e2716fSJoonsoo Kim 	if (alloc_success) {
19524e2716fSJoonsoo Kim 		zone->compact_considered = 0;
19624e2716fSJoonsoo Kim 		zone->compact_defer_shift = 0;
19724e2716fSJoonsoo Kim 	}
19824e2716fSJoonsoo Kim 	if (order >= zone->compact_order_failed)
19924e2716fSJoonsoo Kim 		zone->compact_order_failed = order + 1;
20024e2716fSJoonsoo Kim 
20124e2716fSJoonsoo Kim 	trace_mm_compaction_defer_reset(zone, order);
20224e2716fSJoonsoo Kim }
20324e2716fSJoonsoo Kim 
20424e2716fSJoonsoo Kim /* Returns true if restarting compaction after many failures */
2052271b016SHui Su static bool compaction_restarting(struct zone *zone, int order)
20624e2716fSJoonsoo Kim {
20724e2716fSJoonsoo Kim 	if (order < zone->compact_order_failed)
20824e2716fSJoonsoo Kim 		return false;
20924e2716fSJoonsoo Kim 
21024e2716fSJoonsoo Kim 	return zone->compact_defer_shift == COMPACT_MAX_DEFER_SHIFT &&
21124e2716fSJoonsoo Kim 		zone->compact_considered >= 1UL << zone->compact_defer_shift;
21224e2716fSJoonsoo Kim }
21324e2716fSJoonsoo Kim 
214bb13ffebSMel Gorman /* Returns true if the pageblock should be scanned for pages to isolate. */
215bb13ffebSMel Gorman static inline bool isolation_suitable(struct compact_control *cc,
216bb13ffebSMel Gorman 					struct page *page)
217bb13ffebSMel Gorman {
218bb13ffebSMel Gorman 	if (cc->ignore_skip_hint)
219bb13ffebSMel Gorman 		return true;
220bb13ffebSMel Gorman 
221bb13ffebSMel Gorman 	return !get_pageblock_skip(page);
222bb13ffebSMel Gorman }
223bb13ffebSMel Gorman 
22402333641SVlastimil Babka static void reset_cached_positions(struct zone *zone)
22502333641SVlastimil Babka {
22602333641SVlastimil Babka 	zone->compact_cached_migrate_pfn[0] = zone->zone_start_pfn;
22702333641SVlastimil Babka 	zone->compact_cached_migrate_pfn[1] = zone->zone_start_pfn;
228623446e4SJoonsoo Kim 	zone->compact_cached_free_pfn =
22906b6640aSVlastimil Babka 				pageblock_start_pfn(zone_end_pfn(zone) - 1);
23002333641SVlastimil Babka }
23102333641SVlastimil Babka 
232bb13ffebSMel Gorman /*
2332271b016SHui Su  * Compound pages of >= pageblock_order should consistently be skipped until
234b527cfe5SVlastimil Babka  * released. It is always pointless to compact pages of such order (if they are
235b527cfe5SVlastimil Babka  * migratable), and the pageblocks they occupy cannot contain any free pages.
23621dc7e02SDavid Rientjes  */
237b527cfe5SVlastimil Babka static bool pageblock_skip_persistent(struct page *page)
23821dc7e02SDavid Rientjes {
239b527cfe5SVlastimil Babka 	if (!PageCompound(page))
24021dc7e02SDavid Rientjes 		return false;
241b527cfe5SVlastimil Babka 
242b527cfe5SVlastimil Babka 	page = compound_head(page);
243b527cfe5SVlastimil Babka 
244b527cfe5SVlastimil Babka 	if (compound_order(page) >= pageblock_order)
24521dc7e02SDavid Rientjes 		return true;
246b527cfe5SVlastimil Babka 
247b527cfe5SVlastimil Babka 	return false;
24821dc7e02SDavid Rientjes }
24921dc7e02SDavid Rientjes 
250e332f741SMel Gorman static bool
251e332f741SMel Gorman __reset_isolation_pfn(struct zone *zone, unsigned long pfn, bool check_source,
252e332f741SMel Gorman 							bool check_target)
253e332f741SMel Gorman {
254e332f741SMel Gorman 	struct page *page = pfn_to_online_page(pfn);
2556b0868c8SMel Gorman 	struct page *block_page;
256e332f741SMel Gorman 	struct page *end_page;
257e332f741SMel Gorman 	unsigned long block_pfn;
258e332f741SMel Gorman 
259e332f741SMel Gorman 	if (!page)
260e332f741SMel Gorman 		return false;
261e332f741SMel Gorman 	if (zone != page_zone(page))
262e332f741SMel Gorman 		return false;
263e332f741SMel Gorman 	if (pageblock_skip_persistent(page))
264e332f741SMel Gorman 		return false;
265e332f741SMel Gorman 
266e332f741SMel Gorman 	/*
267e332f741SMel Gorman 	 * If skip is already cleared do no further checking once the
268e332f741SMel Gorman 	 * restart points have been set.
269e332f741SMel Gorman 	 */
270e332f741SMel Gorman 	if (check_source && check_target && !get_pageblock_skip(page))
271e332f741SMel Gorman 		return true;
272e332f741SMel Gorman 
273e332f741SMel Gorman 	/*
274e332f741SMel Gorman 	 * If clearing skip for the target scanner, do not select a
275e332f741SMel Gorman 	 * non-movable pageblock as the starting point.
276e332f741SMel Gorman 	 */
277e332f741SMel Gorman 	if (!check_source && check_target &&
278e332f741SMel Gorman 	    get_pageblock_migratetype(page) != MIGRATE_MOVABLE)
279e332f741SMel Gorman 		return false;
280e332f741SMel Gorman 
2816b0868c8SMel Gorman 	/* Ensure the start of the pageblock or zone is online and valid */
2826b0868c8SMel Gorman 	block_pfn = pageblock_start_pfn(pfn);
283a2e9a5afSVlastimil Babka 	block_pfn = max(block_pfn, zone->zone_start_pfn);
284a2e9a5afSVlastimil Babka 	block_page = pfn_to_online_page(block_pfn);
2856b0868c8SMel Gorman 	if (block_page) {
2866b0868c8SMel Gorman 		page = block_page;
2876b0868c8SMel Gorman 		pfn = block_pfn;
2886b0868c8SMel Gorman 	}
2896b0868c8SMel Gorman 
2906b0868c8SMel Gorman 	/* Ensure the end of the pageblock or zone is online and valid */
291a2e9a5afSVlastimil Babka 	block_pfn = pageblock_end_pfn(pfn) - 1;
2926b0868c8SMel Gorman 	block_pfn = min(block_pfn, zone_end_pfn(zone) - 1);
2936b0868c8SMel Gorman 	end_page = pfn_to_online_page(block_pfn);
2946b0868c8SMel Gorman 	if (!end_page)
2956b0868c8SMel Gorman 		return false;
2966b0868c8SMel Gorman 
297e332f741SMel Gorman 	/*
298e332f741SMel Gorman 	 * Only clear the hint if a sample indicates there is either a
299e332f741SMel Gorman 	 * free page or an LRU page in the block. One or other condition
300e332f741SMel Gorman 	 * is necessary for the block to be a migration source/target.
301e332f741SMel Gorman 	 */
302e332f741SMel Gorman 	do {
303e332f741SMel Gorman 		if (check_source && PageLRU(page)) {
304e332f741SMel Gorman 			clear_pageblock_skip(page);
305e332f741SMel Gorman 			return true;
306e332f741SMel Gorman 		}
307e332f741SMel Gorman 
308e332f741SMel Gorman 		if (check_target && PageBuddy(page)) {
309e332f741SMel Gorman 			clear_pageblock_skip(page);
310e332f741SMel Gorman 			return true;
311e332f741SMel Gorman 		}
312e332f741SMel Gorman 
313e332f741SMel Gorman 		page += (1 << PAGE_ALLOC_COSTLY_ORDER);
314a2e9a5afSVlastimil Babka 	} while (page <= end_page);
315e332f741SMel Gorman 
316e332f741SMel Gorman 	return false;
317e332f741SMel Gorman }
318e332f741SMel Gorman 
31921dc7e02SDavid Rientjes /*
320bb13ffebSMel Gorman  * This function is called to clear all cached information on pageblocks that
321bb13ffebSMel Gorman  * should be skipped for page isolation when the migrate and free page scanner
322bb13ffebSMel Gorman  * meet.
323bb13ffebSMel Gorman  */
32462997027SMel Gorman static void __reset_isolation_suitable(struct zone *zone)
325bb13ffebSMel Gorman {
326e332f741SMel Gorman 	unsigned long migrate_pfn = zone->zone_start_pfn;
3276b0868c8SMel Gorman 	unsigned long free_pfn = zone_end_pfn(zone) - 1;
328e332f741SMel Gorman 	unsigned long reset_migrate = free_pfn;
329e332f741SMel Gorman 	unsigned long reset_free = migrate_pfn;
330e332f741SMel Gorman 	bool source_set = false;
331e332f741SMel Gorman 	bool free_set = false;
332e332f741SMel Gorman 
333e332f741SMel Gorman 	if (!zone->compact_blockskip_flush)
334e332f741SMel Gorman 		return;
335bb13ffebSMel Gorman 
33662997027SMel Gorman 	zone->compact_blockskip_flush = false;
337bb13ffebSMel Gorman 
338e332f741SMel Gorman 	/*
339e332f741SMel Gorman 	 * Walk the zone and update pageblock skip information. Source looks
340e332f741SMel Gorman 	 * for PageLRU while target looks for PageBuddy. When the scanner
341e332f741SMel Gorman 	 * is found, both PageBuddy and PageLRU are checked as the pageblock
342e332f741SMel Gorman 	 * is suitable as both source and target.
343e332f741SMel Gorman 	 */
344e332f741SMel Gorman 	for (; migrate_pfn < free_pfn; migrate_pfn += pageblock_nr_pages,
345e332f741SMel Gorman 					free_pfn -= pageblock_nr_pages) {
346bb13ffebSMel Gorman 		cond_resched();
347bb13ffebSMel Gorman 
348e332f741SMel Gorman 		/* Update the migrate PFN */
349e332f741SMel Gorman 		if (__reset_isolation_pfn(zone, migrate_pfn, true, source_set) &&
350e332f741SMel Gorman 		    migrate_pfn < reset_migrate) {
351e332f741SMel Gorman 			source_set = true;
352e332f741SMel Gorman 			reset_migrate = migrate_pfn;
353e332f741SMel Gorman 			zone->compact_init_migrate_pfn = reset_migrate;
354e332f741SMel Gorman 			zone->compact_cached_migrate_pfn[0] = reset_migrate;
355e332f741SMel Gorman 			zone->compact_cached_migrate_pfn[1] = reset_migrate;
356bb13ffebSMel Gorman 		}
35702333641SVlastimil Babka 
358e332f741SMel Gorman 		/* Update the free PFN */
359e332f741SMel Gorman 		if (__reset_isolation_pfn(zone, free_pfn, free_set, true) &&
360e332f741SMel Gorman 		    free_pfn > reset_free) {
361e332f741SMel Gorman 			free_set = true;
362e332f741SMel Gorman 			reset_free = free_pfn;
363e332f741SMel Gorman 			zone->compact_init_free_pfn = reset_free;
364e332f741SMel Gorman 			zone->compact_cached_free_pfn = reset_free;
365e332f741SMel Gorman 		}
366e332f741SMel Gorman 	}
367e332f741SMel Gorman 
368e332f741SMel Gorman 	/* Leave no distance if no suitable block was reset */
369e332f741SMel Gorman 	if (reset_migrate >= reset_free) {
370e332f741SMel Gorman 		zone->compact_cached_migrate_pfn[0] = migrate_pfn;
371e332f741SMel Gorman 		zone->compact_cached_migrate_pfn[1] = migrate_pfn;
372e332f741SMel Gorman 		zone->compact_cached_free_pfn = free_pfn;
373e332f741SMel Gorman 	}
374bb13ffebSMel Gorman }
375bb13ffebSMel Gorman 
37662997027SMel Gorman void reset_isolation_suitable(pg_data_t *pgdat)
37762997027SMel Gorman {
37862997027SMel Gorman 	int zoneid;
37962997027SMel Gorman 
38062997027SMel Gorman 	for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
38162997027SMel Gorman 		struct zone *zone = &pgdat->node_zones[zoneid];
38262997027SMel Gorman 		if (!populated_zone(zone))
38362997027SMel Gorman 			continue;
38462997027SMel Gorman 
38562997027SMel Gorman 		/* Only flush if a full compaction finished recently */
38662997027SMel Gorman 		if (zone->compact_blockskip_flush)
38762997027SMel Gorman 			__reset_isolation_suitable(zone);
38862997027SMel Gorman 	}
38962997027SMel Gorman }
39062997027SMel Gorman 
391bb13ffebSMel Gorman /*
392e380bebeSMel Gorman  * Sets the pageblock skip bit if it was clear. Note that this is a hint as
393e380bebeSMel Gorman  * locks are not required for read/writers. Returns true if it was already set.
394e380bebeSMel Gorman  */
395590ccea8SMel Gorman static bool test_and_set_skip(struct compact_control *cc, struct page *page)
396e380bebeSMel Gorman {
397e380bebeSMel Gorman 	bool skip;
398e380bebeSMel Gorman 
399590ccea8SMel Gorman 	/* Do not update if skip hint is being ignored */
400e380bebeSMel Gorman 	if (cc->ignore_skip_hint)
401e380bebeSMel Gorman 		return false;
402e380bebeSMel Gorman 
403e380bebeSMel Gorman 	skip = get_pageblock_skip(page);
404e380bebeSMel Gorman 	if (!skip && !cc->no_set_skip_hint)
405e380bebeSMel Gorman 		set_pageblock_skip(page);
406e380bebeSMel Gorman 
407e380bebeSMel Gorman 	return skip;
408e380bebeSMel Gorman }
409e380bebeSMel Gorman 
410e380bebeSMel Gorman static void update_cached_migrate(struct compact_control *cc, unsigned long pfn)
411e380bebeSMel Gorman {
412e380bebeSMel Gorman 	struct zone *zone = cc->zone;
413e380bebeSMel Gorman 
414e380bebeSMel Gorman 	pfn = pageblock_end_pfn(pfn);
415e380bebeSMel Gorman 
416e380bebeSMel Gorman 	/* Set for isolation rather than compaction */
417e380bebeSMel Gorman 	if (cc->no_set_skip_hint)
418e380bebeSMel Gorman 		return;
419e380bebeSMel Gorman 
420e380bebeSMel Gorman 	if (pfn > zone->compact_cached_migrate_pfn[0])
421e380bebeSMel Gorman 		zone->compact_cached_migrate_pfn[0] = pfn;
422e380bebeSMel Gorman 	if (cc->mode != MIGRATE_ASYNC &&
423e380bebeSMel Gorman 	    pfn > zone->compact_cached_migrate_pfn[1])
424e380bebeSMel Gorman 		zone->compact_cached_migrate_pfn[1] = pfn;
425e380bebeSMel Gorman }
426e380bebeSMel Gorman 
427e380bebeSMel Gorman /*
428bb13ffebSMel Gorman  * If no pages were isolated then mark this pageblock to be skipped in the
42962997027SMel Gorman  * future. The information is later cleared by __reset_isolation_suitable().
430bb13ffebSMel Gorman  */
431c89511abSMel Gorman static void update_pageblock_skip(struct compact_control *cc,
432d097a6f6SMel Gorman 			struct page *page, unsigned long pfn)
433bb13ffebSMel Gorman {
434c89511abSMel Gorman 	struct zone *zone = cc->zone;
4356815bf3fSJoonsoo Kim 
4362583d671SVlastimil Babka 	if (cc->no_set_skip_hint)
4376815bf3fSJoonsoo Kim 		return;
4386815bf3fSJoonsoo Kim 
439bb13ffebSMel Gorman 	if (!page)
440bb13ffebSMel Gorman 		return;
441bb13ffebSMel Gorman 
442bb13ffebSMel Gorman 	set_pageblock_skip(page);
443c89511abSMel Gorman 
44435979ef3SDavid Rientjes 	/* Update where async and sync compaction should restart */
44535979ef3SDavid Rientjes 	if (pfn < zone->compact_cached_free_pfn)
446c89511abSMel Gorman 		zone->compact_cached_free_pfn = pfn;
447c89511abSMel Gorman }
448bb13ffebSMel Gorman #else
449bb13ffebSMel Gorman static inline bool isolation_suitable(struct compact_control *cc,
450bb13ffebSMel Gorman 					struct page *page)
451bb13ffebSMel Gorman {
452bb13ffebSMel Gorman 	return true;
453bb13ffebSMel Gorman }
454bb13ffebSMel Gorman 
455b527cfe5SVlastimil Babka static inline bool pageblock_skip_persistent(struct page *page)
45621dc7e02SDavid Rientjes {
45721dc7e02SDavid Rientjes 	return false;
45821dc7e02SDavid Rientjes }
45921dc7e02SDavid Rientjes 
46021dc7e02SDavid Rientjes static inline void update_pageblock_skip(struct compact_control *cc,
461d097a6f6SMel Gorman 			struct page *page, unsigned long pfn)
462bb13ffebSMel Gorman {
463bb13ffebSMel Gorman }
464e380bebeSMel Gorman 
465e380bebeSMel Gorman static void update_cached_migrate(struct compact_control *cc, unsigned long pfn)
466e380bebeSMel Gorman {
467e380bebeSMel Gorman }
468e380bebeSMel Gorman 
469590ccea8SMel Gorman static bool test_and_set_skip(struct compact_control *cc, struct page *page)
470e380bebeSMel Gorman {
471e380bebeSMel Gorman 	return false;
472e380bebeSMel Gorman }
473bb13ffebSMel Gorman #endif /* CONFIG_COMPACTION */
474bb13ffebSMel Gorman 
4751f9efdefSVlastimil Babka /*
4768b44d279SVlastimil Babka  * Compaction requires the taking of some coarse locks that are potentially
477cb2dcaf0SMel Gorman  * very heavily contended. For async compaction, trylock and record if the
478cb2dcaf0SMel Gorman  * lock is contended. The lock will still be acquired but compaction will
479cb2dcaf0SMel Gorman  * abort when the current block is finished regardless of success rate.
480cb2dcaf0SMel Gorman  * Sync compaction acquires the lock.
4818b44d279SVlastimil Babka  *
482cb2dcaf0SMel Gorman  * Always returns true which makes it easier to track lock state in callers.
4831f9efdefSVlastimil Babka  */
484cb2dcaf0SMel Gorman static bool compact_lock_irqsave(spinlock_t *lock, unsigned long *flags,
4858b44d279SVlastimil Babka 						struct compact_control *cc)
48677337edeSJules Irenge 	__acquires(lock)
4878b44d279SVlastimil Babka {
488cb2dcaf0SMel Gorman 	/* Track if the lock is contended in async mode */
489cb2dcaf0SMel Gorman 	if (cc->mode == MIGRATE_ASYNC && !cc->contended) {
490cb2dcaf0SMel Gorman 		if (spin_trylock_irqsave(lock, *flags))
491cb2dcaf0SMel Gorman 			return true;
492cb2dcaf0SMel Gorman 
493c3486f53SVlastimil Babka 		cc->contended = true;
4948b44d279SVlastimil Babka 	}
4951f9efdefSVlastimil Babka 
496cb2dcaf0SMel Gorman 	spin_lock_irqsave(lock, *flags);
4978b44d279SVlastimil Babka 	return true;
4982a1402aaSMel Gorman }
4992a1402aaSMel Gorman 
50085aa125fSMichal Nazarewicz /*
501c67fe375SMel Gorman  * Compaction requires the taking of some coarse locks that are potentially
5028b44d279SVlastimil Babka  * very heavily contended. The lock should be periodically unlocked to avoid
5038b44d279SVlastimil Babka  * having disabled IRQs for a long time, even when there is nobody waiting on
5048b44d279SVlastimil Babka  * the lock. It might also be that allowing the IRQs will result in
505d56c1584SMiaohe Lin  * need_resched() becoming true. If scheduling is needed, compaction schedules.
5068b44d279SVlastimil Babka  * Either compaction type will also abort if a fatal signal is pending.
5078b44d279SVlastimil Babka  * In either case if the lock was locked, it is dropped and not regained.
508c67fe375SMel Gorman  *
509d56c1584SMiaohe Lin  * Returns true if compaction should abort due to fatal signal pending.
510d56c1584SMiaohe Lin  * Returns false when compaction can continue.
511c67fe375SMel Gorman  */
5128b44d279SVlastimil Babka static bool compact_unlock_should_abort(spinlock_t *lock,
5138b44d279SVlastimil Babka 		unsigned long flags, bool *locked, struct compact_control *cc)
514c67fe375SMel Gorman {
5158b44d279SVlastimil Babka 	if (*locked) {
5168b44d279SVlastimil Babka 		spin_unlock_irqrestore(lock, flags);
5178b44d279SVlastimil Babka 		*locked = false;
518c67fe375SMel Gorman 	}
519c67fe375SMel Gorman 
5208b44d279SVlastimil Babka 	if (fatal_signal_pending(current)) {
521c3486f53SVlastimil Babka 		cc->contended = true;
5228b44d279SVlastimil Babka 		return true;
5238b44d279SVlastimil Babka 	}
5248b44d279SVlastimil Babka 
525cf66f070SMel Gorman 	cond_resched();
526be976572SVlastimil Babka 
527be976572SVlastimil Babka 	return false;
528be976572SVlastimil Babka }
529be976572SVlastimil Babka 
530c67fe375SMel Gorman /*
5319e4be470SJerome Marchand  * Isolate free pages onto a private freelist. If @strict is true, will abort
5329e4be470SJerome Marchand  * returning 0 on any invalid PFNs or non-free pages inside of the pageblock
5339e4be470SJerome Marchand  * (even though it may still end up isolating some pages).
53485aa125fSMichal Nazarewicz  */
535f40d1e42SMel Gorman static unsigned long isolate_freepages_block(struct compact_control *cc,
536e14c720eSVlastimil Babka 				unsigned long *start_pfn,
53785aa125fSMichal Nazarewicz 				unsigned long end_pfn,
53885aa125fSMichal Nazarewicz 				struct list_head *freelist,
5394fca9730SMel Gorman 				unsigned int stride,
54085aa125fSMichal Nazarewicz 				bool strict)
541748446bbSMel Gorman {
542b7aba698SMel Gorman 	int nr_scanned = 0, total_isolated = 0;
543d097a6f6SMel Gorman 	struct page *cursor;
544b8b2d825SXiubo Li 	unsigned long flags = 0;
545f40d1e42SMel Gorman 	bool locked = false;
546e14c720eSVlastimil Babka 	unsigned long blockpfn = *start_pfn;
54766c64223SJoonsoo Kim 	unsigned int order;
548748446bbSMel Gorman 
5494fca9730SMel Gorman 	/* Strict mode is for isolation, speed is secondary */
5504fca9730SMel Gorman 	if (strict)
5514fca9730SMel Gorman 		stride = 1;
5524fca9730SMel Gorman 
553748446bbSMel Gorman 	cursor = pfn_to_page(blockpfn);
554748446bbSMel Gorman 
555f40d1e42SMel Gorman 	/* Isolate free pages. */
5564fca9730SMel Gorman 	for (; blockpfn < end_pfn; blockpfn += stride, cursor += stride) {
55766c64223SJoonsoo Kim 		int isolated;
558748446bbSMel Gorman 		struct page *page = cursor;
559748446bbSMel Gorman 
5608b44d279SVlastimil Babka 		/*
5618b44d279SVlastimil Babka 		 * Periodically drop the lock (if held) regardless of its
5628b44d279SVlastimil Babka 		 * contention, to give chance to IRQs. Abort if fatal signal
563d56c1584SMiaohe Lin 		 * pending.
5648b44d279SVlastimil Babka 		 */
565c036ddffSMiaohe Lin 		if (!(blockpfn % COMPACT_CLUSTER_MAX)
5668b44d279SVlastimil Babka 		    && compact_unlock_should_abort(&cc->zone->lock, flags,
5678b44d279SVlastimil Babka 								&locked, cc))
5688b44d279SVlastimil Babka 			break;
5698b44d279SVlastimil Babka 
570b7aba698SMel Gorman 		nr_scanned++;
5712af120bcSLaura Abbott 
5729fcd6d2eSVlastimil Babka 		/*
5739fcd6d2eSVlastimil Babka 		 * For compound pages such as THP and hugetlbfs, we can save
5749fcd6d2eSVlastimil Babka 		 * potentially a lot of iterations if we skip them at once.
5759fcd6d2eSVlastimil Babka 		 * The check is racy, but we can consider only valid values
5769fcd6d2eSVlastimil Babka 		 * and the only danger is skipping too much.
5779fcd6d2eSVlastimil Babka 		 */
5789fcd6d2eSVlastimil Babka 		if (PageCompound(page)) {
57921dc7e02SDavid Rientjes 			const unsigned int order = compound_order(page);
5809fcd6d2eSVlastimil Babka 
58123baf831SKirill A. Shutemov 			if (likely(order <= MAX_ORDER)) {
58221dc7e02SDavid Rientjes 				blockpfn += (1UL << order) - 1;
58321dc7e02SDavid Rientjes 				cursor += (1UL << order) - 1;
58456d48d8dSBaolin Wang 				nr_scanned += (1UL << order) - 1;
5859fcd6d2eSVlastimil Babka 			}
5869fcd6d2eSVlastimil Babka 			goto isolate_fail;
5879fcd6d2eSVlastimil Babka 		}
5889fcd6d2eSVlastimil Babka 
589f40d1e42SMel Gorman 		if (!PageBuddy(page))
5902af120bcSLaura Abbott 			goto isolate_fail;
591f40d1e42SMel Gorman 
59285f73e6dSMiaohe Lin 		/* If we already hold the lock, we can skip some rechecking. */
59369b7189fSVlastimil Babka 		if (!locked) {
594cb2dcaf0SMel Gorman 			locked = compact_lock_irqsave(&cc->zone->lock,
5958b44d279SVlastimil Babka 								&flags, cc);
596f40d1e42SMel Gorman 
597f40d1e42SMel Gorman 			/* Recheck this is a buddy page under lock */
598f40d1e42SMel Gorman 			if (!PageBuddy(page))
5992af120bcSLaura Abbott 				goto isolate_fail;
60069b7189fSVlastimil Babka 		}
601748446bbSMel Gorman 
60266c64223SJoonsoo Kim 		/* Found a free page, will break it into order-0 pages */
603ab130f91SMatthew Wilcox (Oracle) 		order = buddy_order(page);
60466c64223SJoonsoo Kim 		isolated = __isolate_free_page(page, order);
605a4f04f2cSDavid Rientjes 		if (!isolated)
606a4f04f2cSDavid Rientjes 			break;
60766c64223SJoonsoo Kim 		set_page_private(page, order);
608a4f04f2cSDavid Rientjes 
609b717d6b9SWilliam Lam 		nr_scanned += isolated - 1;
610748446bbSMel Gorman 		total_isolated += isolated;
611a4f04f2cSDavid Rientjes 		cc->nr_freepages += isolated;
61266c64223SJoonsoo Kim 		list_add_tail(&page->lru, freelist);
61366c64223SJoonsoo Kim 
614a4f04f2cSDavid Rientjes 		if (!strict && cc->nr_migratepages <= cc->nr_freepages) {
615932ff6bbSJoonsoo Kim 			blockpfn += isolated;
616932ff6bbSJoonsoo Kim 			break;
617932ff6bbSJoonsoo Kim 		}
618a4f04f2cSDavid Rientjes 		/* Advance to the end of split page */
619748446bbSMel Gorman 		blockpfn += isolated - 1;
620748446bbSMel Gorman 		cursor += isolated - 1;
6212af120bcSLaura Abbott 		continue;
6222af120bcSLaura Abbott 
6232af120bcSLaura Abbott isolate_fail:
6242af120bcSLaura Abbott 		if (strict)
6252af120bcSLaura Abbott 			break;
6262af120bcSLaura Abbott 		else
6272af120bcSLaura Abbott 			continue;
6282af120bcSLaura Abbott 
629748446bbSMel Gorman 	}
630748446bbSMel Gorman 
631a4f04f2cSDavid Rientjes 	if (locked)
632a4f04f2cSDavid Rientjes 		spin_unlock_irqrestore(&cc->zone->lock, flags);
633a4f04f2cSDavid Rientjes 
6349fcd6d2eSVlastimil Babka 	/*
6359fcd6d2eSVlastimil Babka 	 * There is a tiny chance that we have read bogus compound_order(),
6369fcd6d2eSVlastimil Babka 	 * so be careful to not go outside of the pageblock.
6379fcd6d2eSVlastimil Babka 	 */
6389fcd6d2eSVlastimil Babka 	if (unlikely(blockpfn > end_pfn))
6399fcd6d2eSVlastimil Babka 		blockpfn = end_pfn;
6409fcd6d2eSVlastimil Babka 
641e34d85f0SJoonsoo Kim 	trace_mm_compaction_isolate_freepages(*start_pfn, blockpfn,
642e34d85f0SJoonsoo Kim 					nr_scanned, total_isolated);
643e34d85f0SJoonsoo Kim 
644e14c720eSVlastimil Babka 	/* Record how far we have got within the block */
645e14c720eSVlastimil Babka 	*start_pfn = blockpfn;
646e14c720eSVlastimil Babka 
647f40d1e42SMel Gorman 	/*
648f40d1e42SMel Gorman 	 * If strict isolation is requested by CMA then check that all the
649f40d1e42SMel Gorman 	 * pages requested were isolated. If there were any failures, 0 is
650f40d1e42SMel Gorman 	 * returned and CMA will fail.
651f40d1e42SMel Gorman 	 */
6522af120bcSLaura Abbott 	if (strict && blockpfn < end_pfn)
653f40d1e42SMel Gorman 		total_isolated = 0;
654f40d1e42SMel Gorman 
6557f354a54SDavid Rientjes 	cc->total_free_scanned += nr_scanned;
656397487dbSMel Gorman 	if (total_isolated)
657010fc29aSMinchan Kim 		count_compact_events(COMPACTISOLATED, total_isolated);
658748446bbSMel Gorman 	return total_isolated;
659748446bbSMel Gorman }
660748446bbSMel Gorman 
66185aa125fSMichal Nazarewicz /**
66285aa125fSMichal Nazarewicz  * isolate_freepages_range() - isolate free pages.
663e8b098fcSMike Rapoport  * @cc:        Compaction control structure.
66485aa125fSMichal Nazarewicz  * @start_pfn: The first PFN to start isolating.
66585aa125fSMichal Nazarewicz  * @end_pfn:   The one-past-last PFN.
66685aa125fSMichal Nazarewicz  *
66785aa125fSMichal Nazarewicz  * Non-free pages, invalid PFNs, or zone boundaries within the
66885aa125fSMichal Nazarewicz  * [start_pfn, end_pfn) range are considered errors, cause function to
66985aa125fSMichal Nazarewicz  * undo its actions and return zero.
67085aa125fSMichal Nazarewicz  *
67185aa125fSMichal Nazarewicz  * Otherwise, function returns one-past-the-last PFN of isolated page
67285aa125fSMichal Nazarewicz  * (which may be greater then end_pfn if end fell in a middle of
67385aa125fSMichal Nazarewicz  * a free page).
67485aa125fSMichal Nazarewicz  */
675ff9543fdSMichal Nazarewicz unsigned long
676bb13ffebSMel Gorman isolate_freepages_range(struct compact_control *cc,
677bb13ffebSMel Gorman 			unsigned long start_pfn, unsigned long end_pfn)
67885aa125fSMichal Nazarewicz {
679e1409c32SJoonsoo Kim 	unsigned long isolated, pfn, block_start_pfn, block_end_pfn;
68085aa125fSMichal Nazarewicz 	LIST_HEAD(freelist);
68185aa125fSMichal Nazarewicz 
6827d49d886SVlastimil Babka 	pfn = start_pfn;
68306b6640aSVlastimil Babka 	block_start_pfn = pageblock_start_pfn(pfn);
684e1409c32SJoonsoo Kim 	if (block_start_pfn < cc->zone->zone_start_pfn)
685e1409c32SJoonsoo Kim 		block_start_pfn = cc->zone->zone_start_pfn;
68606b6640aSVlastimil Babka 	block_end_pfn = pageblock_end_pfn(pfn);
6877d49d886SVlastimil Babka 
6887d49d886SVlastimil Babka 	for (; pfn < end_pfn; pfn += isolated,
689e1409c32SJoonsoo Kim 				block_start_pfn = block_end_pfn,
6907d49d886SVlastimil Babka 				block_end_pfn += pageblock_nr_pages) {
691e14c720eSVlastimil Babka 		/* Protect pfn from changing by isolate_freepages_block */
692e14c720eSVlastimil Babka 		unsigned long isolate_start_pfn = pfn;
6937d49d886SVlastimil Babka 
69485aa125fSMichal Nazarewicz 		block_end_pfn = min(block_end_pfn, end_pfn);
69585aa125fSMichal Nazarewicz 
69658420016SJoonsoo Kim 		/*
69758420016SJoonsoo Kim 		 * pfn could pass the block_end_pfn if isolated freepage
69858420016SJoonsoo Kim 		 * is more than pageblock order. In this case, we adjust
69958420016SJoonsoo Kim 		 * scanning range to right one.
70058420016SJoonsoo Kim 		 */
70158420016SJoonsoo Kim 		if (pfn >= block_end_pfn) {
70206b6640aSVlastimil Babka 			block_start_pfn = pageblock_start_pfn(pfn);
70306b6640aSVlastimil Babka 			block_end_pfn = pageblock_end_pfn(pfn);
70458420016SJoonsoo Kim 			block_end_pfn = min(block_end_pfn, end_pfn);
70558420016SJoonsoo Kim 		}
70658420016SJoonsoo Kim 
707e1409c32SJoonsoo Kim 		if (!pageblock_pfn_to_page(block_start_pfn,
708e1409c32SJoonsoo Kim 					block_end_pfn, cc->zone))
7097d49d886SVlastimil Babka 			break;
7107d49d886SVlastimil Babka 
711e14c720eSVlastimil Babka 		isolated = isolate_freepages_block(cc, &isolate_start_pfn,
7124fca9730SMel Gorman 					block_end_pfn, &freelist, 0, true);
71385aa125fSMichal Nazarewicz 
71485aa125fSMichal Nazarewicz 		/*
71585aa125fSMichal Nazarewicz 		 * In strict mode, isolate_freepages_block() returns 0 if
71685aa125fSMichal Nazarewicz 		 * there are any holes in the block (ie. invalid PFNs or
71785aa125fSMichal Nazarewicz 		 * non-free pages).
71885aa125fSMichal Nazarewicz 		 */
71985aa125fSMichal Nazarewicz 		if (!isolated)
72085aa125fSMichal Nazarewicz 			break;
72185aa125fSMichal Nazarewicz 
72285aa125fSMichal Nazarewicz 		/*
72385aa125fSMichal Nazarewicz 		 * If we managed to isolate pages, it is always (1 << n) *
72485aa125fSMichal Nazarewicz 		 * pageblock_nr_pages for some non-negative n.  (Max order
72585aa125fSMichal Nazarewicz 		 * page may span two pageblocks).
72685aa125fSMichal Nazarewicz 		 */
72785aa125fSMichal Nazarewicz 	}
72885aa125fSMichal Nazarewicz 
72966c64223SJoonsoo Kim 	/* __isolate_free_page() does not map the pages */
7304469ab98SMel Gorman 	split_map_pages(&freelist);
73185aa125fSMichal Nazarewicz 
73285aa125fSMichal Nazarewicz 	if (pfn < end_pfn) {
73385aa125fSMichal Nazarewicz 		/* Loop terminated early, cleanup. */
73485aa125fSMichal Nazarewicz 		release_freepages(&freelist);
73585aa125fSMichal Nazarewicz 		return 0;
73685aa125fSMichal Nazarewicz 	}
73785aa125fSMichal Nazarewicz 
73885aa125fSMichal Nazarewicz 	/* We don't use freelists for anything. */
73985aa125fSMichal Nazarewicz 	return pfn;
74085aa125fSMichal Nazarewicz }
74185aa125fSMichal Nazarewicz 
742748446bbSMel Gorman /* Similar to reclaim, but different enough that they don't share logic */
743*4fbbb3fdSJohannes Weiner static bool too_many_isolated(struct compact_control *cc)
744748446bbSMel Gorman {
745*4fbbb3fdSJohannes Weiner 	pg_data_t *pgdat = cc->zone->zone_pgdat;
746d818fca1SMel Gorman 	bool too_many;
747d818fca1SMel Gorman 
748bc693045SMinchan Kim 	unsigned long active, inactive, isolated;
749748446bbSMel Gorman 
7505f438eeeSAndrey Ryabinin 	inactive = node_page_state(pgdat, NR_INACTIVE_FILE) +
7515f438eeeSAndrey Ryabinin 			node_page_state(pgdat, NR_INACTIVE_ANON);
7525f438eeeSAndrey Ryabinin 	active = node_page_state(pgdat, NR_ACTIVE_FILE) +
7535f438eeeSAndrey Ryabinin 			node_page_state(pgdat, NR_ACTIVE_ANON);
7545f438eeeSAndrey Ryabinin 	isolated = node_page_state(pgdat, NR_ISOLATED_FILE) +
7555f438eeeSAndrey Ryabinin 			node_page_state(pgdat, NR_ISOLATED_ANON);
756748446bbSMel Gorman 
757*4fbbb3fdSJohannes Weiner 	/*
758*4fbbb3fdSJohannes Weiner 	 * Allow GFP_NOFS to isolate past the limit set for regular
759*4fbbb3fdSJohannes Weiner 	 * compaction runs. This prevents an ABBA deadlock when other
760*4fbbb3fdSJohannes Weiner 	 * compactors have already isolated to the limit, but are
761*4fbbb3fdSJohannes Weiner 	 * blocked on filesystem locks held by the GFP_NOFS thread.
762*4fbbb3fdSJohannes Weiner 	 */
763*4fbbb3fdSJohannes Weiner 	if (cc->gfp_mask & __GFP_FS) {
764*4fbbb3fdSJohannes Weiner 		inactive >>= 3;
765*4fbbb3fdSJohannes Weiner 		active >>= 3;
766*4fbbb3fdSJohannes Weiner 	}
767*4fbbb3fdSJohannes Weiner 
768d818fca1SMel Gorman 	too_many = isolated > (inactive + active) / 2;
769d818fca1SMel Gorman 	if (!too_many)
770d818fca1SMel Gorman 		wake_throttle_isolated(pgdat);
771d818fca1SMel Gorman 
772d818fca1SMel Gorman 	return too_many;
773748446bbSMel Gorman }
774748446bbSMel Gorman 
7752fe86e00SMichal Nazarewicz /**
776edc2ca61SVlastimil Babka  * isolate_migratepages_block() - isolate all migrate-able pages within
777edc2ca61SVlastimil Babka  *				  a single pageblock
7782fe86e00SMichal Nazarewicz  * @cc:		Compaction control structure.
779edc2ca61SVlastimil Babka  * @low_pfn:	The first PFN to isolate
780edc2ca61SVlastimil Babka  * @end_pfn:	The one-past-the-last PFN to isolate, within same pageblock
78189f6c88aSHugh Dickins  * @mode:	Isolation mode to be used.
7822fe86e00SMichal Nazarewicz  *
7832fe86e00SMichal Nazarewicz  * Isolate all pages that can be migrated from the range specified by
784edc2ca61SVlastimil Babka  * [low_pfn, end_pfn). The range is expected to be within same pageblock.
785c2ad7a1fSOscar Salvador  * Returns errno, like -EAGAIN or -EINTR in case e.g signal pending or congestion,
786369fa227SOscar Salvador  * -ENOMEM in case we could not allocate a page, or 0.
787c2ad7a1fSOscar Salvador  * cc->migrate_pfn will contain the next pfn to scan.
7882fe86e00SMichal Nazarewicz  *
789edc2ca61SVlastimil Babka  * The pages are isolated on cc->migratepages list (not required to be empty),
790c2ad7a1fSOscar Salvador  * and cc->nr_migratepages is updated accordingly.
791748446bbSMel Gorman  */
792c2ad7a1fSOscar Salvador static int
793edc2ca61SVlastimil Babka isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
79489f6c88aSHugh Dickins 			unsigned long end_pfn, isolate_mode_t mode)
795748446bbSMel Gorman {
7965f438eeeSAndrey Ryabinin 	pg_data_t *pgdat = cc->zone->zone_pgdat;
797b7aba698SMel Gorman 	unsigned long nr_scanned = 0, nr_isolated = 0;
798fa9add64SHugh Dickins 	struct lruvec *lruvec;
799b8b2d825SXiubo Li 	unsigned long flags = 0;
8006168d0daSAlex Shi 	struct lruvec *locked = NULL;
801bb13ffebSMel Gorman 	struct page *page = NULL, *valid_page = NULL;
80289f6c88aSHugh Dickins 	struct address_space *mapping;
803e34d85f0SJoonsoo Kim 	unsigned long start_pfn = low_pfn;
804fdd048e1SVlastimil Babka 	bool skip_on_failure = false;
805fdd048e1SVlastimil Babka 	unsigned long next_skip_pfn = 0;
806e380bebeSMel Gorman 	bool skip_updated = false;
807c2ad7a1fSOscar Salvador 	int ret = 0;
808c2ad7a1fSOscar Salvador 
809c2ad7a1fSOscar Salvador 	cc->migrate_pfn = low_pfn;
810748446bbSMel Gorman 
811748446bbSMel Gorman 	/*
812748446bbSMel Gorman 	 * Ensure that there are not too many pages isolated from the LRU
813748446bbSMel Gorman 	 * list by either parallel reclaimers or compaction. If there are,
814748446bbSMel Gorman 	 * delay for some time until fewer pages are isolated
815748446bbSMel Gorman 	 */
816*4fbbb3fdSJohannes Weiner 	while (unlikely(too_many_isolated(cc))) {
817d20bdd57SZi Yan 		/* stop isolation if there are still pages not migrated */
818d20bdd57SZi Yan 		if (cc->nr_migratepages)
819c2ad7a1fSOscar Salvador 			return -EAGAIN;
820d20bdd57SZi Yan 
821f9e35b3bSMel Gorman 		/* async migration should just abort */
822e0b9daebSDavid Rientjes 		if (cc->mode == MIGRATE_ASYNC)
823c2ad7a1fSOscar Salvador 			return -EAGAIN;
824f9e35b3bSMel Gorman 
825c3f4a9a2SMel Gorman 		reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
826748446bbSMel Gorman 
827748446bbSMel Gorman 		if (fatal_signal_pending(current))
828c2ad7a1fSOscar Salvador 			return -EINTR;
829748446bbSMel Gorman 	}
830748446bbSMel Gorman 
831cf66f070SMel Gorman 	cond_resched();
832aeef4b83SDavid Rientjes 
833fdd048e1SVlastimil Babka 	if (cc->direct_compaction && (cc->mode == MIGRATE_ASYNC)) {
834fdd048e1SVlastimil Babka 		skip_on_failure = true;
835fdd048e1SVlastimil Babka 		next_skip_pfn = block_end_pfn(low_pfn, cc->order);
836fdd048e1SVlastimil Babka 	}
837fdd048e1SVlastimil Babka 
838748446bbSMel Gorman 	/* Time to isolate some pages for migration */
839748446bbSMel Gorman 	for (; low_pfn < end_pfn; low_pfn++) {
84029c0dde8SVlastimil Babka 
841fdd048e1SVlastimil Babka 		if (skip_on_failure && low_pfn >= next_skip_pfn) {
842fdd048e1SVlastimil Babka 			/*
843fdd048e1SVlastimil Babka 			 * We have isolated all migration candidates in the
844fdd048e1SVlastimil Babka 			 * previous order-aligned block, and did not skip it due
845fdd048e1SVlastimil Babka 			 * to failure. We should migrate the pages now and
846fdd048e1SVlastimil Babka 			 * hopefully succeed compaction.
847fdd048e1SVlastimil Babka 			 */
848fdd048e1SVlastimil Babka 			if (nr_isolated)
849fdd048e1SVlastimil Babka 				break;
850fdd048e1SVlastimil Babka 
851fdd048e1SVlastimil Babka 			/*
852fdd048e1SVlastimil Babka 			 * We failed to isolate in the previous order-aligned
853fdd048e1SVlastimil Babka 			 * block. Set the new boundary to the end of the
854fdd048e1SVlastimil Babka 			 * current block. Note we can't simply increase
855fdd048e1SVlastimil Babka 			 * next_skip_pfn by 1 << order, as low_pfn might have
856fdd048e1SVlastimil Babka 			 * been incremented by a higher number due to skipping
857fdd048e1SVlastimil Babka 			 * a compound or a high-order buddy page in the
858fdd048e1SVlastimil Babka 			 * previous loop iteration.
859fdd048e1SVlastimil Babka 			 */
860fdd048e1SVlastimil Babka 			next_skip_pfn = block_end_pfn(low_pfn, cc->order);
861fdd048e1SVlastimil Babka 		}
862fdd048e1SVlastimil Babka 
8638b44d279SVlastimil Babka 		/*
8648b44d279SVlastimil Babka 		 * Periodically drop the lock (if held) regardless of its
865670105a2SMel Gorman 		 * contention, to give chance to IRQs. Abort completely if
866670105a2SMel Gorman 		 * a fatal signal is pending.
8678b44d279SVlastimil Babka 		 */
868c036ddffSMiaohe Lin 		if (!(low_pfn % COMPACT_CLUSTER_MAX)) {
8696168d0daSAlex Shi 			if (locked) {
8706168d0daSAlex Shi 				unlock_page_lruvec_irqrestore(locked, flags);
8716168d0daSAlex Shi 				locked = NULL;
8726168d0daSAlex Shi 			}
8736168d0daSAlex Shi 
8746168d0daSAlex Shi 			if (fatal_signal_pending(current)) {
8756168d0daSAlex Shi 				cc->contended = true;
876c2ad7a1fSOscar Salvador 				ret = -EINTR;
8776168d0daSAlex Shi 
878670105a2SMel Gorman 				goto fatal_pending;
879670105a2SMel Gorman 			}
880b2eef8c0SAndrea Arcangeli 
8816168d0daSAlex Shi 			cond_resched();
8826168d0daSAlex Shi 		}
8836168d0daSAlex Shi 
884b7aba698SMel Gorman 		nr_scanned++;
885748446bbSMel Gorman 
886748446bbSMel Gorman 		page = pfn_to_page(low_pfn);
887dc908600SMel Gorman 
888e380bebeSMel Gorman 		/*
889e380bebeSMel Gorman 		 * Check if the pageblock has already been marked skipped.
890e380bebeSMel Gorman 		 * Only the aligned PFN is checked as the caller isolates
891e380bebeSMel Gorman 		 * COMPACT_CLUSTER_MAX at a time so the second call must
892e380bebeSMel Gorman 		 * not falsely conclude that the block should be skipped.
893e380bebeSMel Gorman 		 */
894ee0913c4SKefeng Wang 		if (!valid_page && pageblock_aligned(low_pfn)) {
8954af12d04SMiaohe Lin 			if (!isolation_suitable(cc, page)) {
896e380bebeSMel Gorman 				low_pfn = end_pfn;
8979df41314SAlex Shi 				page = NULL;
898e380bebeSMel Gorman 				goto isolate_abort;
899e380bebeSMel Gorman 			}
900bb13ffebSMel Gorman 			valid_page = page;
901e380bebeSMel Gorman 		}
902bb13ffebSMel Gorman 
903369fa227SOscar Salvador 		if (PageHuge(page) && cc->alloc_contig) {
9041c06b6a5SBaolin Wang 			if (locked) {
9051c06b6a5SBaolin Wang 				unlock_page_lruvec_irqrestore(locked, flags);
9061c06b6a5SBaolin Wang 				locked = NULL;
9071c06b6a5SBaolin Wang 			}
9081c06b6a5SBaolin Wang 
909ae37c7ffSOscar Salvador 			ret = isolate_or_dissolve_huge_page(page, &cc->migratepages);
910369fa227SOscar Salvador 
911369fa227SOscar Salvador 			/*
912369fa227SOscar Salvador 			 * Fail isolation in case isolate_or_dissolve_huge_page()
913369fa227SOscar Salvador 			 * reports an error. In case of -ENOMEM, abort right away.
914369fa227SOscar Salvador 			 */
915369fa227SOscar Salvador 			if (ret < 0) {
916369fa227SOscar Salvador 				 /* Do not report -EBUSY down the chain */
917369fa227SOscar Salvador 				if (ret == -EBUSY)
918369fa227SOscar Salvador 					ret = 0;
91966fe1cf7SMiaohe Lin 				low_pfn += compound_nr(page) - 1;
92056d48d8dSBaolin Wang 				nr_scanned += compound_nr(page) - 1;
921369fa227SOscar Salvador 				goto isolate_fail;
922369fa227SOscar Salvador 			}
923369fa227SOscar Salvador 
924ae37c7ffSOscar Salvador 			if (PageHuge(page)) {
925ae37c7ffSOscar Salvador 				/*
926ae37c7ffSOscar Salvador 				 * Hugepage was successfully isolated and placed
927ae37c7ffSOscar Salvador 				 * on the cc->migratepages list.
928ae37c7ffSOscar Salvador 				 */
929ae37c7ffSOscar Salvador 				low_pfn += compound_nr(page) - 1;
930ae37c7ffSOscar Salvador 				goto isolate_success_no_list;
931ae37c7ffSOscar Salvador 			}
932ae37c7ffSOscar Salvador 
933369fa227SOscar Salvador 			/*
934369fa227SOscar Salvador 			 * Ok, the hugepage was dissolved. Now these pages are
935369fa227SOscar Salvador 			 * Buddy and cannot be re-allocated because they are
936369fa227SOscar Salvador 			 * isolated. Fall-through as the check below handles
937369fa227SOscar Salvador 			 * Buddy pages.
938369fa227SOscar Salvador 			 */
939369fa227SOscar Salvador 		}
940369fa227SOscar Salvador 
941c122b208SJoonsoo Kim 		/*
94299c0fd5eSVlastimil Babka 		 * Skip if free. We read page order here without zone lock
94399c0fd5eSVlastimil Babka 		 * which is generally unsafe, but the race window is small and
94499c0fd5eSVlastimil Babka 		 * the worst thing that can happen is that we skip some
94599c0fd5eSVlastimil Babka 		 * potential isolation targets.
9466c14466cSMel Gorman 		 */
94799c0fd5eSVlastimil Babka 		if (PageBuddy(page)) {
948ab130f91SMatthew Wilcox (Oracle) 			unsigned long freepage_order = buddy_order_unsafe(page);
94999c0fd5eSVlastimil Babka 
95099c0fd5eSVlastimil Babka 			/*
95199c0fd5eSVlastimil Babka 			 * Without lock, we cannot be sure that what we got is
95299c0fd5eSVlastimil Babka 			 * a valid page order. Consider only values in the
95399c0fd5eSVlastimil Babka 			 * valid order range to prevent low_pfn overflow.
95499c0fd5eSVlastimil Babka 			 */
95556d48d8dSBaolin Wang 			if (freepage_order > 0 && freepage_order <= MAX_ORDER) {
95699c0fd5eSVlastimil Babka 				low_pfn += (1UL << freepage_order) - 1;
95756d48d8dSBaolin Wang 				nr_scanned += (1UL << freepage_order) - 1;
95856d48d8dSBaolin Wang 			}
959748446bbSMel Gorman 			continue;
96099c0fd5eSVlastimil Babka 		}
961748446bbSMel Gorman 
9629927af74SMel Gorman 		/*
96329c0dde8SVlastimil Babka 		 * Regardless of being on LRU, compound pages such as THP and
9641da2f328SRik van Riel 		 * hugetlbfs are not to be compacted unless we are attempting
9651da2f328SRik van Riel 		 * an allocation much larger than the huge page size (eg CMA).
9661da2f328SRik van Riel 		 * We can potentially save a lot of iterations if we skip them
9671da2f328SRik van Riel 		 * at once. The check is racy, but we can consider only valid
9681da2f328SRik van Riel 		 * values and the only danger is skipping too much.
969bc835011SAndrea Arcangeli 		 */
9701da2f328SRik van Riel 		if (PageCompound(page) && !cc->alloc_contig) {
97121dc7e02SDavid Rientjes 			const unsigned int order = compound_order(page);
97229c0dde8SVlastimil Babka 
97356d48d8dSBaolin Wang 			if (likely(order <= MAX_ORDER)) {
97421dc7e02SDavid Rientjes 				low_pfn += (1UL << order) - 1;
97556d48d8dSBaolin Wang 				nr_scanned += (1UL << order) - 1;
97656d48d8dSBaolin Wang 			}
977fdd048e1SVlastimil Babka 			goto isolate_fail;
9782a1402aaSMel Gorman 		}
9792a1402aaSMel Gorman 
980bda807d4SMinchan Kim 		/*
981bda807d4SMinchan Kim 		 * Check may be lockless but that's ok as we recheck later.
982bda807d4SMinchan Kim 		 * It's possible to migrate LRU and non-lru movable pages.
983bda807d4SMinchan Kim 		 * Skip any other type of page
984bda807d4SMinchan Kim 		 */
985bda807d4SMinchan Kim 		if (!PageLRU(page)) {
986bda807d4SMinchan Kim 			/*
987bda807d4SMinchan Kim 			 * __PageMovable can return false positive so we need
988bda807d4SMinchan Kim 			 * to verify it under page_lock.
989bda807d4SMinchan Kim 			 */
990bda807d4SMinchan Kim 			if (unlikely(__PageMovable(page)) &&
991bda807d4SMinchan Kim 					!PageIsolated(page)) {
992bda807d4SMinchan Kim 				if (locked) {
9936168d0daSAlex Shi 					unlock_page_lruvec_irqrestore(locked, flags);
9946168d0daSAlex Shi 					locked = NULL;
995bda807d4SMinchan Kim 				}
996bda807d4SMinchan Kim 
997cd775580SBaolin Wang 				if (isolate_movable_page(page, mode))
998bda807d4SMinchan Kim 					goto isolate_success;
999bda807d4SMinchan Kim 			}
1000bda807d4SMinchan Kim 
1001fdd048e1SVlastimil Babka 			goto isolate_fail;
1002bda807d4SMinchan Kim 		}
100329c0dde8SVlastimil Babka 
1004119d6d59SDavid Rientjes 		/*
10059df41314SAlex Shi 		 * Be careful not to clear PageLRU until after we're
10069df41314SAlex Shi 		 * sure the page is not being freed elsewhere -- the
10079df41314SAlex Shi 		 * page release code relies on it.
10089df41314SAlex Shi 		 */
10099df41314SAlex Shi 		if (unlikely(!get_page_unless_zero(page)))
10109df41314SAlex Shi 			goto isolate_fail;
10119df41314SAlex Shi 
1012829ae0f8SGavin Shan 		/*
1013829ae0f8SGavin Shan 		 * Migration will fail if an anonymous page is pinned in memory,
1014829ae0f8SGavin Shan 		 * so avoid taking lru_lock and isolating it unnecessarily in an
1015829ae0f8SGavin Shan 		 * admittedly racy check.
1016829ae0f8SGavin Shan 		 */
1017829ae0f8SGavin Shan 		mapping = page_mapping(page);
1018829ae0f8SGavin Shan 		if (!mapping && (page_count(page) - 1) > total_mapcount(page))
1019829ae0f8SGavin Shan 			goto isolate_fail_put;
1020829ae0f8SGavin Shan 
1021829ae0f8SGavin Shan 		/*
1022829ae0f8SGavin Shan 		 * Only allow to migrate anonymous pages in GFP_NOFS context
1023829ae0f8SGavin Shan 		 * because those do not depend on fs locks.
1024829ae0f8SGavin Shan 		 */
1025829ae0f8SGavin Shan 		if (!(cc->gfp_mask & __GFP_FS) && mapping)
1026829ae0f8SGavin Shan 			goto isolate_fail_put;
1027829ae0f8SGavin Shan 
102889f6c88aSHugh Dickins 		/* Only take pages on LRU: a check now makes later tests safe */
102989f6c88aSHugh Dickins 		if (!PageLRU(page))
10309df41314SAlex Shi 			goto isolate_fail_put;
10319df41314SAlex Shi 
103289f6c88aSHugh Dickins 		/* Compaction might skip unevictable pages but CMA takes them */
103389f6c88aSHugh Dickins 		if (!(mode & ISOLATE_UNEVICTABLE) && PageUnevictable(page))
103489f6c88aSHugh Dickins 			goto isolate_fail_put;
103589f6c88aSHugh Dickins 
103689f6c88aSHugh Dickins 		/*
103789f6c88aSHugh Dickins 		 * To minimise LRU disruption, the caller can indicate with
103889f6c88aSHugh Dickins 		 * ISOLATE_ASYNC_MIGRATE that it only wants to isolate pages
103989f6c88aSHugh Dickins 		 * it will be able to migrate without blocking - clean pages
104089f6c88aSHugh Dickins 		 * for the most part.  PageWriteback would require blocking.
104189f6c88aSHugh Dickins 		 */
104289f6c88aSHugh Dickins 		if ((mode & ISOLATE_ASYNC_MIGRATE) && PageWriteback(page))
104389f6c88aSHugh Dickins 			goto isolate_fail_put;
104489f6c88aSHugh Dickins 
104589f6c88aSHugh Dickins 		if ((mode & ISOLATE_ASYNC_MIGRATE) && PageDirty(page)) {
104689f6c88aSHugh Dickins 			bool migrate_dirty;
104789f6c88aSHugh Dickins 
104889f6c88aSHugh Dickins 			/*
104989f6c88aSHugh Dickins 			 * Only pages without mappings or that have a
10509d0ddc0cSMatthew Wilcox (Oracle) 			 * ->migrate_folio callback are possible to migrate
105189f6c88aSHugh Dickins 			 * without blocking. However, we can be racing with
105289f6c88aSHugh Dickins 			 * truncation so it's necessary to lock the page
105389f6c88aSHugh Dickins 			 * to stabilise the mapping as truncation holds
105489f6c88aSHugh Dickins 			 * the page lock until after the page is removed
105589f6c88aSHugh Dickins 			 * from the page cache.
105689f6c88aSHugh Dickins 			 */
105789f6c88aSHugh Dickins 			if (!trylock_page(page))
105889f6c88aSHugh Dickins 				goto isolate_fail_put;
105989f6c88aSHugh Dickins 
106089f6c88aSHugh Dickins 			mapping = page_mapping(page);
10615490da4fSMatthew Wilcox (Oracle) 			migrate_dirty = !mapping ||
10629d0ddc0cSMatthew Wilcox (Oracle) 					mapping->a_ops->migrate_folio;
106389f6c88aSHugh Dickins 			unlock_page(page);
106489f6c88aSHugh Dickins 			if (!migrate_dirty)
106589f6c88aSHugh Dickins 				goto isolate_fail_put;
106689f6c88aSHugh Dickins 		}
106789f6c88aSHugh Dickins 
10689df41314SAlex Shi 		/* Try isolate the page */
10699df41314SAlex Shi 		if (!TestClearPageLRU(page))
10709df41314SAlex Shi 			goto isolate_fail_put;
10719df41314SAlex Shi 
1072b1baabd9SMatthew Wilcox (Oracle) 		lruvec = folio_lruvec(page_folio(page));
10736168d0daSAlex Shi 
107469b7189fSVlastimil Babka 		/* If we already hold the lock, we can skip some rechecking */
10756168d0daSAlex Shi 		if (lruvec != locked) {
10766168d0daSAlex Shi 			if (locked)
10776168d0daSAlex Shi 				unlock_page_lruvec_irqrestore(locked, flags);
10786168d0daSAlex Shi 
10796168d0daSAlex Shi 			compact_lock_irqsave(&lruvec->lru_lock, &flags, cc);
10806168d0daSAlex Shi 			locked = lruvec;
10816168d0daSAlex Shi 
1082e809c3feSMatthew Wilcox (Oracle) 			lruvec_memcg_debug(lruvec, page_folio(page));
1083e380bebeSMel Gorman 
1084590ccea8SMel Gorman 			/*
1085590ccea8SMel Gorman 			 * Try get exclusive access under lock. If marked for
1086590ccea8SMel Gorman 			 * skip, the scan is aborted unless the current context
1087590ccea8SMel Gorman 			 * is a rescan to reach the end of the pageblock.
1088590ccea8SMel Gorman 			 */
1089590ccea8SMel Gorman 			if (!skip_updated && valid_page) {
1090e380bebeSMel Gorman 				skip_updated = true;
1091590ccea8SMel Gorman 				if (test_and_set_skip(cc, valid_page) &&
1092590ccea8SMel Gorman 				    !cc->finish_pageblock) {
1093e380bebeSMel Gorman 					goto isolate_abort;
1094e380bebeSMel Gorman 				}
1095590ccea8SMel Gorman 			}
10962a1402aaSMel Gorman 
109729c0dde8SVlastimil Babka 			/*
109829c0dde8SVlastimil Babka 			 * Page become compound since the non-locked check,
109929c0dde8SVlastimil Babka 			 * and it's on LRU. It can only be a THP so the order
110029c0dde8SVlastimil Babka 			 * is safe to read and it's 0 for tail pages.
110129c0dde8SVlastimil Babka 			 */
11021da2f328SRik van Riel 			if (unlikely(PageCompound(page) && !cc->alloc_contig)) {
1103d8c6546bSMatthew Wilcox (Oracle) 				low_pfn += compound_nr(page) - 1;
110456d48d8dSBaolin Wang 				nr_scanned += compound_nr(page) - 1;
11059df41314SAlex Shi 				SetPageLRU(page);
11069df41314SAlex Shi 				goto isolate_fail_put;
1107bc835011SAndrea Arcangeli 			}
1108d99fd5feSAlex Shi 		}
1109fa9add64SHugh Dickins 
11101da2f328SRik van Riel 		/* The whole page is taken off the LRU; skip the tail pages. */
11111da2f328SRik van Riel 		if (PageCompound(page))
11121da2f328SRik van Riel 			low_pfn += compound_nr(page) - 1;
1113bc835011SAndrea Arcangeli 
1114748446bbSMel Gorman 		/* Successfully isolated */
111546ae6b2cSYu Zhao 		del_page_from_lru_list(page, lruvec);
11161da2f328SRik van Riel 		mod_node_page_state(page_pgdat(page),
11179de4f22aSHuang Ying 				NR_ISOLATED_ANON + page_is_file_lru(page),
11186c357848SMatthew Wilcox (Oracle) 				thp_nr_pages(page));
1119b6c75016SJoonsoo Kim 
1120b6c75016SJoonsoo Kim isolate_success:
1121fdd048e1SVlastimil Babka 		list_add(&page->lru, &cc->migratepages);
1122ae37c7ffSOscar Salvador isolate_success_no_list:
112338935861SZi Yan 		cc->nr_migratepages += compound_nr(page);
112438935861SZi Yan 		nr_isolated += compound_nr(page);
1125b717d6b9SWilliam Lam 		nr_scanned += compound_nr(page) - 1;
1126748446bbSMel Gorman 
1127804d3121SMel Gorman 		/*
1128804d3121SMel Gorman 		 * Avoid isolating too much unless this block is being
112948731c84SMel Gorman 		 * fully scanned (e.g. dirty/writeback pages, parallel allocation)
1130cb2dcaf0SMel Gorman 		 * or a lock is contended. For contention, isolate quickly to
1131cb2dcaf0SMel Gorman 		 * potentially remove one source of contention.
1132804d3121SMel Gorman 		 */
113338935861SZi Yan 		if (cc->nr_migratepages >= COMPACT_CLUSTER_MAX &&
113448731c84SMel Gorman 		    !cc->finish_pageblock && !cc->contended) {
113531b8384aSHillf Danton 			++low_pfn;
1136748446bbSMel Gorman 			break;
1137748446bbSMel Gorman 		}
1138fdd048e1SVlastimil Babka 
1139fdd048e1SVlastimil Babka 		continue;
11409df41314SAlex Shi 
11419df41314SAlex Shi isolate_fail_put:
11429df41314SAlex Shi 		/* Avoid potential deadlock in freeing page under lru_lock */
11439df41314SAlex Shi 		if (locked) {
11446168d0daSAlex Shi 			unlock_page_lruvec_irqrestore(locked, flags);
11456168d0daSAlex Shi 			locked = NULL;
11469df41314SAlex Shi 		}
11479df41314SAlex Shi 		put_page(page);
11489df41314SAlex Shi 
1149fdd048e1SVlastimil Babka isolate_fail:
1150369fa227SOscar Salvador 		if (!skip_on_failure && ret != -ENOMEM)
1151fdd048e1SVlastimil Babka 			continue;
1152fdd048e1SVlastimil Babka 
1153fdd048e1SVlastimil Babka 		/*
1154fdd048e1SVlastimil Babka 		 * We have isolated some pages, but then failed. Release them
1155fdd048e1SVlastimil Babka 		 * instead of migrating, as we cannot form the cc->order buddy
1156fdd048e1SVlastimil Babka 		 * page anyway.
1157fdd048e1SVlastimil Babka 		 */
1158fdd048e1SVlastimil Babka 		if (nr_isolated) {
1159fdd048e1SVlastimil Babka 			if (locked) {
11606168d0daSAlex Shi 				unlock_page_lruvec_irqrestore(locked, flags);
11616168d0daSAlex Shi 				locked = NULL;
1162fdd048e1SVlastimil Babka 			}
1163fdd048e1SVlastimil Babka 			putback_movable_pages(&cc->migratepages);
1164fdd048e1SVlastimil Babka 			cc->nr_migratepages = 0;
1165fdd048e1SVlastimil Babka 			nr_isolated = 0;
1166fdd048e1SVlastimil Babka 		}
1167fdd048e1SVlastimil Babka 
1168fdd048e1SVlastimil Babka 		if (low_pfn < next_skip_pfn) {
1169fdd048e1SVlastimil Babka 			low_pfn = next_skip_pfn - 1;
1170fdd048e1SVlastimil Babka 			/*
1171fdd048e1SVlastimil Babka 			 * The check near the loop beginning would have updated
1172fdd048e1SVlastimil Babka 			 * next_skip_pfn too, but this is a bit simpler.
1173fdd048e1SVlastimil Babka 			 */
1174fdd048e1SVlastimil Babka 			next_skip_pfn += 1UL << cc->order;
1175fdd048e1SVlastimil Babka 		}
1176369fa227SOscar Salvador 
1177369fa227SOscar Salvador 		if (ret == -ENOMEM)
1178369fa227SOscar Salvador 			break;
117931b8384aSHillf Danton 	}
1180748446bbSMel Gorman 
118199c0fd5eSVlastimil Babka 	/*
118299c0fd5eSVlastimil Babka 	 * The PageBuddy() check could have potentially brought us outside
118399c0fd5eSVlastimil Babka 	 * the range to be scanned.
118499c0fd5eSVlastimil Babka 	 */
118599c0fd5eSVlastimil Babka 	if (unlikely(low_pfn > end_pfn))
118699c0fd5eSVlastimil Babka 		low_pfn = end_pfn;
118799c0fd5eSVlastimil Babka 
11889df41314SAlex Shi 	page = NULL;
11899df41314SAlex Shi 
1190e380bebeSMel Gorman isolate_abort:
1191c67fe375SMel Gorman 	if (locked)
11926168d0daSAlex Shi 		unlock_page_lruvec_irqrestore(locked, flags);
11939df41314SAlex Shi 	if (page) {
11949df41314SAlex Shi 		SetPageLRU(page);
11959df41314SAlex Shi 		put_page(page);
11969df41314SAlex Shi 	}
1197748446bbSMel Gorman 
119850b5b094SVlastimil Babka 	/*
119948731c84SMel Gorman 	 * Update the cached scanner pfn once the pageblock has been scanned.
1200804d3121SMel Gorman 	 * Pages will either be migrated in which case there is no point
1201804d3121SMel Gorman 	 * scanning in the near future or migration failed in which case the
1202804d3121SMel Gorman 	 * failure reason may persist. The block is marked for skipping if
1203804d3121SMel Gorman 	 * there were no pages isolated in the block or if the block is
1204804d3121SMel Gorman 	 * rescanned twice in a row.
120550b5b094SVlastimil Babka 	 */
120648731c84SMel Gorman 	if (low_pfn == end_pfn && (!nr_isolated || cc->finish_pageblock)) {
1207e380bebeSMel Gorman 		if (valid_page && !skip_updated)
1208e380bebeSMel Gorman 			set_pageblock_skip(valid_page);
1209e380bebeSMel Gorman 		update_cached_migrate(cc, low_pfn);
1210e380bebeSMel Gorman 	}
1211bb13ffebSMel Gorman 
1212e34d85f0SJoonsoo Kim 	trace_mm_compaction_isolate_migratepages(start_pfn, low_pfn,
1213e34d85f0SJoonsoo Kim 						nr_scanned, nr_isolated);
1214b7aba698SMel Gorman 
1215670105a2SMel Gorman fatal_pending:
12167f354a54SDavid Rientjes 	cc->total_migrate_scanned += nr_scanned;
1217397487dbSMel Gorman 	if (nr_isolated)
1218010fc29aSMinchan Kim 		count_compact_events(COMPACTISOLATED, nr_isolated);
1219397487dbSMel Gorman 
1220c2ad7a1fSOscar Salvador 	cc->migrate_pfn = low_pfn;
1221c2ad7a1fSOscar Salvador 
1222c2ad7a1fSOscar Salvador 	return ret;
12232fe86e00SMichal Nazarewicz }
12242fe86e00SMichal Nazarewicz 
1225edc2ca61SVlastimil Babka /**
1226edc2ca61SVlastimil Babka  * isolate_migratepages_range() - isolate migrate-able pages in a PFN range
1227edc2ca61SVlastimil Babka  * @cc:        Compaction control structure.
1228edc2ca61SVlastimil Babka  * @start_pfn: The first PFN to start isolating.
1229edc2ca61SVlastimil Babka  * @end_pfn:   The one-past-last PFN.
1230edc2ca61SVlastimil Babka  *
1231369fa227SOscar Salvador  * Returns -EAGAIN when contented, -EINTR in case of a signal pending, -ENOMEM
1232369fa227SOscar Salvador  * in case we could not allocate a page, or 0.
1233edc2ca61SVlastimil Babka  */
1234c2ad7a1fSOscar Salvador int
1235edc2ca61SVlastimil Babka isolate_migratepages_range(struct compact_control *cc, unsigned long start_pfn,
1236edc2ca61SVlastimil Babka 							unsigned long end_pfn)
1237edc2ca61SVlastimil Babka {
1238e1409c32SJoonsoo Kim 	unsigned long pfn, block_start_pfn, block_end_pfn;
1239c2ad7a1fSOscar Salvador 	int ret = 0;
1240edc2ca61SVlastimil Babka 
1241edc2ca61SVlastimil Babka 	/* Scan block by block. First and last block may be incomplete */
1242edc2ca61SVlastimil Babka 	pfn = start_pfn;
124306b6640aSVlastimil Babka 	block_start_pfn = pageblock_start_pfn(pfn);
1244e1409c32SJoonsoo Kim 	if (block_start_pfn < cc->zone->zone_start_pfn)
1245e1409c32SJoonsoo Kim 		block_start_pfn = cc->zone->zone_start_pfn;
124606b6640aSVlastimil Babka 	block_end_pfn = pageblock_end_pfn(pfn);
1247edc2ca61SVlastimil Babka 
1248edc2ca61SVlastimil Babka 	for (; pfn < end_pfn; pfn = block_end_pfn,
1249e1409c32SJoonsoo Kim 				block_start_pfn = block_end_pfn,
1250edc2ca61SVlastimil Babka 				block_end_pfn += pageblock_nr_pages) {
1251edc2ca61SVlastimil Babka 
1252edc2ca61SVlastimil Babka 		block_end_pfn = min(block_end_pfn, end_pfn);
1253edc2ca61SVlastimil Babka 
1254e1409c32SJoonsoo Kim 		if (!pageblock_pfn_to_page(block_start_pfn,
1255e1409c32SJoonsoo Kim 					block_end_pfn, cc->zone))
1256edc2ca61SVlastimil Babka 			continue;
1257edc2ca61SVlastimil Babka 
1258c2ad7a1fSOscar Salvador 		ret = isolate_migratepages_block(cc, pfn, block_end_pfn,
1259edc2ca61SVlastimil Babka 						 ISOLATE_UNEVICTABLE);
1260edc2ca61SVlastimil Babka 
1261c2ad7a1fSOscar Salvador 		if (ret)
1262edc2ca61SVlastimil Babka 			break;
12636ea41c0cSJoonsoo Kim 
126438935861SZi Yan 		if (cc->nr_migratepages >= COMPACT_CLUSTER_MAX)
12656ea41c0cSJoonsoo Kim 			break;
1266edc2ca61SVlastimil Babka 	}
1267edc2ca61SVlastimil Babka 
1268c2ad7a1fSOscar Salvador 	return ret;
1269edc2ca61SVlastimil Babka }
1270edc2ca61SVlastimil Babka 
1271ff9543fdSMichal Nazarewicz #endif /* CONFIG_COMPACTION || CONFIG_CMA */
1272ff9543fdSMichal Nazarewicz #ifdef CONFIG_COMPACTION
1273018e9a49SAndrew Morton 
1274b682debdSVlastimil Babka static bool suitable_migration_source(struct compact_control *cc,
1275b682debdSVlastimil Babka 							struct page *page)
1276b682debdSVlastimil Babka {
1277282722b0SVlastimil Babka 	int block_mt;
1278282722b0SVlastimil Babka 
12799bebefd5SMel Gorman 	if (pageblock_skip_persistent(page))
12809bebefd5SMel Gorman 		return false;
12819bebefd5SMel Gorman 
1282282722b0SVlastimil Babka 	if ((cc->mode != MIGRATE_ASYNC) || !cc->direct_compaction)
1283b682debdSVlastimil Babka 		return true;
1284b682debdSVlastimil Babka 
1285282722b0SVlastimil Babka 	block_mt = get_pageblock_migratetype(page);
1286282722b0SVlastimil Babka 
1287282722b0SVlastimil Babka 	if (cc->migratetype == MIGRATE_MOVABLE)
1288282722b0SVlastimil Babka 		return is_migrate_movable(block_mt);
1289282722b0SVlastimil Babka 	else
1290282722b0SVlastimil Babka 		return block_mt == cc->migratetype;
1291b682debdSVlastimil Babka }
1292b682debdSVlastimil Babka 
1293018e9a49SAndrew Morton /* Returns true if the page is within a block suitable for migration to */
12949f7e3387SVlastimil Babka static bool suitable_migration_target(struct compact_control *cc,
12959f7e3387SVlastimil Babka 							struct page *page)
1296018e9a49SAndrew Morton {
1297018e9a49SAndrew Morton 	/* If the page is a large free page, then disallow migration */
1298018e9a49SAndrew Morton 	if (PageBuddy(page)) {
1299018e9a49SAndrew Morton 		/*
1300018e9a49SAndrew Morton 		 * We are checking page_order without zone->lock taken. But
1301018e9a49SAndrew Morton 		 * the only small danger is that we skip a potentially suitable
1302018e9a49SAndrew Morton 		 * pageblock, so it's not worth to check order for valid range.
1303018e9a49SAndrew Morton 		 */
1304ab130f91SMatthew Wilcox (Oracle) 		if (buddy_order_unsafe(page) >= pageblock_order)
1305018e9a49SAndrew Morton 			return false;
1306018e9a49SAndrew Morton 	}
1307018e9a49SAndrew Morton 
13081ef36db2SYisheng Xie 	if (cc->ignore_block_suitable)
13091ef36db2SYisheng Xie 		return true;
13101ef36db2SYisheng Xie 
1311018e9a49SAndrew Morton 	/* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */
1312b682debdSVlastimil Babka 	if (is_migrate_movable(get_pageblock_migratetype(page)))
1313018e9a49SAndrew Morton 		return true;
1314018e9a49SAndrew Morton 
1315018e9a49SAndrew Morton 	/* Otherwise skip the block */
1316018e9a49SAndrew Morton 	return false;
1317018e9a49SAndrew Morton }
1318018e9a49SAndrew Morton 
131970b44595SMel Gorman static inline unsigned int
132070b44595SMel Gorman freelist_scan_limit(struct compact_control *cc)
132170b44595SMel Gorman {
1322dd7ef7bdSQian Cai 	unsigned short shift = BITS_PER_LONG - 1;
1323dd7ef7bdSQian Cai 
1324dd7ef7bdSQian Cai 	return (COMPACT_CLUSTER_MAX >> min(shift, cc->fast_search_fail)) + 1;
132570b44595SMel Gorman }
132670b44595SMel Gorman 
1327ff9543fdSMichal Nazarewicz /*
1328f2849aa0SVlastimil Babka  * Test whether the free scanner has reached the same or lower pageblock than
1329f2849aa0SVlastimil Babka  * the migration scanner, and compaction should thus terminate.
1330f2849aa0SVlastimil Babka  */
1331f2849aa0SVlastimil Babka static inline bool compact_scanners_met(struct compact_control *cc)
1332f2849aa0SVlastimil Babka {
1333f2849aa0SVlastimil Babka 	return (cc->free_pfn >> pageblock_order)
1334f2849aa0SVlastimil Babka 		<= (cc->migrate_pfn >> pageblock_order);
1335f2849aa0SVlastimil Babka }
1336f2849aa0SVlastimil Babka 
13375a811889SMel Gorman /*
13385a811889SMel Gorman  * Used when scanning for a suitable migration target which scans freelists
13395a811889SMel Gorman  * in reverse. Reorders the list such as the unscanned pages are scanned
13405a811889SMel Gorman  * first on the next iteration of the free scanner
13415a811889SMel Gorman  */
13425a811889SMel Gorman static void
13435a811889SMel Gorman move_freelist_head(struct list_head *freelist, struct page *freepage)
13445a811889SMel Gorman {
13455a811889SMel Gorman 	LIST_HEAD(sublist);
13465a811889SMel Gorman 
13475a811889SMel Gorman 	if (!list_is_last(freelist, &freepage->lru)) {
13485a811889SMel Gorman 		list_cut_before(&sublist, freelist, &freepage->lru);
13495a811889SMel Gorman 		list_splice_tail(&sublist, freelist);
13505a811889SMel Gorman 	}
13515a811889SMel Gorman }
13525a811889SMel Gorman 
13535a811889SMel Gorman /*
13545a811889SMel Gorman  * Similar to move_freelist_head except used by the migration scanner
13555a811889SMel Gorman  * when scanning forward. It's possible for these list operations to
13565a811889SMel Gorman  * move against each other if they search the free list exactly in
13575a811889SMel Gorman  * lockstep.
13585a811889SMel Gorman  */
135970b44595SMel Gorman static void
136070b44595SMel Gorman move_freelist_tail(struct list_head *freelist, struct page *freepage)
136170b44595SMel Gorman {
136270b44595SMel Gorman 	LIST_HEAD(sublist);
136370b44595SMel Gorman 
136470b44595SMel Gorman 	if (!list_is_first(freelist, &freepage->lru)) {
136570b44595SMel Gorman 		list_cut_position(&sublist, freelist, &freepage->lru);
136670b44595SMel Gorman 		list_splice_tail(&sublist, freelist);
136770b44595SMel Gorman 	}
136870b44595SMel Gorman }
136970b44595SMel Gorman 
13705a811889SMel Gorman static void
1371be21b32aSNARIBAYASHI Akira fast_isolate_around(struct compact_control *cc, unsigned long pfn)
13725a811889SMel Gorman {
13735a811889SMel Gorman 	unsigned long start_pfn, end_pfn;
13746e2b7044SVlastimil Babka 	struct page *page;
13755a811889SMel Gorman 
13765a811889SMel Gorman 	/* Do not search around if there are enough pages already */
13775a811889SMel Gorman 	if (cc->nr_freepages >= cc->nr_migratepages)
13785a811889SMel Gorman 		return;
13795a811889SMel Gorman 
13805a811889SMel Gorman 	/* Minimise scanning during async compaction */
13815a811889SMel Gorman 	if (cc->direct_compaction && cc->mode == MIGRATE_ASYNC)
13825a811889SMel Gorman 		return;
13835a811889SMel Gorman 
13845a811889SMel Gorman 	/* Pageblock boundaries */
13856e2b7044SVlastimil Babka 	start_pfn = max(pageblock_start_pfn(pfn), cc->zone->zone_start_pfn);
13866e2b7044SVlastimil Babka 	end_pfn = min(pageblock_end_pfn(pfn), zone_end_pfn(cc->zone));
13876e2b7044SVlastimil Babka 
13886e2b7044SVlastimil Babka 	page = pageblock_pfn_to_page(start_pfn, end_pfn, cc->zone);
13896e2b7044SVlastimil Babka 	if (!page)
13906e2b7044SVlastimil Babka 		return;
13915a811889SMel Gorman 
13924fca9730SMel Gorman 	isolate_freepages_block(cc, &start_pfn, end_pfn, &cc->freepages, 1, false);
13935a811889SMel Gorman 
13945a811889SMel Gorman 	/* Skip this pageblock in the future as it's full or nearly full */
13955a811889SMel Gorman 	if (cc->nr_freepages < cc->nr_migratepages)
13965a811889SMel Gorman 		set_pageblock_skip(page);
1397be21b32aSNARIBAYASHI Akira 
1398be21b32aSNARIBAYASHI Akira 	return;
13995a811889SMel Gorman }
14005a811889SMel Gorman 
1401dbe2d4e4SMel Gorman /* Search orders in round-robin fashion */
1402dbe2d4e4SMel Gorman static int next_search_order(struct compact_control *cc, int order)
1403dbe2d4e4SMel Gorman {
1404dbe2d4e4SMel Gorman 	order--;
1405dbe2d4e4SMel Gorman 	if (order < 0)
1406dbe2d4e4SMel Gorman 		order = cc->order - 1;
1407dbe2d4e4SMel Gorman 
1408dbe2d4e4SMel Gorman 	/* Search wrapped around? */
1409dbe2d4e4SMel Gorman 	if (order == cc->search_order) {
1410dbe2d4e4SMel Gorman 		cc->search_order--;
1411dbe2d4e4SMel Gorman 		if (cc->search_order < 0)
1412dbe2d4e4SMel Gorman 			cc->search_order = cc->order - 1;
1413dbe2d4e4SMel Gorman 		return -1;
1414dbe2d4e4SMel Gorman 	}
1415dbe2d4e4SMel Gorman 
1416dbe2d4e4SMel Gorman 	return order;
1417dbe2d4e4SMel Gorman }
1418dbe2d4e4SMel Gorman 
14195a811889SMel Gorman static unsigned long
14205a811889SMel Gorman fast_isolate_freepages(struct compact_control *cc)
14215a811889SMel Gorman {
1422b55ca526SWonhyuk Yang 	unsigned int limit = max(1U, freelist_scan_limit(cc) >> 1);
14235a811889SMel Gorman 	unsigned int nr_scanned = 0;
142474e21484SRokudo Yan 	unsigned long low_pfn, min_pfn, highest = 0;
14255a811889SMel Gorman 	unsigned long nr_isolated = 0;
14265a811889SMel Gorman 	unsigned long distance;
14275a811889SMel Gorman 	struct page *page = NULL;
14285a811889SMel Gorman 	bool scan_start = false;
14295a811889SMel Gorman 	int order;
14305a811889SMel Gorman 
14315a811889SMel Gorman 	/* Full compaction passes in a negative order */
14325a811889SMel Gorman 	if (cc->order <= 0)
14335a811889SMel Gorman 		return cc->free_pfn;
14345a811889SMel Gorman 
14355a811889SMel Gorman 	/*
14365a811889SMel Gorman 	 * If starting the scan, use a deeper search and use the highest
14375a811889SMel Gorman 	 * PFN found if a suitable one is not found.
14385a811889SMel Gorman 	 */
1439e332f741SMel Gorman 	if (cc->free_pfn >= cc->zone->compact_init_free_pfn) {
14405a811889SMel Gorman 		limit = pageblock_nr_pages >> 1;
14415a811889SMel Gorman 		scan_start = true;
14425a811889SMel Gorman 	}
14435a811889SMel Gorman 
14445a811889SMel Gorman 	/*
14455a811889SMel Gorman 	 * Preferred point is in the top quarter of the scan space but take
14465a811889SMel Gorman 	 * a pfn from the top half if the search is problematic.
14475a811889SMel Gorman 	 */
14485a811889SMel Gorman 	distance = (cc->free_pfn - cc->migrate_pfn);
14495a811889SMel Gorman 	low_pfn = pageblock_start_pfn(cc->free_pfn - (distance >> 2));
14505a811889SMel Gorman 	min_pfn = pageblock_start_pfn(cc->free_pfn - (distance >> 1));
14515a811889SMel Gorman 
14525a811889SMel Gorman 	if (WARN_ON_ONCE(min_pfn > low_pfn))
14535a811889SMel Gorman 		low_pfn = min_pfn;
14545a811889SMel Gorman 
1455dbe2d4e4SMel Gorman 	/*
1456dbe2d4e4SMel Gorman 	 * Search starts from the last successful isolation order or the next
1457dbe2d4e4SMel Gorman 	 * order to search after a previous failure
1458dbe2d4e4SMel Gorman 	 */
1459dbe2d4e4SMel Gorman 	cc->search_order = min_t(unsigned int, cc->order - 1, cc->search_order);
1460dbe2d4e4SMel Gorman 
1461dbe2d4e4SMel Gorman 	for (order = cc->search_order;
1462dbe2d4e4SMel Gorman 	     !page && order >= 0;
1463dbe2d4e4SMel Gorman 	     order = next_search_order(cc, order)) {
14645a811889SMel Gorman 		struct free_area *area = &cc->zone->free_area[order];
14655a811889SMel Gorman 		struct list_head *freelist;
14665a811889SMel Gorman 		struct page *freepage;
14675a811889SMel Gorman 		unsigned long flags;
14685a811889SMel Gorman 		unsigned int order_scanned = 0;
146974e21484SRokudo Yan 		unsigned long high_pfn = 0;
14705a811889SMel Gorman 
14715a811889SMel Gorman 		if (!area->nr_free)
14725a811889SMel Gorman 			continue;
14735a811889SMel Gorman 
14745a811889SMel Gorman 		spin_lock_irqsave(&cc->zone->lock, flags);
14755a811889SMel Gorman 		freelist = &area->free_list[MIGRATE_MOVABLE];
14765a811889SMel Gorman 		list_for_each_entry_reverse(freepage, freelist, lru) {
14775a811889SMel Gorman 			unsigned long pfn;
14785a811889SMel Gorman 
14795a811889SMel Gorman 			order_scanned++;
14805a811889SMel Gorman 			nr_scanned++;
14815a811889SMel Gorman 			pfn = page_to_pfn(freepage);
14825a811889SMel Gorman 
14835a811889SMel Gorman 			if (pfn >= highest)
14846e2b7044SVlastimil Babka 				highest = max(pageblock_start_pfn(pfn),
14856e2b7044SVlastimil Babka 					      cc->zone->zone_start_pfn);
14865a811889SMel Gorman 
14875a811889SMel Gorman 			if (pfn >= low_pfn) {
14885a811889SMel Gorman 				cc->fast_search_fail = 0;
1489dbe2d4e4SMel Gorman 				cc->search_order = order;
14905a811889SMel Gorman 				page = freepage;
14915a811889SMel Gorman 				break;
14925a811889SMel Gorman 			}
14935a811889SMel Gorman 
14945a811889SMel Gorman 			if (pfn >= min_pfn && pfn > high_pfn) {
14955a811889SMel Gorman 				high_pfn = pfn;
14965a811889SMel Gorman 
14975a811889SMel Gorman 				/* Shorten the scan if a candidate is found */
14985a811889SMel Gorman 				limit >>= 1;
14995a811889SMel Gorman 			}
15005a811889SMel Gorman 
15015a811889SMel Gorman 			if (order_scanned >= limit)
15025a811889SMel Gorman 				break;
15035a811889SMel Gorman 		}
15045a811889SMel Gorman 
15055a811889SMel Gorman 		/* Use a minimum pfn if a preferred one was not found */
15065a811889SMel Gorman 		if (!page && high_pfn) {
15075a811889SMel Gorman 			page = pfn_to_page(high_pfn);
15085a811889SMel Gorman 
15095a811889SMel Gorman 			/* Update freepage for the list reorder below */
15105a811889SMel Gorman 			freepage = page;
15115a811889SMel Gorman 		}
15125a811889SMel Gorman 
15135a811889SMel Gorman 		/* Reorder to so a future search skips recent pages */
15145a811889SMel Gorman 		move_freelist_head(freelist, freepage);
15155a811889SMel Gorman 
15165a811889SMel Gorman 		/* Isolate the page if available */
15175a811889SMel Gorman 		if (page) {
15185a811889SMel Gorman 			if (__isolate_free_page(page, order)) {
15195a811889SMel Gorman 				set_page_private(page, order);
15205a811889SMel Gorman 				nr_isolated = 1 << order;
1521b717d6b9SWilliam Lam 				nr_scanned += nr_isolated - 1;
15225a811889SMel Gorman 				cc->nr_freepages += nr_isolated;
15235a811889SMel Gorman 				list_add_tail(&page->lru, &cc->freepages);
15245a811889SMel Gorman 				count_compact_events(COMPACTISOLATED, nr_isolated);
15255a811889SMel Gorman 			} else {
15265a811889SMel Gorman 				/* If isolation fails, abort the search */
15275b56d996SQian Cai 				order = cc->search_order + 1;
15285a811889SMel Gorman 				page = NULL;
15295a811889SMel Gorman 			}
15305a811889SMel Gorman 		}
15315a811889SMel Gorman 
15325a811889SMel Gorman 		spin_unlock_irqrestore(&cc->zone->lock, flags);
15335a811889SMel Gorman 
15345a811889SMel Gorman 		/*
1535b55ca526SWonhyuk Yang 		 * Smaller scan on next order so the total scan is related
15365a811889SMel Gorman 		 * to freelist_scan_limit.
15375a811889SMel Gorman 		 */
15385a811889SMel Gorman 		if (order_scanned >= limit)
1539b55ca526SWonhyuk Yang 			limit = max(1U, limit >> 1);
15405a811889SMel Gorman 	}
15415a811889SMel Gorman 
15425a811889SMel Gorman 	if (!page) {
15435a811889SMel Gorman 		cc->fast_search_fail++;
15445a811889SMel Gorman 		if (scan_start) {
15455a811889SMel Gorman 			/*
15465a811889SMel Gorman 			 * Use the highest PFN found above min. If one was
1547f3867755SEthon Paul 			 * not found, be pessimistic for direct compaction
15485a811889SMel Gorman 			 * and use the min mark.
15495a811889SMel Gorman 			 */
1550ca2864e5SMiaohe Lin 			if (highest >= min_pfn) {
15515a811889SMel Gorman 				page = pfn_to_page(highest);
15525a811889SMel Gorman 				cc->free_pfn = highest;
15535a811889SMel Gorman 			} else {
1554e577c8b6SSuzuki K Poulose 				if (cc->direct_compaction && pfn_valid(min_pfn)) {
155573a6e474SBaoquan He 					page = pageblock_pfn_to_page(min_pfn,
15566e2b7044SVlastimil Babka 						min(pageblock_end_pfn(min_pfn),
15576e2b7044SVlastimil Babka 						    zone_end_pfn(cc->zone)),
155873a6e474SBaoquan He 						cc->zone);
15595a811889SMel Gorman 					cc->free_pfn = min_pfn;
15605a811889SMel Gorman 				}
15615a811889SMel Gorman 			}
15625a811889SMel Gorman 		}
15635a811889SMel Gorman 	}
15645a811889SMel Gorman 
1565d097a6f6SMel Gorman 	if (highest && highest >= cc->zone->compact_cached_free_pfn) {
1566d097a6f6SMel Gorman 		highest -= pageblock_nr_pages;
15675a811889SMel Gorman 		cc->zone->compact_cached_free_pfn = highest;
1568d097a6f6SMel Gorman 	}
15695a811889SMel Gorman 
15705a811889SMel Gorman 	cc->total_free_scanned += nr_scanned;
15715a811889SMel Gorman 	if (!page)
15725a811889SMel Gorman 		return cc->free_pfn;
15735a811889SMel Gorman 
15745a811889SMel Gorman 	low_pfn = page_to_pfn(page);
1575be21b32aSNARIBAYASHI Akira 	fast_isolate_around(cc, low_pfn);
15765a811889SMel Gorman 	return low_pfn;
15775a811889SMel Gorman }
15785a811889SMel Gorman 
1579f2849aa0SVlastimil Babka /*
1580ff9543fdSMichal Nazarewicz  * Based on information in the current compact_control, find blocks
1581ff9543fdSMichal Nazarewicz  * suitable for isolating free pages from and then isolate them.
1582ff9543fdSMichal Nazarewicz  */
1583edc2ca61SVlastimil Babka static void isolate_freepages(struct compact_control *cc)
1584ff9543fdSMichal Nazarewicz {
1585edc2ca61SVlastimil Babka 	struct zone *zone = cc->zone;
1586ff9543fdSMichal Nazarewicz 	struct page *page;
1587c96b9e50SVlastimil Babka 	unsigned long block_start_pfn;	/* start of current pageblock */
1588e14c720eSVlastimil Babka 	unsigned long isolate_start_pfn; /* exact pfn we start at */
1589c96b9e50SVlastimil Babka 	unsigned long block_end_pfn;	/* end of current pageblock */
1590c96b9e50SVlastimil Babka 	unsigned long low_pfn;	     /* lowest pfn scanner is able to scan */
1591ff9543fdSMichal Nazarewicz 	struct list_head *freelist = &cc->freepages;
15924fca9730SMel Gorman 	unsigned int stride;
15932fe86e00SMichal Nazarewicz 
15945a811889SMel Gorman 	/* Try a small search of the free lists for a candidate */
159500bc102fSMiaohe Lin 	fast_isolate_freepages(cc);
15965a811889SMel Gorman 	if (cc->nr_freepages)
15975a811889SMel Gorman 		goto splitmap;
15985a811889SMel Gorman 
1599ff9543fdSMichal Nazarewicz 	/*
1600ff9543fdSMichal Nazarewicz 	 * Initialise the free scanner. The starting point is where we last
160149e068f0SVlastimil Babka 	 * successfully isolated from, zone-cached value, or the end of the
1602e14c720eSVlastimil Babka 	 * zone when isolating for the first time. For looping we also need
1603e14c720eSVlastimil Babka 	 * this pfn aligned down to the pageblock boundary, because we do
1604c96b9e50SVlastimil Babka 	 * block_start_pfn -= pageblock_nr_pages in the for loop.
1605c96b9e50SVlastimil Babka 	 * For ending point, take care when isolating in last pageblock of a
1606a1c1dbebSRandy Dunlap 	 * zone which ends in the middle of a pageblock.
160749e068f0SVlastimil Babka 	 * The low boundary is the end of the pageblock the migration scanner
160849e068f0SVlastimil Babka 	 * is using.
1609ff9543fdSMichal Nazarewicz 	 */
1610e14c720eSVlastimil Babka 	isolate_start_pfn = cc->free_pfn;
16115a811889SMel Gorman 	block_start_pfn = pageblock_start_pfn(isolate_start_pfn);
1612c96b9e50SVlastimil Babka 	block_end_pfn = min(block_start_pfn + pageblock_nr_pages,
1613c96b9e50SVlastimil Babka 						zone_end_pfn(zone));
161406b6640aSVlastimil Babka 	low_pfn = pageblock_end_pfn(cc->migrate_pfn);
16154fca9730SMel Gorman 	stride = cc->mode == MIGRATE_ASYNC ? COMPACT_CLUSTER_MAX : 1;
16162fe86e00SMichal Nazarewicz 
1617ff9543fdSMichal Nazarewicz 	/*
1618ff9543fdSMichal Nazarewicz 	 * Isolate free pages until enough are available to migrate the
1619ff9543fdSMichal Nazarewicz 	 * pages on cc->migratepages. We stop searching if the migrate
1620ff9543fdSMichal Nazarewicz 	 * and free page scanners meet or enough free pages are isolated.
1621ff9543fdSMichal Nazarewicz 	 */
1622f5f61a32SVlastimil Babka 	for (; block_start_pfn >= low_pfn;
1623c96b9e50SVlastimil Babka 				block_end_pfn = block_start_pfn,
1624e14c720eSVlastimil Babka 				block_start_pfn -= pageblock_nr_pages,
1625e14c720eSVlastimil Babka 				isolate_start_pfn = block_start_pfn) {
16264fca9730SMel Gorman 		unsigned long nr_isolated;
16274fca9730SMel Gorman 
1628f6ea3adbSDavid Rientjes 		/*
1629f6ea3adbSDavid Rientjes 		 * This can iterate a massively long zone without finding any
1630cb810ad2SMel Gorman 		 * suitable migration targets, so periodically check resched.
1631f6ea3adbSDavid Rientjes 		 */
1632c036ddffSMiaohe Lin 		if (!(block_start_pfn % (COMPACT_CLUSTER_MAX * pageblock_nr_pages)))
1633cf66f070SMel Gorman 			cond_resched();
1634f6ea3adbSDavid Rientjes 
16357d49d886SVlastimil Babka 		page = pageblock_pfn_to_page(block_start_pfn, block_end_pfn,
16367d49d886SVlastimil Babka 									zone);
16377d49d886SVlastimil Babka 		if (!page)
1638ff9543fdSMichal Nazarewicz 			continue;
1639ff9543fdSMichal Nazarewicz 
1640ff9543fdSMichal Nazarewicz 		/* Check the block is suitable for migration */
16419f7e3387SVlastimil Babka 		if (!suitable_migration_target(cc, page))
1642ff9543fdSMichal Nazarewicz 			continue;
164368e3e926SLinus Torvalds 
1644bb13ffebSMel Gorman 		/* If isolation recently failed, do not retry */
1645bb13ffebSMel Gorman 		if (!isolation_suitable(cc, page))
1646bb13ffebSMel Gorman 			continue;
1647bb13ffebSMel Gorman 
1648e14c720eSVlastimil Babka 		/* Found a block suitable for isolating free pages from. */
16494fca9730SMel Gorman 		nr_isolated = isolate_freepages_block(cc, &isolate_start_pfn,
16504fca9730SMel Gorman 					block_end_pfn, freelist, stride, false);
1651ff9543fdSMichal Nazarewicz 
1652d097a6f6SMel Gorman 		/* Update the skip hint if the full pageblock was scanned */
1653d097a6f6SMel Gorman 		if (isolate_start_pfn == block_end_pfn)
1654d097a6f6SMel Gorman 			update_pageblock_skip(cc, page, block_start_pfn);
1655d097a6f6SMel Gorman 
1656cb2dcaf0SMel Gorman 		/* Are enough freepages isolated? */
1657cb2dcaf0SMel Gorman 		if (cc->nr_freepages >= cc->nr_migratepages) {
1658a46cbf3bSDavid Rientjes 			if (isolate_start_pfn >= block_end_pfn) {
1659a46cbf3bSDavid Rientjes 				/*
1660a46cbf3bSDavid Rientjes 				 * Restart at previous pageblock if more
1661a46cbf3bSDavid Rientjes 				 * freepages can be isolated next time.
1662a46cbf3bSDavid Rientjes 				 */
1663f5f61a32SVlastimil Babka 				isolate_start_pfn =
1664e14c720eSVlastimil Babka 					block_start_pfn - pageblock_nr_pages;
1665a46cbf3bSDavid Rientjes 			}
1666be976572SVlastimil Babka 			break;
1667a46cbf3bSDavid Rientjes 		} else if (isolate_start_pfn < block_end_pfn) {
1668f5f61a32SVlastimil Babka 			/*
1669a46cbf3bSDavid Rientjes 			 * If isolation failed early, do not continue
1670a46cbf3bSDavid Rientjes 			 * needlessly.
1671f5f61a32SVlastimil Babka 			 */
1672a46cbf3bSDavid Rientjes 			break;
1673f5f61a32SVlastimil Babka 		}
16744fca9730SMel Gorman 
16754fca9730SMel Gorman 		/* Adjust stride depending on isolation */
16764fca9730SMel Gorman 		if (nr_isolated) {
16774fca9730SMel Gorman 			stride = 1;
16784fca9730SMel Gorman 			continue;
16794fca9730SMel Gorman 		}
16804fca9730SMel Gorman 		stride = min_t(unsigned int, COMPACT_CLUSTER_MAX, stride << 1);
1681c89511abSMel Gorman 	}
1682ff9543fdSMichal Nazarewicz 
16837ed695e0SVlastimil Babka 	/*
1684f5f61a32SVlastimil Babka 	 * Record where the free scanner will restart next time. Either we
1685f5f61a32SVlastimil Babka 	 * broke from the loop and set isolate_start_pfn based on the last
1686f5f61a32SVlastimil Babka 	 * call to isolate_freepages_block(), or we met the migration scanner
1687f5f61a32SVlastimil Babka 	 * and the loop terminated due to isolate_start_pfn < low_pfn
16887ed695e0SVlastimil Babka 	 */
1689f5f61a32SVlastimil Babka 	cc->free_pfn = isolate_start_pfn;
16905a811889SMel Gorman 
16915a811889SMel Gorman splitmap:
16925a811889SMel Gorman 	/* __isolate_free_page() does not map the pages */
16935a811889SMel Gorman 	split_map_pages(freelist);
1694748446bbSMel Gorman }
1695748446bbSMel Gorman 
1696748446bbSMel Gorman /*
1697748446bbSMel Gorman  * This is a migrate-callback that "allocates" freepages by taking pages
1698748446bbSMel Gorman  * from the isolated freelists in the block we are migrating to.
1699748446bbSMel Gorman  */
17004e096ae1SMatthew Wilcox (Oracle) static struct folio *compaction_alloc(struct folio *src, unsigned long data)
1701748446bbSMel Gorman {
1702748446bbSMel Gorman 	struct compact_control *cc = (struct compact_control *)data;
17034e096ae1SMatthew Wilcox (Oracle) 	struct folio *dst;
1704748446bbSMel Gorman 
1705748446bbSMel Gorman 	if (list_empty(&cc->freepages)) {
1706edc2ca61SVlastimil Babka 		isolate_freepages(cc);
1707748446bbSMel Gorman 
1708748446bbSMel Gorman 		if (list_empty(&cc->freepages))
1709748446bbSMel Gorman 			return NULL;
1710748446bbSMel Gorman 	}
1711748446bbSMel Gorman 
17124e096ae1SMatthew Wilcox (Oracle) 	dst = list_entry(cc->freepages.next, struct folio, lru);
17134e096ae1SMatthew Wilcox (Oracle) 	list_del(&dst->lru);
1714748446bbSMel Gorman 	cc->nr_freepages--;
1715748446bbSMel Gorman 
17164e096ae1SMatthew Wilcox (Oracle) 	return dst;
1717748446bbSMel Gorman }
1718748446bbSMel Gorman 
1719748446bbSMel Gorman /*
1720d53aea3dSDavid Rientjes  * This is a migrate-callback that "frees" freepages back to the isolated
1721d53aea3dSDavid Rientjes  * freelist.  All pages on the freelist are from the same zone, so there is no
1722d53aea3dSDavid Rientjes  * special handling needed for NUMA.
1723d53aea3dSDavid Rientjes  */
17244e096ae1SMatthew Wilcox (Oracle) static void compaction_free(struct folio *dst, unsigned long data)
1725d53aea3dSDavid Rientjes {
1726d53aea3dSDavid Rientjes 	struct compact_control *cc = (struct compact_control *)data;
1727d53aea3dSDavid Rientjes 
17284e096ae1SMatthew Wilcox (Oracle) 	list_add(&dst->lru, &cc->freepages);
1729d53aea3dSDavid Rientjes 	cc->nr_freepages++;
1730d53aea3dSDavid Rientjes }
1731d53aea3dSDavid Rientjes 
1732ff9543fdSMichal Nazarewicz /* possible outcome of isolate_migratepages */
1733ff9543fdSMichal Nazarewicz typedef enum {
1734ff9543fdSMichal Nazarewicz 	ISOLATE_ABORT,		/* Abort compaction now */
1735ff9543fdSMichal Nazarewicz 	ISOLATE_NONE,		/* No pages isolated, continue scanning */
1736ff9543fdSMichal Nazarewicz 	ISOLATE_SUCCESS,	/* Pages isolated, migrate */
1737ff9543fdSMichal Nazarewicz } isolate_migrate_t;
1738ff9543fdSMichal Nazarewicz 
1739ff9543fdSMichal Nazarewicz /*
17405bbe3547SEric B Munson  * Allow userspace to control policy on scanning the unevictable LRU for
17415bbe3547SEric B Munson  * compactable pages.
17425bbe3547SEric B Munson  */
174348fe8ab8SMinghao Chi static int sysctl_compact_unevictable_allowed __read_mostly = CONFIG_COMPACT_UNEVICTABLE_DEFAULT;
174448fe8ab8SMinghao Chi /*
174548fe8ab8SMinghao Chi  * Tunable for proactive compaction. It determines how
174648fe8ab8SMinghao Chi  * aggressively the kernel should compact memory in the
174748fe8ab8SMinghao Chi  * background. It takes values in the range [0, 100].
174848fe8ab8SMinghao Chi  */
174948fe8ab8SMinghao Chi static unsigned int __read_mostly sysctl_compaction_proactiveness = 20;
175048fe8ab8SMinghao Chi static int sysctl_extfrag_threshold = 500;
17518b9167cdSWen Yang static int __read_mostly sysctl_compact_memory;
17525bbe3547SEric B Munson 
175370b44595SMel Gorman static inline void
175470b44595SMel Gorman update_fast_start_pfn(struct compact_control *cc, unsigned long pfn)
175570b44595SMel Gorman {
175670b44595SMel Gorman 	if (cc->fast_start_pfn == ULONG_MAX)
175770b44595SMel Gorman 		return;
175870b44595SMel Gorman 
175970b44595SMel Gorman 	if (!cc->fast_start_pfn)
176070b44595SMel Gorman 		cc->fast_start_pfn = pfn;
176170b44595SMel Gorman 
176270b44595SMel Gorman 	cc->fast_start_pfn = min(cc->fast_start_pfn, pfn);
176370b44595SMel Gorman }
176470b44595SMel Gorman 
176570b44595SMel Gorman static inline unsigned long
176670b44595SMel Gorman reinit_migrate_pfn(struct compact_control *cc)
176770b44595SMel Gorman {
176870b44595SMel Gorman 	if (!cc->fast_start_pfn || cc->fast_start_pfn == ULONG_MAX)
176970b44595SMel Gorman 		return cc->migrate_pfn;
177070b44595SMel Gorman 
177170b44595SMel Gorman 	cc->migrate_pfn = cc->fast_start_pfn;
177270b44595SMel Gorman 	cc->fast_start_pfn = ULONG_MAX;
177370b44595SMel Gorman 
177470b44595SMel Gorman 	return cc->migrate_pfn;
177570b44595SMel Gorman }
177670b44595SMel Gorman 
177770b44595SMel Gorman /*
177870b44595SMel Gorman  * Briefly search the free lists for a migration source that already has
177970b44595SMel Gorman  * some free pages to reduce the number of pages that need migration
178070b44595SMel Gorman  * before a pageblock is free.
178170b44595SMel Gorman  */
178270b44595SMel Gorman static unsigned long fast_find_migrateblock(struct compact_control *cc)
178370b44595SMel Gorman {
178470b44595SMel Gorman 	unsigned int limit = freelist_scan_limit(cc);
178570b44595SMel Gorman 	unsigned int nr_scanned = 0;
178670b44595SMel Gorman 	unsigned long distance;
178770b44595SMel Gorman 	unsigned long pfn = cc->migrate_pfn;
178870b44595SMel Gorman 	unsigned long high_pfn;
178970b44595SMel Gorman 	int order;
179015d28d0dSWonhyuk Yang 	bool found_block = false;
179170b44595SMel Gorman 
179270b44595SMel Gorman 	/* Skip hints are relied on to avoid repeats on the fast search */
179370b44595SMel Gorman 	if (cc->ignore_skip_hint)
179470b44595SMel Gorman 		return pfn;
179570b44595SMel Gorman 
179670b44595SMel Gorman 	/*
1797f9d7fc1aSMel Gorman 	 * If the pageblock should be finished then do not select a different
1798f9d7fc1aSMel Gorman 	 * pageblock.
1799f9d7fc1aSMel Gorman 	 */
1800f9d7fc1aSMel Gorman 	if (cc->finish_pageblock)
1801f9d7fc1aSMel Gorman 		return pfn;
1802f9d7fc1aSMel Gorman 
1803f9d7fc1aSMel Gorman 	/*
180470b44595SMel Gorman 	 * If the migrate_pfn is not at the start of a zone or the start
180570b44595SMel Gorman 	 * of a pageblock then assume this is a continuation of a previous
180670b44595SMel Gorman 	 * scan restarted due to COMPACT_CLUSTER_MAX.
180770b44595SMel Gorman 	 */
180870b44595SMel Gorman 	if (pfn != cc->zone->zone_start_pfn && pfn != pageblock_start_pfn(pfn))
180970b44595SMel Gorman 		return pfn;
181070b44595SMel Gorman 
181170b44595SMel Gorman 	/*
181270b44595SMel Gorman 	 * For smaller orders, just linearly scan as the number of pages
181370b44595SMel Gorman 	 * to migrate should be relatively small and does not necessarily
181470b44595SMel Gorman 	 * justify freeing up a large block for a small allocation.
181570b44595SMel Gorman 	 */
181670b44595SMel Gorman 	if (cc->order <= PAGE_ALLOC_COSTLY_ORDER)
181770b44595SMel Gorman 		return pfn;
181870b44595SMel Gorman 
181970b44595SMel Gorman 	/*
182070b44595SMel Gorman 	 * Only allow kcompactd and direct requests for movable pages to
182170b44595SMel Gorman 	 * quickly clear out a MOVABLE pageblock for allocation. This
182270b44595SMel Gorman 	 * reduces the risk that a large movable pageblock is freed for
182370b44595SMel Gorman 	 * an unmovable/reclaimable small allocation.
182470b44595SMel Gorman 	 */
182570b44595SMel Gorman 	if (cc->direct_compaction && cc->migratetype != MIGRATE_MOVABLE)
182670b44595SMel Gorman 		return pfn;
182770b44595SMel Gorman 
182870b44595SMel Gorman 	/*
182970b44595SMel Gorman 	 * When starting the migration scanner, pick any pageblock within the
183070b44595SMel Gorman 	 * first half of the search space. Otherwise try and pick a pageblock
183170b44595SMel Gorman 	 * within the first eighth to reduce the chances that a migration
183270b44595SMel Gorman 	 * target later becomes a source.
183370b44595SMel Gorman 	 */
183470b44595SMel Gorman 	distance = (cc->free_pfn - cc->migrate_pfn) >> 1;
183570b44595SMel Gorman 	if (cc->migrate_pfn != cc->zone->zone_start_pfn)
183670b44595SMel Gorman 		distance >>= 2;
183770b44595SMel Gorman 	high_pfn = pageblock_start_pfn(cc->migrate_pfn + distance);
183870b44595SMel Gorman 
183970b44595SMel Gorman 	for (order = cc->order - 1;
184015d28d0dSWonhyuk Yang 	     order >= PAGE_ALLOC_COSTLY_ORDER && !found_block && nr_scanned < limit;
184170b44595SMel Gorman 	     order--) {
184270b44595SMel Gorman 		struct free_area *area = &cc->zone->free_area[order];
184370b44595SMel Gorman 		struct list_head *freelist;
184470b44595SMel Gorman 		unsigned long flags;
184570b44595SMel Gorman 		struct page *freepage;
184670b44595SMel Gorman 
184770b44595SMel Gorman 		if (!area->nr_free)
184870b44595SMel Gorman 			continue;
184970b44595SMel Gorman 
185070b44595SMel Gorman 		spin_lock_irqsave(&cc->zone->lock, flags);
185170b44595SMel Gorman 		freelist = &area->free_list[MIGRATE_MOVABLE];
185270b44595SMel Gorman 		list_for_each_entry(freepage, freelist, lru) {
185370b44595SMel Gorman 			unsigned long free_pfn;
185470b44595SMel Gorman 
185515d28d0dSWonhyuk Yang 			if (nr_scanned++ >= limit) {
185615d28d0dSWonhyuk Yang 				move_freelist_tail(freelist, freepage);
185715d28d0dSWonhyuk Yang 				break;
185815d28d0dSWonhyuk Yang 			}
185915d28d0dSWonhyuk Yang 
186070b44595SMel Gorman 			free_pfn = page_to_pfn(freepage);
186170b44595SMel Gorman 			if (free_pfn < high_pfn) {
186270b44595SMel Gorman 				/*
186370b44595SMel Gorman 				 * Avoid if skipped recently. Ideally it would
186470b44595SMel Gorman 				 * move to the tail but even safe iteration of
186570b44595SMel Gorman 				 * the list assumes an entry is deleted, not
186670b44595SMel Gorman 				 * reordered.
186770b44595SMel Gorman 				 */
186815d28d0dSWonhyuk Yang 				if (get_pageblock_skip(freepage))
186970b44595SMel Gorman 					continue;
187070b44595SMel Gorman 
187170b44595SMel Gorman 				/* Reorder to so a future search skips recent pages */
187270b44595SMel Gorman 				move_freelist_tail(freelist, freepage);
187370b44595SMel Gorman 
1874e380bebeSMel Gorman 				update_fast_start_pfn(cc, free_pfn);
187570b44595SMel Gorman 				pfn = pageblock_start_pfn(free_pfn);
1876bbe832b9SRei Yamamoto 				if (pfn < cc->zone->zone_start_pfn)
1877bbe832b9SRei Yamamoto 					pfn = cc->zone->zone_start_pfn;
187870b44595SMel Gorman 				cc->fast_search_fail = 0;
187915d28d0dSWonhyuk Yang 				found_block = true;
188070b44595SMel Gorman 				break;
188170b44595SMel Gorman 			}
188270b44595SMel Gorman 		}
188370b44595SMel Gorman 		spin_unlock_irqrestore(&cc->zone->lock, flags);
188470b44595SMel Gorman 	}
188570b44595SMel Gorman 
188670b44595SMel Gorman 	cc->total_migrate_scanned += nr_scanned;
188770b44595SMel Gorman 
188870b44595SMel Gorman 	/*
188970b44595SMel Gorman 	 * If fast scanning failed then use a cached entry for a page block
189070b44595SMel Gorman 	 * that had free pages as the basis for starting a linear scan.
189170b44595SMel Gorman 	 */
189215d28d0dSWonhyuk Yang 	if (!found_block) {
189315d28d0dSWonhyuk Yang 		cc->fast_search_fail++;
189470b44595SMel Gorman 		pfn = reinit_migrate_pfn(cc);
189515d28d0dSWonhyuk Yang 	}
189670b44595SMel Gorman 	return pfn;
189770b44595SMel Gorman }
189870b44595SMel Gorman 
18995bbe3547SEric B Munson /*
1900edc2ca61SVlastimil Babka  * Isolate all pages that can be migrated from the first suitable block,
1901edc2ca61SVlastimil Babka  * starting at the block pointed to by the migrate scanner pfn within
1902edc2ca61SVlastimil Babka  * compact_control.
1903ff9543fdSMichal Nazarewicz  */
190432aaf055SPengfei Li static isolate_migrate_t isolate_migratepages(struct compact_control *cc)
1905ff9543fdSMichal Nazarewicz {
1906e1409c32SJoonsoo Kim 	unsigned long block_start_pfn;
1907e1409c32SJoonsoo Kim 	unsigned long block_end_pfn;
1908e1409c32SJoonsoo Kim 	unsigned long low_pfn;
1909edc2ca61SVlastimil Babka 	struct page *page;
1910edc2ca61SVlastimil Babka 	const isolate_mode_t isolate_mode =
19115bbe3547SEric B Munson 		(sysctl_compact_unevictable_allowed ? ISOLATE_UNEVICTABLE : 0) |
19121d2047feSHugh Dickins 		(cc->mode != MIGRATE_SYNC ? ISOLATE_ASYNC_MIGRATE : 0);
191370b44595SMel Gorman 	bool fast_find_block;
1914ff9543fdSMichal Nazarewicz 
1915edc2ca61SVlastimil Babka 	/*
1916edc2ca61SVlastimil Babka 	 * Start at where we last stopped, or beginning of the zone as
191770b44595SMel Gorman 	 * initialized by compact_zone(). The first failure will use
191870b44595SMel Gorman 	 * the lowest PFN as the starting point for linear scanning.
1919edc2ca61SVlastimil Babka 	 */
192070b44595SMel Gorman 	low_pfn = fast_find_migrateblock(cc);
192106b6640aSVlastimil Babka 	block_start_pfn = pageblock_start_pfn(low_pfn);
192232aaf055SPengfei Li 	if (block_start_pfn < cc->zone->zone_start_pfn)
192332aaf055SPengfei Li 		block_start_pfn = cc->zone->zone_start_pfn;
1924ff9543fdSMichal Nazarewicz 
192570b44595SMel Gorman 	/*
192670b44595SMel Gorman 	 * fast_find_migrateblock marks a pageblock skipped so to avoid
192770b44595SMel Gorman 	 * the isolation_suitable check below, check whether the fast
192870b44595SMel Gorman 	 * search was successful.
192970b44595SMel Gorman 	 */
193070b44595SMel Gorman 	fast_find_block = low_pfn != cc->migrate_pfn && !cc->fast_search_fail;
193170b44595SMel Gorman 
1932ff9543fdSMichal Nazarewicz 	/* Only scan within a pageblock boundary */
193306b6640aSVlastimil Babka 	block_end_pfn = pageblock_end_pfn(low_pfn);
1934ff9543fdSMichal Nazarewicz 
1935edc2ca61SVlastimil Babka 	/*
1936edc2ca61SVlastimil Babka 	 * Iterate over whole pageblocks until we find the first suitable.
1937edc2ca61SVlastimil Babka 	 * Do not cross the free scanner.
1938edc2ca61SVlastimil Babka 	 */
1939e1409c32SJoonsoo Kim 	for (; block_end_pfn <= cc->free_pfn;
194070b44595SMel Gorman 			fast_find_block = false,
1941c2ad7a1fSOscar Salvador 			cc->migrate_pfn = low_pfn = block_end_pfn,
1942e1409c32SJoonsoo Kim 			block_start_pfn = block_end_pfn,
1943e1409c32SJoonsoo Kim 			block_end_pfn += pageblock_nr_pages) {
1944edc2ca61SVlastimil Babka 
1945edc2ca61SVlastimil Babka 		/*
1946edc2ca61SVlastimil Babka 		 * This can potentially iterate a massively long zone with
1947edc2ca61SVlastimil Babka 		 * many pageblocks unsuitable, so periodically check if we
1948cb810ad2SMel Gorman 		 * need to schedule.
1949edc2ca61SVlastimil Babka 		 */
1950c036ddffSMiaohe Lin 		if (!(low_pfn % (COMPACT_CLUSTER_MAX * pageblock_nr_pages)))
1951cf66f070SMel Gorman 			cond_resched();
1952edc2ca61SVlastimil Babka 
195332aaf055SPengfei Li 		page = pageblock_pfn_to_page(block_start_pfn,
195432aaf055SPengfei Li 						block_end_pfn, cc->zone);
19557d49d886SVlastimil Babka 		if (!page)
1956edc2ca61SVlastimil Babka 			continue;
1957edc2ca61SVlastimil Babka 
1958e380bebeSMel Gorman 		/*
1959e380bebeSMel Gorman 		 * If isolation recently failed, do not retry. Only check the
1960e380bebeSMel Gorman 		 * pageblock once. COMPACT_CLUSTER_MAX causes a pageblock
1961e380bebeSMel Gorman 		 * to be visited multiple times. Assume skip was checked
1962e380bebeSMel Gorman 		 * before making it "skip" so other compaction instances do
1963e380bebeSMel Gorman 		 * not scan the same block.
1964e380bebeSMel Gorman 		 */
1965ee0913c4SKefeng Wang 		if (pageblock_aligned(low_pfn) &&
1966e380bebeSMel Gorman 		    !fast_find_block && !isolation_suitable(cc, page))
1967edc2ca61SVlastimil Babka 			continue;
1968edc2ca61SVlastimil Babka 
1969edc2ca61SVlastimil Babka 		/*
1970556162bfSMiaohe Lin 		 * For async direct compaction, only scan the pageblocks of the
1971556162bfSMiaohe Lin 		 * same migratetype without huge pages. Async direct compaction
1972556162bfSMiaohe Lin 		 * is optimistic to see if the minimum amount of work satisfies
1973556162bfSMiaohe Lin 		 * the allocation. The cached PFN is updated as it's possible
1974556162bfSMiaohe Lin 		 * that all remaining blocks between source and target are
1975556162bfSMiaohe Lin 		 * unsuitable and the compaction scanners fail to meet.
1976edc2ca61SVlastimil Babka 		 */
19779bebefd5SMel Gorman 		if (!suitable_migration_source(cc, page)) {
19789bebefd5SMel Gorman 			update_cached_migrate(cc, block_end_pfn);
1979edc2ca61SVlastimil Babka 			continue;
19809bebefd5SMel Gorman 		}
1981ff9543fdSMichal Nazarewicz 
1982ff9543fdSMichal Nazarewicz 		/* Perform the isolation */
1983c2ad7a1fSOscar Salvador 		if (isolate_migratepages_block(cc, low_pfn, block_end_pfn,
1984c2ad7a1fSOscar Salvador 						isolate_mode))
1985ff9543fdSMichal Nazarewicz 			return ISOLATE_ABORT;
1986ff9543fdSMichal Nazarewicz 
1987edc2ca61SVlastimil Babka 		/*
1988edc2ca61SVlastimil Babka 		 * Either we isolated something and proceed with migration. Or
1989edc2ca61SVlastimil Babka 		 * we failed and compact_zone should decide if we should
1990edc2ca61SVlastimil Babka 		 * continue or not.
1991edc2ca61SVlastimil Babka 		 */
1992edc2ca61SVlastimil Babka 		break;
1993edc2ca61SVlastimil Babka 	}
1994edc2ca61SVlastimil Babka 
1995edc2ca61SVlastimil Babka 	return cc->nr_migratepages ? ISOLATE_SUCCESS : ISOLATE_NONE;
1996ff9543fdSMichal Nazarewicz }
1997ff9543fdSMichal Nazarewicz 
199821c527a3SYaowei Bai /*
199921c527a3SYaowei Bai  * order == -1 is expected when compacting via
200021c527a3SYaowei Bai  * /proc/sys/vm/compact_memory
200121c527a3SYaowei Bai  */
200221c527a3SYaowei Bai static inline bool is_via_compact_memory(int order)
200321c527a3SYaowei Bai {
200421c527a3SYaowei Bai 	return order == -1;
200521c527a3SYaowei Bai }
200621c527a3SYaowei Bai 
2007b4a0215eSKefeng Wang /*
2008b4a0215eSKefeng Wang  * Determine whether kswapd is (or recently was!) running on this node.
2009b4a0215eSKefeng Wang  *
2010b4a0215eSKefeng Wang  * pgdat_kswapd_lock() pins pgdat->kswapd, so a concurrent kswapd_stop() can't
2011b4a0215eSKefeng Wang  * zero it.
2012b4a0215eSKefeng Wang  */
2013facdaa91SNitin Gupta static bool kswapd_is_running(pg_data_t *pgdat)
2014facdaa91SNitin Gupta {
2015b4a0215eSKefeng Wang 	bool running;
2016b4a0215eSKefeng Wang 
2017b4a0215eSKefeng Wang 	pgdat_kswapd_lock(pgdat);
2018b4a0215eSKefeng Wang 	running = pgdat->kswapd && task_is_running(pgdat->kswapd);
2019b4a0215eSKefeng Wang 	pgdat_kswapd_unlock(pgdat);
2020b4a0215eSKefeng Wang 
2021b4a0215eSKefeng Wang 	return running;
2022facdaa91SNitin Gupta }
2023facdaa91SNitin Gupta 
2024facdaa91SNitin Gupta /*
2025facdaa91SNitin Gupta  * A zone's fragmentation score is the external fragmentation wrt to the
202640d7e203SCharan Teja Reddy  * COMPACTION_HPAGE_ORDER. It returns a value in the range [0, 100].
202740d7e203SCharan Teja Reddy  */
202840d7e203SCharan Teja Reddy static unsigned int fragmentation_score_zone(struct zone *zone)
202940d7e203SCharan Teja Reddy {
203040d7e203SCharan Teja Reddy 	return extfrag_for_order(zone, COMPACTION_HPAGE_ORDER);
203140d7e203SCharan Teja Reddy }
203240d7e203SCharan Teja Reddy 
203340d7e203SCharan Teja Reddy /*
203440d7e203SCharan Teja Reddy  * A weighted zone's fragmentation score is the external fragmentation
203540d7e203SCharan Teja Reddy  * wrt to the COMPACTION_HPAGE_ORDER scaled by the zone's size. It
203640d7e203SCharan Teja Reddy  * returns a value in the range [0, 100].
2037facdaa91SNitin Gupta  *
2038facdaa91SNitin Gupta  * The scaling factor ensures that proactive compaction focuses on larger
2039facdaa91SNitin Gupta  * zones like ZONE_NORMAL, rather than smaller, specialized zones like
2040facdaa91SNitin Gupta  * ZONE_DMA32. For smaller zones, the score value remains close to zero,
2041facdaa91SNitin Gupta  * and thus never exceeds the high threshold for proactive compaction.
2042facdaa91SNitin Gupta  */
204340d7e203SCharan Teja Reddy static unsigned int fragmentation_score_zone_weighted(struct zone *zone)
2044facdaa91SNitin Gupta {
2045facdaa91SNitin Gupta 	unsigned long score;
2046facdaa91SNitin Gupta 
204740d7e203SCharan Teja Reddy 	score = zone->present_pages * fragmentation_score_zone(zone);
2048facdaa91SNitin Gupta 	return div64_ul(score, zone->zone_pgdat->node_present_pages + 1);
2049facdaa91SNitin Gupta }
2050facdaa91SNitin Gupta 
2051facdaa91SNitin Gupta /*
2052facdaa91SNitin Gupta  * The per-node proactive (background) compaction process is started by its
2053facdaa91SNitin Gupta  * corresponding kcompactd thread when the node's fragmentation score
2054facdaa91SNitin Gupta  * exceeds the high threshold. The compaction process remains active till
2055facdaa91SNitin Gupta  * the node's score falls below the low threshold, or one of the back-off
2056facdaa91SNitin Gupta  * conditions is met.
2057facdaa91SNitin Gupta  */
2058d34c0a75SNitin Gupta static unsigned int fragmentation_score_node(pg_data_t *pgdat)
2059facdaa91SNitin Gupta {
2060d34c0a75SNitin Gupta 	unsigned int score = 0;
2061facdaa91SNitin Gupta 	int zoneid;
2062facdaa91SNitin Gupta 
2063facdaa91SNitin Gupta 	for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
2064facdaa91SNitin Gupta 		struct zone *zone;
2065facdaa91SNitin Gupta 
2066facdaa91SNitin Gupta 		zone = &pgdat->node_zones[zoneid];
20679e552271SBaolin Wang 		if (!populated_zone(zone))
20689e552271SBaolin Wang 			continue;
206940d7e203SCharan Teja Reddy 		score += fragmentation_score_zone_weighted(zone);
2070facdaa91SNitin Gupta 	}
2071facdaa91SNitin Gupta 
2072facdaa91SNitin Gupta 	return score;
2073facdaa91SNitin Gupta }
2074facdaa91SNitin Gupta 
2075d34c0a75SNitin Gupta static unsigned int fragmentation_score_wmark(pg_data_t *pgdat, bool low)
2076facdaa91SNitin Gupta {
2077d34c0a75SNitin Gupta 	unsigned int wmark_low;
2078facdaa91SNitin Gupta 
2079facdaa91SNitin Gupta 	/*
2080f0953a1bSIngo Molnar 	 * Cap the low watermark to avoid excessive compaction
2081f0953a1bSIngo Molnar 	 * activity in case a user sets the proactiveness tunable
2082facdaa91SNitin Gupta 	 * close to 100 (maximum).
2083facdaa91SNitin Gupta 	 */
2084d34c0a75SNitin Gupta 	wmark_low = max(100U - sysctl_compaction_proactiveness, 5U);
2085d34c0a75SNitin Gupta 	return low ? wmark_low : min(wmark_low + 10, 100U);
2086facdaa91SNitin Gupta }
2087facdaa91SNitin Gupta 
2088facdaa91SNitin Gupta static bool should_proactive_compact_node(pg_data_t *pgdat)
2089facdaa91SNitin Gupta {
2090facdaa91SNitin Gupta 	int wmark_high;
2091facdaa91SNitin Gupta 
2092facdaa91SNitin Gupta 	if (!sysctl_compaction_proactiveness || kswapd_is_running(pgdat))
2093facdaa91SNitin Gupta 		return false;
2094facdaa91SNitin Gupta 
2095facdaa91SNitin Gupta 	wmark_high = fragmentation_score_wmark(pgdat, false);
2096facdaa91SNitin Gupta 	return fragmentation_score_node(pgdat) > wmark_high;
2097facdaa91SNitin Gupta }
2098facdaa91SNitin Gupta 
209940cacbcbSMel Gorman static enum compact_result __compact_finished(struct compact_control *cc)
2100748446bbSMel Gorman {
21018fb74b9fSMel Gorman 	unsigned int order;
2102d39773a0SVlastimil Babka 	const int migratetype = cc->migratetype;
2103cb2dcaf0SMel Gorman 	int ret;
2104748446bbSMel Gorman 
2105753341a4SMel Gorman 	/* Compaction run completes if the migrate and free scanner meet */
2106f2849aa0SVlastimil Babka 	if (compact_scanners_met(cc)) {
210755b7c4c9SVlastimil Babka 		/* Let the next compaction start anew. */
210840cacbcbSMel Gorman 		reset_cached_positions(cc->zone);
210955b7c4c9SVlastimil Babka 
211062997027SMel Gorman 		/*
211162997027SMel Gorman 		 * Mark that the PG_migrate_skip information should be cleared
2112accf6242SVlastimil Babka 		 * by kswapd when it goes to sleep. kcompactd does not set the
211362997027SMel Gorman 		 * flag itself as the decision to be clear should be directly
211462997027SMel Gorman 		 * based on an allocation request.
211562997027SMel Gorman 		 */
2116accf6242SVlastimil Babka 		if (cc->direct_compaction)
211740cacbcbSMel Gorman 			cc->zone->compact_blockskip_flush = true;
211862997027SMel Gorman 
2119c8f7de0bSMichal Hocko 		if (cc->whole_zone)
2120748446bbSMel Gorman 			return COMPACT_COMPLETE;
2121c8f7de0bSMichal Hocko 		else
2122c8f7de0bSMichal Hocko 			return COMPACT_PARTIAL_SKIPPED;
2123bb13ffebSMel Gorman 	}
2124748446bbSMel Gorman 
2125facdaa91SNitin Gupta 	if (cc->proactive_compaction) {
2126facdaa91SNitin Gupta 		int score, wmark_low;
2127facdaa91SNitin Gupta 		pg_data_t *pgdat;
2128facdaa91SNitin Gupta 
2129facdaa91SNitin Gupta 		pgdat = cc->zone->zone_pgdat;
2130facdaa91SNitin Gupta 		if (kswapd_is_running(pgdat))
2131facdaa91SNitin Gupta 			return COMPACT_PARTIAL_SKIPPED;
2132facdaa91SNitin Gupta 
2133facdaa91SNitin Gupta 		score = fragmentation_score_zone(cc->zone);
2134facdaa91SNitin Gupta 		wmark_low = fragmentation_score_wmark(pgdat, true);
2135facdaa91SNitin Gupta 
2136facdaa91SNitin Gupta 		if (score > wmark_low)
2137facdaa91SNitin Gupta 			ret = COMPACT_CONTINUE;
2138facdaa91SNitin Gupta 		else
2139facdaa91SNitin Gupta 			ret = COMPACT_SUCCESS;
2140facdaa91SNitin Gupta 
2141facdaa91SNitin Gupta 		goto out;
2142facdaa91SNitin Gupta 	}
2143facdaa91SNitin Gupta 
214421c527a3SYaowei Bai 	if (is_via_compact_memory(cc->order))
214556de7263SMel Gorman 		return COMPACT_CONTINUE;
214656de7263SMel Gorman 
2147baf6a9a1SVlastimil Babka 	/*
2148efe771c7SMel Gorman 	 * Always finish scanning a pageblock to reduce the possibility of
2149efe771c7SMel Gorman 	 * fallbacks in the future. This is particularly important when
2150efe771c7SMel Gorman 	 * migration source is unmovable/reclaimable but it's not worth
2151efe771c7SMel Gorman 	 * special casing.
2152baf6a9a1SVlastimil Babka 	 */
2153ee0913c4SKefeng Wang 	if (!pageblock_aligned(cc->migrate_pfn))
2154baf6a9a1SVlastimil Babka 		return COMPACT_CONTINUE;
2155baf6a9a1SVlastimil Babka 
215656de7263SMel Gorman 	/* Direct compactor: Is a suitable page free? */
2157cb2dcaf0SMel Gorman 	ret = COMPACT_NO_SUITABLE_PAGE;
215823baf831SKirill A. Shutemov 	for (order = cc->order; order <= MAX_ORDER; order++) {
215940cacbcbSMel Gorman 		struct free_area *area = &cc->zone->free_area[order];
21602149cdaeSJoonsoo Kim 		bool can_steal;
21618fb74b9fSMel Gorman 
216256de7263SMel Gorman 		/* Job done if page is free of the right migratetype */
2163b03641afSDan Williams 		if (!free_area_empty(area, migratetype))
2164cf378319SVlastimil Babka 			return COMPACT_SUCCESS;
216556de7263SMel Gorman 
21662149cdaeSJoonsoo Kim #ifdef CONFIG_CMA
21672149cdaeSJoonsoo Kim 		/* MIGRATE_MOVABLE can fallback on MIGRATE_CMA */
21682149cdaeSJoonsoo Kim 		if (migratetype == MIGRATE_MOVABLE &&
2169b03641afSDan Williams 			!free_area_empty(area, MIGRATE_CMA))
2170cf378319SVlastimil Babka 			return COMPACT_SUCCESS;
21712149cdaeSJoonsoo Kim #endif
21722149cdaeSJoonsoo Kim 		/*
21732149cdaeSJoonsoo Kim 		 * Job done if allocation would steal freepages from
21742149cdaeSJoonsoo Kim 		 * other migratetype buddy lists.
21752149cdaeSJoonsoo Kim 		 */
21762149cdaeSJoonsoo Kim 		if (find_suitable_fallback(area, order, migratetype,
2177fa599c44SMiaohe Lin 						true, &can_steal) != -1)
2178baf6a9a1SVlastimil Babka 			/*
2179fa599c44SMiaohe Lin 			 * Movable pages are OK in any pageblock. If we are
2180fa599c44SMiaohe Lin 			 * stealing for a non-movable allocation, make sure
2181fa599c44SMiaohe Lin 			 * we finish compacting the current pageblock first
2182fa599c44SMiaohe Lin 			 * (which is assured by the above migrate_pfn align
2183fa599c44SMiaohe Lin 			 * check) so it is as free as possible and we won't
2184fa599c44SMiaohe Lin 			 * have to steal another one soon.
2185baf6a9a1SVlastimil Babka 			 */
2186baf6a9a1SVlastimil Babka 			return COMPACT_SUCCESS;
2187baf6a9a1SVlastimil Babka 	}
2188baf6a9a1SVlastimil Babka 
2189facdaa91SNitin Gupta out:
2190cb2dcaf0SMel Gorman 	if (cc->contended || fatal_signal_pending(current))
2191cb2dcaf0SMel Gorman 		ret = COMPACT_CONTENDED;
2192cb2dcaf0SMel Gorman 
2193cb2dcaf0SMel Gorman 	return ret;
2194837d026dSJoonsoo Kim }
2195837d026dSJoonsoo Kim 
219640cacbcbSMel Gorman static enum compact_result compact_finished(struct compact_control *cc)
2197837d026dSJoonsoo Kim {
2198837d026dSJoonsoo Kim 	int ret;
2199837d026dSJoonsoo Kim 
220040cacbcbSMel Gorman 	ret = __compact_finished(cc);
220140cacbcbSMel Gorman 	trace_mm_compaction_finished(cc->zone, cc->order, ret);
2202837d026dSJoonsoo Kim 	if (ret == COMPACT_NO_SUITABLE_PAGE)
2203837d026dSJoonsoo Kim 		ret = COMPACT_CONTINUE;
2204837d026dSJoonsoo Kim 
2205837d026dSJoonsoo Kim 	return ret;
2206748446bbSMel Gorman }
2207748446bbSMel Gorman 
22083cf04937SJohannes Weiner static bool __compaction_suitable(struct zone *zone, int order,
220997a225e6SJoonsoo Kim 				  int highest_zoneidx,
221086a294a8SMichal Hocko 				  unsigned long wmark_target)
22113e7d3449SMel Gorman {
22123e7d3449SMel Gorman 	unsigned long watermark;
22133957c776SMichal Hocko 	/*
22149861a62cSVlastimil Babka 	 * Watermarks for order-0 must be met for compaction to be able to
2215984fdba6SVlastimil Babka 	 * isolate free pages for migration targets. This means that the
2216984fdba6SVlastimil Babka 	 * watermark and alloc_flags have to match, or be more pessimistic than
2217984fdba6SVlastimil Babka 	 * the check in __isolate_free_page(). We don't use the direct
2218984fdba6SVlastimil Babka 	 * compactor's alloc_flags, as they are not relevant for freepage
221997a225e6SJoonsoo Kim 	 * isolation. We however do use the direct compactor's highest_zoneidx
222097a225e6SJoonsoo Kim 	 * to skip over zones where lowmem reserves would prevent allocation
222197a225e6SJoonsoo Kim 	 * even if compaction succeeds.
22228348faf9SVlastimil Babka 	 * For costly orders, we require low watermark instead of min for
22238348faf9SVlastimil Babka 	 * compaction to proceed to increase its chances.
2224d883c6cfSJoonsoo Kim 	 * ALLOC_CMA is used, as pages in CMA pageblocks are considered
2225d883c6cfSJoonsoo Kim 	 * suitable migration targets
22263e7d3449SMel Gorman 	 */
22278348faf9SVlastimil Babka 	watermark = (order > PAGE_ALLOC_COSTLY_ORDER) ?
22288348faf9SVlastimil Babka 				low_wmark_pages(zone) : min_wmark_pages(zone);
22298348faf9SVlastimil Babka 	watermark += compact_gap(order);
22303cf04937SJohannes Weiner 	return __zone_watermark_ok(zone, 0, watermark, highest_zoneidx,
22313cf04937SJohannes Weiner 				   ALLOC_CMA, wmark_target);
2232cc5c9f09SVlastimil Babka }
2233cc5c9f09SVlastimil Babka 
22342b1a20c3SHui Su /*
22352b1a20c3SHui Su  * compaction_suitable: Is this suitable to run compaction on this zone now?
22362b1a20c3SHui Su  */
22373cf04937SJohannes Weiner bool compaction_suitable(struct zone *zone, int order, int highest_zoneidx)
2238cc5c9f09SVlastimil Babka {
22393cf04937SJohannes Weiner 	enum compact_result compact_result;
22403cf04937SJohannes Weiner 	bool suitable;
2241cc5c9f09SVlastimil Babka 
22423cf04937SJohannes Weiner 	suitable = __compaction_suitable(zone, order, highest_zoneidx,
2243cc5c9f09SVlastimil Babka 					 zone_page_state(zone, NR_FREE_PAGES));
22443e7d3449SMel Gorman 	/*
22453e7d3449SMel Gorman 	 * fragmentation index determines if allocation failures are due to
22463e7d3449SMel Gorman 	 * low memory or external fragmentation
22473e7d3449SMel Gorman 	 *
2248ebff3980SVlastimil Babka 	 * index of -1000 would imply allocations might succeed depending on
2249ebff3980SVlastimil Babka 	 * watermarks, but we already failed the high-order watermark check
22503e7d3449SMel Gorman 	 * index towards 0 implies failure is due to lack of memory
22513e7d3449SMel Gorman 	 * index towards 1000 implies failure is due to fragmentation
22523e7d3449SMel Gorman 	 *
225320311420SVlastimil Babka 	 * Only compact if a failure would be due to fragmentation. Also
225420311420SVlastimil Babka 	 * ignore fragindex for non-costly orders where the alternative to
225520311420SVlastimil Babka 	 * a successful reclaim/compaction is OOM. Fragindex and the
225620311420SVlastimil Babka 	 * vm.extfrag_threshold sysctl is meant as a heuristic to prevent
225720311420SVlastimil Babka 	 * excessive compaction for costly orders, but it should not be at the
225820311420SVlastimil Babka 	 * expense of system stability.
22593e7d3449SMel Gorman 	 */
22603cf04937SJohannes Weiner 	if (suitable) {
22613cf04937SJohannes Weiner 		compact_result = COMPACT_CONTINUE;
22623cf04937SJohannes Weiner 		if (order > PAGE_ALLOC_COSTLY_ORDER) {
22633cf04937SJohannes Weiner 			int fragindex = fragmentation_index(zone, order);
22643cf04937SJohannes Weiner 
22653cf04937SJohannes Weiner 			if (fragindex >= 0 &&
22663cf04937SJohannes Weiner 			    fragindex <= sysctl_extfrag_threshold) {
22673cf04937SJohannes Weiner 				suitable = false;
22683cf04937SJohannes Weiner 				compact_result = COMPACT_NOT_SUITABLE_ZONE;
22693cf04937SJohannes Weiner 			}
22703cf04937SJohannes Weiner 		}
22713cf04937SJohannes Weiner 	} else {
22723cf04937SJohannes Weiner 		compact_result = COMPACT_SKIPPED;
22733e7d3449SMel Gorman 	}
22743e7d3449SMel Gorman 
22753cf04937SJohannes Weiner 	trace_mm_compaction_suitable(zone, order, compact_result);
2276837d026dSJoonsoo Kim 
22773cf04937SJohannes Weiner 	return suitable;
2278837d026dSJoonsoo Kim }
2279837d026dSJoonsoo Kim 
228086a294a8SMichal Hocko bool compaction_zonelist_suitable(struct alloc_context *ac, int order,
228186a294a8SMichal Hocko 		int alloc_flags)
228286a294a8SMichal Hocko {
228386a294a8SMichal Hocko 	struct zone *zone;
228486a294a8SMichal Hocko 	struct zoneref *z;
228586a294a8SMichal Hocko 
228686a294a8SMichal Hocko 	/*
228786a294a8SMichal Hocko 	 * Make sure at least one zone would pass __compaction_suitable if we continue
228886a294a8SMichal Hocko 	 * retrying the reclaim.
228986a294a8SMichal Hocko 	 */
229097a225e6SJoonsoo Kim 	for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
229197a225e6SJoonsoo Kim 				ac->highest_zoneidx, ac->nodemask) {
229286a294a8SMichal Hocko 		unsigned long available;
229386a294a8SMichal Hocko 
229486a294a8SMichal Hocko 		/*
229586a294a8SMichal Hocko 		 * Do not consider all the reclaimable memory because we do not
229686a294a8SMichal Hocko 		 * want to trash just for a single high order allocation which
229786a294a8SMichal Hocko 		 * is even not guaranteed to appear even if __compaction_suitable
229886a294a8SMichal Hocko 		 * is happy about the watermark check.
229986a294a8SMichal Hocko 		 */
23005a1c84b4SMel Gorman 		available = zone_reclaimable_pages(zone) / order;
230186a294a8SMichal Hocko 		available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
2302e8606320SJohannes Weiner 		if (__compaction_suitable(zone, order, ac->highest_zoneidx,
23033cf04937SJohannes Weiner 					  available))
230486a294a8SMichal Hocko 			return true;
230586a294a8SMichal Hocko 	}
230686a294a8SMichal Hocko 
230786a294a8SMichal Hocko 	return false;
230886a294a8SMichal Hocko }
230986a294a8SMichal Hocko 
23105e1f0f09SMel Gorman static enum compact_result
23115e1f0f09SMel Gorman compact_zone(struct compact_control *cc, struct capture_control *capc)
2312748446bbSMel Gorman {
2313ea7ab982SMichal Hocko 	enum compact_result ret;
231440cacbcbSMel Gorman 	unsigned long start_pfn = cc->zone->zone_start_pfn;
231540cacbcbSMel Gorman 	unsigned long end_pfn = zone_end_pfn(cc->zone);
2316566e54e1SMel Gorman 	unsigned long last_migrated_pfn;
2317e0b9daebSDavid Rientjes 	const bool sync = cc->mode != MIGRATE_ASYNC;
23188854c55fSMel Gorman 	bool update_cached;
231984b328aaSBaolin Wang 	unsigned int nr_succeeded = 0;
2320748446bbSMel Gorman 
2321a94b5252SYafang Shao 	/*
2322a94b5252SYafang Shao 	 * These counters track activities during zone compaction.  Initialize
2323a94b5252SYafang Shao 	 * them before compacting a new zone.
2324a94b5252SYafang Shao 	 */
2325a94b5252SYafang Shao 	cc->total_migrate_scanned = 0;
2326a94b5252SYafang Shao 	cc->total_free_scanned = 0;
2327a94b5252SYafang Shao 	cc->nr_migratepages = 0;
2328a94b5252SYafang Shao 	cc->nr_freepages = 0;
2329a94b5252SYafang Shao 	INIT_LIST_HEAD(&cc->freepages);
2330a94b5252SYafang Shao 	INIT_LIST_HEAD(&cc->migratepages);
2331a94b5252SYafang Shao 
233201c0bfe0SWei Yang 	cc->migratetype = gfp_migratetype(cc->gfp_mask);
2333e8606320SJohannes Weiner 
2334e8606320SJohannes Weiner 	if (!is_via_compact_memory(cc->order)) {
2335e8606320SJohannes Weiner 		unsigned long watermark;
2336e8606320SJohannes Weiner 
2337e8606320SJohannes Weiner 		/* Allocation can already succeed, nothing to do */
2338e8606320SJohannes Weiner 		watermark = wmark_pages(cc->zone,
2339e8606320SJohannes Weiner 					cc->alloc_flags & ALLOC_WMARK_MASK);
2340e8606320SJohannes Weiner 		if (zone_watermark_ok(cc->zone, cc->order, watermark,
2341e8606320SJohannes Weiner 				      cc->highest_zoneidx, cc->alloc_flags))
2342e8606320SJohannes Weiner 			return COMPACT_SUCCESS;
2343e8606320SJohannes Weiner 
23443e7d3449SMel Gorman 		/* Compaction is likely to fail */
23453cf04937SJohannes Weiner 		if (!compaction_suitable(cc->zone, cc->order,
23463cf04937SJohannes Weiner 					 cc->highest_zoneidx))
23473cf04937SJohannes Weiner 			return COMPACT_SKIPPED;
2348e8606320SJohannes Weiner 	}
2349c46649deSMichal Hocko 
2350c89511abSMel Gorman 	/*
2351d3132e4bSVlastimil Babka 	 * Clear pageblock skip if there were failures recently and compaction
2352accf6242SVlastimil Babka 	 * is about to be retried after being deferred.
2353d3132e4bSVlastimil Babka 	 */
235440cacbcbSMel Gorman 	if (compaction_restarting(cc->zone, cc->order))
235540cacbcbSMel Gorman 		__reset_isolation_suitable(cc->zone);
2356d3132e4bSVlastimil Babka 
2357d3132e4bSVlastimil Babka 	/*
2358c89511abSMel Gorman 	 * Setup to move all movable pages to the end of the zone. Used cached
235906ed2998SVlastimil Babka 	 * information on where the scanners should start (unless we explicitly
236006ed2998SVlastimil Babka 	 * want to compact the whole zone), but check that it is initialised
236106ed2998SVlastimil Babka 	 * by ensuring the values are within zone boundaries.
2362c89511abSMel Gorman 	 */
236370b44595SMel Gorman 	cc->fast_start_pfn = 0;
236406ed2998SVlastimil Babka 	if (cc->whole_zone) {
236506ed2998SVlastimil Babka 		cc->migrate_pfn = start_pfn;
236606ed2998SVlastimil Babka 		cc->free_pfn = pageblock_start_pfn(end_pfn - 1);
236706ed2998SVlastimil Babka 	} else {
236840cacbcbSMel Gorman 		cc->migrate_pfn = cc->zone->compact_cached_migrate_pfn[sync];
236940cacbcbSMel Gorman 		cc->free_pfn = cc->zone->compact_cached_free_pfn;
2370623446e4SJoonsoo Kim 		if (cc->free_pfn < start_pfn || cc->free_pfn >= end_pfn) {
237106b6640aSVlastimil Babka 			cc->free_pfn = pageblock_start_pfn(end_pfn - 1);
237240cacbcbSMel Gorman 			cc->zone->compact_cached_free_pfn = cc->free_pfn;
2373c89511abSMel Gorman 		}
2374623446e4SJoonsoo Kim 		if (cc->migrate_pfn < start_pfn || cc->migrate_pfn >= end_pfn) {
2375c89511abSMel Gorman 			cc->migrate_pfn = start_pfn;
237640cacbcbSMel Gorman 			cc->zone->compact_cached_migrate_pfn[0] = cc->migrate_pfn;
237740cacbcbSMel Gorman 			cc->zone->compact_cached_migrate_pfn[1] = cc->migrate_pfn;
2378c89511abSMel Gorman 		}
2379c8f7de0bSMichal Hocko 
2380e332f741SMel Gorman 		if (cc->migrate_pfn <= cc->zone->compact_init_migrate_pfn)
2381c8f7de0bSMichal Hocko 			cc->whole_zone = true;
238206ed2998SVlastimil Babka 	}
2383c8f7de0bSMichal Hocko 
2384566e54e1SMel Gorman 	last_migrated_pfn = 0;
2385748446bbSMel Gorman 
23868854c55fSMel Gorman 	/*
23878854c55fSMel Gorman 	 * Migrate has separate cached PFNs for ASYNC and SYNC* migration on
23888854c55fSMel Gorman 	 * the basis that some migrations will fail in ASYNC mode. However,
23898854c55fSMel Gorman 	 * if the cached PFNs match and pageblocks are skipped due to having
23908854c55fSMel Gorman 	 * no isolation candidates, then the sync state does not matter.
23918854c55fSMel Gorman 	 * Until a pageblock with isolation candidates is found, keep the
23928854c55fSMel Gorman 	 * cached PFNs in sync to avoid revisiting the same blocks.
23938854c55fSMel Gorman 	 */
23948854c55fSMel Gorman 	update_cached = !sync &&
23958854c55fSMel Gorman 		cc->zone->compact_cached_migrate_pfn[0] == cc->zone->compact_cached_migrate_pfn[1];
23968854c55fSMel Gorman 
2397abd4349fSBaolin Wang 	trace_mm_compaction_begin(cc, start_pfn, end_pfn, sync);
23980eb927c0SMel Gorman 
2399361a2a22SMinchan Kim 	/* lru_add_drain_all could be expensive with involving other CPUs */
2400361a2a22SMinchan Kim 	lru_add_drain();
2401748446bbSMel Gorman 
240240cacbcbSMel Gorman 	while ((ret = compact_finished(cc)) == COMPACT_CONTINUE) {
24039d502c1cSMinchan Kim 		int err;
240419d3cf9dSYanfei Xu 		unsigned long iteration_start_pfn = cc->migrate_pfn;
2405748446bbSMel Gorman 
2406804d3121SMel Gorman 		/*
240748731c84SMel Gorman 		 * Avoid multiple rescans of the same pageblock which can
240848731c84SMel Gorman 		 * happen if a page cannot be isolated (dirty/writeback in
240948731c84SMel Gorman 		 * async mode) or if the migrated pages are being allocated
241048731c84SMel Gorman 		 * before the pageblock is cleared.  The first rescan will
241148731c84SMel Gorman 		 * capture the entire pageblock for migration. If it fails,
241248731c84SMel Gorman 		 * it'll be marked skip and scanning will proceed as normal.
2413804d3121SMel Gorman 		 */
241448731c84SMel Gorman 		cc->finish_pageblock = false;
2415804d3121SMel Gorman 		if (pageblock_start_pfn(last_migrated_pfn) ==
241619d3cf9dSYanfei Xu 		    pageblock_start_pfn(iteration_start_pfn)) {
241748731c84SMel Gorman 			cc->finish_pageblock = true;
2418804d3121SMel Gorman 		}
2419804d3121SMel Gorman 
2420cfccd2e6SMel Gorman rescan:
242132aaf055SPengfei Li 		switch (isolate_migratepages(cc)) {
2422f9e35b3bSMel Gorman 		case ISOLATE_ABORT:
24232d1e1041SVlastimil Babka 			ret = COMPACT_CONTENDED;
24245733c7d1SRafael Aquini 			putback_movable_pages(&cc->migratepages);
2425e64c5237SShaohua Li 			cc->nr_migratepages = 0;
2426f9e35b3bSMel Gorman 			goto out;
2427f9e35b3bSMel Gorman 		case ISOLATE_NONE:
24288854c55fSMel Gorman 			if (update_cached) {
24298854c55fSMel Gorman 				cc->zone->compact_cached_migrate_pfn[1] =
24308854c55fSMel Gorman 					cc->zone->compact_cached_migrate_pfn[0];
24318854c55fSMel Gorman 			}
24328854c55fSMel Gorman 
2433fdaf7f5cSVlastimil Babka 			/*
2434fdaf7f5cSVlastimil Babka 			 * We haven't isolated and migrated anything, but
2435fdaf7f5cSVlastimil Babka 			 * there might still be unflushed migrations from
2436fdaf7f5cSVlastimil Babka 			 * previous cc->order aligned block.
2437fdaf7f5cSVlastimil Babka 			 */
2438fdaf7f5cSVlastimil Babka 			goto check_drain;
2439f9e35b3bSMel Gorman 		case ISOLATE_SUCCESS:
24408854c55fSMel Gorman 			update_cached = false;
244119d3cf9dSYanfei Xu 			last_migrated_pfn = iteration_start_pfn;
2442f9e35b3bSMel Gorman 		}
2443748446bbSMel Gorman 
2444d53aea3dSDavid Rientjes 		err = migrate_pages(&cc->migratepages, compaction_alloc,
2445e0b9daebSDavid Rientjes 				compaction_free, (unsigned long)cc, cc->mode,
244684b328aaSBaolin Wang 				MR_COMPACTION, &nr_succeeded);
2447748446bbSMel Gorman 
2448abd4349fSBaolin Wang 		trace_mm_compaction_migratepages(cc, nr_succeeded);
2449748446bbSMel Gorman 
2450f8c9301fSVlastimil Babka 		/* All pages were either migrated or will be released */
2451f8c9301fSVlastimil Babka 		cc->nr_migratepages = 0;
24529d502c1cSMinchan Kim 		if (err) {
24535733c7d1SRafael Aquini 			putback_movable_pages(&cc->migratepages);
24547ed695e0SVlastimil Babka 			/*
24557ed695e0SVlastimil Babka 			 * migrate_pages() may return -ENOMEM when scanners meet
24567ed695e0SVlastimil Babka 			 * and we want compact_finished() to detect it
24577ed695e0SVlastimil Babka 			 */
2458f2849aa0SVlastimil Babka 			if (err == -ENOMEM && !compact_scanners_met(cc)) {
24592d1e1041SVlastimil Babka 				ret = COMPACT_CONTENDED;
24604bf2bba3SDavid Rientjes 				goto out;
2461748446bbSMel Gorman 			}
2462fdd048e1SVlastimil Babka 			/*
2463cfccd2e6SMel Gorman 			 * If an ASYNC or SYNC_LIGHT fails to migrate a page
24649ecc5fc5SMel Gorman 			 * within the current order-aligned block and
24659ecc5fc5SMel Gorman 			 * fast_find_migrateblock may be used then scan the
2466cfccd2e6SMel Gorman 			 * remainder of the pageblock. This will mark the
2467cfccd2e6SMel Gorman 			 * pageblock "skip" to avoid rescanning in the near
2468cfccd2e6SMel Gorman 			 * future. This will isolate more pages than necessary
2469cfccd2e6SMel Gorman 			 * for the request but avoid loops due to
2470cfccd2e6SMel Gorman 			 * fast_find_migrateblock revisiting blocks that were
2471cfccd2e6SMel Gorman 			 * recently partially scanned.
2472fdd048e1SVlastimil Babka 			 */
2473539aa041SMel Gorman 			if (!pageblock_aligned(cc->migrate_pfn) &&
24749ecc5fc5SMel Gorman 			    !cc->ignore_skip_hint && !cc->finish_pageblock &&
2475cfccd2e6SMel Gorman 			    (cc->mode < MIGRATE_SYNC)) {
2476cfccd2e6SMel Gorman 				cc->finish_pageblock = true;
2477cfccd2e6SMel Gorman 
2478cfccd2e6SMel Gorman 				/*
2479cfccd2e6SMel Gorman 				 * Draining pcplists does not help THP if
2480cfccd2e6SMel Gorman 				 * any page failed to migrate. Even after
2481cfccd2e6SMel Gorman 				 * drain, the pageblock will not be free.
2482cfccd2e6SMel Gorman 				 */
2483cfccd2e6SMel Gorman 				if (cc->order == COMPACTION_HPAGE_ORDER)
2484566e54e1SMel Gorman 					last_migrated_pfn = 0;
2485cfccd2e6SMel Gorman 
2486cfccd2e6SMel Gorman 				goto rescan;
2487fdd048e1SVlastimil Babka 			}
24884bf2bba3SDavid Rientjes 		}
2489fdaf7f5cSVlastimil Babka 
249016b3be40SMel Gorman 		/* Stop if a page has been captured */
249116b3be40SMel Gorman 		if (capc && capc->page) {
249216b3be40SMel Gorman 			ret = COMPACT_SUCCESS;
249316b3be40SMel Gorman 			break;
249416b3be40SMel Gorman 		}
249516b3be40SMel Gorman 
2496fdaf7f5cSVlastimil Babka check_drain:
2497fdaf7f5cSVlastimil Babka 		/*
2498fdaf7f5cSVlastimil Babka 		 * Has the migration scanner moved away from the previous
2499fdaf7f5cSVlastimil Babka 		 * cc->order aligned block where we migrated from? If yes,
2500fdaf7f5cSVlastimil Babka 		 * flush the pages that were freed, so that they can merge and
2501fdaf7f5cSVlastimil Babka 		 * compact_finished() can detect immediately if allocation
2502fdaf7f5cSVlastimil Babka 		 * would succeed.
2503fdaf7f5cSVlastimil Babka 		 */
2504566e54e1SMel Gorman 		if (cc->order > 0 && last_migrated_pfn) {
2505fdaf7f5cSVlastimil Babka 			unsigned long current_block_start =
250606b6640aSVlastimil Babka 				block_start_pfn(cc->migrate_pfn, cc->order);
2507fdaf7f5cSVlastimil Babka 
2508566e54e1SMel Gorman 			if (last_migrated_pfn < current_block_start) {
2509b01b2141SIngo Molnar 				lru_add_drain_cpu_zone(cc->zone);
2510fdaf7f5cSVlastimil Babka 				/* No more flushing until we migrate again */
2511566e54e1SMel Gorman 				last_migrated_pfn = 0;
2512fdaf7f5cSVlastimil Babka 			}
2513fdaf7f5cSVlastimil Babka 		}
2514748446bbSMel Gorman 	}
2515748446bbSMel Gorman 
2516f9e35b3bSMel Gorman out:
25176bace090SVlastimil Babka 	/*
25186bace090SVlastimil Babka 	 * Release free pages and update where the free scanner should restart,
25196bace090SVlastimil Babka 	 * so we don't leave any returned pages behind in the next attempt.
25206bace090SVlastimil Babka 	 */
25216bace090SVlastimil Babka 	if (cc->nr_freepages > 0) {
25226bace090SVlastimil Babka 		unsigned long free_pfn = release_freepages(&cc->freepages);
25236bace090SVlastimil Babka 
25246bace090SVlastimil Babka 		cc->nr_freepages = 0;
25256bace090SVlastimil Babka 		VM_BUG_ON(free_pfn == 0);
25266bace090SVlastimil Babka 		/* The cached pfn is always the first in a pageblock */
252706b6640aSVlastimil Babka 		free_pfn = pageblock_start_pfn(free_pfn);
25286bace090SVlastimil Babka 		/*
25296bace090SVlastimil Babka 		 * Only go back, not forward. The cached pfn might have been
25306bace090SVlastimil Babka 		 * already reset to zone end in compact_finished()
25316bace090SVlastimil Babka 		 */
253240cacbcbSMel Gorman 		if (free_pfn > cc->zone->compact_cached_free_pfn)
253340cacbcbSMel Gorman 			cc->zone->compact_cached_free_pfn = free_pfn;
25346bace090SVlastimil Babka 	}
2535748446bbSMel Gorman 
25367f354a54SDavid Rientjes 	count_compact_events(COMPACTMIGRATE_SCANNED, cc->total_migrate_scanned);
25377f354a54SDavid Rientjes 	count_compact_events(COMPACTFREE_SCANNED, cc->total_free_scanned);
25387f354a54SDavid Rientjes 
2539abd4349fSBaolin Wang 	trace_mm_compaction_end(cc, start_pfn, end_pfn, sync, ret);
25400eb927c0SMel Gorman 
2541753ec50dSBaolin Wang 	VM_BUG_ON(!list_empty(&cc->freepages));
2542753ec50dSBaolin Wang 	VM_BUG_ON(!list_empty(&cc->migratepages));
2543753ec50dSBaolin Wang 
2544748446bbSMel Gorman 	return ret;
2545748446bbSMel Gorman }
254676ab0f53SMel Gorman 
2547ea7ab982SMichal Hocko static enum compact_result compact_zone_order(struct zone *zone, int order,
2548c3486f53SVlastimil Babka 		gfp_t gfp_mask, enum compact_priority prio,
254997a225e6SJoonsoo Kim 		unsigned int alloc_flags, int highest_zoneidx,
25505e1f0f09SMel Gorman 		struct page **capture)
255156de7263SMel Gorman {
2552ea7ab982SMichal Hocko 	enum compact_result ret;
255356de7263SMel Gorman 	struct compact_control cc = {
255456de7263SMel Gorman 		.order = order,
2555dbe2d4e4SMel Gorman 		.search_order = order,
25566d7ce559SDavid Rientjes 		.gfp_mask = gfp_mask,
255756de7263SMel Gorman 		.zone = zone,
2558a5508cd8SVlastimil Babka 		.mode = (prio == COMPACT_PRIO_ASYNC) ?
2559a5508cd8SVlastimil Babka 					MIGRATE_ASYNC :	MIGRATE_SYNC_LIGHT,
2560ebff3980SVlastimil Babka 		.alloc_flags = alloc_flags,
256197a225e6SJoonsoo Kim 		.highest_zoneidx = highest_zoneidx,
2562accf6242SVlastimil Babka 		.direct_compaction = true,
2563a8e025e5SVlastimil Babka 		.whole_zone = (prio == MIN_COMPACT_PRIORITY),
25649f7e3387SVlastimil Babka 		.ignore_skip_hint = (prio == MIN_COMPACT_PRIORITY),
25659f7e3387SVlastimil Babka 		.ignore_block_suitable = (prio == MIN_COMPACT_PRIORITY)
256656de7263SMel Gorman 	};
25675e1f0f09SMel Gorman 	struct capture_control capc = {
25685e1f0f09SMel Gorman 		.cc = &cc,
25695e1f0f09SMel Gorman 		.page = NULL,
25705e1f0f09SMel Gorman 	};
25715e1f0f09SMel Gorman 
2572b9e20f0dSVlastimil Babka 	/*
2573b9e20f0dSVlastimil Babka 	 * Make sure the structs are really initialized before we expose the
2574b9e20f0dSVlastimil Babka 	 * capture control, in case we are interrupted and the interrupt handler
2575b9e20f0dSVlastimil Babka 	 * frees a page.
2576b9e20f0dSVlastimil Babka 	 */
2577b9e20f0dSVlastimil Babka 	barrier();
2578b9e20f0dSVlastimil Babka 	WRITE_ONCE(current->capture_control, &capc);
257956de7263SMel Gorman 
25805e1f0f09SMel Gorman 	ret = compact_zone(&cc, &capc);
2581e64c5237SShaohua Li 
2582b9e20f0dSVlastimil Babka 	/*
2583b9e20f0dSVlastimil Babka 	 * Make sure we hide capture control first before we read the captured
2584b9e20f0dSVlastimil Babka 	 * page pointer, otherwise an interrupt could free and capture a page
2585b9e20f0dSVlastimil Babka 	 * and we would leak it.
2586b9e20f0dSVlastimil Babka 	 */
2587b9e20f0dSVlastimil Babka 	WRITE_ONCE(current->capture_control, NULL);
2588b9e20f0dSVlastimil Babka 	*capture = READ_ONCE(capc.page);
258906dac2f4SCharan Teja Reddy 	/*
259006dac2f4SCharan Teja Reddy 	 * Technically, it is also possible that compaction is skipped but
259106dac2f4SCharan Teja Reddy 	 * the page is still captured out of luck(IRQ came and freed the page).
259206dac2f4SCharan Teja Reddy 	 * Returning COMPACT_SUCCESS in such cases helps in properly accounting
259306dac2f4SCharan Teja Reddy 	 * the COMPACT[STALL|FAIL] when compaction is skipped.
259406dac2f4SCharan Teja Reddy 	 */
259506dac2f4SCharan Teja Reddy 	if (*capture)
259606dac2f4SCharan Teja Reddy 		ret = COMPACT_SUCCESS;
25975e1f0f09SMel Gorman 
2598e64c5237SShaohua Li 	return ret;
259956de7263SMel Gorman }
260056de7263SMel Gorman 
260156de7263SMel Gorman /**
260256de7263SMel Gorman  * try_to_compact_pages - Direct compact to satisfy a high-order allocation
260356de7263SMel Gorman  * @gfp_mask: The GFP mask of the current allocation
26041a6d53a1SVlastimil Babka  * @order: The order of the current allocation
26051a6d53a1SVlastimil Babka  * @alloc_flags: The allocation flags of the current allocation
26061a6d53a1SVlastimil Babka  * @ac: The context of current allocation
2607112d2d29SYang Shi  * @prio: Determines how hard direct compaction should try to succeed
26086467552cSVlastimil Babka  * @capture: Pointer to free page created by compaction will be stored here
260956de7263SMel Gorman  *
261056de7263SMel Gorman  * This is the main entry point for direct page compaction.
261156de7263SMel Gorman  */
2612ea7ab982SMichal Hocko enum compact_result try_to_compact_pages(gfp_t gfp_mask, unsigned int order,
2613c603844bSMel Gorman 		unsigned int alloc_flags, const struct alloc_context *ac,
26145e1f0f09SMel Gorman 		enum compact_priority prio, struct page **capture)
261556de7263SMel Gorman {
2616fe573327SVasily Averin 	int may_perform_io = (__force int)(gfp_mask & __GFP_IO);
261756de7263SMel Gorman 	struct zoneref *z;
261856de7263SMel Gorman 	struct zone *zone;
26191d4746d3SMichal Hocko 	enum compact_result rc = COMPACT_SKIPPED;
262056de7263SMel Gorman 
262173e64c51SMichal Hocko 	/*
262273e64c51SMichal Hocko 	 * Check if the GFP flags allow compaction - GFP_NOIO is really
262373e64c51SMichal Hocko 	 * tricky context because the migration might require IO
262473e64c51SMichal Hocko 	 */
262573e64c51SMichal Hocko 	if (!may_perform_io)
262653853e2dSVlastimil Babka 		return COMPACT_SKIPPED;
262756de7263SMel Gorman 
2628a5508cd8SVlastimil Babka 	trace_mm_compaction_try_to_compact_pages(order, gfp_mask, prio);
2629837d026dSJoonsoo Kim 
263056de7263SMel Gorman 	/* Compact each zone in the list */
263197a225e6SJoonsoo Kim 	for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
263297a225e6SJoonsoo Kim 					ac->highest_zoneidx, ac->nodemask) {
2633ea7ab982SMichal Hocko 		enum compact_result status;
263456de7263SMel Gorman 
2635a8e025e5SVlastimil Babka 		if (prio > MIN_COMPACT_PRIORITY
2636a8e025e5SVlastimil Babka 					&& compaction_deferred(zone, order)) {
26371d4746d3SMichal Hocko 			rc = max_t(enum compact_result, COMPACT_DEFERRED, rc);
263853853e2dSVlastimil Babka 			continue;
26391d4746d3SMichal Hocko 		}
264053853e2dSVlastimil Babka 
2641a5508cd8SVlastimil Babka 		status = compact_zone_order(zone, order, gfp_mask, prio,
264297a225e6SJoonsoo Kim 				alloc_flags, ac->highest_zoneidx, capture);
264356de7263SMel Gorman 		rc = max(status, rc);
264456de7263SMel Gorman 
26457ceb009aSVlastimil Babka 		/* The allocation should succeed, stop compacting */
26467ceb009aSVlastimil Babka 		if (status == COMPACT_SUCCESS) {
264753853e2dSVlastimil Babka 			/*
264853853e2dSVlastimil Babka 			 * We think the allocation will succeed in this zone,
264953853e2dSVlastimil Babka 			 * but it is not certain, hence the false. The caller
265053853e2dSVlastimil Babka 			 * will repeat this with true if allocation indeed
265153853e2dSVlastimil Babka 			 * succeeds in this zone.
265253853e2dSVlastimil Babka 			 */
265353853e2dSVlastimil Babka 			compaction_defer_reset(zone, order, false);
26541f9efdefSVlastimil Babka 
2655c3486f53SVlastimil Babka 			break;
26561f9efdefSVlastimil Babka 		}
26571f9efdefSVlastimil Babka 
2658a5508cd8SVlastimil Babka 		if (prio != COMPACT_PRIO_ASYNC && (status == COMPACT_COMPLETE ||
2659c3486f53SVlastimil Babka 					status == COMPACT_PARTIAL_SKIPPED))
266053853e2dSVlastimil Babka 			/*
266153853e2dSVlastimil Babka 			 * We think that allocation won't succeed in this zone
266253853e2dSVlastimil Babka 			 * so we defer compaction there. If it ends up
266353853e2dSVlastimil Babka 			 * succeeding after all, it will be reset.
266453853e2dSVlastimil Babka 			 */
266553853e2dSVlastimil Babka 			defer_compaction(zone, order);
26661f9efdefSVlastimil Babka 
26671f9efdefSVlastimil Babka 		/*
26681f9efdefSVlastimil Babka 		 * We might have stopped compacting due to need_resched() in
26691f9efdefSVlastimil Babka 		 * async compaction, or due to a fatal signal detected. In that
2670c3486f53SVlastimil Babka 		 * case do not try further zones
26711f9efdefSVlastimil Babka 		 */
2672c3486f53SVlastimil Babka 		if ((prio == COMPACT_PRIO_ASYNC && need_resched())
2673c3486f53SVlastimil Babka 					|| fatal_signal_pending(current))
26741f9efdefSVlastimil Babka 			break;
26751f9efdefSVlastimil Babka 	}
26761f9efdefSVlastimil Babka 
267756de7263SMel Gorman 	return rc;
267856de7263SMel Gorman }
267956de7263SMel Gorman 
2680facdaa91SNitin Gupta /*
2681facdaa91SNitin Gupta  * Compact all zones within a node till each zone's fragmentation score
2682facdaa91SNitin Gupta  * reaches within proactive compaction thresholds (as determined by the
2683facdaa91SNitin Gupta  * proactiveness tunable).
2684facdaa91SNitin Gupta  *
2685facdaa91SNitin Gupta  * It is possible that the function returns before reaching score targets
2686facdaa91SNitin Gupta  * due to various back-off conditions, such as, contention on per-node or
2687facdaa91SNitin Gupta  * per-zone locks.
2688facdaa91SNitin Gupta  */
2689facdaa91SNitin Gupta static void proactive_compact_node(pg_data_t *pgdat)
2690facdaa91SNitin Gupta {
2691facdaa91SNitin Gupta 	int zoneid;
2692facdaa91SNitin Gupta 	struct zone *zone;
2693facdaa91SNitin Gupta 	struct compact_control cc = {
2694facdaa91SNitin Gupta 		.order = -1,
2695facdaa91SNitin Gupta 		.mode = MIGRATE_SYNC_LIGHT,
2696facdaa91SNitin Gupta 		.ignore_skip_hint = true,
2697facdaa91SNitin Gupta 		.whole_zone = true,
2698facdaa91SNitin Gupta 		.gfp_mask = GFP_KERNEL,
2699facdaa91SNitin Gupta 		.proactive_compaction = true,
2700facdaa91SNitin Gupta 	};
2701facdaa91SNitin Gupta 
2702facdaa91SNitin Gupta 	for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
2703facdaa91SNitin Gupta 		zone = &pgdat->node_zones[zoneid];
2704facdaa91SNitin Gupta 		if (!populated_zone(zone))
2705facdaa91SNitin Gupta 			continue;
2706facdaa91SNitin Gupta 
2707facdaa91SNitin Gupta 		cc.zone = zone;
2708facdaa91SNitin Gupta 
2709facdaa91SNitin Gupta 		compact_zone(&cc, NULL);
2710facdaa91SNitin Gupta 
27111bfb7684SBaolin Wang 		count_compact_events(KCOMPACTD_MIGRATE_SCANNED,
27121bfb7684SBaolin Wang 				     cc.total_migrate_scanned);
27131bfb7684SBaolin Wang 		count_compact_events(KCOMPACTD_FREE_SCANNED,
27141bfb7684SBaolin Wang 				     cc.total_free_scanned);
2715facdaa91SNitin Gupta 	}
2716facdaa91SNitin Gupta }
271756de7263SMel Gorman 
271876ab0f53SMel Gorman /* Compact all zones within a node */
27197103f16dSAndrew Morton static void compact_node(int nid)
27207be62de9SRik van Riel {
2721791cae96SVlastimil Babka 	pg_data_t *pgdat = NODE_DATA(nid);
2722791cae96SVlastimil Babka 	int zoneid;
2723791cae96SVlastimil Babka 	struct zone *zone;
27247be62de9SRik van Riel 	struct compact_control cc = {
27257be62de9SRik van Riel 		.order = -1,
2726e0b9daebSDavid Rientjes 		.mode = MIGRATE_SYNC,
272791ca9186SDavid Rientjes 		.ignore_skip_hint = true,
272806ed2998SVlastimil Babka 		.whole_zone = true,
272973e64c51SMichal Hocko 		.gfp_mask = GFP_KERNEL,
27307be62de9SRik van Riel 	};
27317be62de9SRik van Riel 
2732791cae96SVlastimil Babka 
2733791cae96SVlastimil Babka 	for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
2734791cae96SVlastimil Babka 
2735791cae96SVlastimil Babka 		zone = &pgdat->node_zones[zoneid];
2736791cae96SVlastimil Babka 		if (!populated_zone(zone))
2737791cae96SVlastimil Babka 			continue;
2738791cae96SVlastimil Babka 
2739791cae96SVlastimil Babka 		cc.zone = zone;
2740791cae96SVlastimil Babka 
27415e1f0f09SMel Gorman 		compact_zone(&cc, NULL);
2742791cae96SVlastimil Babka 	}
27437be62de9SRik van Riel }
27447be62de9SRik van Riel 
274576ab0f53SMel Gorman /* Compact all nodes in the system */
27467964c06dSJason Liu static void compact_nodes(void)
274776ab0f53SMel Gorman {
274876ab0f53SMel Gorman 	int nid;
274976ab0f53SMel Gorman 
27508575ec29SHugh Dickins 	/* Flush pending updates to the LRU lists */
27518575ec29SHugh Dickins 	lru_add_drain_all();
27528575ec29SHugh Dickins 
275376ab0f53SMel Gorman 	for_each_online_node(nid)
275476ab0f53SMel Gorman 		compact_node(nid);
275576ab0f53SMel Gorman }
275676ab0f53SMel Gorman 
275748fe8ab8SMinghao Chi static int compaction_proactiveness_sysctl_handler(struct ctl_table *table, int write,
275865d759c8SCharan Teja Reddy 		void *buffer, size_t *length, loff_t *ppos)
275965d759c8SCharan Teja Reddy {
276065d759c8SCharan Teja Reddy 	int rc, nid;
276165d759c8SCharan Teja Reddy 
276265d759c8SCharan Teja Reddy 	rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
276365d759c8SCharan Teja Reddy 	if (rc)
276465d759c8SCharan Teja Reddy 		return rc;
276565d759c8SCharan Teja Reddy 
276665d759c8SCharan Teja Reddy 	if (write && sysctl_compaction_proactiveness) {
276765d759c8SCharan Teja Reddy 		for_each_online_node(nid) {
276865d759c8SCharan Teja Reddy 			pg_data_t *pgdat = NODE_DATA(nid);
276965d759c8SCharan Teja Reddy 
277065d759c8SCharan Teja Reddy 			if (pgdat->proactive_compact_trigger)
277165d759c8SCharan Teja Reddy 				continue;
277265d759c8SCharan Teja Reddy 
277365d759c8SCharan Teja Reddy 			pgdat->proactive_compact_trigger = true;
27748fff8b6fSBaolin Wang 			trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, -1,
27758fff8b6fSBaolin Wang 							     pgdat->nr_zones - 1);
277665d759c8SCharan Teja Reddy 			wake_up_interruptible(&pgdat->kcompactd_wait);
277765d759c8SCharan Teja Reddy 		}
277865d759c8SCharan Teja Reddy 	}
277965d759c8SCharan Teja Reddy 
278065d759c8SCharan Teja Reddy 	return 0;
278165d759c8SCharan Teja Reddy }
278265d759c8SCharan Teja Reddy 
2783facdaa91SNitin Gupta /*
2784fec4eb2cSYaowei Bai  * This is the entry point for compacting all nodes via
2785fec4eb2cSYaowei Bai  * /proc/sys/vm/compact_memory
2786fec4eb2cSYaowei Bai  */
278748fe8ab8SMinghao Chi static int sysctl_compaction_handler(struct ctl_table *table, int write,
278832927393SChristoph Hellwig 			void *buffer, size_t *length, loff_t *ppos)
278976ab0f53SMel Gorman {
27908b9167cdSWen Yang 	int ret;
27918b9167cdSWen Yang 
27928b9167cdSWen Yang 	ret = proc_dointvec(table, write, buffer, length, ppos);
27938b9167cdSWen Yang 	if (ret)
27948b9167cdSWen Yang 		return ret;
27958b9167cdSWen Yang 
27968b9167cdSWen Yang 	if (sysctl_compact_memory != 1)
27978b9167cdSWen Yang 		return -EINVAL;
27988b9167cdSWen Yang 
279976ab0f53SMel Gorman 	if (write)
28007964c06dSJason Liu 		compact_nodes();
280176ab0f53SMel Gorman 
280276ab0f53SMel Gorman 	return 0;
280376ab0f53SMel Gorman }
2804ed4a6d7fSMel Gorman 
2805ed4a6d7fSMel Gorman #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
280617adb230SYueHaibing static ssize_t compact_store(struct device *dev,
280710fbcf4cSKay Sievers 			     struct device_attribute *attr,
2808ed4a6d7fSMel Gorman 			     const char *buf, size_t count)
2809ed4a6d7fSMel Gorman {
28108575ec29SHugh Dickins 	int nid = dev->id;
28118575ec29SHugh Dickins 
28128575ec29SHugh Dickins 	if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
28138575ec29SHugh Dickins 		/* Flush pending updates to the LRU lists */
28148575ec29SHugh Dickins 		lru_add_drain_all();
28158575ec29SHugh Dickins 
28168575ec29SHugh Dickins 		compact_node(nid);
28178575ec29SHugh Dickins 	}
2818ed4a6d7fSMel Gorman 
2819ed4a6d7fSMel Gorman 	return count;
2820ed4a6d7fSMel Gorman }
282117adb230SYueHaibing static DEVICE_ATTR_WO(compact);
2822ed4a6d7fSMel Gorman 
2823ed4a6d7fSMel Gorman int compaction_register_node(struct node *node)
2824ed4a6d7fSMel Gorman {
282510fbcf4cSKay Sievers 	return device_create_file(&node->dev, &dev_attr_compact);
2826ed4a6d7fSMel Gorman }
2827ed4a6d7fSMel Gorman 
2828ed4a6d7fSMel Gorman void compaction_unregister_node(struct node *node)
2829ed4a6d7fSMel Gorman {
283010fbcf4cSKay Sievers 	return device_remove_file(&node->dev, &dev_attr_compact);
2831ed4a6d7fSMel Gorman }
2832ed4a6d7fSMel Gorman #endif /* CONFIG_SYSFS && CONFIG_NUMA */
2833ff9543fdSMichal Nazarewicz 
2834698b1b30SVlastimil Babka static inline bool kcompactd_work_requested(pg_data_t *pgdat)
2835698b1b30SVlastimil Babka {
283665d759c8SCharan Teja Reddy 	return pgdat->kcompactd_max_order > 0 || kthread_should_stop() ||
283765d759c8SCharan Teja Reddy 		pgdat->proactive_compact_trigger;
2838698b1b30SVlastimil Babka }
2839698b1b30SVlastimil Babka 
2840698b1b30SVlastimil Babka static bool kcompactd_node_suitable(pg_data_t *pgdat)
2841698b1b30SVlastimil Babka {
2842698b1b30SVlastimil Babka 	int zoneid;
2843698b1b30SVlastimil Babka 	struct zone *zone;
284497a225e6SJoonsoo Kim 	enum zone_type highest_zoneidx = pgdat->kcompactd_highest_zoneidx;
2845698b1b30SVlastimil Babka 
284697a225e6SJoonsoo Kim 	for (zoneid = 0; zoneid <= highest_zoneidx; zoneid++) {
2847698b1b30SVlastimil Babka 		zone = &pgdat->node_zones[zoneid];
2848698b1b30SVlastimil Babka 
2849698b1b30SVlastimil Babka 		if (!populated_zone(zone))
2850698b1b30SVlastimil Babka 			continue;
2851698b1b30SVlastimil Babka 
2852e8606320SJohannes Weiner 		/* Allocation can already succeed, check other zones */
2853e8606320SJohannes Weiner 		if (zone_watermark_ok(zone, pgdat->kcompactd_max_order,
2854e8606320SJohannes Weiner 				      min_wmark_pages(zone),
2855e8606320SJohannes Weiner 				      highest_zoneidx, 0))
2856e8606320SJohannes Weiner 			continue;
2857e8606320SJohannes Weiner 
2858e8606320SJohannes Weiner 		if (compaction_suitable(zone, pgdat->kcompactd_max_order,
28593cf04937SJohannes Weiner 					highest_zoneidx))
2860698b1b30SVlastimil Babka 			return true;
2861698b1b30SVlastimil Babka 	}
2862698b1b30SVlastimil Babka 
2863698b1b30SVlastimil Babka 	return false;
2864698b1b30SVlastimil Babka }
2865698b1b30SVlastimil Babka 
2866698b1b30SVlastimil Babka static void kcompactd_do_work(pg_data_t *pgdat)
2867698b1b30SVlastimil Babka {
2868698b1b30SVlastimil Babka 	/*
2869698b1b30SVlastimil Babka 	 * With no special task, compact all zones so that a page of requested
2870698b1b30SVlastimil Babka 	 * order is allocatable.
2871698b1b30SVlastimil Babka 	 */
2872698b1b30SVlastimil Babka 	int zoneid;
2873698b1b30SVlastimil Babka 	struct zone *zone;
2874698b1b30SVlastimil Babka 	struct compact_control cc = {
2875698b1b30SVlastimil Babka 		.order = pgdat->kcompactd_max_order,
2876dbe2d4e4SMel Gorman 		.search_order = pgdat->kcompactd_max_order,
287797a225e6SJoonsoo Kim 		.highest_zoneidx = pgdat->kcompactd_highest_zoneidx,
2878698b1b30SVlastimil Babka 		.mode = MIGRATE_SYNC_LIGHT,
2879a0647dc9SDavid Rientjes 		.ignore_skip_hint = false,
288073e64c51SMichal Hocko 		.gfp_mask = GFP_KERNEL,
2881698b1b30SVlastimil Babka 	};
2882698b1b30SVlastimil Babka 	trace_mm_compaction_kcompactd_wake(pgdat->node_id, cc.order,
288397a225e6SJoonsoo Kim 							cc.highest_zoneidx);
28847f354a54SDavid Rientjes 	count_compact_event(KCOMPACTD_WAKE);
2885698b1b30SVlastimil Babka 
288697a225e6SJoonsoo Kim 	for (zoneid = 0; zoneid <= cc.highest_zoneidx; zoneid++) {
2887698b1b30SVlastimil Babka 		int status;
2888698b1b30SVlastimil Babka 
2889698b1b30SVlastimil Babka 		zone = &pgdat->node_zones[zoneid];
2890698b1b30SVlastimil Babka 		if (!populated_zone(zone))
2891698b1b30SVlastimil Babka 			continue;
2892698b1b30SVlastimil Babka 
2893698b1b30SVlastimil Babka 		if (compaction_deferred(zone, cc.order))
2894698b1b30SVlastimil Babka 			continue;
2895698b1b30SVlastimil Babka 
2896e8606320SJohannes Weiner 		/* Allocation can already succeed, nothing to do */
2897e8606320SJohannes Weiner 		if (zone_watermark_ok(zone, cc.order,
2898e8606320SJohannes Weiner 				      min_wmark_pages(zone), zoneid, 0))
2899698b1b30SVlastimil Babka 			continue;
2900698b1b30SVlastimil Babka 
29013cf04937SJohannes Weiner 		if (!compaction_suitable(zone, cc.order, zoneid))
2902e8606320SJohannes Weiner 			continue;
2903f98a497eSJohannes Weiner 
2904172400c6SVlastimil Babka 		if (kthread_should_stop())
2905172400c6SVlastimil Babka 			return;
2906a94b5252SYafang Shao 
2907a94b5252SYafang Shao 		cc.zone = zone;
29085e1f0f09SMel Gorman 		status = compact_zone(&cc, NULL);
2909698b1b30SVlastimil Babka 
29107ceb009aSVlastimil Babka 		if (status == COMPACT_SUCCESS) {
2911698b1b30SVlastimil Babka 			compaction_defer_reset(zone, cc.order, false);
2912c8f7de0bSMichal Hocko 		} else if (status == COMPACT_PARTIAL_SKIPPED || status == COMPACT_COMPLETE) {
2913698b1b30SVlastimil Babka 			/*
2914bc3106b2SDavid Rientjes 			 * Buddy pages may become stranded on pcps that could
2915bc3106b2SDavid Rientjes 			 * otherwise coalesce on the zone's free area for
2916bc3106b2SDavid Rientjes 			 * order >= cc.order.  This is ratelimited by the
2917bc3106b2SDavid Rientjes 			 * upcoming deferral.
2918bc3106b2SDavid Rientjes 			 */
2919bc3106b2SDavid Rientjes 			drain_all_pages(zone);
2920bc3106b2SDavid Rientjes 
2921bc3106b2SDavid Rientjes 			/*
2922698b1b30SVlastimil Babka 			 * We use sync migration mode here, so we defer like
2923698b1b30SVlastimil Babka 			 * sync direct compaction does.
2924698b1b30SVlastimil Babka 			 */
2925698b1b30SVlastimil Babka 			defer_compaction(zone, cc.order);
2926698b1b30SVlastimil Babka 		}
2927698b1b30SVlastimil Babka 
29287f354a54SDavid Rientjes 		count_compact_events(KCOMPACTD_MIGRATE_SCANNED,
29297f354a54SDavid Rientjes 				     cc.total_migrate_scanned);
29307f354a54SDavid Rientjes 		count_compact_events(KCOMPACTD_FREE_SCANNED,
29317f354a54SDavid Rientjes 				     cc.total_free_scanned);
2932698b1b30SVlastimil Babka 	}
2933698b1b30SVlastimil Babka 
2934698b1b30SVlastimil Babka 	/*
2935698b1b30SVlastimil Babka 	 * Regardless of success, we are done until woken up next. But remember
293697a225e6SJoonsoo Kim 	 * the requested order/highest_zoneidx in case it was higher/tighter
293797a225e6SJoonsoo Kim 	 * than our current ones
2938698b1b30SVlastimil Babka 	 */
2939698b1b30SVlastimil Babka 	if (pgdat->kcompactd_max_order <= cc.order)
2940698b1b30SVlastimil Babka 		pgdat->kcompactd_max_order = 0;
294197a225e6SJoonsoo Kim 	if (pgdat->kcompactd_highest_zoneidx >= cc.highest_zoneidx)
294297a225e6SJoonsoo Kim 		pgdat->kcompactd_highest_zoneidx = pgdat->nr_zones - 1;
2943698b1b30SVlastimil Babka }
2944698b1b30SVlastimil Babka 
294597a225e6SJoonsoo Kim void wakeup_kcompactd(pg_data_t *pgdat, int order, int highest_zoneidx)
2946698b1b30SVlastimil Babka {
2947698b1b30SVlastimil Babka 	if (!order)
2948698b1b30SVlastimil Babka 		return;
2949698b1b30SVlastimil Babka 
2950698b1b30SVlastimil Babka 	if (pgdat->kcompactd_max_order < order)
2951698b1b30SVlastimil Babka 		pgdat->kcompactd_max_order = order;
2952698b1b30SVlastimil Babka 
295397a225e6SJoonsoo Kim 	if (pgdat->kcompactd_highest_zoneidx > highest_zoneidx)
295497a225e6SJoonsoo Kim 		pgdat->kcompactd_highest_zoneidx = highest_zoneidx;
2955698b1b30SVlastimil Babka 
29566818600fSDavidlohr Bueso 	/*
29576818600fSDavidlohr Bueso 	 * Pairs with implicit barrier in wait_event_freezable()
29586818600fSDavidlohr Bueso 	 * such that wakeups are not missed.
29596818600fSDavidlohr Bueso 	 */
29606818600fSDavidlohr Bueso 	if (!wq_has_sleeper(&pgdat->kcompactd_wait))
2961698b1b30SVlastimil Babka 		return;
2962698b1b30SVlastimil Babka 
2963698b1b30SVlastimil Babka 	if (!kcompactd_node_suitable(pgdat))
2964698b1b30SVlastimil Babka 		return;
2965698b1b30SVlastimil Babka 
2966698b1b30SVlastimil Babka 	trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, order,
296797a225e6SJoonsoo Kim 							highest_zoneidx);
2968698b1b30SVlastimil Babka 	wake_up_interruptible(&pgdat->kcompactd_wait);
2969698b1b30SVlastimil Babka }
2970698b1b30SVlastimil Babka 
2971698b1b30SVlastimil Babka /*
2972698b1b30SVlastimil Babka  * The background compaction daemon, started as a kernel thread
2973698b1b30SVlastimil Babka  * from the init process.
2974698b1b30SVlastimil Babka  */
2975698b1b30SVlastimil Babka static int kcompactd(void *p)
2976698b1b30SVlastimil Babka {
2977698b1b30SVlastimil Babka 	pg_data_t *pgdat = (pg_data_t *)p;
2978698b1b30SVlastimil Babka 	struct task_struct *tsk = current;
2979e1e92bfaSCharan Teja Reddy 	long default_timeout = msecs_to_jiffies(HPAGE_FRAG_CHECK_INTERVAL_MSEC);
2980e1e92bfaSCharan Teja Reddy 	long timeout = default_timeout;
2981698b1b30SVlastimil Babka 
2982698b1b30SVlastimil Babka 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
2983698b1b30SVlastimil Babka 
2984698b1b30SVlastimil Babka 	if (!cpumask_empty(cpumask))
2985698b1b30SVlastimil Babka 		set_cpus_allowed_ptr(tsk, cpumask);
2986698b1b30SVlastimil Babka 
2987698b1b30SVlastimil Babka 	set_freezable();
2988698b1b30SVlastimil Babka 
2989698b1b30SVlastimil Babka 	pgdat->kcompactd_max_order = 0;
299097a225e6SJoonsoo Kim 	pgdat->kcompactd_highest_zoneidx = pgdat->nr_zones - 1;
2991698b1b30SVlastimil Babka 
2992698b1b30SVlastimil Babka 	while (!kthread_should_stop()) {
2993eb414681SJohannes Weiner 		unsigned long pflags;
2994eb414681SJohannes Weiner 
299565d759c8SCharan Teja Reddy 		/*
299665d759c8SCharan Teja Reddy 		 * Avoid the unnecessary wakeup for proactive compaction
299765d759c8SCharan Teja Reddy 		 * when it is disabled.
299865d759c8SCharan Teja Reddy 		 */
299965d759c8SCharan Teja Reddy 		if (!sysctl_compaction_proactiveness)
300065d759c8SCharan Teja Reddy 			timeout = MAX_SCHEDULE_TIMEOUT;
3001698b1b30SVlastimil Babka 		trace_mm_compaction_kcompactd_sleep(pgdat->node_id);
3002facdaa91SNitin Gupta 		if (wait_event_freezable_timeout(pgdat->kcompactd_wait,
300365d759c8SCharan Teja Reddy 			kcompactd_work_requested(pgdat), timeout) &&
300465d759c8SCharan Teja Reddy 			!pgdat->proactive_compact_trigger) {
3005698b1b30SVlastimil Babka 
3006eb414681SJohannes Weiner 			psi_memstall_enter(&pflags);
3007698b1b30SVlastimil Babka 			kcompactd_do_work(pgdat);
3008eb414681SJohannes Weiner 			psi_memstall_leave(&pflags);
3009e1e92bfaSCharan Teja Reddy 			/*
3010e1e92bfaSCharan Teja Reddy 			 * Reset the timeout value. The defer timeout from
3011e1e92bfaSCharan Teja Reddy 			 * proactive compaction is lost here but that is fine
3012e1e92bfaSCharan Teja Reddy 			 * as the condition of the zone changing substantionally
3013e1e92bfaSCharan Teja Reddy 			 * then carrying on with the previous defer interval is
3014e1e92bfaSCharan Teja Reddy 			 * not useful.
3015e1e92bfaSCharan Teja Reddy 			 */
3016e1e92bfaSCharan Teja Reddy 			timeout = default_timeout;
3017facdaa91SNitin Gupta 			continue;
3018facdaa91SNitin Gupta 		}
3019facdaa91SNitin Gupta 
3020e1e92bfaSCharan Teja Reddy 		/*
3021e1e92bfaSCharan Teja Reddy 		 * Start the proactive work with default timeout. Based
3022e1e92bfaSCharan Teja Reddy 		 * on the fragmentation score, this timeout is updated.
3023e1e92bfaSCharan Teja Reddy 		 */
3024e1e92bfaSCharan Teja Reddy 		timeout = default_timeout;
3025facdaa91SNitin Gupta 		if (should_proactive_compact_node(pgdat)) {
3026facdaa91SNitin Gupta 			unsigned int prev_score, score;
3027facdaa91SNitin Gupta 
3028facdaa91SNitin Gupta 			prev_score = fragmentation_score_node(pgdat);
3029facdaa91SNitin Gupta 			proactive_compact_node(pgdat);
3030facdaa91SNitin Gupta 			score = fragmentation_score_node(pgdat);
3031facdaa91SNitin Gupta 			/*
3032facdaa91SNitin Gupta 			 * Defer proactive compaction if the fragmentation
3033facdaa91SNitin Gupta 			 * score did not go down i.e. no progress made.
3034facdaa91SNitin Gupta 			 */
3035e1e92bfaSCharan Teja Reddy 			if (unlikely(score >= prev_score))
3036e1e92bfaSCharan Teja Reddy 				timeout =
3037e1e92bfaSCharan Teja Reddy 				   default_timeout << COMPACT_MAX_DEFER_SHIFT;
3038facdaa91SNitin Gupta 		}
303965d759c8SCharan Teja Reddy 		if (unlikely(pgdat->proactive_compact_trigger))
304065d759c8SCharan Teja Reddy 			pgdat->proactive_compact_trigger = false;
3041698b1b30SVlastimil Babka 	}
3042698b1b30SVlastimil Babka 
3043698b1b30SVlastimil Babka 	return 0;
3044698b1b30SVlastimil Babka }
3045698b1b30SVlastimil Babka 
3046698b1b30SVlastimil Babka /*
3047698b1b30SVlastimil Babka  * This kcompactd start function will be called by init and node-hot-add.
3048698b1b30SVlastimil Babka  * On node-hot-add, kcompactd will moved to proper cpus if cpus are hot-added.
3049698b1b30SVlastimil Babka  */
3050024c61eaSMiaohe Lin void kcompactd_run(int nid)
3051698b1b30SVlastimil Babka {
3052698b1b30SVlastimil Babka 	pg_data_t *pgdat = NODE_DATA(nid);
3053698b1b30SVlastimil Babka 
3054698b1b30SVlastimil Babka 	if (pgdat->kcompactd)
3055024c61eaSMiaohe Lin 		return;
3056698b1b30SVlastimil Babka 
3057698b1b30SVlastimil Babka 	pgdat->kcompactd = kthread_run(kcompactd, pgdat, "kcompactd%d", nid);
3058698b1b30SVlastimil Babka 	if (IS_ERR(pgdat->kcompactd)) {
3059698b1b30SVlastimil Babka 		pr_err("Failed to start kcompactd on node %d\n", nid);
3060698b1b30SVlastimil Babka 		pgdat->kcompactd = NULL;
3061698b1b30SVlastimil Babka 	}
3062698b1b30SVlastimil Babka }
3063698b1b30SVlastimil Babka 
3064698b1b30SVlastimil Babka /*
3065698b1b30SVlastimil Babka  * Called by memory hotplug when all memory in a node is offlined. Caller must
3066e8da368aSYun-Ze Li  * be holding mem_hotplug_begin/done().
3067698b1b30SVlastimil Babka  */
3068698b1b30SVlastimil Babka void kcompactd_stop(int nid)
3069698b1b30SVlastimil Babka {
3070698b1b30SVlastimil Babka 	struct task_struct *kcompactd = NODE_DATA(nid)->kcompactd;
3071698b1b30SVlastimil Babka 
3072698b1b30SVlastimil Babka 	if (kcompactd) {
3073698b1b30SVlastimil Babka 		kthread_stop(kcompactd);
3074698b1b30SVlastimil Babka 		NODE_DATA(nid)->kcompactd = NULL;
3075698b1b30SVlastimil Babka 	}
3076698b1b30SVlastimil Babka }
3077698b1b30SVlastimil Babka 
3078698b1b30SVlastimil Babka /*
3079698b1b30SVlastimil Babka  * It's optimal to keep kcompactd on the same CPUs as their memory, but
3080698b1b30SVlastimil Babka  * not required for correctness. So if the last cpu in a node goes
3081698b1b30SVlastimil Babka  * away, we get changed to run anywhere: as the first one comes back,
3082698b1b30SVlastimil Babka  * restore their cpu bindings.
3083698b1b30SVlastimil Babka  */
3084e46b1db2SAnna-Maria Gleixner static int kcompactd_cpu_online(unsigned int cpu)
3085698b1b30SVlastimil Babka {
3086698b1b30SVlastimil Babka 	int nid;
3087698b1b30SVlastimil Babka 
3088698b1b30SVlastimil Babka 	for_each_node_state(nid, N_MEMORY) {
3089698b1b30SVlastimil Babka 		pg_data_t *pgdat = NODE_DATA(nid);
3090698b1b30SVlastimil Babka 		const struct cpumask *mask;
3091698b1b30SVlastimil Babka 
3092698b1b30SVlastimil Babka 		mask = cpumask_of_node(pgdat->node_id);
3093698b1b30SVlastimil Babka 
3094698b1b30SVlastimil Babka 		if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
3095698b1b30SVlastimil Babka 			/* One of our CPUs online: restore mask */
30963109de30SMiaohe Lin 			if (pgdat->kcompactd)
3097698b1b30SVlastimil Babka 				set_cpus_allowed_ptr(pgdat->kcompactd, mask);
3098698b1b30SVlastimil Babka 	}
3099e46b1db2SAnna-Maria Gleixner 	return 0;
3100698b1b30SVlastimil Babka }
3101698b1b30SVlastimil Babka 
310248fe8ab8SMinghao Chi static int proc_dointvec_minmax_warn_RT_change(struct ctl_table *table,
310348fe8ab8SMinghao Chi 		int write, void *buffer, size_t *lenp, loff_t *ppos)
310448fe8ab8SMinghao Chi {
310548fe8ab8SMinghao Chi 	int ret, old;
310648fe8ab8SMinghao Chi 
310748fe8ab8SMinghao Chi 	if (!IS_ENABLED(CONFIG_PREEMPT_RT) || !write)
310848fe8ab8SMinghao Chi 		return proc_dointvec_minmax(table, write, buffer, lenp, ppos);
310948fe8ab8SMinghao Chi 
311048fe8ab8SMinghao Chi 	old = *(int *)table->data;
311148fe8ab8SMinghao Chi 	ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
311248fe8ab8SMinghao Chi 	if (ret)
311348fe8ab8SMinghao Chi 		return ret;
311448fe8ab8SMinghao Chi 	if (old != *(int *)table->data)
311548fe8ab8SMinghao Chi 		pr_warn_once("sysctl attribute %s changed by %s[%d]\n",
311648fe8ab8SMinghao Chi 			     table->procname, current->comm,
311748fe8ab8SMinghao Chi 			     task_pid_nr(current));
311848fe8ab8SMinghao Chi 	return ret;
311948fe8ab8SMinghao Chi }
312048fe8ab8SMinghao Chi 
312148fe8ab8SMinghao Chi static struct ctl_table vm_compaction[] = {
312248fe8ab8SMinghao Chi 	{
312348fe8ab8SMinghao Chi 		.procname	= "compact_memory",
31248b9167cdSWen Yang 		.data		= &sysctl_compact_memory,
312548fe8ab8SMinghao Chi 		.maxlen		= sizeof(int),
312648fe8ab8SMinghao Chi 		.mode		= 0200,
312748fe8ab8SMinghao Chi 		.proc_handler	= sysctl_compaction_handler,
312848fe8ab8SMinghao Chi 	},
312948fe8ab8SMinghao Chi 	{
313048fe8ab8SMinghao Chi 		.procname	= "compaction_proactiveness",
313148fe8ab8SMinghao Chi 		.data		= &sysctl_compaction_proactiveness,
313248fe8ab8SMinghao Chi 		.maxlen		= sizeof(sysctl_compaction_proactiveness),
313348fe8ab8SMinghao Chi 		.mode		= 0644,
313448fe8ab8SMinghao Chi 		.proc_handler	= compaction_proactiveness_sysctl_handler,
313548fe8ab8SMinghao Chi 		.extra1		= SYSCTL_ZERO,
313648fe8ab8SMinghao Chi 		.extra2		= SYSCTL_ONE_HUNDRED,
313748fe8ab8SMinghao Chi 	},
313848fe8ab8SMinghao Chi 	{
313948fe8ab8SMinghao Chi 		.procname	= "extfrag_threshold",
314048fe8ab8SMinghao Chi 		.data		= &sysctl_extfrag_threshold,
314148fe8ab8SMinghao Chi 		.maxlen		= sizeof(int),
314248fe8ab8SMinghao Chi 		.mode		= 0644,
314348fe8ab8SMinghao Chi 		.proc_handler	= proc_dointvec_minmax,
314448fe8ab8SMinghao Chi 		.extra1		= SYSCTL_ZERO,
314548fe8ab8SMinghao Chi 		.extra2		= SYSCTL_ONE_THOUSAND,
314648fe8ab8SMinghao Chi 	},
314748fe8ab8SMinghao Chi 	{
314848fe8ab8SMinghao Chi 		.procname	= "compact_unevictable_allowed",
314948fe8ab8SMinghao Chi 		.data		= &sysctl_compact_unevictable_allowed,
315048fe8ab8SMinghao Chi 		.maxlen		= sizeof(int),
315148fe8ab8SMinghao Chi 		.mode		= 0644,
315248fe8ab8SMinghao Chi 		.proc_handler	= proc_dointvec_minmax_warn_RT_change,
315348fe8ab8SMinghao Chi 		.extra1		= SYSCTL_ZERO,
315448fe8ab8SMinghao Chi 		.extra2		= SYSCTL_ONE,
315548fe8ab8SMinghao Chi 	},
315648fe8ab8SMinghao Chi 	{ }
315748fe8ab8SMinghao Chi };
315848fe8ab8SMinghao Chi 
3159698b1b30SVlastimil Babka static int __init kcompactd_init(void)
3160698b1b30SVlastimil Babka {
3161698b1b30SVlastimil Babka 	int nid;
3162e46b1db2SAnna-Maria Gleixner 	int ret;
3163e46b1db2SAnna-Maria Gleixner 
3164e46b1db2SAnna-Maria Gleixner 	ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
3165e46b1db2SAnna-Maria Gleixner 					"mm/compaction:online",
3166e46b1db2SAnna-Maria Gleixner 					kcompactd_cpu_online, NULL);
3167e46b1db2SAnna-Maria Gleixner 	if (ret < 0) {
3168e46b1db2SAnna-Maria Gleixner 		pr_err("kcompactd: failed to register hotplug callbacks.\n");
3169e46b1db2SAnna-Maria Gleixner 		return ret;
3170e46b1db2SAnna-Maria Gleixner 	}
3171698b1b30SVlastimil Babka 
3172698b1b30SVlastimil Babka 	for_each_node_state(nid, N_MEMORY)
3173698b1b30SVlastimil Babka 		kcompactd_run(nid);
317448fe8ab8SMinghao Chi 	register_sysctl_init("vm", vm_compaction);
3175698b1b30SVlastimil Babka 	return 0;
3176698b1b30SVlastimil Babka }
3177698b1b30SVlastimil Babka subsys_initcall(kcompactd_init)
3178698b1b30SVlastimil Babka 
3179ff9543fdSMichal Nazarewicz #endif /* CONFIG_COMPACTION */
3180