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