1 // SPDX-License-Identifier: GPL-2.0
3 * linux/mm/compaction.c
5 * Memory compaction for the reduction of external fragmentation. Note that
6 * this heavily depends upon page migration to do all the real heavy
9 * Copyright IBM Corp. 2007-2010 Mel Gorman <mel@csn.ul.ie>
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>
28 #ifdef CONFIG_COMPACTION
30 * Fragmentation score check interval for proactive compaction purposes.
32 #define HPAGE_FRAG_CHECK_INTERVAL_MSEC (500)
34 static inline void count_compact_event(enum vm_event_item item)
39 static inline void count_compact_events(enum vm_event_item item, long delta)
41 count_vm_events(item, delta);
44 #define count_compact_event(item) do { } while (0)
45 #define count_compact_events(item, delta) do { } while (0)
48 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
50 #define CREATE_TRACE_POINTS
51 #include <trace/events/compaction.h>
53 #define block_start_pfn(pfn, order) round_down(pfn, 1UL << (order))
54 #define block_end_pfn(pfn, order) ALIGN((pfn) + 1, 1UL << (order))
57 * Page order with-respect-to which proactive compaction
58 * calculates external fragmentation, which is used as
59 * the "fragmentation score" of a node/zone.
61 #if defined CONFIG_TRANSPARENT_HUGEPAGE
62 #define COMPACTION_HPAGE_ORDER HPAGE_PMD_ORDER
63 #elif defined CONFIG_HUGETLBFS
64 #define COMPACTION_HPAGE_ORDER HUGETLB_PAGE_ORDER
66 #define COMPACTION_HPAGE_ORDER (PMD_SHIFT - PAGE_SHIFT)
69 static unsigned long release_freepages(struct list_head *freelist)
71 struct page *page, *next;
72 unsigned long high_pfn = 0;
74 list_for_each_entry_safe(page, next, freelist, lru) {
75 unsigned long pfn = page_to_pfn(page);
85 static void split_map_pages(struct list_head *list)
87 unsigned int i, order, nr_pages;
88 struct page *page, *next;
91 list_for_each_entry_safe(page, next, list, lru) {
94 order = page_private(page);
95 nr_pages = 1 << order;
97 post_alloc_hook(page, order, __GFP_MOVABLE);
99 split_page(page, order);
101 for (i = 0; i < nr_pages; i++) {
102 list_add(&page->lru, &tmp_list);
107 list_splice(&tmp_list, list);
110 #ifdef CONFIG_COMPACTION
111 bool PageMovable(struct page *page)
113 const struct movable_operations *mops;
115 VM_BUG_ON_PAGE(!PageLocked(page), page);
116 if (!__PageMovable(page))
119 mops = page_movable_ops(page);
126 void __SetPageMovable(struct page *page, const struct movable_operations *mops)
128 VM_BUG_ON_PAGE(!PageLocked(page), page);
129 VM_BUG_ON_PAGE((unsigned long)mops & PAGE_MAPPING_MOVABLE, page);
130 page->mapping = (void *)((unsigned long)mops | PAGE_MAPPING_MOVABLE);
132 EXPORT_SYMBOL(__SetPageMovable);
134 void __ClearPageMovable(struct page *page)
136 VM_BUG_ON_PAGE(!PageMovable(page), page);
138 * This page still has the type of a movable page, but it's
139 * actually not movable any more.
141 page->mapping = (void *)PAGE_MAPPING_MOVABLE;
143 EXPORT_SYMBOL(__ClearPageMovable);
145 /* Do not skip compaction more than 64 times */
146 #define COMPACT_MAX_DEFER_SHIFT 6
149 * Compaction is deferred when compaction fails to result in a page
150 * allocation success. 1 << compact_defer_shift, compactions are skipped up
151 * to a limit of 1 << COMPACT_MAX_DEFER_SHIFT
153 static void defer_compaction(struct zone *zone, int order)
155 zone->compact_considered = 0;
156 zone->compact_defer_shift++;
158 if (order < zone->compact_order_failed)
159 zone->compact_order_failed = order;
161 if (zone->compact_defer_shift > COMPACT_MAX_DEFER_SHIFT)
162 zone->compact_defer_shift = COMPACT_MAX_DEFER_SHIFT;
164 trace_mm_compaction_defer_compaction(zone, order);
167 /* Returns true if compaction should be skipped this time */
168 static bool compaction_deferred(struct zone *zone, int order)
170 unsigned long defer_limit = 1UL << zone->compact_defer_shift;
172 if (order < zone->compact_order_failed)
175 /* Avoid possible overflow */
176 if (++zone->compact_considered >= defer_limit) {
177 zone->compact_considered = defer_limit;
181 trace_mm_compaction_deferred(zone, order);
187 * Update defer tracking counters after successful compaction of given order,
188 * which means an allocation either succeeded (alloc_success == true) or is
189 * expected to succeed.
191 void compaction_defer_reset(struct zone *zone, int order,
195 zone->compact_considered = 0;
196 zone->compact_defer_shift = 0;
198 if (order >= zone->compact_order_failed)
199 zone->compact_order_failed = order + 1;
201 trace_mm_compaction_defer_reset(zone, order);
204 /* Returns true if restarting compaction after many failures */
205 static bool compaction_restarting(struct zone *zone, int order)
207 if (order < zone->compact_order_failed)
210 return zone->compact_defer_shift == COMPACT_MAX_DEFER_SHIFT &&
211 zone->compact_considered >= 1UL << zone->compact_defer_shift;
214 /* Returns true if the pageblock should be scanned for pages to isolate. */
215 static inline bool isolation_suitable(struct compact_control *cc,
218 if (cc->ignore_skip_hint)
221 return !get_pageblock_skip(page);
224 static void reset_cached_positions(struct zone *zone)
226 zone->compact_cached_migrate_pfn[0] = zone->zone_start_pfn;
227 zone->compact_cached_migrate_pfn[1] = zone->zone_start_pfn;
228 zone->compact_cached_free_pfn =
229 pageblock_start_pfn(zone_end_pfn(zone) - 1);
232 #ifdef CONFIG_SPARSEMEM
234 * If the PFN falls into an offline section, return the start PFN of the
235 * next online section. If the PFN falls into an online section or if
236 * there is no next online section, return 0.
238 static unsigned long skip_offline_sections(unsigned long start_pfn)
240 unsigned long start_nr = pfn_to_section_nr(start_pfn);
242 if (online_section_nr(start_nr))
245 while (++start_nr <= __highest_present_section_nr) {
246 if (online_section_nr(start_nr))
247 return section_nr_to_pfn(start_nr);
253 static unsigned long skip_offline_sections(unsigned long start_pfn)
260 * Compound pages of >= pageblock_order should consistently be skipped until
261 * released. It is always pointless to compact pages of such order (if they are
262 * migratable), and the pageblocks they occupy cannot contain any free pages.
264 static bool pageblock_skip_persistent(struct page *page)
266 if (!PageCompound(page))
269 page = compound_head(page);
271 if (compound_order(page) >= pageblock_order)
278 __reset_isolation_pfn(struct zone *zone, unsigned long pfn, bool check_source,
281 struct page *page = pfn_to_online_page(pfn);
282 struct page *block_page;
283 struct page *end_page;
284 unsigned long block_pfn;
288 if (zone != page_zone(page))
290 if (pageblock_skip_persistent(page))
294 * If skip is already cleared do no further checking once the
295 * restart points have been set.
297 if (check_source && check_target && !get_pageblock_skip(page))
301 * If clearing skip for the target scanner, do not select a
302 * non-movable pageblock as the starting point.
304 if (!check_source && check_target &&
305 get_pageblock_migratetype(page) != MIGRATE_MOVABLE)
308 /* Ensure the start of the pageblock or zone is online and valid */
309 block_pfn = pageblock_start_pfn(pfn);
310 block_pfn = max(block_pfn, zone->zone_start_pfn);
311 block_page = pfn_to_online_page(block_pfn);
317 /* Ensure the end of the pageblock or zone is online and valid */
318 block_pfn = pageblock_end_pfn(pfn) - 1;
319 block_pfn = min(block_pfn, zone_end_pfn(zone) - 1);
320 end_page = pfn_to_online_page(block_pfn);
325 * Only clear the hint if a sample indicates there is either a
326 * free page or an LRU page in the block. One or other condition
327 * is necessary for the block to be a migration source/target.
330 if (check_source && PageLRU(page)) {
331 clear_pageblock_skip(page);
335 if (check_target && PageBuddy(page)) {
336 clear_pageblock_skip(page);
340 page += (1 << PAGE_ALLOC_COSTLY_ORDER);
341 } while (page <= end_page);
347 * This function is called to clear all cached information on pageblocks that
348 * should be skipped for page isolation when the migrate and free page scanner
351 static void __reset_isolation_suitable(struct zone *zone)
353 unsigned long migrate_pfn = zone->zone_start_pfn;
354 unsigned long free_pfn = zone_end_pfn(zone) - 1;
355 unsigned long reset_migrate = free_pfn;
356 unsigned long reset_free = migrate_pfn;
357 bool source_set = false;
358 bool free_set = false;
360 if (!zone->compact_blockskip_flush)
363 zone->compact_blockskip_flush = false;
366 * Walk the zone and update pageblock skip information. Source looks
367 * for PageLRU while target looks for PageBuddy. When the scanner
368 * is found, both PageBuddy and PageLRU are checked as the pageblock
369 * is suitable as both source and target.
371 for (; migrate_pfn < free_pfn; migrate_pfn += pageblock_nr_pages,
372 free_pfn -= pageblock_nr_pages) {
375 /* Update the migrate PFN */
376 if (__reset_isolation_pfn(zone, migrate_pfn, true, source_set) &&
377 migrate_pfn < reset_migrate) {
379 reset_migrate = migrate_pfn;
380 zone->compact_init_migrate_pfn = reset_migrate;
381 zone->compact_cached_migrate_pfn[0] = reset_migrate;
382 zone->compact_cached_migrate_pfn[1] = reset_migrate;
385 /* Update the free PFN */
386 if (__reset_isolation_pfn(zone, free_pfn, free_set, true) &&
387 free_pfn > reset_free) {
389 reset_free = free_pfn;
390 zone->compact_init_free_pfn = reset_free;
391 zone->compact_cached_free_pfn = reset_free;
395 /* Leave no distance if no suitable block was reset */
396 if (reset_migrate >= reset_free) {
397 zone->compact_cached_migrate_pfn[0] = migrate_pfn;
398 zone->compact_cached_migrate_pfn[1] = migrate_pfn;
399 zone->compact_cached_free_pfn = free_pfn;
403 void reset_isolation_suitable(pg_data_t *pgdat)
407 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
408 struct zone *zone = &pgdat->node_zones[zoneid];
409 if (!populated_zone(zone))
412 /* Only flush if a full compaction finished recently */
413 if (zone->compact_blockskip_flush)
414 __reset_isolation_suitable(zone);
419 * Sets the pageblock skip bit if it was clear. Note that this is a hint as
420 * locks are not required for read/writers. Returns true if it was already set.
422 static bool test_and_set_skip(struct compact_control *cc, struct page *page)
426 /* Do not update if skip hint is being ignored */
427 if (cc->ignore_skip_hint)
430 skip = get_pageblock_skip(page);
431 if (!skip && !cc->no_set_skip_hint)
432 set_pageblock_skip(page);
437 static void update_cached_migrate(struct compact_control *cc, unsigned long pfn)
439 struct zone *zone = cc->zone;
441 pfn = pageblock_end_pfn(pfn);
443 /* Set for isolation rather than compaction */
444 if (cc->no_set_skip_hint)
447 if (pfn > zone->compact_cached_migrate_pfn[0])
448 zone->compact_cached_migrate_pfn[0] = pfn;
449 if (cc->mode != MIGRATE_ASYNC &&
450 pfn > zone->compact_cached_migrate_pfn[1])
451 zone->compact_cached_migrate_pfn[1] = pfn;
455 * If no pages were isolated then mark this pageblock to be skipped in the
456 * future. The information is later cleared by __reset_isolation_suitable().
458 static void update_pageblock_skip(struct compact_control *cc,
459 struct page *page, unsigned long pfn)
461 struct zone *zone = cc->zone;
463 if (cc->no_set_skip_hint)
466 set_pageblock_skip(page);
468 /* Update where async and sync compaction should restart */
469 if (pfn < zone->compact_cached_free_pfn)
470 zone->compact_cached_free_pfn = pfn;
473 static inline bool isolation_suitable(struct compact_control *cc,
479 static inline bool pageblock_skip_persistent(struct page *page)
484 static inline void update_pageblock_skip(struct compact_control *cc,
485 struct page *page, unsigned long pfn)
489 static void update_cached_migrate(struct compact_control *cc, unsigned long pfn)
493 static bool test_and_set_skip(struct compact_control *cc, struct page *page)
497 #endif /* CONFIG_COMPACTION */
500 * Compaction requires the taking of some coarse locks that are potentially
501 * very heavily contended. For async compaction, trylock and record if the
502 * lock is contended. The lock will still be acquired but compaction will
503 * abort when the current block is finished regardless of success rate.
504 * Sync compaction acquires the lock.
506 * Always returns true which makes it easier to track lock state in callers.
508 static bool compact_lock_irqsave(spinlock_t *lock, unsigned long *flags,
509 struct compact_control *cc)
512 /* Track if the lock is contended in async mode */
513 if (cc->mode == MIGRATE_ASYNC && !cc->contended) {
514 if (spin_trylock_irqsave(lock, *flags))
517 cc->contended = true;
520 spin_lock_irqsave(lock, *flags);
525 * Compaction requires the taking of some coarse locks that are potentially
526 * very heavily contended. The lock should be periodically unlocked to avoid
527 * having disabled IRQs for a long time, even when there is nobody waiting on
528 * the lock. It might also be that allowing the IRQs will result in
529 * need_resched() becoming true. If scheduling is needed, compaction schedules.
530 * Either compaction type will also abort if a fatal signal is pending.
531 * In either case if the lock was locked, it is dropped and not regained.
533 * Returns true if compaction should abort due to fatal signal pending.
534 * Returns false when compaction can continue.
536 static bool compact_unlock_should_abort(spinlock_t *lock,
537 unsigned long flags, bool *locked, struct compact_control *cc)
540 spin_unlock_irqrestore(lock, flags);
544 if (fatal_signal_pending(current)) {
545 cc->contended = true;
555 * Isolate free pages onto a private freelist. If @strict is true, will abort
556 * returning 0 on any invalid PFNs or non-free pages inside of the pageblock
557 * (even though it may still end up isolating some pages).
559 static unsigned long isolate_freepages_block(struct compact_control *cc,
560 unsigned long *start_pfn,
561 unsigned long end_pfn,
562 struct list_head *freelist,
566 int nr_scanned = 0, total_isolated = 0;
568 unsigned long flags = 0;
570 unsigned long blockpfn = *start_pfn;
573 /* Strict mode is for isolation, speed is secondary */
577 cursor = pfn_to_page(blockpfn);
579 /* Isolate free pages. */
580 for (; blockpfn < end_pfn; blockpfn += stride, cursor += stride) {
582 struct page *page = cursor;
585 * Periodically drop the lock (if held) regardless of its
586 * contention, to give chance to IRQs. Abort if fatal signal
589 if (!(blockpfn % COMPACT_CLUSTER_MAX)
590 && compact_unlock_should_abort(&cc->zone->lock, flags,
597 * For compound pages such as THP and hugetlbfs, we can save
598 * potentially a lot of iterations if we skip them at once.
599 * The check is racy, but we can consider only valid values
600 * and the only danger is skipping too much.
602 if (PageCompound(page)) {
603 const unsigned int order = compound_order(page);
605 if (likely(order <= MAX_ORDER)) {
606 blockpfn += (1UL << order) - 1;
607 cursor += (1UL << order) - 1;
608 nr_scanned += (1UL << order) - 1;
613 if (!PageBuddy(page))
616 /* If we already hold the lock, we can skip some rechecking. */
618 locked = compact_lock_irqsave(&cc->zone->lock,
621 /* Recheck this is a buddy page under lock */
622 if (!PageBuddy(page))
626 /* Found a free page, will break it into order-0 pages */
627 order = buddy_order(page);
628 isolated = __isolate_free_page(page, order);
631 set_page_private(page, order);
633 nr_scanned += isolated - 1;
634 total_isolated += isolated;
635 cc->nr_freepages += isolated;
636 list_add_tail(&page->lru, freelist);
638 if (!strict && cc->nr_migratepages <= cc->nr_freepages) {
639 blockpfn += isolated;
642 /* Advance to the end of split page */
643 blockpfn += isolated - 1;
644 cursor += isolated - 1;
656 spin_unlock_irqrestore(&cc->zone->lock, flags);
659 * There is a tiny chance that we have read bogus compound_order(),
660 * so be careful to not go outside of the pageblock.
662 if (unlikely(blockpfn > end_pfn))
665 trace_mm_compaction_isolate_freepages(*start_pfn, blockpfn,
666 nr_scanned, total_isolated);
668 /* Record how far we have got within the block */
669 *start_pfn = blockpfn;
672 * If strict isolation is requested by CMA then check that all the
673 * pages requested were isolated. If there were any failures, 0 is
674 * returned and CMA will fail.
676 if (strict && blockpfn < end_pfn)
679 cc->total_free_scanned += nr_scanned;
681 count_compact_events(COMPACTISOLATED, total_isolated);
682 return total_isolated;
686 * isolate_freepages_range() - isolate free pages.
687 * @cc: Compaction control structure.
688 * @start_pfn: The first PFN to start isolating.
689 * @end_pfn: The one-past-last PFN.
691 * Non-free pages, invalid PFNs, or zone boundaries within the
692 * [start_pfn, end_pfn) range are considered errors, cause function to
693 * undo its actions and return zero.
695 * Otherwise, function returns one-past-the-last PFN of isolated page
696 * (which may be greater then end_pfn if end fell in a middle of
700 isolate_freepages_range(struct compact_control *cc,
701 unsigned long start_pfn, unsigned long end_pfn)
703 unsigned long isolated, pfn, block_start_pfn, block_end_pfn;
707 block_start_pfn = pageblock_start_pfn(pfn);
708 if (block_start_pfn < cc->zone->zone_start_pfn)
709 block_start_pfn = cc->zone->zone_start_pfn;
710 block_end_pfn = pageblock_end_pfn(pfn);
712 for (; pfn < end_pfn; pfn += isolated,
713 block_start_pfn = block_end_pfn,
714 block_end_pfn += pageblock_nr_pages) {
715 /* Protect pfn from changing by isolate_freepages_block */
716 unsigned long isolate_start_pfn = pfn;
718 block_end_pfn = min(block_end_pfn, end_pfn);
721 * pfn could pass the block_end_pfn if isolated freepage
722 * is more than pageblock order. In this case, we adjust
723 * scanning range to right one.
725 if (pfn >= block_end_pfn) {
726 block_start_pfn = pageblock_start_pfn(pfn);
727 block_end_pfn = pageblock_end_pfn(pfn);
728 block_end_pfn = min(block_end_pfn, end_pfn);
731 if (!pageblock_pfn_to_page(block_start_pfn,
732 block_end_pfn, cc->zone))
735 isolated = isolate_freepages_block(cc, &isolate_start_pfn,
736 block_end_pfn, &freelist, 0, true);
739 * In strict mode, isolate_freepages_block() returns 0 if
740 * there are any holes in the block (ie. invalid PFNs or
747 * If we managed to isolate pages, it is always (1 << n) *
748 * pageblock_nr_pages for some non-negative n. (Max order
749 * page may span two pageblocks).
753 /* __isolate_free_page() does not map the pages */
754 split_map_pages(&freelist);
757 /* Loop terminated early, cleanup. */
758 release_freepages(&freelist);
762 /* We don't use freelists for anything. */
766 /* Similar to reclaim, but different enough that they don't share logic */
767 static bool too_many_isolated(struct compact_control *cc)
769 pg_data_t *pgdat = cc->zone->zone_pgdat;
772 unsigned long active, inactive, isolated;
774 inactive = node_page_state(pgdat, NR_INACTIVE_FILE) +
775 node_page_state(pgdat, NR_INACTIVE_ANON);
776 active = node_page_state(pgdat, NR_ACTIVE_FILE) +
777 node_page_state(pgdat, NR_ACTIVE_ANON);
778 isolated = node_page_state(pgdat, NR_ISOLATED_FILE) +
779 node_page_state(pgdat, NR_ISOLATED_ANON);
782 * Allow GFP_NOFS to isolate past the limit set for regular
783 * compaction runs. This prevents an ABBA deadlock when other
784 * compactors have already isolated to the limit, but are
785 * blocked on filesystem locks held by the GFP_NOFS thread.
787 if (cc->gfp_mask & __GFP_FS) {
792 too_many = isolated > (inactive + active) / 2;
794 wake_throttle_isolated(pgdat);
800 * isolate_migratepages_block() - isolate all migrate-able pages within
802 * @cc: Compaction control structure.
803 * @low_pfn: The first PFN to isolate
804 * @end_pfn: The one-past-the-last PFN to isolate, within same pageblock
805 * @mode: Isolation mode to be used.
807 * Isolate all pages that can be migrated from the range specified by
808 * [low_pfn, end_pfn). The range is expected to be within same pageblock.
809 * Returns errno, like -EAGAIN or -EINTR in case e.g signal pending or congestion,
810 * -ENOMEM in case we could not allocate a page, or 0.
811 * cc->migrate_pfn will contain the next pfn to scan.
813 * The pages are isolated on cc->migratepages list (not required to be empty),
814 * and cc->nr_migratepages is updated accordingly.
817 isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
818 unsigned long end_pfn, isolate_mode_t mode)
820 pg_data_t *pgdat = cc->zone->zone_pgdat;
821 unsigned long nr_scanned = 0, nr_isolated = 0;
822 struct lruvec *lruvec;
823 unsigned long flags = 0;
824 struct lruvec *locked = NULL;
825 struct folio *folio = NULL;
826 struct page *page = NULL, *valid_page = NULL;
827 struct address_space *mapping;
828 unsigned long start_pfn = low_pfn;
829 bool skip_on_failure = false;
830 unsigned long next_skip_pfn = 0;
831 bool skip_updated = false;
834 cc->migrate_pfn = low_pfn;
837 * Ensure that there are not too many pages isolated from the LRU
838 * list by either parallel reclaimers or compaction. If there are,
839 * delay for some time until fewer pages are isolated
841 while (unlikely(too_many_isolated(cc))) {
842 /* stop isolation if there are still pages not migrated */
843 if (cc->nr_migratepages)
846 /* async migration should just abort */
847 if (cc->mode == MIGRATE_ASYNC)
850 reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
852 if (fatal_signal_pending(current))
858 if (cc->direct_compaction && (cc->mode == MIGRATE_ASYNC)) {
859 skip_on_failure = true;
860 next_skip_pfn = block_end_pfn(low_pfn, cc->order);
863 /* Time to isolate some pages for migration */
864 for (; low_pfn < end_pfn; low_pfn++) {
866 if (skip_on_failure && low_pfn >= next_skip_pfn) {
868 * We have isolated all migration candidates in the
869 * previous order-aligned block, and did not skip it due
870 * to failure. We should migrate the pages now and
871 * hopefully succeed compaction.
877 * We failed to isolate in the previous order-aligned
878 * block. Set the new boundary to the end of the
879 * current block. Note we can't simply increase
880 * next_skip_pfn by 1 << order, as low_pfn might have
881 * been incremented by a higher number due to skipping
882 * a compound or a high-order buddy page in the
883 * previous loop iteration.
885 next_skip_pfn = block_end_pfn(low_pfn, cc->order);
889 * Periodically drop the lock (if held) regardless of its
890 * contention, to give chance to IRQs. Abort completely if
891 * a fatal signal is pending.
893 if (!(low_pfn % COMPACT_CLUSTER_MAX)) {
895 unlock_page_lruvec_irqrestore(locked, flags);
899 if (fatal_signal_pending(current)) {
900 cc->contended = true;
911 page = pfn_to_page(low_pfn);
914 * Check if the pageblock has already been marked skipped.
915 * Only the first PFN is checked as the caller isolates
916 * COMPACT_CLUSTER_MAX at a time so the second call must
917 * not falsely conclude that the block should be skipped.
919 if (!valid_page && (pageblock_aligned(low_pfn) ||
920 low_pfn == cc->zone->zone_start_pfn)) {
921 if (!isolation_suitable(cc, page)) {
929 if (PageHuge(page) && cc->alloc_contig) {
931 unlock_page_lruvec_irqrestore(locked, flags);
935 ret = isolate_or_dissolve_huge_page(page, &cc->migratepages);
938 * Fail isolation in case isolate_or_dissolve_huge_page()
939 * reports an error. In case of -ENOMEM, abort right away.
942 /* Do not report -EBUSY down the chain */
945 low_pfn += compound_nr(page) - 1;
946 nr_scanned += compound_nr(page) - 1;
950 if (PageHuge(page)) {
952 * Hugepage was successfully isolated and placed
953 * on the cc->migratepages list.
955 folio = page_folio(page);
956 low_pfn += folio_nr_pages(folio) - 1;
957 goto isolate_success_no_list;
961 * Ok, the hugepage was dissolved. Now these pages are
962 * Buddy and cannot be re-allocated because they are
963 * isolated. Fall-through as the check below handles
969 * Skip if free. We read page order here without zone lock
970 * which is generally unsafe, but the race window is small and
971 * the worst thing that can happen is that we skip some
972 * potential isolation targets.
974 if (PageBuddy(page)) {
975 unsigned long freepage_order = buddy_order_unsafe(page);
978 * Without lock, we cannot be sure that what we got is
979 * a valid page order. Consider only values in the
980 * valid order range to prevent low_pfn overflow.
982 if (freepage_order > 0 && freepage_order <= MAX_ORDER) {
983 low_pfn += (1UL << freepage_order) - 1;
984 nr_scanned += (1UL << freepage_order) - 1;
990 * Regardless of being on LRU, compound pages such as THP and
991 * hugetlbfs are not to be compacted unless we are attempting
992 * an allocation much larger than the huge page size (eg CMA).
993 * We can potentially save a lot of iterations if we skip them
994 * at once. The check is racy, but we can consider only valid
995 * values and the only danger is skipping too much.
997 if (PageCompound(page) && !cc->alloc_contig) {
998 const unsigned int order = compound_order(page);
1000 if (likely(order <= MAX_ORDER)) {
1001 low_pfn += (1UL << order) - 1;
1002 nr_scanned += (1UL << order) - 1;
1008 * Check may be lockless but that's ok as we recheck later.
1009 * It's possible to migrate LRU and non-lru movable pages.
1010 * Skip any other type of page
1012 if (!PageLRU(page)) {
1014 * __PageMovable can return false positive so we need
1015 * to verify it under page_lock.
1017 if (unlikely(__PageMovable(page)) &&
1018 !PageIsolated(page)) {
1020 unlock_page_lruvec_irqrestore(locked, flags);
1024 if (isolate_movable_page(page, mode)) {
1025 folio = page_folio(page);
1026 goto isolate_success;
1034 * Be careful not to clear PageLRU until after we're
1035 * sure the page is not being freed elsewhere -- the
1036 * page release code relies on it.
1038 folio = folio_get_nontail_page(page);
1039 if (unlikely(!folio))
1043 * Migration will fail if an anonymous page is pinned in memory,
1044 * so avoid taking lru_lock and isolating it unnecessarily in an
1045 * admittedly racy check.
1047 mapping = folio_mapping(folio);
1048 if (!mapping && (folio_ref_count(folio) - 1) > folio_mapcount(folio))
1049 goto isolate_fail_put;
1052 * Only allow to migrate anonymous pages in GFP_NOFS context
1053 * because those do not depend on fs locks.
1055 if (!(cc->gfp_mask & __GFP_FS) && mapping)
1056 goto isolate_fail_put;
1058 /* Only take pages on LRU: a check now makes later tests safe */
1059 if (!folio_test_lru(folio))
1060 goto isolate_fail_put;
1062 /* Compaction might skip unevictable pages but CMA takes them */
1063 if (!(mode & ISOLATE_UNEVICTABLE) && folio_test_unevictable(folio))
1064 goto isolate_fail_put;
1067 * To minimise LRU disruption, the caller can indicate with
1068 * ISOLATE_ASYNC_MIGRATE that it only wants to isolate pages
1069 * it will be able to migrate without blocking - clean pages
1070 * for the most part. PageWriteback would require blocking.
1072 if ((mode & ISOLATE_ASYNC_MIGRATE) && folio_test_writeback(folio))
1073 goto isolate_fail_put;
1075 if ((mode & ISOLATE_ASYNC_MIGRATE) && folio_test_dirty(folio)) {
1079 * Only pages without mappings or that have a
1080 * ->migrate_folio callback are possible to migrate
1081 * without blocking. However, we can be racing with
1082 * truncation so it's necessary to lock the page
1083 * to stabilise the mapping as truncation holds
1084 * the page lock until after the page is removed
1085 * from the page cache.
1087 if (!folio_trylock(folio))
1088 goto isolate_fail_put;
1090 mapping = folio_mapping(folio);
1091 migrate_dirty = !mapping ||
1092 mapping->a_ops->migrate_folio;
1093 folio_unlock(folio);
1095 goto isolate_fail_put;
1098 /* Try isolate the folio */
1099 if (!folio_test_clear_lru(folio))
1100 goto isolate_fail_put;
1102 lruvec = folio_lruvec(folio);
1104 /* If we already hold the lock, we can skip some rechecking */
1105 if (lruvec != locked) {
1107 unlock_page_lruvec_irqrestore(locked, flags);
1109 compact_lock_irqsave(&lruvec->lru_lock, &flags, cc);
1112 lruvec_memcg_debug(lruvec, folio);
1115 * Try get exclusive access under lock. If marked for
1116 * skip, the scan is aborted unless the current context
1117 * is a rescan to reach the end of the pageblock.
1119 if (!skip_updated && valid_page) {
1120 skip_updated = true;
1121 if (test_and_set_skip(cc, valid_page) &&
1122 !cc->finish_pageblock) {
1128 * folio become large since the non-locked check,
1131 if (unlikely(folio_test_large(folio) && !cc->alloc_contig)) {
1132 low_pfn += folio_nr_pages(folio) - 1;
1133 nr_scanned += folio_nr_pages(folio) - 1;
1134 folio_set_lru(folio);
1135 goto isolate_fail_put;
1139 /* The folio is taken off the LRU */
1140 if (folio_test_large(folio))
1141 low_pfn += folio_nr_pages(folio) - 1;
1143 /* Successfully isolated */
1144 lruvec_del_folio(lruvec, folio);
1145 node_stat_mod_folio(folio,
1146 NR_ISOLATED_ANON + folio_is_file_lru(folio),
1147 folio_nr_pages(folio));
1150 list_add(&folio->lru, &cc->migratepages);
1151 isolate_success_no_list:
1152 cc->nr_migratepages += folio_nr_pages(folio);
1153 nr_isolated += folio_nr_pages(folio);
1154 nr_scanned += folio_nr_pages(folio) - 1;
1157 * Avoid isolating too much unless this block is being
1158 * fully scanned (e.g. dirty/writeback pages, parallel allocation)
1159 * or a lock is contended. For contention, isolate quickly to
1160 * potentially remove one source of contention.
1162 if (cc->nr_migratepages >= COMPACT_CLUSTER_MAX &&
1163 !cc->finish_pageblock && !cc->contended) {
1171 /* Avoid potential deadlock in freeing page under lru_lock */
1173 unlock_page_lruvec_irqrestore(locked, flags);
1179 if (!skip_on_failure && ret != -ENOMEM)
1183 * We have isolated some pages, but then failed. Release them
1184 * instead of migrating, as we cannot form the cc->order buddy
1189 unlock_page_lruvec_irqrestore(locked, flags);
1192 putback_movable_pages(&cc->migratepages);
1193 cc->nr_migratepages = 0;
1197 if (low_pfn < next_skip_pfn) {
1198 low_pfn = next_skip_pfn - 1;
1200 * The check near the loop beginning would have updated
1201 * next_skip_pfn too, but this is a bit simpler.
1203 next_skip_pfn += 1UL << cc->order;
1211 * The PageBuddy() check could have potentially brought us outside
1212 * the range to be scanned.
1214 if (unlikely(low_pfn > end_pfn))
1221 unlock_page_lruvec_irqrestore(locked, flags);
1223 folio_set_lru(folio);
1228 * Update the cached scanner pfn once the pageblock has been scanned.
1229 * Pages will either be migrated in which case there is no point
1230 * scanning in the near future or migration failed in which case the
1231 * failure reason may persist. The block is marked for skipping if
1232 * there were no pages isolated in the block or if the block is
1233 * rescanned twice in a row.
1235 if (low_pfn == end_pfn && (!nr_isolated || cc->finish_pageblock)) {
1236 if (!cc->no_set_skip_hint && valid_page && !skip_updated)
1237 set_pageblock_skip(valid_page);
1238 update_cached_migrate(cc, low_pfn);
1241 trace_mm_compaction_isolate_migratepages(start_pfn, low_pfn,
1242 nr_scanned, nr_isolated);
1245 cc->total_migrate_scanned += nr_scanned;
1247 count_compact_events(COMPACTISOLATED, nr_isolated);
1249 cc->migrate_pfn = low_pfn;
1255 * isolate_migratepages_range() - isolate migrate-able pages in a PFN range
1256 * @cc: Compaction control structure.
1257 * @start_pfn: The first PFN to start isolating.
1258 * @end_pfn: The one-past-last PFN.
1260 * Returns -EAGAIN when contented, -EINTR in case of a signal pending, -ENOMEM
1261 * in case we could not allocate a page, or 0.
1264 isolate_migratepages_range(struct compact_control *cc, unsigned long start_pfn,
1265 unsigned long end_pfn)
1267 unsigned long pfn, block_start_pfn, block_end_pfn;
1270 /* Scan block by block. First and last block may be incomplete */
1272 block_start_pfn = pageblock_start_pfn(pfn);
1273 if (block_start_pfn < cc->zone->zone_start_pfn)
1274 block_start_pfn = cc->zone->zone_start_pfn;
1275 block_end_pfn = pageblock_end_pfn(pfn);
1277 for (; pfn < end_pfn; pfn = block_end_pfn,
1278 block_start_pfn = block_end_pfn,
1279 block_end_pfn += pageblock_nr_pages) {
1281 block_end_pfn = min(block_end_pfn, end_pfn);
1283 if (!pageblock_pfn_to_page(block_start_pfn,
1284 block_end_pfn, cc->zone))
1287 ret = isolate_migratepages_block(cc, pfn, block_end_pfn,
1288 ISOLATE_UNEVICTABLE);
1293 if (cc->nr_migratepages >= COMPACT_CLUSTER_MAX)
1300 #endif /* CONFIG_COMPACTION || CONFIG_CMA */
1301 #ifdef CONFIG_COMPACTION
1303 static bool suitable_migration_source(struct compact_control *cc,
1308 if (pageblock_skip_persistent(page))
1311 if ((cc->mode != MIGRATE_ASYNC) || !cc->direct_compaction)
1314 block_mt = get_pageblock_migratetype(page);
1316 if (cc->migratetype == MIGRATE_MOVABLE)
1317 return is_migrate_movable(block_mt);
1319 return block_mt == cc->migratetype;
1322 /* Returns true if the page is within a block suitable for migration to */
1323 static bool suitable_migration_target(struct compact_control *cc,
1326 /* If the page is a large free page, then disallow migration */
1327 if (PageBuddy(page)) {
1329 * We are checking page_order without zone->lock taken. But
1330 * the only small danger is that we skip a potentially suitable
1331 * pageblock, so it's not worth to check order for valid range.
1333 if (buddy_order_unsafe(page) >= pageblock_order)
1337 if (cc->ignore_block_suitable)
1340 /* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */
1341 if (is_migrate_movable(get_pageblock_migratetype(page)))
1344 /* Otherwise skip the block */
1348 static inline unsigned int
1349 freelist_scan_limit(struct compact_control *cc)
1351 unsigned short shift = BITS_PER_LONG - 1;
1353 return (COMPACT_CLUSTER_MAX >> min(shift, cc->fast_search_fail)) + 1;
1357 * Test whether the free scanner has reached the same or lower pageblock than
1358 * the migration scanner, and compaction should thus terminate.
1360 static inline bool compact_scanners_met(struct compact_control *cc)
1362 return (cc->free_pfn >> pageblock_order)
1363 <= (cc->migrate_pfn >> pageblock_order);
1367 * Used when scanning for a suitable migration target which scans freelists
1368 * in reverse. Reorders the list such as the unscanned pages are scanned
1369 * first on the next iteration of the free scanner
1372 move_freelist_head(struct list_head *freelist, struct page *freepage)
1376 if (!list_is_last(freelist, &freepage->lru)) {
1377 list_cut_before(&sublist, freelist, &freepage->lru);
1378 list_splice_tail(&sublist, freelist);
1383 * Similar to move_freelist_head except used by the migration scanner
1384 * when scanning forward. It's possible for these list operations to
1385 * move against each other if they search the free list exactly in
1389 move_freelist_tail(struct list_head *freelist, struct page *freepage)
1393 if (!list_is_first(freelist, &freepage->lru)) {
1394 list_cut_position(&sublist, freelist, &freepage->lru);
1395 list_splice_tail(&sublist, freelist);
1400 fast_isolate_around(struct compact_control *cc, unsigned long pfn)
1402 unsigned long start_pfn, end_pfn;
1405 /* Do not search around if there are enough pages already */
1406 if (cc->nr_freepages >= cc->nr_migratepages)
1409 /* Minimise scanning during async compaction */
1410 if (cc->direct_compaction && cc->mode == MIGRATE_ASYNC)
1413 /* Pageblock boundaries */
1414 start_pfn = max(pageblock_start_pfn(pfn), cc->zone->zone_start_pfn);
1415 end_pfn = min(pageblock_end_pfn(pfn), zone_end_pfn(cc->zone));
1417 page = pageblock_pfn_to_page(start_pfn, end_pfn, cc->zone);
1421 isolate_freepages_block(cc, &start_pfn, end_pfn, &cc->freepages, 1, false);
1423 /* Skip this pageblock in the future as it's full or nearly full */
1424 if (start_pfn == end_pfn)
1425 set_pageblock_skip(page);
1430 /* Search orders in round-robin fashion */
1431 static int next_search_order(struct compact_control *cc, int order)
1435 order = cc->order - 1;
1437 /* Search wrapped around? */
1438 if (order == cc->search_order) {
1440 if (cc->search_order < 0)
1441 cc->search_order = cc->order - 1;
1448 static void fast_isolate_freepages(struct compact_control *cc)
1450 unsigned int limit = max(1U, freelist_scan_limit(cc) >> 1);
1451 unsigned int nr_scanned = 0, total_isolated = 0;
1452 unsigned long low_pfn, min_pfn, highest = 0;
1453 unsigned long nr_isolated = 0;
1454 unsigned long distance;
1455 struct page *page = NULL;
1456 bool scan_start = false;
1459 /* Full compaction passes in a negative order */
1464 * If starting the scan, use a deeper search and use the highest
1465 * PFN found if a suitable one is not found.
1467 if (cc->free_pfn >= cc->zone->compact_init_free_pfn) {
1468 limit = pageblock_nr_pages >> 1;
1473 * Preferred point is in the top quarter of the scan space but take
1474 * a pfn from the top half if the search is problematic.
1476 distance = (cc->free_pfn - cc->migrate_pfn);
1477 low_pfn = pageblock_start_pfn(cc->free_pfn - (distance >> 2));
1478 min_pfn = pageblock_start_pfn(cc->free_pfn - (distance >> 1));
1480 if (WARN_ON_ONCE(min_pfn > low_pfn))
1484 * Search starts from the last successful isolation order or the next
1485 * order to search after a previous failure
1487 cc->search_order = min_t(unsigned int, cc->order - 1, cc->search_order);
1489 for (order = cc->search_order;
1490 !page && order >= 0;
1491 order = next_search_order(cc, order)) {
1492 struct free_area *area = &cc->zone->free_area[order];
1493 struct list_head *freelist;
1494 struct page *freepage;
1495 unsigned long flags;
1496 unsigned int order_scanned = 0;
1497 unsigned long high_pfn = 0;
1502 spin_lock_irqsave(&cc->zone->lock, flags);
1503 freelist = &area->free_list[MIGRATE_MOVABLE];
1504 list_for_each_entry_reverse(freepage, freelist, lru) {
1509 pfn = page_to_pfn(freepage);
1512 highest = max(pageblock_start_pfn(pfn),
1513 cc->zone->zone_start_pfn);
1515 if (pfn >= low_pfn) {
1516 cc->fast_search_fail = 0;
1517 cc->search_order = order;
1522 if (pfn >= min_pfn && pfn > high_pfn) {
1525 /* Shorten the scan if a candidate is found */
1529 if (order_scanned >= limit)
1533 /* Use a minimum pfn if a preferred one was not found */
1534 if (!page && high_pfn) {
1535 page = pfn_to_page(high_pfn);
1537 /* Update freepage for the list reorder below */
1541 /* Reorder to so a future search skips recent pages */
1542 move_freelist_head(freelist, freepage);
1544 /* Isolate the page if available */
1546 if (__isolate_free_page(page, order)) {
1547 set_page_private(page, order);
1548 nr_isolated = 1 << order;
1549 nr_scanned += nr_isolated - 1;
1550 total_isolated += nr_isolated;
1551 cc->nr_freepages += nr_isolated;
1552 list_add_tail(&page->lru, &cc->freepages);
1553 count_compact_events(COMPACTISOLATED, nr_isolated);
1555 /* If isolation fails, abort the search */
1556 order = cc->search_order + 1;
1561 spin_unlock_irqrestore(&cc->zone->lock, flags);
1563 /* Skip fast search if enough freepages isolated */
1564 if (cc->nr_freepages >= cc->nr_migratepages)
1568 * Smaller scan on next order so the total scan is related
1569 * to freelist_scan_limit.
1571 if (order_scanned >= limit)
1572 limit = max(1U, limit >> 1);
1575 trace_mm_compaction_fast_isolate_freepages(min_pfn, cc->free_pfn,
1576 nr_scanned, total_isolated);
1579 cc->fast_search_fail++;
1582 * Use the highest PFN found above min. If one was
1583 * not found, be pessimistic for direct compaction
1584 * and use the min mark.
1586 if (highest >= min_pfn) {
1587 page = pfn_to_page(highest);
1588 cc->free_pfn = highest;
1590 if (cc->direct_compaction && pfn_valid(min_pfn)) {
1591 page = pageblock_pfn_to_page(min_pfn,
1592 min(pageblock_end_pfn(min_pfn),
1593 zone_end_pfn(cc->zone)),
1595 cc->free_pfn = min_pfn;
1601 if (highest && highest >= cc->zone->compact_cached_free_pfn) {
1602 highest -= pageblock_nr_pages;
1603 cc->zone->compact_cached_free_pfn = highest;
1606 cc->total_free_scanned += nr_scanned;
1610 low_pfn = page_to_pfn(page);
1611 fast_isolate_around(cc, low_pfn);
1615 * Based on information in the current compact_control, find blocks
1616 * suitable for isolating free pages from and then isolate them.
1618 static void isolate_freepages(struct compact_control *cc)
1620 struct zone *zone = cc->zone;
1622 unsigned long block_start_pfn; /* start of current pageblock */
1623 unsigned long isolate_start_pfn; /* exact pfn we start at */
1624 unsigned long block_end_pfn; /* end of current pageblock */
1625 unsigned long low_pfn; /* lowest pfn scanner is able to scan */
1626 struct list_head *freelist = &cc->freepages;
1627 unsigned int stride;
1629 /* Try a small search of the free lists for a candidate */
1630 fast_isolate_freepages(cc);
1631 if (cc->nr_freepages)
1635 * Initialise the free scanner. The starting point is where we last
1636 * successfully isolated from, zone-cached value, or the end of the
1637 * zone when isolating for the first time. For looping we also need
1638 * this pfn aligned down to the pageblock boundary, because we do
1639 * block_start_pfn -= pageblock_nr_pages in the for loop.
1640 * For ending point, take care when isolating in last pageblock of a
1641 * zone which ends in the middle of a pageblock.
1642 * The low boundary is the end of the pageblock the migration scanner
1645 isolate_start_pfn = cc->free_pfn;
1646 block_start_pfn = pageblock_start_pfn(isolate_start_pfn);
1647 block_end_pfn = min(block_start_pfn + pageblock_nr_pages,
1648 zone_end_pfn(zone));
1649 low_pfn = pageblock_end_pfn(cc->migrate_pfn);
1650 stride = cc->mode == MIGRATE_ASYNC ? COMPACT_CLUSTER_MAX : 1;
1653 * Isolate free pages until enough are available to migrate the
1654 * pages on cc->migratepages. We stop searching if the migrate
1655 * and free page scanners meet or enough free pages are isolated.
1657 for (; block_start_pfn >= low_pfn;
1658 block_end_pfn = block_start_pfn,
1659 block_start_pfn -= pageblock_nr_pages,
1660 isolate_start_pfn = block_start_pfn) {
1661 unsigned long nr_isolated;
1664 * This can iterate a massively long zone without finding any
1665 * suitable migration targets, so periodically check resched.
1667 if (!(block_start_pfn % (COMPACT_CLUSTER_MAX * pageblock_nr_pages)))
1670 page = pageblock_pfn_to_page(block_start_pfn, block_end_pfn,
1675 /* Check the block is suitable for migration */
1676 if (!suitable_migration_target(cc, page))
1679 /* If isolation recently failed, do not retry */
1680 if (!isolation_suitable(cc, page))
1683 /* Found a block suitable for isolating free pages from. */
1684 nr_isolated = isolate_freepages_block(cc, &isolate_start_pfn,
1685 block_end_pfn, freelist, stride, false);
1687 /* Update the skip hint if the full pageblock was scanned */
1688 if (isolate_start_pfn == block_end_pfn)
1689 update_pageblock_skip(cc, page, block_start_pfn);
1691 /* Are enough freepages isolated? */
1692 if (cc->nr_freepages >= cc->nr_migratepages) {
1693 if (isolate_start_pfn >= block_end_pfn) {
1695 * Restart at previous pageblock if more
1696 * freepages can be isolated next time.
1699 block_start_pfn - pageblock_nr_pages;
1702 } else if (isolate_start_pfn < block_end_pfn) {
1704 * If isolation failed early, do not continue
1710 /* Adjust stride depending on isolation */
1715 stride = min_t(unsigned int, COMPACT_CLUSTER_MAX, stride << 1);
1719 * Record where the free scanner will restart next time. Either we
1720 * broke from the loop and set isolate_start_pfn based on the last
1721 * call to isolate_freepages_block(), or we met the migration scanner
1722 * and the loop terminated due to isolate_start_pfn < low_pfn
1724 cc->free_pfn = isolate_start_pfn;
1727 /* __isolate_free_page() does not map the pages */
1728 split_map_pages(freelist);
1732 * This is a migrate-callback that "allocates" freepages by taking pages
1733 * from the isolated freelists in the block we are migrating to.
1735 static struct folio *compaction_alloc(struct folio *src, unsigned long data)
1737 struct compact_control *cc = (struct compact_control *)data;
1740 if (list_empty(&cc->freepages)) {
1741 isolate_freepages(cc);
1743 if (list_empty(&cc->freepages))
1747 dst = list_entry(cc->freepages.next, struct folio, lru);
1748 list_del(&dst->lru);
1755 * This is a migrate-callback that "frees" freepages back to the isolated
1756 * freelist. All pages on the freelist are from the same zone, so there is no
1757 * special handling needed for NUMA.
1759 static void compaction_free(struct folio *dst, unsigned long data)
1761 struct compact_control *cc = (struct compact_control *)data;
1763 list_add(&dst->lru, &cc->freepages);
1767 /* possible outcome of isolate_migratepages */
1769 ISOLATE_ABORT, /* Abort compaction now */
1770 ISOLATE_NONE, /* No pages isolated, continue scanning */
1771 ISOLATE_SUCCESS, /* Pages isolated, migrate */
1772 } isolate_migrate_t;
1775 * Allow userspace to control policy on scanning the unevictable LRU for
1776 * compactable pages.
1778 static int sysctl_compact_unevictable_allowed __read_mostly = CONFIG_COMPACT_UNEVICTABLE_DEFAULT;
1780 * Tunable for proactive compaction. It determines how
1781 * aggressively the kernel should compact memory in the
1782 * background. It takes values in the range [0, 100].
1784 static unsigned int __read_mostly sysctl_compaction_proactiveness = 20;
1785 static int sysctl_extfrag_threshold = 500;
1786 static int __read_mostly sysctl_compact_memory;
1789 update_fast_start_pfn(struct compact_control *cc, unsigned long pfn)
1791 if (cc->fast_start_pfn == ULONG_MAX)
1794 if (!cc->fast_start_pfn)
1795 cc->fast_start_pfn = pfn;
1797 cc->fast_start_pfn = min(cc->fast_start_pfn, pfn);
1800 static inline unsigned long
1801 reinit_migrate_pfn(struct compact_control *cc)
1803 if (!cc->fast_start_pfn || cc->fast_start_pfn == ULONG_MAX)
1804 return cc->migrate_pfn;
1806 cc->migrate_pfn = cc->fast_start_pfn;
1807 cc->fast_start_pfn = ULONG_MAX;
1809 return cc->migrate_pfn;
1813 * Briefly search the free lists for a migration source that already has
1814 * some free pages to reduce the number of pages that need migration
1815 * before a pageblock is free.
1817 static unsigned long fast_find_migrateblock(struct compact_control *cc)
1819 unsigned int limit = freelist_scan_limit(cc);
1820 unsigned int nr_scanned = 0;
1821 unsigned long distance;
1822 unsigned long pfn = cc->migrate_pfn;
1823 unsigned long high_pfn;
1825 bool found_block = false;
1827 /* Skip hints are relied on to avoid repeats on the fast search */
1828 if (cc->ignore_skip_hint)
1832 * If the pageblock should be finished then do not select a different
1835 if (cc->finish_pageblock)
1839 * If the migrate_pfn is not at the start of a zone or the start
1840 * of a pageblock then assume this is a continuation of a previous
1841 * scan restarted due to COMPACT_CLUSTER_MAX.
1843 if (pfn != cc->zone->zone_start_pfn && pfn != pageblock_start_pfn(pfn))
1847 * For smaller orders, just linearly scan as the number of pages
1848 * to migrate should be relatively small and does not necessarily
1849 * justify freeing up a large block for a small allocation.
1851 if (cc->order <= PAGE_ALLOC_COSTLY_ORDER)
1855 * Only allow kcompactd and direct requests for movable pages to
1856 * quickly clear out a MOVABLE pageblock for allocation. This
1857 * reduces the risk that a large movable pageblock is freed for
1858 * an unmovable/reclaimable small allocation.
1860 if (cc->direct_compaction && cc->migratetype != MIGRATE_MOVABLE)
1864 * When starting the migration scanner, pick any pageblock within the
1865 * first half of the search space. Otherwise try and pick a pageblock
1866 * within the first eighth to reduce the chances that a migration
1867 * target later becomes a source.
1869 distance = (cc->free_pfn - cc->migrate_pfn) >> 1;
1870 if (cc->migrate_pfn != cc->zone->zone_start_pfn)
1872 high_pfn = pageblock_start_pfn(cc->migrate_pfn + distance);
1874 for (order = cc->order - 1;
1875 order >= PAGE_ALLOC_COSTLY_ORDER && !found_block && nr_scanned < limit;
1877 struct free_area *area = &cc->zone->free_area[order];
1878 struct list_head *freelist;
1879 unsigned long flags;
1880 struct page *freepage;
1885 spin_lock_irqsave(&cc->zone->lock, flags);
1886 freelist = &area->free_list[MIGRATE_MOVABLE];
1887 list_for_each_entry(freepage, freelist, lru) {
1888 unsigned long free_pfn;
1890 if (nr_scanned++ >= limit) {
1891 move_freelist_tail(freelist, freepage);
1895 free_pfn = page_to_pfn(freepage);
1896 if (free_pfn < high_pfn) {
1898 * Avoid if skipped recently. Ideally it would
1899 * move to the tail but even safe iteration of
1900 * the list assumes an entry is deleted, not
1903 if (get_pageblock_skip(freepage))
1906 /* Reorder to so a future search skips recent pages */
1907 move_freelist_tail(freelist, freepage);
1909 update_fast_start_pfn(cc, free_pfn);
1910 pfn = pageblock_start_pfn(free_pfn);
1911 if (pfn < cc->zone->zone_start_pfn)
1912 pfn = cc->zone->zone_start_pfn;
1913 cc->fast_search_fail = 0;
1918 spin_unlock_irqrestore(&cc->zone->lock, flags);
1921 cc->total_migrate_scanned += nr_scanned;
1924 * If fast scanning failed then use a cached entry for a page block
1925 * that had free pages as the basis for starting a linear scan.
1928 cc->fast_search_fail++;
1929 pfn = reinit_migrate_pfn(cc);
1935 * Isolate all pages that can be migrated from the first suitable block,
1936 * starting at the block pointed to by the migrate scanner pfn within
1939 static isolate_migrate_t isolate_migratepages(struct compact_control *cc)
1941 unsigned long block_start_pfn;
1942 unsigned long block_end_pfn;
1943 unsigned long low_pfn;
1945 const isolate_mode_t isolate_mode =
1946 (sysctl_compact_unevictable_allowed ? ISOLATE_UNEVICTABLE : 0) |
1947 (cc->mode != MIGRATE_SYNC ? ISOLATE_ASYNC_MIGRATE : 0);
1948 bool fast_find_block;
1951 * Start at where we last stopped, or beginning of the zone as
1952 * initialized by compact_zone(). The first failure will use
1953 * the lowest PFN as the starting point for linear scanning.
1955 low_pfn = fast_find_migrateblock(cc);
1956 block_start_pfn = pageblock_start_pfn(low_pfn);
1957 if (block_start_pfn < cc->zone->zone_start_pfn)
1958 block_start_pfn = cc->zone->zone_start_pfn;
1961 * fast_find_migrateblock marks a pageblock skipped so to avoid
1962 * the isolation_suitable check below, check whether the fast
1963 * search was successful.
1965 fast_find_block = low_pfn != cc->migrate_pfn && !cc->fast_search_fail;
1967 /* Only scan within a pageblock boundary */
1968 block_end_pfn = pageblock_end_pfn(low_pfn);
1971 * Iterate over whole pageblocks until we find the first suitable.
1972 * Do not cross the free scanner.
1974 for (; block_end_pfn <= cc->free_pfn;
1975 fast_find_block = false,
1976 cc->migrate_pfn = low_pfn = block_end_pfn,
1977 block_start_pfn = block_end_pfn,
1978 block_end_pfn += pageblock_nr_pages) {
1981 * This can potentially iterate a massively long zone with
1982 * many pageblocks unsuitable, so periodically check if we
1985 if (!(low_pfn % (COMPACT_CLUSTER_MAX * pageblock_nr_pages)))
1988 page = pageblock_pfn_to_page(block_start_pfn,
1989 block_end_pfn, cc->zone);
1991 unsigned long next_pfn;
1993 next_pfn = skip_offline_sections(block_start_pfn);
1995 block_end_pfn = min(next_pfn, cc->free_pfn);
2000 * If isolation recently failed, do not retry. Only check the
2001 * pageblock once. COMPACT_CLUSTER_MAX causes a pageblock
2002 * to be visited multiple times. Assume skip was checked
2003 * before making it "skip" so other compaction instances do
2004 * not scan the same block.
2006 if ((pageblock_aligned(low_pfn) ||
2007 low_pfn == cc->zone->zone_start_pfn) &&
2008 !fast_find_block && !isolation_suitable(cc, page))
2012 * For async direct compaction, only scan the pageblocks of the
2013 * same migratetype without huge pages. Async direct compaction
2014 * is optimistic to see if the minimum amount of work satisfies
2015 * the allocation. The cached PFN is updated as it's possible
2016 * that all remaining blocks between source and target are
2017 * unsuitable and the compaction scanners fail to meet.
2019 if (!suitable_migration_source(cc, page)) {
2020 update_cached_migrate(cc, block_end_pfn);
2024 /* Perform the isolation */
2025 if (isolate_migratepages_block(cc, low_pfn, block_end_pfn,
2027 return ISOLATE_ABORT;
2030 * Either we isolated something and proceed with migration. Or
2031 * we failed and compact_zone should decide if we should
2037 return cc->nr_migratepages ? ISOLATE_SUCCESS : ISOLATE_NONE;
2041 * order == -1 is expected when compacting via
2042 * /proc/sys/vm/compact_memory
2044 static inline bool is_via_compact_memory(int order)
2050 * Determine whether kswapd is (or recently was!) running on this node.
2052 * pgdat_kswapd_lock() pins pgdat->kswapd, so a concurrent kswapd_stop() can't
2055 static bool kswapd_is_running(pg_data_t *pgdat)
2059 pgdat_kswapd_lock(pgdat);
2060 running = pgdat->kswapd && task_is_running(pgdat->kswapd);
2061 pgdat_kswapd_unlock(pgdat);
2067 * A zone's fragmentation score is the external fragmentation wrt to the
2068 * COMPACTION_HPAGE_ORDER. It returns a value in the range [0, 100].
2070 static unsigned int fragmentation_score_zone(struct zone *zone)
2072 return extfrag_for_order(zone, COMPACTION_HPAGE_ORDER);
2076 * A weighted zone's fragmentation score is the external fragmentation
2077 * wrt to the COMPACTION_HPAGE_ORDER scaled by the zone's size. It
2078 * returns a value in the range [0, 100].
2080 * The scaling factor ensures that proactive compaction focuses on larger
2081 * zones like ZONE_NORMAL, rather than smaller, specialized zones like
2082 * ZONE_DMA32. For smaller zones, the score value remains close to zero,
2083 * and thus never exceeds the high threshold for proactive compaction.
2085 static unsigned int fragmentation_score_zone_weighted(struct zone *zone)
2087 unsigned long score;
2089 score = zone->present_pages * fragmentation_score_zone(zone);
2090 return div64_ul(score, zone->zone_pgdat->node_present_pages + 1);
2094 * The per-node proactive (background) compaction process is started by its
2095 * corresponding kcompactd thread when the node's fragmentation score
2096 * exceeds the high threshold. The compaction process remains active till
2097 * the node's score falls below the low threshold, or one of the back-off
2098 * conditions is met.
2100 static unsigned int fragmentation_score_node(pg_data_t *pgdat)
2102 unsigned int score = 0;
2105 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
2108 zone = &pgdat->node_zones[zoneid];
2109 if (!populated_zone(zone))
2111 score += fragmentation_score_zone_weighted(zone);
2117 static unsigned int fragmentation_score_wmark(pg_data_t *pgdat, bool low)
2119 unsigned int wmark_low;
2122 * Cap the low watermark to avoid excessive compaction
2123 * activity in case a user sets the proactiveness tunable
2124 * close to 100 (maximum).
2126 wmark_low = max(100U - sysctl_compaction_proactiveness, 5U);
2127 return low ? wmark_low : min(wmark_low + 10, 100U);
2130 static bool should_proactive_compact_node(pg_data_t *pgdat)
2134 if (!sysctl_compaction_proactiveness || kswapd_is_running(pgdat))
2137 wmark_high = fragmentation_score_wmark(pgdat, false);
2138 return fragmentation_score_node(pgdat) > wmark_high;
2141 static enum compact_result __compact_finished(struct compact_control *cc)
2144 const int migratetype = cc->migratetype;
2147 /* Compaction run completes if the migrate and free scanner meet */
2148 if (compact_scanners_met(cc)) {
2149 /* Let the next compaction start anew. */
2150 reset_cached_positions(cc->zone);
2153 * Mark that the PG_migrate_skip information should be cleared
2154 * by kswapd when it goes to sleep. kcompactd does not set the
2155 * flag itself as the decision to be clear should be directly
2156 * based on an allocation request.
2158 if (cc->direct_compaction)
2159 cc->zone->compact_blockskip_flush = true;
2162 return COMPACT_COMPLETE;
2164 return COMPACT_PARTIAL_SKIPPED;
2167 if (cc->proactive_compaction) {
2168 int score, wmark_low;
2171 pgdat = cc->zone->zone_pgdat;
2172 if (kswapd_is_running(pgdat))
2173 return COMPACT_PARTIAL_SKIPPED;
2175 score = fragmentation_score_zone(cc->zone);
2176 wmark_low = fragmentation_score_wmark(pgdat, true);
2178 if (score > wmark_low)
2179 ret = COMPACT_CONTINUE;
2181 ret = COMPACT_SUCCESS;
2186 if (is_via_compact_memory(cc->order))
2187 return COMPACT_CONTINUE;
2190 * Always finish scanning a pageblock to reduce the possibility of
2191 * fallbacks in the future. This is particularly important when
2192 * migration source is unmovable/reclaimable but it's not worth
2195 if (!pageblock_aligned(cc->migrate_pfn))
2196 return COMPACT_CONTINUE;
2198 /* Direct compactor: Is a suitable page free? */
2199 ret = COMPACT_NO_SUITABLE_PAGE;
2200 for (order = cc->order; order <= MAX_ORDER; order++) {
2201 struct free_area *area = &cc->zone->free_area[order];
2204 /* Job done if page is free of the right migratetype */
2205 if (!free_area_empty(area, migratetype))
2206 return COMPACT_SUCCESS;
2209 /* MIGRATE_MOVABLE can fallback on MIGRATE_CMA */
2210 if (migratetype == MIGRATE_MOVABLE &&
2211 !free_area_empty(area, MIGRATE_CMA))
2212 return COMPACT_SUCCESS;
2215 * Job done if allocation would steal freepages from
2216 * other migratetype buddy lists.
2218 if (find_suitable_fallback(area, order, migratetype,
2219 true, &can_steal) != -1)
2221 * Movable pages are OK in any pageblock. If we are
2222 * stealing for a non-movable allocation, make sure
2223 * we finish compacting the current pageblock first
2224 * (which is assured by the above migrate_pfn align
2225 * check) so it is as free as possible and we won't
2226 * have to steal another one soon.
2228 return COMPACT_SUCCESS;
2232 if (cc->contended || fatal_signal_pending(current))
2233 ret = COMPACT_CONTENDED;
2238 static enum compact_result compact_finished(struct compact_control *cc)
2242 ret = __compact_finished(cc);
2243 trace_mm_compaction_finished(cc->zone, cc->order, ret);
2244 if (ret == COMPACT_NO_SUITABLE_PAGE)
2245 ret = COMPACT_CONTINUE;
2250 static bool __compaction_suitable(struct zone *zone, int order,
2251 int highest_zoneidx,
2252 unsigned long wmark_target)
2254 unsigned long watermark;
2256 * Watermarks for order-0 must be met for compaction to be able to
2257 * isolate free pages for migration targets. This means that the
2258 * watermark and alloc_flags have to match, or be more pessimistic than
2259 * the check in __isolate_free_page(). We don't use the direct
2260 * compactor's alloc_flags, as they are not relevant for freepage
2261 * isolation. We however do use the direct compactor's highest_zoneidx
2262 * to skip over zones where lowmem reserves would prevent allocation
2263 * even if compaction succeeds.
2264 * For costly orders, we require low watermark instead of min for
2265 * compaction to proceed to increase its chances.
2266 * ALLOC_CMA is used, as pages in CMA pageblocks are considered
2267 * suitable migration targets
2269 watermark = (order > PAGE_ALLOC_COSTLY_ORDER) ?
2270 low_wmark_pages(zone) : min_wmark_pages(zone);
2271 watermark += compact_gap(order);
2272 return __zone_watermark_ok(zone, 0, watermark, highest_zoneidx,
2273 ALLOC_CMA, wmark_target);
2277 * compaction_suitable: Is this suitable to run compaction on this zone now?
2279 bool compaction_suitable(struct zone *zone, int order, int highest_zoneidx)
2281 enum compact_result compact_result;
2284 suitable = __compaction_suitable(zone, order, highest_zoneidx,
2285 zone_page_state(zone, NR_FREE_PAGES));
2287 * fragmentation index determines if allocation failures are due to
2288 * low memory or external fragmentation
2290 * index of -1000 would imply allocations might succeed depending on
2291 * watermarks, but we already failed the high-order watermark check
2292 * index towards 0 implies failure is due to lack of memory
2293 * index towards 1000 implies failure is due to fragmentation
2295 * Only compact if a failure would be due to fragmentation. Also
2296 * ignore fragindex for non-costly orders where the alternative to
2297 * a successful reclaim/compaction is OOM. Fragindex and the
2298 * vm.extfrag_threshold sysctl is meant as a heuristic to prevent
2299 * excessive compaction for costly orders, but it should not be at the
2300 * expense of system stability.
2303 compact_result = COMPACT_CONTINUE;
2304 if (order > PAGE_ALLOC_COSTLY_ORDER) {
2305 int fragindex = fragmentation_index(zone, order);
2307 if (fragindex >= 0 &&
2308 fragindex <= sysctl_extfrag_threshold) {
2310 compact_result = COMPACT_NOT_SUITABLE_ZONE;
2314 compact_result = COMPACT_SKIPPED;
2317 trace_mm_compaction_suitable(zone, order, compact_result);
2322 bool compaction_zonelist_suitable(struct alloc_context *ac, int order,
2329 * Make sure at least one zone would pass __compaction_suitable if we continue
2330 * retrying the reclaim.
2332 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
2333 ac->highest_zoneidx, ac->nodemask) {
2334 unsigned long available;
2337 * Do not consider all the reclaimable memory because we do not
2338 * want to trash just for a single high order allocation which
2339 * is even not guaranteed to appear even if __compaction_suitable
2340 * is happy about the watermark check.
2342 available = zone_reclaimable_pages(zone) / order;
2343 available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
2344 if (__compaction_suitable(zone, order, ac->highest_zoneidx,
2352 static enum compact_result
2353 compact_zone(struct compact_control *cc, struct capture_control *capc)
2355 enum compact_result ret;
2356 unsigned long start_pfn = cc->zone->zone_start_pfn;
2357 unsigned long end_pfn = zone_end_pfn(cc->zone);
2358 unsigned long last_migrated_pfn;
2359 const bool sync = cc->mode != MIGRATE_ASYNC;
2361 unsigned int nr_succeeded = 0;
2364 * These counters track activities during zone compaction. Initialize
2365 * them before compacting a new zone.
2367 cc->total_migrate_scanned = 0;
2368 cc->total_free_scanned = 0;
2369 cc->nr_migratepages = 0;
2370 cc->nr_freepages = 0;
2371 INIT_LIST_HEAD(&cc->freepages);
2372 INIT_LIST_HEAD(&cc->migratepages);
2374 cc->migratetype = gfp_migratetype(cc->gfp_mask);
2376 if (!is_via_compact_memory(cc->order)) {
2377 unsigned long watermark;
2379 /* Allocation can already succeed, nothing to do */
2380 watermark = wmark_pages(cc->zone,
2381 cc->alloc_flags & ALLOC_WMARK_MASK);
2382 if (zone_watermark_ok(cc->zone, cc->order, watermark,
2383 cc->highest_zoneidx, cc->alloc_flags))
2384 return COMPACT_SUCCESS;
2386 /* Compaction is likely to fail */
2387 if (!compaction_suitable(cc->zone, cc->order,
2388 cc->highest_zoneidx))
2389 return COMPACT_SKIPPED;
2393 * Clear pageblock skip if there were failures recently and compaction
2394 * is about to be retried after being deferred.
2396 if (compaction_restarting(cc->zone, cc->order))
2397 __reset_isolation_suitable(cc->zone);
2400 * Setup to move all movable pages to the end of the zone. Used cached
2401 * information on where the scanners should start (unless we explicitly
2402 * want to compact the whole zone), but check that it is initialised
2403 * by ensuring the values are within zone boundaries.
2405 cc->fast_start_pfn = 0;
2406 if (cc->whole_zone) {
2407 cc->migrate_pfn = start_pfn;
2408 cc->free_pfn = pageblock_start_pfn(end_pfn - 1);
2410 cc->migrate_pfn = cc->zone->compact_cached_migrate_pfn[sync];
2411 cc->free_pfn = cc->zone->compact_cached_free_pfn;
2412 if (cc->free_pfn < start_pfn || cc->free_pfn >= end_pfn) {
2413 cc->free_pfn = pageblock_start_pfn(end_pfn - 1);
2414 cc->zone->compact_cached_free_pfn = cc->free_pfn;
2416 if (cc->migrate_pfn < start_pfn || cc->migrate_pfn >= end_pfn) {
2417 cc->migrate_pfn = start_pfn;
2418 cc->zone->compact_cached_migrate_pfn[0] = cc->migrate_pfn;
2419 cc->zone->compact_cached_migrate_pfn[1] = cc->migrate_pfn;
2422 if (cc->migrate_pfn <= cc->zone->compact_init_migrate_pfn)
2423 cc->whole_zone = true;
2426 last_migrated_pfn = 0;
2429 * Migrate has separate cached PFNs for ASYNC and SYNC* migration on
2430 * the basis that some migrations will fail in ASYNC mode. However,
2431 * if the cached PFNs match and pageblocks are skipped due to having
2432 * no isolation candidates, then the sync state does not matter.
2433 * Until a pageblock with isolation candidates is found, keep the
2434 * cached PFNs in sync to avoid revisiting the same blocks.
2436 update_cached = !sync &&
2437 cc->zone->compact_cached_migrate_pfn[0] == cc->zone->compact_cached_migrate_pfn[1];
2439 trace_mm_compaction_begin(cc, start_pfn, end_pfn, sync);
2441 /* lru_add_drain_all could be expensive with involving other CPUs */
2444 while ((ret = compact_finished(cc)) == COMPACT_CONTINUE) {
2446 unsigned long iteration_start_pfn = cc->migrate_pfn;
2449 * Avoid multiple rescans of the same pageblock which can
2450 * happen if a page cannot be isolated (dirty/writeback in
2451 * async mode) or if the migrated pages are being allocated
2452 * before the pageblock is cleared. The first rescan will
2453 * capture the entire pageblock for migration. If it fails,
2454 * it'll be marked skip and scanning will proceed as normal.
2456 cc->finish_pageblock = false;
2457 if (pageblock_start_pfn(last_migrated_pfn) ==
2458 pageblock_start_pfn(iteration_start_pfn)) {
2459 cc->finish_pageblock = true;
2463 switch (isolate_migratepages(cc)) {
2465 ret = COMPACT_CONTENDED;
2466 putback_movable_pages(&cc->migratepages);
2467 cc->nr_migratepages = 0;
2470 if (update_cached) {
2471 cc->zone->compact_cached_migrate_pfn[1] =
2472 cc->zone->compact_cached_migrate_pfn[0];
2476 * We haven't isolated and migrated anything, but
2477 * there might still be unflushed migrations from
2478 * previous cc->order aligned block.
2481 case ISOLATE_SUCCESS:
2482 update_cached = false;
2483 last_migrated_pfn = iteration_start_pfn;
2486 err = migrate_pages(&cc->migratepages, compaction_alloc,
2487 compaction_free, (unsigned long)cc, cc->mode,
2488 MR_COMPACTION, &nr_succeeded);
2490 trace_mm_compaction_migratepages(cc, nr_succeeded);
2492 /* All pages were either migrated or will be released */
2493 cc->nr_migratepages = 0;
2495 putback_movable_pages(&cc->migratepages);
2497 * migrate_pages() may return -ENOMEM when scanners meet
2498 * and we want compact_finished() to detect it
2500 if (err == -ENOMEM && !compact_scanners_met(cc)) {
2501 ret = COMPACT_CONTENDED;
2505 * If an ASYNC or SYNC_LIGHT fails to migrate a page
2506 * within the current order-aligned block and
2507 * fast_find_migrateblock may be used then scan the
2508 * remainder of the pageblock. This will mark the
2509 * pageblock "skip" to avoid rescanning in the near
2510 * future. This will isolate more pages than necessary
2511 * for the request but avoid loops due to
2512 * fast_find_migrateblock revisiting blocks that were
2513 * recently partially scanned.
2515 if (!pageblock_aligned(cc->migrate_pfn) &&
2516 !cc->ignore_skip_hint && !cc->finish_pageblock &&
2517 (cc->mode < MIGRATE_SYNC)) {
2518 cc->finish_pageblock = true;
2521 * Draining pcplists does not help THP if
2522 * any page failed to migrate. Even after
2523 * drain, the pageblock will not be free.
2525 if (cc->order == COMPACTION_HPAGE_ORDER)
2526 last_migrated_pfn = 0;
2532 /* Stop if a page has been captured */
2533 if (capc && capc->page) {
2534 ret = COMPACT_SUCCESS;
2540 * Has the migration scanner moved away from the previous
2541 * cc->order aligned block where we migrated from? If yes,
2542 * flush the pages that were freed, so that they can merge and
2543 * compact_finished() can detect immediately if allocation
2546 if (cc->order > 0 && last_migrated_pfn) {
2547 unsigned long current_block_start =
2548 block_start_pfn(cc->migrate_pfn, cc->order);
2550 if (last_migrated_pfn < current_block_start) {
2551 lru_add_drain_cpu_zone(cc->zone);
2552 /* No more flushing until we migrate again */
2553 last_migrated_pfn = 0;
2560 * Release free pages and update where the free scanner should restart,
2561 * so we don't leave any returned pages behind in the next attempt.
2563 if (cc->nr_freepages > 0) {
2564 unsigned long free_pfn = release_freepages(&cc->freepages);
2566 cc->nr_freepages = 0;
2567 VM_BUG_ON(free_pfn == 0);
2568 /* The cached pfn is always the first in a pageblock */
2569 free_pfn = pageblock_start_pfn(free_pfn);
2571 * Only go back, not forward. The cached pfn might have been
2572 * already reset to zone end in compact_finished()
2574 if (free_pfn > cc->zone->compact_cached_free_pfn)
2575 cc->zone->compact_cached_free_pfn = free_pfn;
2578 count_compact_events(COMPACTMIGRATE_SCANNED, cc->total_migrate_scanned);
2579 count_compact_events(COMPACTFREE_SCANNED, cc->total_free_scanned);
2581 trace_mm_compaction_end(cc, start_pfn, end_pfn, sync, ret);
2583 VM_BUG_ON(!list_empty(&cc->freepages));
2584 VM_BUG_ON(!list_empty(&cc->migratepages));
2589 static enum compact_result compact_zone_order(struct zone *zone, int order,
2590 gfp_t gfp_mask, enum compact_priority prio,
2591 unsigned int alloc_flags, int highest_zoneidx,
2592 struct page **capture)
2594 enum compact_result ret;
2595 struct compact_control cc = {
2597 .search_order = order,
2598 .gfp_mask = gfp_mask,
2600 .mode = (prio == COMPACT_PRIO_ASYNC) ?
2601 MIGRATE_ASYNC : MIGRATE_SYNC_LIGHT,
2602 .alloc_flags = alloc_flags,
2603 .highest_zoneidx = highest_zoneidx,
2604 .direct_compaction = true,
2605 .whole_zone = (prio == MIN_COMPACT_PRIORITY),
2606 .ignore_skip_hint = (prio == MIN_COMPACT_PRIORITY),
2607 .ignore_block_suitable = (prio == MIN_COMPACT_PRIORITY)
2609 struct capture_control capc = {
2615 * Make sure the structs are really initialized before we expose the
2616 * capture control, in case we are interrupted and the interrupt handler
2620 WRITE_ONCE(current->capture_control, &capc);
2622 ret = compact_zone(&cc, &capc);
2625 * Make sure we hide capture control first before we read the captured
2626 * page pointer, otherwise an interrupt could free and capture a page
2627 * and we would leak it.
2629 WRITE_ONCE(current->capture_control, NULL);
2630 *capture = READ_ONCE(capc.page);
2632 * Technically, it is also possible that compaction is skipped but
2633 * the page is still captured out of luck(IRQ came and freed the page).
2634 * Returning COMPACT_SUCCESS in such cases helps in properly accounting
2635 * the COMPACT[STALL|FAIL] when compaction is skipped.
2638 ret = COMPACT_SUCCESS;
2644 * try_to_compact_pages - Direct compact to satisfy a high-order allocation
2645 * @gfp_mask: The GFP mask of the current allocation
2646 * @order: The order of the current allocation
2647 * @alloc_flags: The allocation flags of the current allocation
2648 * @ac: The context of current allocation
2649 * @prio: Determines how hard direct compaction should try to succeed
2650 * @capture: Pointer to free page created by compaction will be stored here
2652 * This is the main entry point for direct page compaction.
2654 enum compact_result try_to_compact_pages(gfp_t gfp_mask, unsigned int order,
2655 unsigned int alloc_flags, const struct alloc_context *ac,
2656 enum compact_priority prio, struct page **capture)
2658 int may_perform_io = (__force int)(gfp_mask & __GFP_IO);
2661 enum compact_result rc = COMPACT_SKIPPED;
2664 * Check if the GFP flags allow compaction - GFP_NOIO is really
2665 * tricky context because the migration might require IO
2667 if (!may_perform_io)
2668 return COMPACT_SKIPPED;
2670 trace_mm_compaction_try_to_compact_pages(order, gfp_mask, prio);
2672 /* Compact each zone in the list */
2673 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
2674 ac->highest_zoneidx, ac->nodemask) {
2675 enum compact_result status;
2677 if (prio > MIN_COMPACT_PRIORITY
2678 && compaction_deferred(zone, order)) {
2679 rc = max_t(enum compact_result, COMPACT_DEFERRED, rc);
2683 status = compact_zone_order(zone, order, gfp_mask, prio,
2684 alloc_flags, ac->highest_zoneidx, capture);
2685 rc = max(status, rc);
2687 /* The allocation should succeed, stop compacting */
2688 if (status == COMPACT_SUCCESS) {
2690 * We think the allocation will succeed in this zone,
2691 * but it is not certain, hence the false. The caller
2692 * will repeat this with true if allocation indeed
2693 * succeeds in this zone.
2695 compaction_defer_reset(zone, order, false);
2700 if (prio != COMPACT_PRIO_ASYNC && (status == COMPACT_COMPLETE ||
2701 status == COMPACT_PARTIAL_SKIPPED))
2703 * We think that allocation won't succeed in this zone
2704 * so we defer compaction there. If it ends up
2705 * succeeding after all, it will be reset.
2707 defer_compaction(zone, order);
2710 * We might have stopped compacting due to need_resched() in
2711 * async compaction, or due to a fatal signal detected. In that
2712 * case do not try further zones
2714 if ((prio == COMPACT_PRIO_ASYNC && need_resched())
2715 || fatal_signal_pending(current))
2723 * Compact all zones within a node till each zone's fragmentation score
2724 * reaches within proactive compaction thresholds (as determined by the
2725 * proactiveness tunable).
2727 * It is possible that the function returns before reaching score targets
2728 * due to various back-off conditions, such as, contention on per-node or
2731 static void proactive_compact_node(pg_data_t *pgdat)
2735 struct compact_control cc = {
2737 .mode = MIGRATE_SYNC_LIGHT,
2738 .ignore_skip_hint = true,
2740 .gfp_mask = GFP_KERNEL,
2741 .proactive_compaction = true,
2744 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
2745 zone = &pgdat->node_zones[zoneid];
2746 if (!populated_zone(zone))
2751 compact_zone(&cc, NULL);
2753 count_compact_events(KCOMPACTD_MIGRATE_SCANNED,
2754 cc.total_migrate_scanned);
2755 count_compact_events(KCOMPACTD_FREE_SCANNED,
2756 cc.total_free_scanned);
2760 /* Compact all zones within a node */
2761 static void compact_node(int nid)
2763 pg_data_t *pgdat = NODE_DATA(nid);
2766 struct compact_control cc = {
2768 .mode = MIGRATE_SYNC,
2769 .ignore_skip_hint = true,
2771 .gfp_mask = GFP_KERNEL,
2775 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
2777 zone = &pgdat->node_zones[zoneid];
2778 if (!populated_zone(zone))
2783 compact_zone(&cc, NULL);
2787 /* Compact all nodes in the system */
2788 static void compact_nodes(void)
2792 /* Flush pending updates to the LRU lists */
2793 lru_add_drain_all();
2795 for_each_online_node(nid)
2799 static int compaction_proactiveness_sysctl_handler(struct ctl_table *table, int write,
2800 void *buffer, size_t *length, loff_t *ppos)
2804 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
2808 if (write && sysctl_compaction_proactiveness) {
2809 for_each_online_node(nid) {
2810 pg_data_t *pgdat = NODE_DATA(nid);
2812 if (pgdat->proactive_compact_trigger)
2815 pgdat->proactive_compact_trigger = true;
2816 trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, -1,
2817 pgdat->nr_zones - 1);
2818 wake_up_interruptible(&pgdat->kcompactd_wait);
2826 * This is the entry point for compacting all nodes via
2827 * /proc/sys/vm/compact_memory
2829 static int sysctl_compaction_handler(struct ctl_table *table, int write,
2830 void *buffer, size_t *length, loff_t *ppos)
2834 ret = proc_dointvec(table, write, buffer, length, ppos);
2838 if (sysctl_compact_memory != 1)
2847 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
2848 static ssize_t compact_store(struct device *dev,
2849 struct device_attribute *attr,
2850 const char *buf, size_t count)
2854 if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
2855 /* Flush pending updates to the LRU lists */
2856 lru_add_drain_all();
2863 static DEVICE_ATTR_WO(compact);
2865 int compaction_register_node(struct node *node)
2867 return device_create_file(&node->dev, &dev_attr_compact);
2870 void compaction_unregister_node(struct node *node)
2872 return device_remove_file(&node->dev, &dev_attr_compact);
2874 #endif /* CONFIG_SYSFS && CONFIG_NUMA */
2876 static inline bool kcompactd_work_requested(pg_data_t *pgdat)
2878 return pgdat->kcompactd_max_order > 0 || kthread_should_stop() ||
2879 pgdat->proactive_compact_trigger;
2882 static bool kcompactd_node_suitable(pg_data_t *pgdat)
2886 enum zone_type highest_zoneidx = pgdat->kcompactd_highest_zoneidx;
2888 for (zoneid = 0; zoneid <= highest_zoneidx; zoneid++) {
2889 zone = &pgdat->node_zones[zoneid];
2891 if (!populated_zone(zone))
2894 /* Allocation can already succeed, check other zones */
2895 if (zone_watermark_ok(zone, pgdat->kcompactd_max_order,
2896 min_wmark_pages(zone),
2897 highest_zoneidx, 0))
2900 if (compaction_suitable(zone, pgdat->kcompactd_max_order,
2908 static void kcompactd_do_work(pg_data_t *pgdat)
2911 * With no special task, compact all zones so that a page of requested
2912 * order is allocatable.
2916 struct compact_control cc = {
2917 .order = pgdat->kcompactd_max_order,
2918 .search_order = pgdat->kcompactd_max_order,
2919 .highest_zoneidx = pgdat->kcompactd_highest_zoneidx,
2920 .mode = MIGRATE_SYNC_LIGHT,
2921 .ignore_skip_hint = false,
2922 .gfp_mask = GFP_KERNEL,
2924 trace_mm_compaction_kcompactd_wake(pgdat->node_id, cc.order,
2925 cc.highest_zoneidx);
2926 count_compact_event(KCOMPACTD_WAKE);
2928 for (zoneid = 0; zoneid <= cc.highest_zoneidx; zoneid++) {
2931 zone = &pgdat->node_zones[zoneid];
2932 if (!populated_zone(zone))
2935 if (compaction_deferred(zone, cc.order))
2938 /* Allocation can already succeed, nothing to do */
2939 if (zone_watermark_ok(zone, cc.order,
2940 min_wmark_pages(zone), zoneid, 0))
2943 if (!compaction_suitable(zone, cc.order, zoneid))
2946 if (kthread_should_stop())
2950 status = compact_zone(&cc, NULL);
2952 if (status == COMPACT_SUCCESS) {
2953 compaction_defer_reset(zone, cc.order, false);
2954 } else if (status == COMPACT_PARTIAL_SKIPPED || status == COMPACT_COMPLETE) {
2956 * Buddy pages may become stranded on pcps that could
2957 * otherwise coalesce on the zone's free area for
2958 * order >= cc.order. This is ratelimited by the
2959 * upcoming deferral.
2961 drain_all_pages(zone);
2964 * We use sync migration mode here, so we defer like
2965 * sync direct compaction does.
2967 defer_compaction(zone, cc.order);
2970 count_compact_events(KCOMPACTD_MIGRATE_SCANNED,
2971 cc.total_migrate_scanned);
2972 count_compact_events(KCOMPACTD_FREE_SCANNED,
2973 cc.total_free_scanned);
2977 * Regardless of success, we are done until woken up next. But remember
2978 * the requested order/highest_zoneidx in case it was higher/tighter
2979 * than our current ones
2981 if (pgdat->kcompactd_max_order <= cc.order)
2982 pgdat->kcompactd_max_order = 0;
2983 if (pgdat->kcompactd_highest_zoneidx >= cc.highest_zoneidx)
2984 pgdat->kcompactd_highest_zoneidx = pgdat->nr_zones - 1;
2987 void wakeup_kcompactd(pg_data_t *pgdat, int order, int highest_zoneidx)
2992 if (pgdat->kcompactd_max_order < order)
2993 pgdat->kcompactd_max_order = order;
2995 if (pgdat->kcompactd_highest_zoneidx > highest_zoneidx)
2996 pgdat->kcompactd_highest_zoneidx = highest_zoneidx;
2999 * Pairs with implicit barrier in wait_event_freezable()
3000 * such that wakeups are not missed.
3002 if (!wq_has_sleeper(&pgdat->kcompactd_wait))
3005 if (!kcompactd_node_suitable(pgdat))
3008 trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, order,
3010 wake_up_interruptible(&pgdat->kcompactd_wait);
3014 * The background compaction daemon, started as a kernel thread
3015 * from the init process.
3017 static int kcompactd(void *p)
3019 pg_data_t *pgdat = (pg_data_t *)p;
3020 struct task_struct *tsk = current;
3021 long default_timeout = msecs_to_jiffies(HPAGE_FRAG_CHECK_INTERVAL_MSEC);
3022 long timeout = default_timeout;
3024 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
3026 if (!cpumask_empty(cpumask))
3027 set_cpus_allowed_ptr(tsk, cpumask);
3031 pgdat->kcompactd_max_order = 0;
3032 pgdat->kcompactd_highest_zoneidx = pgdat->nr_zones - 1;
3034 while (!kthread_should_stop()) {
3035 unsigned long pflags;
3038 * Avoid the unnecessary wakeup for proactive compaction
3039 * when it is disabled.
3041 if (!sysctl_compaction_proactiveness)
3042 timeout = MAX_SCHEDULE_TIMEOUT;
3043 trace_mm_compaction_kcompactd_sleep(pgdat->node_id);
3044 if (wait_event_freezable_timeout(pgdat->kcompactd_wait,
3045 kcompactd_work_requested(pgdat), timeout) &&
3046 !pgdat->proactive_compact_trigger) {
3048 psi_memstall_enter(&pflags);
3049 kcompactd_do_work(pgdat);
3050 psi_memstall_leave(&pflags);
3052 * Reset the timeout value. The defer timeout from
3053 * proactive compaction is lost here but that is fine
3054 * as the condition of the zone changing substantionally
3055 * then carrying on with the previous defer interval is
3058 timeout = default_timeout;
3063 * Start the proactive work with default timeout. Based
3064 * on the fragmentation score, this timeout is updated.
3066 timeout = default_timeout;
3067 if (should_proactive_compact_node(pgdat)) {
3068 unsigned int prev_score, score;
3070 prev_score = fragmentation_score_node(pgdat);
3071 proactive_compact_node(pgdat);
3072 score = fragmentation_score_node(pgdat);
3074 * Defer proactive compaction if the fragmentation
3075 * score did not go down i.e. no progress made.
3077 if (unlikely(score >= prev_score))
3079 default_timeout << COMPACT_MAX_DEFER_SHIFT;
3081 if (unlikely(pgdat->proactive_compact_trigger))
3082 pgdat->proactive_compact_trigger = false;
3089 * This kcompactd start function will be called by init and node-hot-add.
3090 * On node-hot-add, kcompactd will moved to proper cpus if cpus are hot-added.
3092 void __meminit kcompactd_run(int nid)
3094 pg_data_t *pgdat = NODE_DATA(nid);
3096 if (pgdat->kcompactd)
3099 pgdat->kcompactd = kthread_run(kcompactd, pgdat, "kcompactd%d", nid);
3100 if (IS_ERR(pgdat->kcompactd)) {
3101 pr_err("Failed to start kcompactd on node %d\n", nid);
3102 pgdat->kcompactd = NULL;
3107 * Called by memory hotplug when all memory in a node is offlined. Caller must
3108 * be holding mem_hotplug_begin/done().
3110 void __meminit kcompactd_stop(int nid)
3112 struct task_struct *kcompactd = NODE_DATA(nid)->kcompactd;
3115 kthread_stop(kcompactd);
3116 NODE_DATA(nid)->kcompactd = NULL;
3121 * It's optimal to keep kcompactd on the same CPUs as their memory, but
3122 * not required for correctness. So if the last cpu in a node goes
3123 * away, we get changed to run anywhere: as the first one comes back,
3124 * restore their cpu bindings.
3126 static int kcompactd_cpu_online(unsigned int cpu)
3130 for_each_node_state(nid, N_MEMORY) {
3131 pg_data_t *pgdat = NODE_DATA(nid);
3132 const struct cpumask *mask;
3134 mask = cpumask_of_node(pgdat->node_id);
3136 if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
3137 /* One of our CPUs online: restore mask */
3138 if (pgdat->kcompactd)
3139 set_cpus_allowed_ptr(pgdat->kcompactd, mask);
3144 static int proc_dointvec_minmax_warn_RT_change(struct ctl_table *table,
3145 int write, void *buffer, size_t *lenp, loff_t *ppos)
3149 if (!IS_ENABLED(CONFIG_PREEMPT_RT) || !write)
3150 return proc_dointvec_minmax(table, write, buffer, lenp, ppos);
3152 old = *(int *)table->data;
3153 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
3156 if (old != *(int *)table->data)
3157 pr_warn_once("sysctl attribute %s changed by %s[%d]\n",
3158 table->procname, current->comm,
3159 task_pid_nr(current));
3163 static struct ctl_table vm_compaction[] = {
3165 .procname = "compact_memory",
3166 .data = &sysctl_compact_memory,
3167 .maxlen = sizeof(int),
3169 .proc_handler = sysctl_compaction_handler,
3172 .procname = "compaction_proactiveness",
3173 .data = &sysctl_compaction_proactiveness,
3174 .maxlen = sizeof(sysctl_compaction_proactiveness),
3176 .proc_handler = compaction_proactiveness_sysctl_handler,
3177 .extra1 = SYSCTL_ZERO,
3178 .extra2 = SYSCTL_ONE_HUNDRED,
3181 .procname = "extfrag_threshold",
3182 .data = &sysctl_extfrag_threshold,
3183 .maxlen = sizeof(int),
3185 .proc_handler = proc_dointvec_minmax,
3186 .extra1 = SYSCTL_ZERO,
3187 .extra2 = SYSCTL_ONE_THOUSAND,
3190 .procname = "compact_unevictable_allowed",
3191 .data = &sysctl_compact_unevictable_allowed,
3192 .maxlen = sizeof(int),
3194 .proc_handler = proc_dointvec_minmax_warn_RT_change,
3195 .extra1 = SYSCTL_ZERO,
3196 .extra2 = SYSCTL_ONE,
3201 static int __init kcompactd_init(void)
3206 ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
3207 "mm/compaction:online",
3208 kcompactd_cpu_online, NULL);
3210 pr_err("kcompactd: failed to register hotplug callbacks.\n");
3214 for_each_node_state(nid, N_MEMORY)
3216 register_sysctl_init("vm", vm_compaction);
3219 subsys_initcall(kcompactd_init)
3221 #endif /* CONFIG_COMPACTION */