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
29 static inline void count_compact_event(enum vm_event_item item
)
34 static inline void count_compact_events(enum vm_event_item item
, long delta
)
36 count_vm_events(item
, delta
);
39 #define count_compact_event(item) do { } while (0)
40 #define count_compact_events(item, delta) do { } while (0)
43 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
45 #define CREATE_TRACE_POINTS
46 #include <trace/events/compaction.h>
48 #define block_start_pfn(pfn, order) round_down(pfn, 1UL << (order))
49 #define block_end_pfn(pfn, order) ALIGN((pfn) + 1, 1UL << (order))
50 #define pageblock_start_pfn(pfn) block_start_pfn(pfn, pageblock_order)
51 #define pageblock_end_pfn(pfn) block_end_pfn(pfn, pageblock_order)
53 static unsigned long release_freepages(struct list_head
*freelist
)
55 struct page
*page
, *next
;
56 unsigned long high_pfn
= 0;
58 list_for_each_entry_safe(page
, next
, freelist
, lru
) {
59 unsigned long pfn
= page_to_pfn(page
);
69 static void map_pages(struct list_head
*list
)
71 unsigned int i
, order
, nr_pages
;
72 struct page
*page
, *next
;
75 list_for_each_entry_safe(page
, next
, list
, lru
) {
78 order
= page_private(page
);
79 nr_pages
= 1 << order
;
81 post_alloc_hook(page
, order
, __GFP_MOVABLE
);
83 split_page(page
, order
);
85 for (i
= 0; i
< nr_pages
; i
++) {
86 list_add(&page
->lru
, &tmp_list
);
91 list_splice(&tmp_list
, list
);
94 #ifdef CONFIG_COMPACTION
96 int PageMovable(struct page
*page
)
98 struct address_space
*mapping
;
100 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
101 if (!__PageMovable(page
))
104 mapping
= page_mapping(page
);
105 if (mapping
&& mapping
->a_ops
&& mapping
->a_ops
->isolate_page
)
110 EXPORT_SYMBOL(PageMovable
);
112 void __SetPageMovable(struct page
*page
, struct address_space
*mapping
)
114 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
115 VM_BUG_ON_PAGE((unsigned long)mapping
& PAGE_MAPPING_MOVABLE
, page
);
116 page
->mapping
= (void *)((unsigned long)mapping
| PAGE_MAPPING_MOVABLE
);
118 EXPORT_SYMBOL(__SetPageMovable
);
120 void __ClearPageMovable(struct page
*page
)
122 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
123 VM_BUG_ON_PAGE(!PageMovable(page
), page
);
125 * Clear registered address_space val with keeping PAGE_MAPPING_MOVABLE
126 * flag so that VM can catch up released page by driver after isolation.
127 * With it, VM migration doesn't try to put it back.
129 page
->mapping
= (void *)((unsigned long)page
->mapping
&
130 PAGE_MAPPING_MOVABLE
);
132 EXPORT_SYMBOL(__ClearPageMovable
);
134 /* Do not skip compaction more than 64 times */
135 #define COMPACT_MAX_DEFER_SHIFT 6
138 * Compaction is deferred when compaction fails to result in a page
139 * allocation success. 1 << compact_defer_limit compactions are skipped up
140 * to a limit of 1 << COMPACT_MAX_DEFER_SHIFT
142 void defer_compaction(struct zone
*zone
, int order
)
144 zone
->compact_considered
= 0;
145 zone
->compact_defer_shift
++;
147 if (order
< zone
->compact_order_failed
)
148 zone
->compact_order_failed
= order
;
150 if (zone
->compact_defer_shift
> COMPACT_MAX_DEFER_SHIFT
)
151 zone
->compact_defer_shift
= COMPACT_MAX_DEFER_SHIFT
;
153 trace_mm_compaction_defer_compaction(zone
, order
);
156 /* Returns true if compaction should be skipped this time */
157 bool compaction_deferred(struct zone
*zone
, int order
)
159 unsigned long defer_limit
= 1UL << zone
->compact_defer_shift
;
161 if (order
< zone
->compact_order_failed
)
164 /* Avoid possible overflow */
165 if (++zone
->compact_considered
> defer_limit
)
166 zone
->compact_considered
= defer_limit
;
168 if (zone
->compact_considered
>= defer_limit
)
171 trace_mm_compaction_deferred(zone
, order
);
177 * Update defer tracking counters after successful compaction of given order,
178 * which means an allocation either succeeded (alloc_success == true) or is
179 * expected to succeed.
181 void compaction_defer_reset(struct zone
*zone
, int order
,
185 zone
->compact_considered
= 0;
186 zone
->compact_defer_shift
= 0;
188 if (order
>= zone
->compact_order_failed
)
189 zone
->compact_order_failed
= order
+ 1;
191 trace_mm_compaction_defer_reset(zone
, order
);
194 /* Returns true if restarting compaction after many failures */
195 bool compaction_restarting(struct zone
*zone
, int order
)
197 if (order
< zone
->compact_order_failed
)
200 return zone
->compact_defer_shift
== COMPACT_MAX_DEFER_SHIFT
&&
201 zone
->compact_considered
>= 1UL << zone
->compact_defer_shift
;
204 /* Returns true if the pageblock should be scanned for pages to isolate. */
205 static inline bool isolation_suitable(struct compact_control
*cc
,
208 if (cc
->ignore_skip_hint
)
211 return !get_pageblock_skip(page
);
214 static void reset_cached_positions(struct zone
*zone
)
216 zone
->compact_cached_migrate_pfn
[0] = zone
->zone_start_pfn
;
217 zone
->compact_cached_migrate_pfn
[1] = zone
->zone_start_pfn
;
218 zone
->compact_cached_free_pfn
=
219 pageblock_start_pfn(zone_end_pfn(zone
) - 1);
223 * This function is called to clear all cached information on pageblocks that
224 * should be skipped for page isolation when the migrate and free page scanner
227 static void __reset_isolation_suitable(struct zone
*zone
)
229 unsigned long start_pfn
= zone
->zone_start_pfn
;
230 unsigned long end_pfn
= zone_end_pfn(zone
);
233 zone
->compact_blockskip_flush
= false;
235 /* Walk the zone and mark every pageblock as suitable for isolation */
236 for (pfn
= start_pfn
; pfn
< end_pfn
; pfn
+= pageblock_nr_pages
) {
241 page
= pfn_to_online_page(pfn
);
244 if (zone
!= page_zone(page
))
247 clear_pageblock_skip(page
);
250 reset_cached_positions(zone
);
253 void reset_isolation_suitable(pg_data_t
*pgdat
)
257 for (zoneid
= 0; zoneid
< MAX_NR_ZONES
; zoneid
++) {
258 struct zone
*zone
= &pgdat
->node_zones
[zoneid
];
259 if (!populated_zone(zone
))
262 /* Only flush if a full compaction finished recently */
263 if (zone
->compact_blockskip_flush
)
264 __reset_isolation_suitable(zone
);
269 * If no pages were isolated then mark this pageblock to be skipped in the
270 * future. The information is later cleared by __reset_isolation_suitable().
272 static void update_pageblock_skip(struct compact_control
*cc
,
273 struct page
*page
, unsigned long nr_isolated
,
274 bool migrate_scanner
)
276 struct zone
*zone
= cc
->zone
;
279 if (cc
->ignore_skip_hint
)
288 set_pageblock_skip(page
);
290 pfn
= page_to_pfn(page
);
292 /* Update where async and sync compaction should restart */
293 if (migrate_scanner
) {
294 if (pfn
> zone
->compact_cached_migrate_pfn
[0])
295 zone
->compact_cached_migrate_pfn
[0] = pfn
;
296 if (cc
->mode
!= MIGRATE_ASYNC
&&
297 pfn
> zone
->compact_cached_migrate_pfn
[1])
298 zone
->compact_cached_migrate_pfn
[1] = pfn
;
300 if (pfn
< zone
->compact_cached_free_pfn
)
301 zone
->compact_cached_free_pfn
= pfn
;
305 static inline bool isolation_suitable(struct compact_control
*cc
,
311 static void update_pageblock_skip(struct compact_control
*cc
,
312 struct page
*page
, unsigned long nr_isolated
,
313 bool migrate_scanner
)
316 #endif /* CONFIG_COMPACTION */
319 * Compaction requires the taking of some coarse locks that are potentially
320 * very heavily contended. For async compaction, back out if the lock cannot
321 * be taken immediately. For sync compaction, spin on the lock if needed.
323 * Returns true if the lock is held
324 * Returns false if the lock is not held and compaction should abort
326 static bool compact_trylock_irqsave(spinlock_t
*lock
, unsigned long *flags
,
327 struct compact_control
*cc
)
329 if (cc
->mode
== MIGRATE_ASYNC
) {
330 if (!spin_trylock_irqsave(lock
, *flags
)) {
331 cc
->contended
= true;
335 spin_lock_irqsave(lock
, *flags
);
342 * Compaction requires the taking of some coarse locks that are potentially
343 * very heavily contended. The lock should be periodically unlocked to avoid
344 * having disabled IRQs for a long time, even when there is nobody waiting on
345 * the lock. It might also be that allowing the IRQs will result in
346 * need_resched() becoming true. If scheduling is needed, async compaction
347 * aborts. Sync compaction schedules.
348 * Either compaction type will also abort if a fatal signal is pending.
349 * In either case if the lock was locked, it is dropped and not regained.
351 * Returns true if compaction should abort due to fatal signal pending, or
352 * async compaction due to need_resched()
353 * Returns false when compaction can continue (sync compaction might have
356 static bool compact_unlock_should_abort(spinlock_t
*lock
,
357 unsigned long flags
, bool *locked
, struct compact_control
*cc
)
360 spin_unlock_irqrestore(lock
, flags
);
364 if (fatal_signal_pending(current
)) {
365 cc
->contended
= true;
369 if (need_resched()) {
370 if (cc
->mode
== MIGRATE_ASYNC
) {
371 cc
->contended
= true;
381 * Aside from avoiding lock contention, compaction also periodically checks
382 * need_resched() and either schedules in sync compaction or aborts async
383 * compaction. This is similar to what compact_unlock_should_abort() does, but
384 * is used where no lock is concerned.
386 * Returns false when no scheduling was needed, or sync compaction scheduled.
387 * Returns true when async compaction should abort.
389 static inline bool compact_should_abort(struct compact_control
*cc
)
391 /* async compaction aborts if contended */
392 if (need_resched()) {
393 if (cc
->mode
== MIGRATE_ASYNC
) {
394 cc
->contended
= true;
405 * Isolate free pages onto a private freelist. If @strict is true, will abort
406 * returning 0 on any invalid PFNs or non-free pages inside of the pageblock
407 * (even though it may still end up isolating some pages).
409 static unsigned long isolate_freepages_block(struct compact_control
*cc
,
410 unsigned long *start_pfn
,
411 unsigned long end_pfn
,
412 struct list_head
*freelist
,
415 int nr_scanned
= 0, total_isolated
= 0;
416 struct page
*cursor
, *valid_page
= NULL
;
417 unsigned long flags
= 0;
419 unsigned long blockpfn
= *start_pfn
;
422 cursor
= pfn_to_page(blockpfn
);
424 /* Isolate free pages. */
425 for (; blockpfn
< end_pfn
; blockpfn
++, cursor
++) {
427 struct page
*page
= cursor
;
430 * Periodically drop the lock (if held) regardless of its
431 * contention, to give chance to IRQs. Abort if fatal signal
432 * pending or async compaction detects need_resched()
434 if (!(blockpfn
% SWAP_CLUSTER_MAX
)
435 && compact_unlock_should_abort(&cc
->zone
->lock
, flags
,
440 if (!pfn_valid_within(blockpfn
))
447 * For compound pages such as THP and hugetlbfs, we can save
448 * potentially a lot of iterations if we skip them at once.
449 * The check is racy, but we can consider only valid values
450 * and the only danger is skipping too much.
452 if (PageCompound(page
)) {
453 unsigned int comp_order
= compound_order(page
);
455 if (likely(comp_order
< MAX_ORDER
)) {
456 blockpfn
+= (1UL << comp_order
) - 1;
457 cursor
+= (1UL << comp_order
) - 1;
463 if (!PageBuddy(page
))
467 * If we already hold the lock, we can skip some rechecking.
468 * Note that if we hold the lock now, checked_pageblock was
469 * already set in some previous iteration (or strict is true),
470 * so it is correct to skip the suitable migration target
475 * The zone lock must be held to isolate freepages.
476 * Unfortunately this is a very coarse lock and can be
477 * heavily contended if there are parallel allocations
478 * or parallel compactions. For async compaction do not
479 * spin on the lock and we acquire the lock as late as
482 locked
= compact_trylock_irqsave(&cc
->zone
->lock
,
487 /* Recheck this is a buddy page under lock */
488 if (!PageBuddy(page
))
492 /* Found a free page, will break it into order-0 pages */
493 order
= page_order(page
);
494 isolated
= __isolate_free_page(page
, order
);
497 set_page_private(page
, order
);
499 total_isolated
+= isolated
;
500 cc
->nr_freepages
+= isolated
;
501 list_add_tail(&page
->lru
, freelist
);
503 if (!strict
&& cc
->nr_migratepages
<= cc
->nr_freepages
) {
504 blockpfn
+= isolated
;
507 /* Advance to the end of split page */
508 blockpfn
+= isolated
- 1;
509 cursor
+= isolated
- 1;
521 spin_unlock_irqrestore(&cc
->zone
->lock
, flags
);
524 * There is a tiny chance that we have read bogus compound_order(),
525 * so be careful to not go outside of the pageblock.
527 if (unlikely(blockpfn
> end_pfn
))
530 trace_mm_compaction_isolate_freepages(*start_pfn
, blockpfn
,
531 nr_scanned
, total_isolated
);
533 /* Record how far we have got within the block */
534 *start_pfn
= blockpfn
;
537 * If strict isolation is requested by CMA then check that all the
538 * pages requested were isolated. If there were any failures, 0 is
539 * returned and CMA will fail.
541 if (strict
&& blockpfn
< end_pfn
)
544 /* Update the pageblock-skip if the whole pageblock was scanned */
545 if (blockpfn
== end_pfn
)
546 update_pageblock_skip(cc
, valid_page
, total_isolated
, false);
548 cc
->total_free_scanned
+= nr_scanned
;
550 count_compact_events(COMPACTISOLATED
, total_isolated
);
551 return total_isolated
;
555 * isolate_freepages_range() - isolate free pages.
556 * @start_pfn: The first PFN to start isolating.
557 * @end_pfn: The one-past-last PFN.
559 * Non-free pages, invalid PFNs, or zone boundaries within the
560 * [start_pfn, end_pfn) range are considered errors, cause function to
561 * undo its actions and return zero.
563 * Otherwise, function returns one-past-the-last PFN of isolated page
564 * (which may be greater then end_pfn if end fell in a middle of
568 isolate_freepages_range(struct compact_control
*cc
,
569 unsigned long start_pfn
, unsigned long end_pfn
)
571 unsigned long isolated
, pfn
, block_start_pfn
, block_end_pfn
;
575 block_start_pfn
= pageblock_start_pfn(pfn
);
576 if (block_start_pfn
< cc
->zone
->zone_start_pfn
)
577 block_start_pfn
= cc
->zone
->zone_start_pfn
;
578 block_end_pfn
= pageblock_end_pfn(pfn
);
580 for (; pfn
< end_pfn
; pfn
+= isolated
,
581 block_start_pfn
= block_end_pfn
,
582 block_end_pfn
+= pageblock_nr_pages
) {
583 /* Protect pfn from changing by isolate_freepages_block */
584 unsigned long isolate_start_pfn
= pfn
;
586 block_end_pfn
= min(block_end_pfn
, end_pfn
);
589 * pfn could pass the block_end_pfn if isolated freepage
590 * is more than pageblock order. In this case, we adjust
591 * scanning range to right one.
593 if (pfn
>= block_end_pfn
) {
594 block_start_pfn
= pageblock_start_pfn(pfn
);
595 block_end_pfn
= pageblock_end_pfn(pfn
);
596 block_end_pfn
= min(block_end_pfn
, end_pfn
);
599 if (!pageblock_pfn_to_page(block_start_pfn
,
600 block_end_pfn
, cc
->zone
))
603 isolated
= isolate_freepages_block(cc
, &isolate_start_pfn
,
604 block_end_pfn
, &freelist
, true);
607 * In strict mode, isolate_freepages_block() returns 0 if
608 * there are any holes in the block (ie. invalid PFNs or
615 * If we managed to isolate pages, it is always (1 << n) *
616 * pageblock_nr_pages for some non-negative n. (Max order
617 * page may span two pageblocks).
621 /* __isolate_free_page() does not map the pages */
622 map_pages(&freelist
);
625 /* Loop terminated early, cleanup. */
626 release_freepages(&freelist
);
630 /* We don't use freelists for anything. */
634 /* Similar to reclaim, but different enough that they don't share logic */
635 static bool too_many_isolated(struct zone
*zone
)
637 unsigned long active
, inactive
, isolated
;
639 inactive
= node_page_state(zone
->zone_pgdat
, NR_INACTIVE_FILE
) +
640 node_page_state(zone
->zone_pgdat
, NR_INACTIVE_ANON
);
641 active
= node_page_state(zone
->zone_pgdat
, NR_ACTIVE_FILE
) +
642 node_page_state(zone
->zone_pgdat
, NR_ACTIVE_ANON
);
643 isolated
= node_page_state(zone
->zone_pgdat
, NR_ISOLATED_FILE
) +
644 node_page_state(zone
->zone_pgdat
, NR_ISOLATED_ANON
);
646 return isolated
> (inactive
+ active
) / 2;
650 * isolate_migratepages_block() - isolate all migrate-able pages within
652 * @cc: Compaction control structure.
653 * @low_pfn: The first PFN to isolate
654 * @end_pfn: The one-past-the-last PFN to isolate, within same pageblock
655 * @isolate_mode: Isolation mode to be used.
657 * Isolate all pages that can be migrated from the range specified by
658 * [low_pfn, end_pfn). The range is expected to be within same pageblock.
659 * Returns zero if there is a fatal signal pending, otherwise PFN of the
660 * first page that was not scanned (which may be both less, equal to or more
663 * The pages are isolated on cc->migratepages list (not required to be empty),
664 * and cc->nr_migratepages is updated accordingly. The cc->migrate_pfn field
665 * is neither read nor updated.
668 isolate_migratepages_block(struct compact_control
*cc
, unsigned long low_pfn
,
669 unsigned long end_pfn
, isolate_mode_t isolate_mode
)
671 struct zone
*zone
= cc
->zone
;
672 unsigned long nr_scanned
= 0, nr_isolated
= 0;
673 struct lruvec
*lruvec
;
674 unsigned long flags
= 0;
676 struct page
*page
= NULL
, *valid_page
= NULL
;
677 unsigned long start_pfn
= low_pfn
;
678 bool skip_on_failure
= false;
679 unsigned long next_skip_pfn
= 0;
682 * Ensure that there are not too many pages isolated from the LRU
683 * list by either parallel reclaimers or compaction. If there are,
684 * delay for some time until fewer pages are isolated
686 while (unlikely(too_many_isolated(zone
))) {
687 /* async migration should just abort */
688 if (cc
->mode
== MIGRATE_ASYNC
)
691 congestion_wait(BLK_RW_ASYNC
, HZ
/10);
693 if (fatal_signal_pending(current
))
697 if (compact_should_abort(cc
))
700 if (cc
->direct_compaction
&& (cc
->mode
== MIGRATE_ASYNC
)) {
701 skip_on_failure
= true;
702 next_skip_pfn
= block_end_pfn(low_pfn
, cc
->order
);
705 /* Time to isolate some pages for migration */
706 for (; low_pfn
< end_pfn
; low_pfn
++) {
708 if (skip_on_failure
&& low_pfn
>= next_skip_pfn
) {
710 * We have isolated all migration candidates in the
711 * previous order-aligned block, and did not skip it due
712 * to failure. We should migrate the pages now and
713 * hopefully succeed compaction.
719 * We failed to isolate in the previous order-aligned
720 * block. Set the new boundary to the end of the
721 * current block. Note we can't simply increase
722 * next_skip_pfn by 1 << order, as low_pfn might have
723 * been incremented by a higher number due to skipping
724 * a compound or a high-order buddy page in the
725 * previous loop iteration.
727 next_skip_pfn
= block_end_pfn(low_pfn
, cc
->order
);
731 * Periodically drop the lock (if held) regardless of its
732 * contention, to give chance to IRQs. Abort async compaction
735 if (!(low_pfn
% SWAP_CLUSTER_MAX
)
736 && compact_unlock_should_abort(zone_lru_lock(zone
), flags
,
740 if (!pfn_valid_within(low_pfn
))
744 page
= pfn_to_page(low_pfn
);
750 * Skip if free. We read page order here without zone lock
751 * which is generally unsafe, but the race window is small and
752 * the worst thing that can happen is that we skip some
753 * potential isolation targets.
755 if (PageBuddy(page
)) {
756 unsigned long freepage_order
= page_order_unsafe(page
);
759 * Without lock, we cannot be sure that what we got is
760 * a valid page order. Consider only values in the
761 * valid order range to prevent low_pfn overflow.
763 if (freepage_order
> 0 && freepage_order
< MAX_ORDER
)
764 low_pfn
+= (1UL << freepage_order
) - 1;
769 * Regardless of being on LRU, compound pages such as THP and
770 * hugetlbfs are not to be compacted. We can potentially save
771 * a lot of iterations if we skip them at once. The check is
772 * racy, but we can consider only valid values and the only
773 * danger is skipping too much.
775 if (PageCompound(page
)) {
776 unsigned int comp_order
= compound_order(page
);
778 if (likely(comp_order
< MAX_ORDER
))
779 low_pfn
+= (1UL << comp_order
) - 1;
785 * Check may be lockless but that's ok as we recheck later.
786 * It's possible to migrate LRU and non-lru movable pages.
787 * Skip any other type of page
789 if (!PageLRU(page
)) {
791 * __PageMovable can return false positive so we need
792 * to verify it under page_lock.
794 if (unlikely(__PageMovable(page
)) &&
795 !PageIsolated(page
)) {
797 spin_unlock_irqrestore(zone_lru_lock(zone
),
802 if (!isolate_movable_page(page
, isolate_mode
))
803 goto isolate_success
;
810 * Migration will fail if an anonymous page is pinned in memory,
811 * so avoid taking lru_lock and isolating it unnecessarily in an
812 * admittedly racy check.
814 if (!page_mapping(page
) &&
815 page_count(page
) > page_mapcount(page
))
819 * Only allow to migrate anonymous pages in GFP_NOFS context
820 * because those do not depend on fs locks.
822 if (!(cc
->gfp_mask
& __GFP_FS
) && page_mapping(page
))
825 /* If we already hold the lock, we can skip some rechecking */
827 locked
= compact_trylock_irqsave(zone_lru_lock(zone
),
832 /* Recheck PageLRU and PageCompound under lock */
837 * Page become compound since the non-locked check,
838 * and it's on LRU. It can only be a THP so the order
839 * is safe to read and it's 0 for tail pages.
841 if (unlikely(PageCompound(page
))) {
842 low_pfn
+= (1UL << compound_order(page
)) - 1;
847 lruvec
= mem_cgroup_page_lruvec(page
, zone
->zone_pgdat
);
849 /* Try isolate the page */
850 if (__isolate_lru_page(page
, isolate_mode
) != 0)
853 VM_BUG_ON_PAGE(PageCompound(page
), page
);
855 /* Successfully isolated */
856 del_page_from_lru_list(page
, lruvec
, page_lru(page
));
857 inc_node_page_state(page
,
858 NR_ISOLATED_ANON
+ page_is_file_cache(page
));
861 list_add(&page
->lru
, &cc
->migratepages
);
862 cc
->nr_migratepages
++;
866 * Record where we could have freed pages by migration and not
867 * yet flushed them to buddy allocator.
868 * - this is the lowest page that was isolated and likely be
869 * then freed by migration.
871 if (!cc
->last_migrated_pfn
)
872 cc
->last_migrated_pfn
= low_pfn
;
874 /* Avoid isolating too much */
875 if (cc
->nr_migratepages
== COMPACT_CLUSTER_MAX
) {
882 if (!skip_on_failure
)
886 * We have isolated some pages, but then failed. Release them
887 * instead of migrating, as we cannot form the cc->order buddy
892 spin_unlock_irqrestore(zone_lru_lock(zone
), flags
);
895 putback_movable_pages(&cc
->migratepages
);
896 cc
->nr_migratepages
= 0;
897 cc
->last_migrated_pfn
= 0;
901 if (low_pfn
< next_skip_pfn
) {
902 low_pfn
= next_skip_pfn
- 1;
904 * The check near the loop beginning would have updated
905 * next_skip_pfn too, but this is a bit simpler.
907 next_skip_pfn
+= 1UL << cc
->order
;
912 * The PageBuddy() check could have potentially brought us outside
913 * the range to be scanned.
915 if (unlikely(low_pfn
> end_pfn
))
919 spin_unlock_irqrestore(zone_lru_lock(zone
), flags
);
922 * Update the pageblock-skip information and cached scanner pfn,
923 * if the whole pageblock was scanned without isolating any page.
925 if (low_pfn
== end_pfn
)
926 update_pageblock_skip(cc
, valid_page
, nr_isolated
, true);
928 trace_mm_compaction_isolate_migratepages(start_pfn
, low_pfn
,
929 nr_scanned
, nr_isolated
);
931 cc
->total_migrate_scanned
+= nr_scanned
;
933 count_compact_events(COMPACTISOLATED
, nr_isolated
);
939 * isolate_migratepages_range() - isolate migrate-able pages in a PFN range
940 * @cc: Compaction control structure.
941 * @start_pfn: The first PFN to start isolating.
942 * @end_pfn: The one-past-last PFN.
944 * Returns zero if isolation fails fatally due to e.g. pending signal.
945 * Otherwise, function returns one-past-the-last PFN of isolated page
946 * (which may be greater than end_pfn if end fell in a middle of a THP page).
949 isolate_migratepages_range(struct compact_control
*cc
, unsigned long start_pfn
,
950 unsigned long end_pfn
)
952 unsigned long pfn
, block_start_pfn
, block_end_pfn
;
954 /* Scan block by block. First and last block may be incomplete */
956 block_start_pfn
= pageblock_start_pfn(pfn
);
957 if (block_start_pfn
< cc
->zone
->zone_start_pfn
)
958 block_start_pfn
= cc
->zone
->zone_start_pfn
;
959 block_end_pfn
= pageblock_end_pfn(pfn
);
961 for (; pfn
< end_pfn
; pfn
= block_end_pfn
,
962 block_start_pfn
= block_end_pfn
,
963 block_end_pfn
+= pageblock_nr_pages
) {
965 block_end_pfn
= min(block_end_pfn
, end_pfn
);
967 if (!pageblock_pfn_to_page(block_start_pfn
,
968 block_end_pfn
, cc
->zone
))
971 pfn
= isolate_migratepages_block(cc
, pfn
, block_end_pfn
,
972 ISOLATE_UNEVICTABLE
);
977 if (cc
->nr_migratepages
== COMPACT_CLUSTER_MAX
)
984 #endif /* CONFIG_COMPACTION || CONFIG_CMA */
985 #ifdef CONFIG_COMPACTION
987 static bool suitable_migration_source(struct compact_control
*cc
,
992 if ((cc
->mode
!= MIGRATE_ASYNC
) || !cc
->direct_compaction
)
995 block_mt
= get_pageblock_migratetype(page
);
997 if (cc
->migratetype
== MIGRATE_MOVABLE
)
998 return is_migrate_movable(block_mt
);
1000 return block_mt
== cc
->migratetype
;
1003 /* Returns true if the page is within a block suitable for migration to */
1004 static bool suitable_migration_target(struct compact_control
*cc
,
1007 /* If the page is a large free page, then disallow migration */
1008 if (PageBuddy(page
)) {
1010 * We are checking page_order without zone->lock taken. But
1011 * the only small danger is that we skip a potentially suitable
1012 * pageblock, so it's not worth to check order for valid range.
1014 if (page_order_unsafe(page
) >= pageblock_order
)
1018 if (cc
->ignore_block_suitable
)
1021 /* If the block is MIGRATE_MOVABLE, allow migration */
1022 if (get_pageblock_migratetype(page
) == MIGRATE_MOVABLE
)
1025 /* Otherwise skip the block */
1030 * Test whether the free scanner has reached the same or lower pageblock than
1031 * the migration scanner, and compaction should thus terminate.
1033 static inline bool compact_scanners_met(struct compact_control
*cc
)
1035 return (cc
->free_pfn
>> pageblock_order
)
1036 <= (cc
->migrate_pfn
>> pageblock_order
);
1040 * Based on information in the current compact_control, find blocks
1041 * suitable for isolating free pages from and then isolate them.
1043 static void isolate_freepages(struct compact_control
*cc
)
1045 struct zone
*zone
= cc
->zone
;
1047 unsigned long block_start_pfn
; /* start of current pageblock */
1048 unsigned long isolate_start_pfn
; /* exact pfn we start at */
1049 unsigned long block_end_pfn
; /* end of current pageblock */
1050 unsigned long low_pfn
; /* lowest pfn scanner is able to scan */
1051 struct list_head
*freelist
= &cc
->freepages
;
1054 * Initialise the free scanner. The starting point is where we last
1055 * successfully isolated from, zone-cached value, or the end of the
1056 * zone when isolating for the first time. For looping we also need
1057 * this pfn aligned down to the pageblock boundary, because we do
1058 * block_start_pfn -= pageblock_nr_pages in the for loop.
1059 * For ending point, take care when isolating in last pageblock of a
1060 * a zone which ends in the middle of a pageblock.
1061 * The low boundary is the end of the pageblock the migration scanner
1064 isolate_start_pfn
= cc
->free_pfn
;
1065 block_start_pfn
= pageblock_start_pfn(cc
->free_pfn
);
1066 block_end_pfn
= min(block_start_pfn
+ pageblock_nr_pages
,
1067 zone_end_pfn(zone
));
1068 low_pfn
= pageblock_end_pfn(cc
->migrate_pfn
);
1071 * Isolate free pages until enough are available to migrate the
1072 * pages on cc->migratepages. We stop searching if the migrate
1073 * and free page scanners meet or enough free pages are isolated.
1075 for (; block_start_pfn
>= low_pfn
;
1076 block_end_pfn
= block_start_pfn
,
1077 block_start_pfn
-= pageblock_nr_pages
,
1078 isolate_start_pfn
= block_start_pfn
) {
1080 * This can iterate a massively long zone without finding any
1081 * suitable migration targets, so periodically check if we need
1082 * to schedule, or even abort async compaction.
1084 if (!(block_start_pfn
% (SWAP_CLUSTER_MAX
* pageblock_nr_pages
))
1085 && compact_should_abort(cc
))
1088 page
= pageblock_pfn_to_page(block_start_pfn
, block_end_pfn
,
1093 /* Check the block is suitable for migration */
1094 if (!suitable_migration_target(cc
, page
))
1097 /* If isolation recently failed, do not retry */
1098 if (!isolation_suitable(cc
, page
))
1101 /* Found a block suitable for isolating free pages from. */
1102 isolate_freepages_block(cc
, &isolate_start_pfn
, block_end_pfn
,
1106 * If we isolated enough freepages, or aborted due to lock
1107 * contention, terminate.
1109 if ((cc
->nr_freepages
>= cc
->nr_migratepages
)
1111 if (isolate_start_pfn
>= block_end_pfn
) {
1113 * Restart at previous pageblock if more
1114 * freepages can be isolated next time.
1117 block_start_pfn
- pageblock_nr_pages
;
1120 } else if (isolate_start_pfn
< block_end_pfn
) {
1122 * If isolation failed early, do not continue
1129 /* __isolate_free_page() does not map the pages */
1130 map_pages(freelist
);
1133 * Record where the free scanner will restart next time. Either we
1134 * broke from the loop and set isolate_start_pfn based on the last
1135 * call to isolate_freepages_block(), or we met the migration scanner
1136 * and the loop terminated due to isolate_start_pfn < low_pfn
1138 cc
->free_pfn
= isolate_start_pfn
;
1142 * This is a migrate-callback that "allocates" freepages by taking pages
1143 * from the isolated freelists in the block we are migrating to.
1145 static struct page
*compaction_alloc(struct page
*migratepage
,
1149 struct compact_control
*cc
= (struct compact_control
*)data
;
1150 struct page
*freepage
;
1153 * Isolate free pages if necessary, and if we are not aborting due to
1156 if (list_empty(&cc
->freepages
)) {
1158 isolate_freepages(cc
);
1160 if (list_empty(&cc
->freepages
))
1164 freepage
= list_entry(cc
->freepages
.next
, struct page
, lru
);
1165 list_del(&freepage
->lru
);
1172 * This is a migrate-callback that "frees" freepages back to the isolated
1173 * freelist. All pages on the freelist are from the same zone, so there is no
1174 * special handling needed for NUMA.
1176 static void compaction_free(struct page
*page
, unsigned long data
)
1178 struct compact_control
*cc
= (struct compact_control
*)data
;
1180 list_add(&page
->lru
, &cc
->freepages
);
1184 /* possible outcome of isolate_migratepages */
1186 ISOLATE_ABORT
, /* Abort compaction now */
1187 ISOLATE_NONE
, /* No pages isolated, continue scanning */
1188 ISOLATE_SUCCESS
, /* Pages isolated, migrate */
1189 } isolate_migrate_t
;
1192 * Allow userspace to control policy on scanning the unevictable LRU for
1193 * compactable pages.
1195 int sysctl_compact_unevictable_allowed __read_mostly
= 1;
1198 * Isolate all pages that can be migrated from the first suitable block,
1199 * starting at the block pointed to by the migrate scanner pfn within
1202 static isolate_migrate_t
isolate_migratepages(struct zone
*zone
,
1203 struct compact_control
*cc
)
1205 unsigned long block_start_pfn
;
1206 unsigned long block_end_pfn
;
1207 unsigned long low_pfn
;
1209 const isolate_mode_t isolate_mode
=
1210 (sysctl_compact_unevictable_allowed
? ISOLATE_UNEVICTABLE
: 0) |
1211 (cc
->mode
!= MIGRATE_SYNC
? ISOLATE_ASYNC_MIGRATE
: 0);
1214 * Start at where we last stopped, or beginning of the zone as
1215 * initialized by compact_zone()
1217 low_pfn
= cc
->migrate_pfn
;
1218 block_start_pfn
= pageblock_start_pfn(low_pfn
);
1219 if (block_start_pfn
< zone
->zone_start_pfn
)
1220 block_start_pfn
= zone
->zone_start_pfn
;
1222 /* Only scan within a pageblock boundary */
1223 block_end_pfn
= pageblock_end_pfn(low_pfn
);
1226 * Iterate over whole pageblocks until we find the first suitable.
1227 * Do not cross the free scanner.
1229 for (; block_end_pfn
<= cc
->free_pfn
;
1230 low_pfn
= block_end_pfn
,
1231 block_start_pfn
= block_end_pfn
,
1232 block_end_pfn
+= pageblock_nr_pages
) {
1235 * This can potentially iterate a massively long zone with
1236 * many pageblocks unsuitable, so periodically check if we
1237 * need to schedule, or even abort async compaction.
1239 if (!(low_pfn
% (SWAP_CLUSTER_MAX
* pageblock_nr_pages
))
1240 && compact_should_abort(cc
))
1243 page
= pageblock_pfn_to_page(block_start_pfn
, block_end_pfn
,
1248 /* If isolation recently failed, do not retry */
1249 if (!isolation_suitable(cc
, page
))
1253 * For async compaction, also only scan in MOVABLE blocks.
1254 * Async compaction is optimistic to see if the minimum amount
1255 * of work satisfies the allocation.
1257 if (!suitable_migration_source(cc
, page
))
1260 /* Perform the isolation */
1261 low_pfn
= isolate_migratepages_block(cc
, low_pfn
,
1262 block_end_pfn
, isolate_mode
);
1264 if (!low_pfn
|| cc
->contended
)
1265 return ISOLATE_ABORT
;
1268 * Either we isolated something and proceed with migration. Or
1269 * we failed and compact_zone should decide if we should
1275 /* Record where migration scanner will be restarted. */
1276 cc
->migrate_pfn
= low_pfn
;
1278 return cc
->nr_migratepages
? ISOLATE_SUCCESS
: ISOLATE_NONE
;
1282 * order == -1 is expected when compacting via
1283 * /proc/sys/vm/compact_memory
1285 static inline bool is_via_compact_memory(int order
)
1290 static enum compact_result
__compact_finished(struct zone
*zone
,
1291 struct compact_control
*cc
)
1294 const int migratetype
= cc
->migratetype
;
1296 if (cc
->contended
|| fatal_signal_pending(current
))
1297 return COMPACT_CONTENDED
;
1299 /* Compaction run completes if the migrate and free scanner meet */
1300 if (compact_scanners_met(cc
)) {
1301 /* Let the next compaction start anew. */
1302 reset_cached_positions(zone
);
1305 * Mark that the PG_migrate_skip information should be cleared
1306 * by kswapd when it goes to sleep. kcompactd does not set the
1307 * flag itself as the decision to be clear should be directly
1308 * based on an allocation request.
1310 if (cc
->direct_compaction
)
1311 zone
->compact_blockskip_flush
= true;
1314 return COMPACT_COMPLETE
;
1316 return COMPACT_PARTIAL_SKIPPED
;
1319 if (is_via_compact_memory(cc
->order
))
1320 return COMPACT_CONTINUE
;
1322 if (cc
->finishing_block
) {
1324 * We have finished the pageblock, but better check again that
1325 * we really succeeded.
1327 if (IS_ALIGNED(cc
->migrate_pfn
, pageblock_nr_pages
))
1328 cc
->finishing_block
= false;
1330 return COMPACT_CONTINUE
;
1333 /* Direct compactor: Is a suitable page free? */
1334 for (order
= cc
->order
; order
< MAX_ORDER
; order
++) {
1335 struct free_area
*area
= &zone
->free_area
[order
];
1338 /* Job done if page is free of the right migratetype */
1339 if (!list_empty(&area
->free_list
[migratetype
]))
1340 return COMPACT_SUCCESS
;
1343 * Job done if allocation would steal freepages from
1344 * other migratetype buddy lists.
1346 if (find_suitable_fallback(area
, order
, migratetype
,
1347 true, &can_steal
) != -1) {
1349 /* movable pages are OK in any pageblock */
1350 if (migratetype
== MIGRATE_MOVABLE
)
1351 return COMPACT_SUCCESS
;
1354 * We are stealing for a non-movable allocation. Make
1355 * sure we finish compacting the current pageblock
1356 * first so it is as free as possible and we won't
1357 * have to steal another one soon. This only applies
1358 * to sync compaction, as async compaction operates
1359 * on pageblocks of the same migratetype.
1361 if (cc
->mode
== MIGRATE_ASYNC
||
1362 IS_ALIGNED(cc
->migrate_pfn
,
1363 pageblock_nr_pages
)) {
1364 return COMPACT_SUCCESS
;
1367 cc
->finishing_block
= true;
1368 return COMPACT_CONTINUE
;
1372 return COMPACT_NO_SUITABLE_PAGE
;
1375 static enum compact_result
compact_finished(struct zone
*zone
,
1376 struct compact_control
*cc
)
1380 ret
= __compact_finished(zone
, cc
);
1381 trace_mm_compaction_finished(zone
, cc
->order
, ret
);
1382 if (ret
== COMPACT_NO_SUITABLE_PAGE
)
1383 ret
= COMPACT_CONTINUE
;
1389 * compaction_suitable: Is this suitable to run compaction on this zone now?
1391 * COMPACT_SKIPPED - If there are too few free pages for compaction
1392 * COMPACT_SUCCESS - If the allocation would succeed without compaction
1393 * COMPACT_CONTINUE - If compaction should run now
1395 static enum compact_result
__compaction_suitable(struct zone
*zone
, int order
,
1396 unsigned int alloc_flags
,
1398 unsigned long wmark_target
)
1400 unsigned long watermark
;
1402 if (is_via_compact_memory(order
))
1403 return COMPACT_CONTINUE
;
1405 watermark
= zone
->watermark
[alloc_flags
& ALLOC_WMARK_MASK
];
1407 * If watermarks for high-order allocation are already met, there
1408 * should be no need for compaction at all.
1410 if (zone_watermark_ok(zone
, order
, watermark
, classzone_idx
,
1412 return COMPACT_SUCCESS
;
1415 * Watermarks for order-0 must be met for compaction to be able to
1416 * isolate free pages for migration targets. This means that the
1417 * watermark and alloc_flags have to match, or be more pessimistic than
1418 * the check in __isolate_free_page(). We don't use the direct
1419 * compactor's alloc_flags, as they are not relevant for freepage
1420 * isolation. We however do use the direct compactor's classzone_idx to
1421 * skip over zones where lowmem reserves would prevent allocation even
1422 * if compaction succeeds.
1423 * For costly orders, we require low watermark instead of min for
1424 * compaction to proceed to increase its chances.
1426 watermark
= (order
> PAGE_ALLOC_COSTLY_ORDER
) ?
1427 low_wmark_pages(zone
) : min_wmark_pages(zone
);
1428 watermark
+= compact_gap(order
);
1429 if (!__zone_watermark_ok(zone
, 0, watermark
, classzone_idx
,
1431 return COMPACT_SKIPPED
;
1433 return COMPACT_CONTINUE
;
1436 enum compact_result
compaction_suitable(struct zone
*zone
, int order
,
1437 unsigned int alloc_flags
,
1440 enum compact_result ret
;
1443 ret
= __compaction_suitable(zone
, order
, alloc_flags
, classzone_idx
,
1444 zone_page_state(zone
, NR_FREE_PAGES
));
1446 * fragmentation index determines if allocation failures are due to
1447 * low memory or external fragmentation
1449 * index of -1000 would imply allocations might succeed depending on
1450 * watermarks, but we already failed the high-order watermark check
1451 * index towards 0 implies failure is due to lack of memory
1452 * index towards 1000 implies failure is due to fragmentation
1454 * Only compact if a failure would be due to fragmentation. Also
1455 * ignore fragindex for non-costly orders where the alternative to
1456 * a successful reclaim/compaction is OOM. Fragindex and the
1457 * vm.extfrag_threshold sysctl is meant as a heuristic to prevent
1458 * excessive compaction for costly orders, but it should not be at the
1459 * expense of system stability.
1461 if (ret
== COMPACT_CONTINUE
&& (order
> PAGE_ALLOC_COSTLY_ORDER
)) {
1462 fragindex
= fragmentation_index(zone
, order
);
1463 if (fragindex
>= 0 && fragindex
<= sysctl_extfrag_threshold
)
1464 ret
= COMPACT_NOT_SUITABLE_ZONE
;
1467 trace_mm_compaction_suitable(zone
, order
, ret
);
1468 if (ret
== COMPACT_NOT_SUITABLE_ZONE
)
1469 ret
= COMPACT_SKIPPED
;
1474 bool compaction_zonelist_suitable(struct alloc_context
*ac
, int order
,
1481 * Make sure at least one zone would pass __compaction_suitable if we continue
1482 * retrying the reclaim.
1484 for_each_zone_zonelist_nodemask(zone
, z
, ac
->zonelist
, ac
->high_zoneidx
,
1486 unsigned long available
;
1487 enum compact_result compact_result
;
1490 * Do not consider all the reclaimable memory because we do not
1491 * want to trash just for a single high order allocation which
1492 * is even not guaranteed to appear even if __compaction_suitable
1493 * is happy about the watermark check.
1495 available
= zone_reclaimable_pages(zone
) / order
;
1496 available
+= zone_page_state_snapshot(zone
, NR_FREE_PAGES
);
1497 compact_result
= __compaction_suitable(zone
, order
, alloc_flags
,
1498 ac_classzone_idx(ac
), available
);
1499 if (compact_result
!= COMPACT_SKIPPED
)
1506 static enum compact_result
compact_zone(struct zone
*zone
, struct compact_control
*cc
)
1508 enum compact_result ret
;
1509 unsigned long start_pfn
= zone
->zone_start_pfn
;
1510 unsigned long end_pfn
= zone_end_pfn(zone
);
1511 const bool sync
= cc
->mode
!= MIGRATE_ASYNC
;
1514 cc
->migratetype
= gfpflags_to_migratetype(cc
->gfp_mask
);
1515 ret
= compaction_suitable(zone
, cc
->order
, cc
->alloc_flags
,
1517 /* Compaction is likely to fail */
1518 if (ret
== COMPACT_SUCCESS
|| ret
== COMPACT_SKIPPED
)
1521 /* huh, compaction_suitable is returning something unexpected */
1522 VM_BUG_ON(ret
!= COMPACT_CONTINUE
);
1525 * Clear pageblock skip if there were failures recently and compaction
1526 * is about to be retried after being deferred.
1528 if (compaction_restarting(zone
, cc
->order
))
1529 __reset_isolation_suitable(zone
);
1532 * Setup to move all movable pages to the end of the zone. Used cached
1533 * information on where the scanners should start (unless we explicitly
1534 * want to compact the whole zone), but check that it is initialised
1535 * by ensuring the values are within zone boundaries.
1537 if (cc
->whole_zone
) {
1538 cc
->migrate_pfn
= start_pfn
;
1539 cc
->free_pfn
= pageblock_start_pfn(end_pfn
- 1);
1541 cc
->migrate_pfn
= zone
->compact_cached_migrate_pfn
[sync
];
1542 cc
->free_pfn
= zone
->compact_cached_free_pfn
;
1543 if (cc
->free_pfn
< start_pfn
|| cc
->free_pfn
>= end_pfn
) {
1544 cc
->free_pfn
= pageblock_start_pfn(end_pfn
- 1);
1545 zone
->compact_cached_free_pfn
= cc
->free_pfn
;
1547 if (cc
->migrate_pfn
< start_pfn
|| cc
->migrate_pfn
>= end_pfn
) {
1548 cc
->migrate_pfn
= start_pfn
;
1549 zone
->compact_cached_migrate_pfn
[0] = cc
->migrate_pfn
;
1550 zone
->compact_cached_migrate_pfn
[1] = cc
->migrate_pfn
;
1553 if (cc
->migrate_pfn
== start_pfn
)
1554 cc
->whole_zone
= true;
1557 cc
->last_migrated_pfn
= 0;
1559 mm_event_start(&event_ts
);
1560 trace_mm_compaction_begin(start_pfn
, cc
->migrate_pfn
,
1561 cc
->free_pfn
, end_pfn
, sync
);
1563 migrate_prep_local();
1565 while ((ret
= compact_finished(zone
, cc
)) == COMPACT_CONTINUE
) {
1568 switch (isolate_migratepages(zone
, cc
)) {
1570 ret
= COMPACT_CONTENDED
;
1571 putback_movable_pages(&cc
->migratepages
);
1572 cc
->nr_migratepages
= 0;
1576 * We haven't isolated and migrated anything, but
1577 * there might still be unflushed migrations from
1578 * previous cc->order aligned block.
1581 case ISOLATE_SUCCESS
:
1585 err
= migrate_pages(&cc
->migratepages
, compaction_alloc
,
1586 compaction_free
, (unsigned long)cc
, cc
->mode
,
1589 trace_mm_compaction_migratepages(cc
->nr_migratepages
, err
,
1592 /* All pages were either migrated or will be released */
1593 cc
->nr_migratepages
= 0;
1595 putback_movable_pages(&cc
->migratepages
);
1597 * migrate_pages() may return -ENOMEM when scanners meet
1598 * and we want compact_finished() to detect it
1600 if (err
== -ENOMEM
&& !compact_scanners_met(cc
)) {
1601 ret
= COMPACT_CONTENDED
;
1605 * We failed to migrate at least one page in the current
1606 * order-aligned block, so skip the rest of it.
1608 if (cc
->direct_compaction
&&
1609 (cc
->mode
== MIGRATE_ASYNC
)) {
1610 cc
->migrate_pfn
= block_end_pfn(
1611 cc
->migrate_pfn
- 1, cc
->order
);
1612 /* Draining pcplists is useless in this case */
1613 cc
->last_migrated_pfn
= 0;
1620 * Has the migration scanner moved away from the previous
1621 * cc->order aligned block where we migrated from? If yes,
1622 * flush the pages that were freed, so that they can merge and
1623 * compact_finished() can detect immediately if allocation
1626 if (cc
->order
> 0 && cc
->last_migrated_pfn
) {
1628 unsigned long current_block_start
=
1629 block_start_pfn(cc
->migrate_pfn
, cc
->order
);
1631 if (cc
->last_migrated_pfn
< current_block_start
) {
1633 lru_add_drain_cpu(cpu
);
1634 drain_local_pages(zone
);
1636 /* No more flushing until we migrate again */
1637 cc
->last_migrated_pfn
= 0;
1644 mm_event_end(MM_COMPACTION
, event_ts
);
1646 * Release free pages and update where the free scanner should restart,
1647 * so we don't leave any returned pages behind in the next attempt.
1649 if (cc
->nr_freepages
> 0) {
1650 unsigned long free_pfn
= release_freepages(&cc
->freepages
);
1652 cc
->nr_freepages
= 0;
1653 VM_BUG_ON(free_pfn
== 0);
1654 /* The cached pfn is always the first in a pageblock */
1655 free_pfn
= pageblock_start_pfn(free_pfn
);
1657 * Only go back, not forward. The cached pfn might have been
1658 * already reset to zone end in compact_finished()
1660 if (free_pfn
> zone
->compact_cached_free_pfn
)
1661 zone
->compact_cached_free_pfn
= free_pfn
;
1664 count_compact_events(COMPACTMIGRATE_SCANNED
, cc
->total_migrate_scanned
);
1665 count_compact_events(COMPACTFREE_SCANNED
, cc
->total_free_scanned
);
1667 trace_mm_compaction_end(start_pfn
, cc
->migrate_pfn
,
1668 cc
->free_pfn
, end_pfn
, sync
, ret
);
1673 static enum compact_result
compact_zone_order(struct zone
*zone
, int order
,
1674 gfp_t gfp_mask
, enum compact_priority prio
,
1675 unsigned int alloc_flags
, int classzone_idx
)
1677 enum compact_result ret
;
1678 struct compact_control cc
= {
1680 .nr_migratepages
= 0,
1681 .total_migrate_scanned
= 0,
1682 .total_free_scanned
= 0,
1684 .gfp_mask
= gfp_mask
,
1686 .mode
= (prio
== COMPACT_PRIO_ASYNC
) ?
1687 MIGRATE_ASYNC
: MIGRATE_SYNC_LIGHT
,
1688 .alloc_flags
= alloc_flags
,
1689 .classzone_idx
= classzone_idx
,
1690 .direct_compaction
= true,
1691 .whole_zone
= (prio
== MIN_COMPACT_PRIORITY
),
1692 .ignore_skip_hint
= (prio
== MIN_COMPACT_PRIORITY
),
1693 .ignore_block_suitable
= (prio
== MIN_COMPACT_PRIORITY
)
1695 INIT_LIST_HEAD(&cc
.freepages
);
1696 INIT_LIST_HEAD(&cc
.migratepages
);
1698 ret
= compact_zone(zone
, &cc
);
1700 VM_BUG_ON(!list_empty(&cc
.freepages
));
1701 VM_BUG_ON(!list_empty(&cc
.migratepages
));
1706 int sysctl_extfrag_threshold
= 500;
1709 * try_to_compact_pages - Direct compact to satisfy a high-order allocation
1710 * @gfp_mask: The GFP mask of the current allocation
1711 * @order: The order of the current allocation
1712 * @alloc_flags: The allocation flags of the current allocation
1713 * @ac: The context of current allocation
1714 * @mode: The migration mode for async, sync light, or sync migration
1716 * This is the main entry point for direct page compaction.
1718 enum compact_result
try_to_compact_pages(gfp_t gfp_mask
, unsigned int order
,
1719 unsigned int alloc_flags
, const struct alloc_context
*ac
,
1720 enum compact_priority prio
)
1722 int may_perform_io
= gfp_mask
& __GFP_IO
;
1725 enum compact_result rc
= COMPACT_SKIPPED
;
1729 * Check if the GFP flags allow compaction - GFP_NOIO is really
1730 * tricky context because the migration might require IO
1732 if (!may_perform_io
)
1733 return COMPACT_SKIPPED
;
1735 mm_event_start(&event_ts
);
1736 trace_mm_compaction_try_to_compact_pages(order
, gfp_mask
, prio
);
1738 /* Compact each zone in the list */
1739 for_each_zone_zonelist_nodemask(zone
, z
, ac
->zonelist
, ac
->high_zoneidx
,
1741 enum compact_result status
;
1743 if (prio
> MIN_COMPACT_PRIORITY
1744 && compaction_deferred(zone
, order
)) {
1745 rc
= max_t(enum compact_result
, COMPACT_DEFERRED
, rc
);
1749 status
= compact_zone_order(zone
, order
, gfp_mask
, prio
,
1750 alloc_flags
, ac_classzone_idx(ac
));
1751 rc
= max(status
, rc
);
1753 /* The allocation should succeed, stop compacting */
1754 if (status
== COMPACT_SUCCESS
) {
1756 * We think the allocation will succeed in this zone,
1757 * but it is not certain, hence the false. The caller
1758 * will repeat this with true if allocation indeed
1759 * succeeds in this zone.
1761 compaction_defer_reset(zone
, order
, false);
1766 if (prio
!= COMPACT_PRIO_ASYNC
&& (status
== COMPACT_COMPLETE
||
1767 status
== COMPACT_PARTIAL_SKIPPED
))
1769 * We think that allocation won't succeed in this zone
1770 * so we defer compaction there. If it ends up
1771 * succeeding after all, it will be reset.
1773 defer_compaction(zone
, order
);
1776 * We might have stopped compacting due to need_resched() in
1777 * async compaction, or due to a fatal signal detected. In that
1778 * case do not try further zones
1780 if ((prio
== COMPACT_PRIO_ASYNC
&& need_resched())
1781 || fatal_signal_pending(current
))
1785 mm_event_end(MM_COMPACTION
, event_ts
);
1790 /* Compact all zones within a node */
1791 static void compact_node(int nid
)
1793 pg_data_t
*pgdat
= NODE_DATA(nid
);
1796 struct compact_control cc
= {
1798 .total_migrate_scanned
= 0,
1799 .total_free_scanned
= 0,
1800 .mode
= MIGRATE_SYNC
,
1801 .ignore_skip_hint
= true,
1803 .gfp_mask
= GFP_KERNEL
,
1807 for (zoneid
= 0; zoneid
< MAX_NR_ZONES
; zoneid
++) {
1809 zone
= &pgdat
->node_zones
[zoneid
];
1810 if (!populated_zone(zone
))
1813 cc
.nr_freepages
= 0;
1814 cc
.nr_migratepages
= 0;
1816 INIT_LIST_HEAD(&cc
.freepages
);
1817 INIT_LIST_HEAD(&cc
.migratepages
);
1819 compact_zone(zone
, &cc
);
1821 VM_BUG_ON(!list_empty(&cc
.freepages
));
1822 VM_BUG_ON(!list_empty(&cc
.migratepages
));
1826 /* Compact all nodes in the system */
1827 static void compact_nodes(void)
1831 /* Flush pending updates to the LRU lists */
1832 lru_add_drain_all();
1834 for_each_online_node(nid
)
1838 /* The written value is actually unused, all memory is compacted */
1839 int sysctl_compact_memory
;
1842 * This is the entry point for compacting all nodes via
1843 * /proc/sys/vm/compact_memory
1845 int sysctl_compaction_handler(struct ctl_table
*table
, int write
,
1846 void __user
*buffer
, size_t *length
, loff_t
*ppos
)
1854 int sysctl_extfrag_handler(struct ctl_table
*table
, int write
,
1855 void __user
*buffer
, size_t *length
, loff_t
*ppos
)
1857 proc_dointvec_minmax(table
, write
, buffer
, length
, ppos
);
1862 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
1863 static ssize_t
sysfs_compact_node(struct device
*dev
,
1864 struct device_attribute
*attr
,
1865 const char *buf
, size_t count
)
1869 if (nid
>= 0 && nid
< nr_node_ids
&& node_online(nid
)) {
1870 /* Flush pending updates to the LRU lists */
1871 lru_add_drain_all();
1878 static DEVICE_ATTR(compact
, S_IWUSR
, NULL
, sysfs_compact_node
);
1880 int compaction_register_node(struct node
*node
)
1882 return device_create_file(&node
->dev
, &dev_attr_compact
);
1885 void compaction_unregister_node(struct node
*node
)
1887 return device_remove_file(&node
->dev
, &dev_attr_compact
);
1889 #endif /* CONFIG_SYSFS && CONFIG_NUMA */
1891 static inline bool kcompactd_work_requested(pg_data_t
*pgdat
)
1893 return pgdat
->kcompactd_max_order
> 0 || kthread_should_stop();
1896 static bool kcompactd_node_suitable(pg_data_t
*pgdat
)
1900 enum zone_type classzone_idx
= pgdat
->kcompactd_classzone_idx
;
1902 for (zoneid
= 0; zoneid
<= classzone_idx
; zoneid
++) {
1903 zone
= &pgdat
->node_zones
[zoneid
];
1905 if (!populated_zone(zone
))
1908 if (compaction_suitable(zone
, pgdat
->kcompactd_max_order
, 0,
1909 classzone_idx
) == COMPACT_CONTINUE
)
1916 static void kcompactd_do_work(pg_data_t
*pgdat
)
1919 * With no special task, compact all zones so that a page of requested
1920 * order is allocatable.
1924 struct compact_control cc
= {
1925 .order
= pgdat
->kcompactd_max_order
,
1926 .total_migrate_scanned
= 0,
1927 .total_free_scanned
= 0,
1928 .classzone_idx
= pgdat
->kcompactd_classzone_idx
,
1929 .mode
= MIGRATE_SYNC_LIGHT
,
1930 .ignore_skip_hint
= true,
1931 .gfp_mask
= GFP_KERNEL
,
1934 trace_mm_compaction_kcompactd_wake(pgdat
->node_id
, cc
.order
,
1936 count_compact_event(KCOMPACTD_WAKE
);
1938 for (zoneid
= 0; zoneid
<= cc
.classzone_idx
; zoneid
++) {
1941 zone
= &pgdat
->node_zones
[zoneid
];
1942 if (!populated_zone(zone
))
1945 if (compaction_deferred(zone
, cc
.order
))
1948 if (compaction_suitable(zone
, cc
.order
, 0, zoneid
) !=
1952 cc
.nr_freepages
= 0;
1953 cc
.nr_migratepages
= 0;
1954 cc
.total_migrate_scanned
= 0;
1955 cc
.total_free_scanned
= 0;
1957 INIT_LIST_HEAD(&cc
.freepages
);
1958 INIT_LIST_HEAD(&cc
.migratepages
);
1960 if (kthread_should_stop())
1962 status
= compact_zone(zone
, &cc
);
1964 if (status
== COMPACT_SUCCESS
) {
1965 compaction_defer_reset(zone
, cc
.order
, false);
1966 } else if (status
== COMPACT_PARTIAL_SKIPPED
|| status
== COMPACT_COMPLETE
) {
1968 * We use sync migration mode here, so we defer like
1969 * sync direct compaction does.
1971 defer_compaction(zone
, cc
.order
);
1974 count_compact_events(KCOMPACTD_MIGRATE_SCANNED
,
1975 cc
.total_migrate_scanned
);
1976 count_compact_events(KCOMPACTD_FREE_SCANNED
,
1977 cc
.total_free_scanned
);
1979 VM_BUG_ON(!list_empty(&cc
.freepages
));
1980 VM_BUG_ON(!list_empty(&cc
.migratepages
));
1984 * Regardless of success, we are done until woken up next. But remember
1985 * the requested order/classzone_idx in case it was higher/tighter than
1988 if (pgdat
->kcompactd_max_order
<= cc
.order
)
1989 pgdat
->kcompactd_max_order
= 0;
1990 if (pgdat
->kcompactd_classzone_idx
>= cc
.classzone_idx
)
1991 pgdat
->kcompactd_classzone_idx
= pgdat
->nr_zones
- 1;
1994 void wakeup_kcompactd(pg_data_t
*pgdat
, int order
, int classzone_idx
)
1999 if (pgdat
->kcompactd_max_order
< order
)
2000 pgdat
->kcompactd_max_order
= order
;
2002 if (pgdat
->kcompactd_classzone_idx
> classzone_idx
)
2003 pgdat
->kcompactd_classzone_idx
= classzone_idx
;
2006 * Pairs with implicit barrier in wait_event_freezable()
2007 * such that wakeups are not missed.
2009 if (!wq_has_sleeper(&pgdat
->kcompactd_wait
))
2012 if (!kcompactd_node_suitable(pgdat
))
2015 trace_mm_compaction_wakeup_kcompactd(pgdat
->node_id
, order
,
2017 wake_up_interruptible(&pgdat
->kcompactd_wait
);
2021 * The background compaction daemon, started as a kernel thread
2022 * from the init process.
2024 static int kcompactd(void *p
)
2026 pg_data_t
*pgdat
= (pg_data_t
*)p
;
2027 struct task_struct
*tsk
= current
;
2029 const struct cpumask
*cpumask
= cpumask_of_node(pgdat
->node_id
);
2031 if (!cpumask_empty(cpumask
))
2032 set_cpus_allowed_ptr(tsk
, cpumask
);
2036 pgdat
->kcompactd_max_order
= 0;
2037 pgdat
->kcompactd_classzone_idx
= pgdat
->nr_zones
- 1;
2039 while (!kthread_should_stop()) {
2040 unsigned long pflags
;
2042 trace_mm_compaction_kcompactd_sleep(pgdat
->node_id
);
2043 wait_event_freezable(pgdat
->kcompactd_wait
,
2044 kcompactd_work_requested(pgdat
));
2046 psi_memstall_enter(&pflags
);
2047 kcompactd_do_work(pgdat
);
2048 psi_memstall_leave(&pflags
);
2055 * This kcompactd start function will be called by init and node-hot-add.
2056 * On node-hot-add, kcompactd will moved to proper cpus if cpus are hot-added.
2058 int kcompactd_run(int nid
)
2060 pg_data_t
*pgdat
= NODE_DATA(nid
);
2063 if (pgdat
->kcompactd
)
2066 pgdat
->kcompactd
= kthread_run(kcompactd
, pgdat
, "kcompactd%d", nid
);
2067 if (IS_ERR(pgdat
->kcompactd
)) {
2068 pr_err("Failed to start kcompactd on node %d\n", nid
);
2069 ret
= PTR_ERR(pgdat
->kcompactd
);
2070 pgdat
->kcompactd
= NULL
;
2076 * Called by memory hotplug when all memory in a node is offlined. Caller must
2077 * hold mem_hotplug_begin/end().
2079 void kcompactd_stop(int nid
)
2081 struct task_struct
*kcompactd
= NODE_DATA(nid
)->kcompactd
;
2084 kthread_stop(kcompactd
);
2085 NODE_DATA(nid
)->kcompactd
= NULL
;
2090 * It's optimal to keep kcompactd on the same CPUs as their memory, but
2091 * not required for correctness. So if the last cpu in a node goes
2092 * away, we get changed to run anywhere: as the first one comes back,
2093 * restore their cpu bindings.
2095 static int kcompactd_cpu_online(unsigned int cpu
)
2099 for_each_node_state(nid
, N_MEMORY
) {
2100 pg_data_t
*pgdat
= NODE_DATA(nid
);
2101 const struct cpumask
*mask
;
2103 mask
= cpumask_of_node(pgdat
->node_id
);
2105 if (cpumask_any_and(cpu_online_mask
, mask
) < nr_cpu_ids
)
2106 /* One of our CPUs online: restore mask */
2107 set_cpus_allowed_ptr(pgdat
->kcompactd
, mask
);
2112 static int __init
kcompactd_init(void)
2117 ret
= cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN
,
2118 "mm/compaction:online",
2119 kcompactd_cpu_online
, NULL
);
2121 pr_err("kcompactd: failed to register hotplug callbacks.\n");
2125 for_each_node_state(nid
, N_MEMORY
)
2129 subsys_initcall(kcompactd_init
)
2131 #endif /* CONFIG_COMPACTION */