2 * linux/mm/compaction.c
4 * Memory compaction for the reduction of external fragmentation. Note that
5 * this heavily depends upon page migration to do all the real heavy
8 * Copyright IBM Corp. 2007-2010 Mel Gorman <mel@csn.ul.ie>
10 #include <linux/cpu.h>
11 #include <linux/swap.h>
12 #include <linux/migrate.h>
13 #include <linux/compaction.h>
14 #include <linux/mm_inline.h>
15 #include <linux/backing-dev.h>
16 #include <linux/sysctl.h>
17 #include <linux/sysfs.h>
18 #include <linux/page-isolation.h>
19 #include <linux/kasan.h>
20 #include <linux/kthread.h>
21 #include <linux/freezer.h>
24 #ifdef CONFIG_COMPACTION
25 static inline void count_compact_event(enum vm_event_item item
)
30 static inline void count_compact_events(enum vm_event_item item
, long delta
)
32 count_vm_events(item
, delta
);
35 #define count_compact_event(item) do { } while (0)
36 #define count_compact_events(item, delta) do { } while (0)
39 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
41 #define CREATE_TRACE_POINTS
42 #include <trace/events/compaction.h>
44 static unsigned long release_freepages(struct list_head
*freelist
)
46 struct page
*page
, *next
;
47 unsigned long high_pfn
= 0;
49 list_for_each_entry_safe(page
, next
, freelist
, lru
) {
50 unsigned long pfn
= page_to_pfn(page
);
60 static void map_pages(struct list_head
*list
)
64 list_for_each_entry(page
, list
, lru
) {
65 arch_alloc_page(page
, 0);
66 kernel_map_pages(page
, 1, 1);
67 kasan_alloc_pages(page
, 0);
71 static inline bool migrate_async_suitable(int migratetype
)
73 return migratetype
== MIGRATE_MOVABLE
;
77 * Check that the whole (or subset of) a pageblock given by the interval of
78 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
79 * with the migration of free compaction scanner. The scanners then need to
80 * use only pfn_valid_within() check for arches that allow holes within
83 * Return struct page pointer of start_pfn, or NULL if checks were not passed.
85 * It's possible on some configurations to have a setup like node0 node1 node0
86 * i.e. it's possible that all pages within a zones range of pages do not
87 * belong to a single zone. We assume that a border between node0 and node1
88 * can occur within a single pageblock, but not a node0 node1 node0
89 * interleaving within a single pageblock. It is therefore sufficient to check
90 * the first and last page of a pageblock and avoid checking each individual
91 * page in a pageblock.
93 static struct page
*pageblock_pfn_to_page(unsigned long start_pfn
,
94 unsigned long end_pfn
, struct zone
*zone
)
96 struct page
*start_page
;
97 struct page
*end_page
;
99 /* end_pfn is one past the range we are checking */
102 if (!pfn_valid(start_pfn
) || !pfn_valid(end_pfn
))
105 start_page
= pfn_to_page(start_pfn
);
107 if (page_zone(start_page
) != zone
)
110 end_page
= pfn_to_page(end_pfn
);
112 /* This gives a shorter code than deriving page_zone(end_page) */
113 if (page_zone_id(start_page
) != page_zone_id(end_page
))
119 #ifdef CONFIG_COMPACTION
121 int PageMovable(struct page
*page
)
123 struct address_space
*mapping
;
125 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
126 if (!__PageMovable(page
))
129 mapping
= page_mapping(page
);
130 if (mapping
&& mapping
->a_ops
&& mapping
->a_ops
->isolate_page
)
135 EXPORT_SYMBOL(PageMovable
);
137 void __SetPageMovable(struct page
*page
, struct address_space
*mapping
)
139 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
140 VM_BUG_ON_PAGE((unsigned long)mapping
& PAGE_MAPPING_MOVABLE
, page
);
141 page
->mapping
= (void *)((unsigned long)mapping
| PAGE_MAPPING_MOVABLE
);
143 EXPORT_SYMBOL(__SetPageMovable
);
145 void __ClearPageMovable(struct page
*page
)
147 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
148 VM_BUG_ON_PAGE(!PageMovable(page
), page
);
150 * Clear registered address_space val with keeping PAGE_MAPPING_MOVABLE
151 * flag so that VM can catch up released page by driver after isolation.
152 * With it, VM migration doesn't try to put it back.
154 page
->mapping
= (void *)((unsigned long)page
->mapping
&
155 PAGE_MAPPING_MOVABLE
);
157 EXPORT_SYMBOL(__ClearPageMovable
);
159 /* Do not skip compaction more than 64 times */
160 #define COMPACT_MAX_DEFER_SHIFT 6
163 * Compaction is deferred when compaction fails to result in a page
164 * allocation success. 1 << compact_defer_limit compactions are skipped up
165 * to a limit of 1 << COMPACT_MAX_DEFER_SHIFT
167 void defer_compaction(struct zone
*zone
, int order
)
169 zone
->compact_considered
= 0;
170 zone
->compact_defer_shift
++;
172 if (order
< zone
->compact_order_failed
)
173 zone
->compact_order_failed
= order
;
175 if (zone
->compact_defer_shift
> COMPACT_MAX_DEFER_SHIFT
)
176 zone
->compact_defer_shift
= COMPACT_MAX_DEFER_SHIFT
;
178 trace_mm_compaction_defer_compaction(zone
, order
);
181 /* Returns true if compaction should be skipped this time */
182 bool compaction_deferred(struct zone
*zone
, int order
)
184 unsigned long defer_limit
= 1UL << zone
->compact_defer_shift
;
186 if (order
< zone
->compact_order_failed
)
189 /* Avoid possible overflow */
190 if (++zone
->compact_considered
> defer_limit
)
191 zone
->compact_considered
= defer_limit
;
193 if (zone
->compact_considered
>= defer_limit
)
196 trace_mm_compaction_deferred(zone
, order
);
202 * Update defer tracking counters after successful compaction of given order,
203 * which means an allocation either succeeded (alloc_success == true) or is
204 * expected to succeed.
206 void compaction_defer_reset(struct zone
*zone
, int order
,
210 zone
->compact_considered
= 0;
211 zone
->compact_defer_shift
= 0;
213 if (order
>= zone
->compact_order_failed
)
214 zone
->compact_order_failed
= order
+ 1;
216 trace_mm_compaction_defer_reset(zone
, order
);
219 /* Returns true if restarting compaction after many failures */
220 bool compaction_restarting(struct zone
*zone
, int order
)
222 if (order
< zone
->compact_order_failed
)
225 return zone
->compact_defer_shift
== COMPACT_MAX_DEFER_SHIFT
&&
226 zone
->compact_considered
>= 1UL << zone
->compact_defer_shift
;
229 /* Returns true if the pageblock should be scanned for pages to isolate. */
230 static inline bool isolation_suitable(struct compact_control
*cc
,
233 if (cc
->ignore_skip_hint
)
236 return !get_pageblock_skip(page
);
239 static void reset_cached_positions(struct zone
*zone
)
241 zone
->compact_cached_migrate_pfn
[0] = zone
->zone_start_pfn
;
242 zone
->compact_cached_migrate_pfn
[1] = zone
->zone_start_pfn
;
243 zone
->compact_cached_free_pfn
= zone_end_pfn(zone
);
247 * This function is called to clear all cached information on pageblocks that
248 * should be skipped for page isolation when the migrate and free page scanner
251 static void __reset_isolation_suitable(struct zone
*zone
)
253 unsigned long start_pfn
= zone
->zone_start_pfn
;
254 unsigned long end_pfn
= zone_end_pfn(zone
);
257 zone
->compact_blockskip_flush
= false;
259 /* Walk the zone and mark every pageblock as suitable for isolation */
260 for (pfn
= start_pfn
; pfn
< end_pfn
; pfn
+= pageblock_nr_pages
) {
268 page
= pfn_to_page(pfn
);
269 if (zone
!= page_zone(page
))
272 clear_pageblock_skip(page
);
275 reset_cached_positions(zone
);
278 void reset_isolation_suitable(pg_data_t
*pgdat
)
282 for (zoneid
= 0; zoneid
< MAX_NR_ZONES
; zoneid
++) {
283 struct zone
*zone
= &pgdat
->node_zones
[zoneid
];
284 if (!populated_zone(zone
))
287 /* Only flush if a full compaction finished recently */
288 if (zone
->compact_blockskip_flush
)
289 __reset_isolation_suitable(zone
);
294 * If no pages were isolated then mark this pageblock to be skipped in the
295 * future. The information is later cleared by __reset_isolation_suitable().
297 static void update_pageblock_skip(struct compact_control
*cc
,
298 struct page
*page
, unsigned long nr_isolated
,
299 bool migrate_scanner
)
301 struct zone
*zone
= cc
->zone
;
304 if (cc
->ignore_skip_hint
)
313 set_pageblock_skip(page
);
315 pfn
= page_to_pfn(page
);
317 /* Update where async and sync compaction should restart */
318 if (migrate_scanner
) {
319 if (pfn
> zone
->compact_cached_migrate_pfn
[0])
320 zone
->compact_cached_migrate_pfn
[0] = pfn
;
321 if (cc
->mode
!= MIGRATE_ASYNC
&&
322 pfn
> zone
->compact_cached_migrate_pfn
[1])
323 zone
->compact_cached_migrate_pfn
[1] = pfn
;
325 if (pfn
< zone
->compact_cached_free_pfn
)
326 zone
->compact_cached_free_pfn
= pfn
;
330 static inline bool isolation_suitable(struct compact_control
*cc
,
336 static void update_pageblock_skip(struct compact_control
*cc
,
337 struct page
*page
, unsigned long nr_isolated
,
338 bool migrate_scanner
)
341 #endif /* CONFIG_COMPACTION */
344 * Compaction requires the taking of some coarse locks that are potentially
345 * very heavily contended. For async compaction, back out if the lock cannot
346 * be taken immediately. For sync compaction, spin on the lock if needed.
348 * Returns true if the lock is held
349 * Returns false if the lock is not held and compaction should abort
351 static bool compact_trylock_irqsave(spinlock_t
*lock
, unsigned long *flags
,
352 struct compact_control
*cc
)
354 if (cc
->mode
== MIGRATE_ASYNC
) {
355 if (!spin_trylock_irqsave(lock
, *flags
)) {
356 cc
->contended
= COMPACT_CONTENDED_LOCK
;
360 spin_lock_irqsave(lock
, *flags
);
367 * Compaction requires the taking of some coarse locks that are potentially
368 * very heavily contended. The lock should be periodically unlocked to avoid
369 * having disabled IRQs for a long time, even when there is nobody waiting on
370 * the lock. It might also be that allowing the IRQs will result in
371 * need_resched() becoming true. If scheduling is needed, async compaction
372 * aborts. Sync compaction schedules.
373 * Either compaction type will also abort if a fatal signal is pending.
374 * In either case if the lock was locked, it is dropped and not regained.
376 * Returns true if compaction should abort due to fatal signal pending, or
377 * async compaction due to need_resched()
378 * Returns false when compaction can continue (sync compaction might have
381 static bool compact_unlock_should_abort(spinlock_t
*lock
,
382 unsigned long flags
, bool *locked
, struct compact_control
*cc
)
385 spin_unlock_irqrestore(lock
, flags
);
389 if (fatal_signal_pending(current
)) {
390 cc
->contended
= COMPACT_CONTENDED_SCHED
;
394 if (need_resched()) {
395 if (cc
->mode
== MIGRATE_ASYNC
) {
396 cc
->contended
= COMPACT_CONTENDED_SCHED
;
406 * Aside from avoiding lock contention, compaction also periodically checks
407 * need_resched() and either schedules in sync compaction or aborts async
408 * compaction. This is similar to what compact_unlock_should_abort() does, but
409 * is used where no lock is concerned.
411 * Returns false when no scheduling was needed, or sync compaction scheduled.
412 * Returns true when async compaction should abort.
414 static inline bool compact_should_abort(struct compact_control
*cc
)
416 /* async compaction aborts if contended */
417 if (need_resched()) {
418 if (cc
->mode
== MIGRATE_ASYNC
) {
419 cc
->contended
= COMPACT_CONTENDED_SCHED
;
430 * Isolate free pages onto a private freelist. If @strict is true, will abort
431 * returning 0 on any invalid PFNs or non-free pages inside of the pageblock
432 * (even though it may still end up isolating some pages).
434 static unsigned long isolate_freepages_block(struct compact_control
*cc
,
435 unsigned long *start_pfn
,
436 unsigned long end_pfn
,
437 struct list_head
*freelist
,
440 int nr_scanned
= 0, total_isolated
= 0;
441 struct page
*cursor
, *valid_page
= NULL
;
442 unsigned long flags
= 0;
444 unsigned long blockpfn
= *start_pfn
;
446 cursor
= pfn_to_page(blockpfn
);
448 /* Isolate free pages. */
449 for (; blockpfn
< end_pfn
; blockpfn
++, cursor
++) {
451 struct page
*page
= cursor
;
454 * Periodically drop the lock (if held) regardless of its
455 * contention, to give chance to IRQs. Abort if fatal signal
456 * pending or async compaction detects need_resched()
458 if (!(blockpfn
% SWAP_CLUSTER_MAX
)
459 && compact_unlock_should_abort(&cc
->zone
->lock
, flags
,
464 if (!pfn_valid_within(blockpfn
))
471 * For compound pages such as THP and hugetlbfs, we can save
472 * potentially a lot of iterations if we skip them at once.
473 * The check is racy, but we can consider only valid values
474 * and the only danger is skipping too much.
476 if (PageCompound(page
)) {
477 unsigned int comp_order
= compound_order(page
);
479 if (likely(comp_order
< MAX_ORDER
)) {
480 blockpfn
+= (1UL << comp_order
) - 1;
481 cursor
+= (1UL << comp_order
) - 1;
487 if (!PageBuddy(page
))
491 * If we already hold the lock, we can skip some rechecking.
492 * Note that if we hold the lock now, checked_pageblock was
493 * already set in some previous iteration (or strict is true),
494 * so it is correct to skip the suitable migration target
499 * The zone lock must be held to isolate freepages.
500 * Unfortunately this is a very coarse lock and can be
501 * heavily contended if there are parallel allocations
502 * or parallel compactions. For async compaction do not
503 * spin on the lock and we acquire the lock as late as
506 locked
= compact_trylock_irqsave(&cc
->zone
->lock
,
511 /* Recheck this is a buddy page under lock */
512 if (!PageBuddy(page
))
516 /* Found a free page, break it into order-0 pages */
517 isolated
= split_free_page(page
);
521 total_isolated
+= isolated
;
522 cc
->nr_freepages
+= isolated
;
523 for (i
= 0; i
< isolated
; i
++) {
524 list_add(&page
->lru
, freelist
);
527 if (!strict
&& cc
->nr_migratepages
<= cc
->nr_freepages
) {
528 blockpfn
+= isolated
;
531 /* Advance to the end of split page */
532 blockpfn
+= isolated
- 1;
533 cursor
+= isolated
- 1;
545 spin_unlock_irqrestore(&cc
->zone
->lock
, flags
);
548 * There is a tiny chance that we have read bogus compound_order(),
549 * so be careful to not go outside of the pageblock.
551 if (unlikely(blockpfn
> end_pfn
))
554 trace_mm_compaction_isolate_freepages(*start_pfn
, blockpfn
,
555 nr_scanned
, total_isolated
);
557 /* Record how far we have got within the block */
558 *start_pfn
= blockpfn
;
561 * If strict isolation is requested by CMA then check that all the
562 * pages requested were isolated. If there were any failures, 0 is
563 * returned and CMA will fail.
565 if (strict
&& blockpfn
< end_pfn
)
568 /* Update the pageblock-skip if the whole pageblock was scanned */
569 if (blockpfn
== end_pfn
)
570 update_pageblock_skip(cc
, valid_page
, total_isolated
, false);
572 count_compact_events(COMPACTFREE_SCANNED
, nr_scanned
);
574 count_compact_events(COMPACTISOLATED
, total_isolated
);
575 return total_isolated
;
579 * isolate_freepages_range() - isolate free pages.
580 * @start_pfn: The first PFN to start isolating.
581 * @end_pfn: The one-past-last PFN.
583 * Non-free pages, invalid PFNs, or zone boundaries within the
584 * [start_pfn, end_pfn) range are considered errors, cause function to
585 * undo its actions and return zero.
587 * Otherwise, function returns one-past-the-last PFN of isolated page
588 * (which may be greater then end_pfn if end fell in a middle of
592 isolate_freepages_range(struct compact_control
*cc
,
593 unsigned long start_pfn
, unsigned long end_pfn
)
595 unsigned long isolated
, pfn
, block_end_pfn
;
599 block_end_pfn
= ALIGN(pfn
+ 1, pageblock_nr_pages
);
601 for (; pfn
< end_pfn
; pfn
+= isolated
,
602 block_end_pfn
+= pageblock_nr_pages
) {
603 /* Protect pfn from changing by isolate_freepages_block */
604 unsigned long isolate_start_pfn
= pfn
;
606 block_end_pfn
= min(block_end_pfn
, end_pfn
);
609 * pfn could pass the block_end_pfn if isolated freepage
610 * is more than pageblock order. In this case, we adjust
611 * scanning range to right one.
613 if (pfn
>= block_end_pfn
) {
614 block_end_pfn
= ALIGN(pfn
+ 1, pageblock_nr_pages
);
615 block_end_pfn
= min(block_end_pfn
, end_pfn
);
618 if (!pageblock_pfn_to_page(pfn
, block_end_pfn
, cc
->zone
))
621 isolated
= isolate_freepages_block(cc
, &isolate_start_pfn
,
622 block_end_pfn
, &freelist
, true);
625 * In strict mode, isolate_freepages_block() returns 0 if
626 * there are any holes in the block (ie. invalid PFNs or
633 * If we managed to isolate pages, it is always (1 << n) *
634 * pageblock_nr_pages for some non-negative n. (Max order
635 * page may span two pageblocks).
639 /* split_free_page does not map the pages */
640 map_pages(&freelist
);
643 /* Loop terminated early, cleanup. */
644 release_freepages(&freelist
);
648 /* We don't use freelists for anything. */
652 /* Update the number of anon and file isolated pages in the zone */
653 static void acct_isolated(struct zone
*zone
, struct compact_control
*cc
)
656 unsigned int count
[2] = { 0, };
658 if (list_empty(&cc
->migratepages
))
661 list_for_each_entry(page
, &cc
->migratepages
, lru
)
662 count
[!!page_is_file_cache(page
)]++;
664 mod_zone_page_state(zone
, NR_ISOLATED_ANON
, count
[0]);
665 mod_zone_page_state(zone
, NR_ISOLATED_FILE
, count
[1]);
668 /* Similar to reclaim, but different enough that they don't share logic */
669 static bool too_many_isolated(struct zone
*zone
)
671 unsigned long active
, inactive
, isolated
;
673 inactive
= zone_page_state(zone
, NR_INACTIVE_FILE
) +
674 zone_page_state(zone
, NR_INACTIVE_ANON
);
675 active
= zone_page_state(zone
, NR_ACTIVE_FILE
) +
676 zone_page_state(zone
, NR_ACTIVE_ANON
);
677 isolated
= zone_page_state(zone
, NR_ISOLATED_FILE
) +
678 zone_page_state(zone
, NR_ISOLATED_ANON
);
680 return isolated
> (inactive
+ active
) / 2;
684 * isolate_migratepages_block() - isolate all migrate-able pages within
686 * @cc: Compaction control structure.
687 * @low_pfn: The first PFN to isolate
688 * @end_pfn: The one-past-the-last PFN to isolate, within same pageblock
689 * @isolate_mode: Isolation mode to be used.
691 * Isolate all pages that can be migrated from the range specified by
692 * [low_pfn, end_pfn). The range is expected to be within same pageblock.
693 * Returns zero if there is a fatal signal pending, otherwise PFN of the
694 * first page that was not scanned (which may be both less, equal to or more
697 * The pages are isolated on cc->migratepages list (not required to be empty),
698 * and cc->nr_migratepages is updated accordingly. The cc->migrate_pfn field
699 * is neither read nor updated.
702 isolate_migratepages_block(struct compact_control
*cc
, unsigned long low_pfn
,
703 unsigned long end_pfn
, isolate_mode_t isolate_mode
)
705 struct zone
*zone
= cc
->zone
;
706 unsigned long nr_scanned
= 0, nr_isolated
= 0;
707 struct list_head
*migratelist
= &cc
->migratepages
;
708 struct lruvec
*lruvec
;
709 unsigned long flags
= 0;
711 struct page
*page
= NULL
, *valid_page
= NULL
;
712 unsigned long start_pfn
= low_pfn
;
715 * Ensure that there are not too many pages isolated from the LRU
716 * list by either parallel reclaimers or compaction. If there are,
717 * delay for some time until fewer pages are isolated
719 while (unlikely(too_many_isolated(zone
))) {
720 /* async migration should just abort */
721 if (cc
->mode
== MIGRATE_ASYNC
)
724 congestion_wait(BLK_RW_ASYNC
, HZ
/10);
726 if (fatal_signal_pending(current
))
730 if (compact_should_abort(cc
))
733 /* Time to isolate some pages for migration */
734 for (; low_pfn
< end_pfn
; low_pfn
++) {
738 * Periodically drop the lock (if held) regardless of its
739 * contention, to give chance to IRQs. Abort async compaction
742 if (!(low_pfn
% SWAP_CLUSTER_MAX
)
743 && compact_unlock_should_abort(&zone
->lru_lock
, flags
,
747 if (!pfn_valid_within(low_pfn
))
751 page
= pfn_to_page(low_pfn
);
757 * Skip if free. We read page order here without zone lock
758 * which is generally unsafe, but the race window is small and
759 * the worst thing that can happen is that we skip some
760 * potential isolation targets.
762 if (PageBuddy(page
)) {
763 unsigned long freepage_order
= page_order_unsafe(page
);
766 * Without lock, we cannot be sure that what we got is
767 * a valid page order. Consider only values in the
768 * valid order range to prevent low_pfn overflow.
770 if (freepage_order
> 0 && freepage_order
< MAX_ORDER
)
771 low_pfn
+= (1UL << freepage_order
) - 1;
776 * Regardless of being on LRU, compound pages such as THP and
777 * hugetlbfs are not to be compacted. We can potentially save
778 * a lot of iterations if we skip them at once. The check is
779 * racy, but we can consider only valid values and the only
780 * danger is skipping too much.
782 if (PageCompound(page
)) {
783 unsigned int comp_order
= compound_order(page
);
785 if (likely(comp_order
< MAX_ORDER
))
786 low_pfn
+= (1UL << comp_order
) - 1;
792 * Check may be lockless but that's ok as we recheck later.
793 * It's possible to migrate LRU and non-lru movable pages.
794 * Skip any other type of page
796 is_lru
= PageLRU(page
);
798 #ifdef CONFIG_ZSWAP_MIGRATION_SUPPORT
800 * __PageMovable can return false positive so we need
801 * to verify it under page_lock.
803 if (unlikely(__PageMovable(page
)) &&
804 !PageIsolated(page
)) {
806 spin_unlock_irqrestore(&zone
->lru_lock
,
811 if (isolate_movable_page(page
, isolate_mode
))
812 goto isolate_success
;
819 * Migration will fail if an anonymous page is pinned in memory,
820 * so avoid taking lru_lock and isolating it unnecessarily in an
821 * admittedly racy check.
823 if (!page_mapping(page
) &&
824 page_count(page
) > page_mapcount(page
))
827 /* If we already hold the lock, we can skip some rechecking */
829 locked
= compact_trylock_irqsave(&zone
->lru_lock
,
834 /* Recheck PageLRU and PageCompound under lock */
839 * Page become compound since the non-locked check,
840 * and it's on LRU. It can only be a THP so the order
841 * is safe to read and it's 0 for tail pages.
843 if (unlikely(PageCompound(page
))) {
844 low_pfn
+= (1UL << compound_order(page
)) - 1;
849 lruvec
= mem_cgroup_page_lruvec(page
, zone
);
851 /* Try isolate the page */
852 if (__isolate_lru_page(page
, isolate_mode
) != 0)
855 VM_BUG_ON_PAGE(PageCompound(page
), page
);
857 /* Successfully isolated */
858 del_page_from_lru_list(page
, lruvec
, page_lru(page
));
860 #ifdef CONFIG_ZSWAP_MIGRATION_SUPPORT
863 list_add(&page
->lru
, migratelist
);
864 cc
->nr_migratepages
++;
867 /* Avoid isolating too much */
868 if (cc
->nr_migratepages
== COMPACT_CLUSTER_MAX
) {
875 * The PageBuddy() check could have potentially brought us outside
876 * the range to be scanned.
878 if (unlikely(low_pfn
> end_pfn
))
882 spin_unlock_irqrestore(&zone
->lru_lock
, flags
);
885 * Update the pageblock-skip information and cached scanner pfn,
886 * if the whole pageblock was scanned without isolating any page.
888 if (low_pfn
== end_pfn
)
889 update_pageblock_skip(cc
, valid_page
, nr_isolated
, true);
891 trace_mm_compaction_isolate_migratepages(start_pfn
, low_pfn
,
892 nr_scanned
, nr_isolated
);
894 count_compact_events(COMPACTMIGRATE_SCANNED
, nr_scanned
);
896 count_compact_events(COMPACTISOLATED
, nr_isolated
);
902 * isolate_migratepages_range() - isolate migrate-able pages in a PFN range
903 * @cc: Compaction control structure.
904 * @start_pfn: The first PFN to start isolating.
905 * @end_pfn: The one-past-last PFN.
907 * Returns zero if isolation fails fatally due to e.g. pending signal.
908 * Otherwise, function returns one-past-the-last PFN of isolated page
909 * (which may be greater than end_pfn if end fell in a middle of a THP page).
912 isolate_migratepages_range(struct compact_control
*cc
, unsigned long start_pfn
,
913 unsigned long end_pfn
)
915 unsigned long pfn
, block_end_pfn
;
917 /* Scan block by block. First and last block may be incomplete */
919 block_end_pfn
= ALIGN(pfn
+ 1, pageblock_nr_pages
);
921 for (; pfn
< end_pfn
; pfn
= block_end_pfn
,
922 block_end_pfn
+= pageblock_nr_pages
) {
924 block_end_pfn
= min(block_end_pfn
, end_pfn
);
926 if (!pageblock_pfn_to_page(pfn
, block_end_pfn
, cc
->zone
))
929 pfn
= isolate_migratepages_block(cc
, pfn
, block_end_pfn
,
930 ISOLATE_UNEVICTABLE
);
935 if (cc
->nr_migratepages
== COMPACT_CLUSTER_MAX
)
938 acct_isolated(cc
->zone
, cc
);
943 #endif /* CONFIG_COMPACTION || CONFIG_CMA */
944 #ifdef CONFIG_COMPACTION
946 /* Returns true if the page is within a block suitable for migration to */
947 static bool suitable_migration_target(struct page
*page
)
949 /* If the page is a large free page, then disallow migration */
950 if (PageBuddy(page
)) {
952 * We are checking page_order without zone->lock taken. But
953 * the only small danger is that we skip a potentially suitable
954 * pageblock, so it's not worth to check order for valid range.
956 if (page_order_unsafe(page
) >= pageblock_order
)
960 /* If the block is MIGRATE_MOVABLE, allow migration */
961 if (migrate_async_suitable(get_pageblock_migratetype(page
)))
964 /* Otherwise skip the block */
969 * Test whether the free scanner has reached the same or lower pageblock than
970 * the migration scanner, and compaction should thus terminate.
972 static inline bool compact_scanners_met(struct compact_control
*cc
)
974 return (cc
->free_pfn
>> pageblock_order
)
975 <= (cc
->migrate_pfn
>> pageblock_order
);
979 * Based on information in the current compact_control, find blocks
980 * suitable for isolating free pages from and then isolate them.
982 static void isolate_freepages(struct compact_control
*cc
)
984 struct zone
*zone
= cc
->zone
;
986 unsigned long block_start_pfn
; /* start of current pageblock */
987 unsigned long isolate_start_pfn
; /* exact pfn we start at */
988 unsigned long block_end_pfn
; /* end of current pageblock */
989 unsigned long low_pfn
; /* lowest pfn scanner is able to scan */
990 struct list_head
*freelist
= &cc
->freepages
;
993 * Initialise the free scanner. The starting point is where we last
994 * successfully isolated from, zone-cached value, or the end of the
995 * zone when isolating for the first time. For looping we also need
996 * this pfn aligned down to the pageblock boundary, because we do
997 * block_start_pfn -= pageblock_nr_pages in the for loop.
998 * For ending point, take care when isolating in last pageblock of a
999 * a zone which ends in the middle of a pageblock.
1000 * The low boundary is the end of the pageblock the migration scanner
1003 isolate_start_pfn
= cc
->free_pfn
;
1004 block_start_pfn
= cc
->free_pfn
& ~(pageblock_nr_pages
-1);
1005 block_end_pfn
= min(block_start_pfn
+ pageblock_nr_pages
,
1006 zone_end_pfn(zone
));
1007 low_pfn
= ALIGN(cc
->migrate_pfn
+ 1, pageblock_nr_pages
);
1010 * Isolate free pages until enough are available to migrate the
1011 * pages on cc->migratepages. We stop searching if the migrate
1012 * and free page scanners meet or enough free pages are isolated.
1014 for (; block_start_pfn
>= low_pfn
;
1015 block_end_pfn
= block_start_pfn
,
1016 block_start_pfn
-= pageblock_nr_pages
,
1017 isolate_start_pfn
= block_start_pfn
) {
1019 * This can iterate a massively long zone without finding any
1020 * suitable migration targets, so periodically check if we need
1021 * to schedule, or even abort async compaction.
1023 if (!(block_start_pfn
% (SWAP_CLUSTER_MAX
* pageblock_nr_pages
))
1024 && compact_should_abort(cc
))
1027 page
= pageblock_pfn_to_page(block_start_pfn
, block_end_pfn
,
1032 /* Check the block is suitable for migration */
1033 if (!suitable_migration_target(page
))
1036 /* If isolation recently failed, do not retry */
1037 if (!isolation_suitable(cc
, page
))
1040 /* Found a block suitable for isolating free pages from. */
1041 isolate_freepages_block(cc
, &isolate_start_pfn
, block_end_pfn
,
1045 * If we isolated enough freepages, or aborted due to lock
1046 * contention, terminate.
1048 if ((cc
->nr_freepages
>= cc
->nr_migratepages
)
1050 if (isolate_start_pfn
>= block_end_pfn
) {
1052 * Restart at previous pageblock if more
1053 * freepages can be isolated next time.
1056 block_start_pfn
- pageblock_nr_pages
;
1059 } else if (isolate_start_pfn
< block_end_pfn
) {
1061 * If isolation failed early, do not continue
1068 /* split_free_page does not map the pages */
1069 map_pages(freelist
);
1072 * Record where the free scanner will restart next time. Either we
1073 * broke from the loop and set isolate_start_pfn based on the last
1074 * call to isolate_freepages_block(), or we met the migration scanner
1075 * and the loop terminated due to isolate_start_pfn < low_pfn
1077 cc
->free_pfn
= isolate_start_pfn
;
1081 * This is a migrate-callback that "allocates" freepages by taking pages
1082 * from the isolated freelists in the block we are migrating to.
1084 static struct page
*compaction_alloc(struct page
*migratepage
,
1088 struct compact_control
*cc
= (struct compact_control
*)data
;
1089 struct page
*freepage
;
1092 * Isolate free pages if necessary, and if we are not aborting due to
1095 if (list_empty(&cc
->freepages
)) {
1097 isolate_freepages(cc
);
1099 if (list_empty(&cc
->freepages
))
1103 freepage
= list_entry(cc
->freepages
.next
, struct page
, lru
);
1104 list_del(&freepage
->lru
);
1111 * This is a migrate-callback that "frees" freepages back to the isolated
1112 * freelist. All pages on the freelist are from the same zone, so there is no
1113 * special handling needed for NUMA.
1115 static void compaction_free(struct page
*page
, unsigned long data
)
1117 struct compact_control
*cc
= (struct compact_control
*)data
;
1119 list_add(&page
->lru
, &cc
->freepages
);
1123 /* possible outcome of isolate_migratepages */
1125 ISOLATE_ABORT
, /* Abort compaction now */
1126 ISOLATE_NONE
, /* No pages isolated, continue scanning */
1127 ISOLATE_SUCCESS
, /* Pages isolated, migrate */
1128 } isolate_migrate_t
;
1131 * Allow userspace to control policy on scanning the unevictable LRU for
1132 * compactable pages.
1134 int sysctl_compact_unevictable_allowed __read_mostly
= 1;
1137 * Isolate all pages that can be migrated from the first suitable block,
1138 * starting at the block pointed to by the migrate scanner pfn within
1141 static isolate_migrate_t
isolate_migratepages(struct zone
*zone
,
1142 struct compact_control
*cc
)
1144 unsigned long low_pfn
, end_pfn
;
1145 unsigned long isolate_start_pfn
;
1147 const isolate_mode_t isolate_mode
=
1148 (sysctl_compact_unevictable_allowed
? ISOLATE_UNEVICTABLE
: 0) |
1149 (cc
->mode
== MIGRATE_ASYNC
? ISOLATE_ASYNC_MIGRATE
: 0);
1152 * Start at where we last stopped, or beginning of the zone as
1153 * initialized by compact_zone()
1155 low_pfn
= cc
->migrate_pfn
;
1157 /* Only scan within a pageblock boundary */
1158 end_pfn
= ALIGN(low_pfn
+ 1, pageblock_nr_pages
);
1161 * Iterate over whole pageblocks until we find the first suitable.
1162 * Do not cross the free scanner.
1164 for (; end_pfn
<= cc
->free_pfn
;
1165 low_pfn
= end_pfn
, end_pfn
+= pageblock_nr_pages
) {
1168 * This can potentially iterate a massively long zone with
1169 * many pageblocks unsuitable, so periodically check if we
1170 * need to schedule, or even abort async compaction.
1172 if (!(low_pfn
% (SWAP_CLUSTER_MAX
* pageblock_nr_pages
))
1173 && compact_should_abort(cc
))
1176 page
= pageblock_pfn_to_page(low_pfn
, end_pfn
, zone
);
1180 /* If isolation recently failed, do not retry */
1181 if (!isolation_suitable(cc
, page
))
1185 * For async compaction, also only scan in MOVABLE blocks.
1186 * Async compaction is optimistic to see if the minimum amount
1187 * of work satisfies the allocation.
1189 if (cc
->mode
== MIGRATE_ASYNC
&&
1190 !migrate_async_suitable(get_pageblock_migratetype(page
)))
1193 /* Perform the isolation */
1194 isolate_start_pfn
= low_pfn
;
1195 low_pfn
= isolate_migratepages_block(cc
, low_pfn
, end_pfn
,
1198 if (!low_pfn
|| cc
->contended
) {
1199 acct_isolated(zone
, cc
);
1200 return ISOLATE_ABORT
;
1204 * Record where we could have freed pages by migration and not
1205 * yet flushed them to buddy allocator.
1206 * - this is the lowest page that could have been isolated and
1207 * then freed by migration.
1209 if (cc
->nr_migratepages
&& !cc
->last_migrated_pfn
)
1210 cc
->last_migrated_pfn
= isolate_start_pfn
;
1213 * Either we isolated something and proceed with migration. Or
1214 * we failed and compact_zone should decide if we should
1220 acct_isolated(zone
, cc
);
1221 /* Record where migration scanner will be restarted. */
1222 cc
->migrate_pfn
= low_pfn
;
1224 return cc
->nr_migratepages
? ISOLATE_SUCCESS
: ISOLATE_NONE
;
1228 * order == -1 is expected when compacting via
1229 * /proc/sys/vm/compact_memory
1231 static inline bool is_via_compact_memory(int order
)
1236 static int __compact_finished(struct zone
*zone
, struct compact_control
*cc
,
1237 const int migratetype
)
1240 unsigned long watermark
;
1242 if (cc
->contended
|| fatal_signal_pending(current
))
1243 return COMPACT_CONTENDED
;
1245 /* Compaction run completes if the migrate and free scanner meet */
1246 if (compact_scanners_met(cc
)) {
1247 /* Let the next compaction start anew. */
1248 reset_cached_positions(zone
);
1251 * Mark that the PG_migrate_skip information should be cleared
1252 * by kswapd when it goes to sleep. kcompactd does not set the
1253 * flag itself as the decision to be clear should be directly
1254 * based on an allocation request.
1256 if (cc
->direct_compaction
)
1257 zone
->compact_blockskip_flush
= true;
1259 return COMPACT_COMPLETE
;
1262 if (is_via_compact_memory(cc
->order
))
1263 return COMPACT_CONTINUE
;
1265 /* Compaction run is not finished if the watermark is not met */
1266 watermark
= low_wmark_pages(zone
);
1268 if (!zone_watermark_ok(zone
, cc
->order
, watermark
, cc
->classzone_idx
,
1270 return COMPACT_CONTINUE
;
1272 /* Direct compactor: Is a suitable page free? */
1273 for (order
= cc
->order
; order
< MAX_ORDER
; order
++) {
1274 struct free_area
*area
= &zone
->free_area
[order
];
1277 /* Job done if page is free of the right migratetype */
1278 if (!list_empty(&area
->free_list
[migratetype
]))
1279 return COMPACT_PARTIAL
;
1282 * Job done if allocation would steal freepages from
1283 * other migratetype buddy lists.
1285 if (find_suitable_fallback(area
, order
, migratetype
,
1286 true, &can_steal
) != -1)
1287 return COMPACT_PARTIAL
;
1290 return COMPACT_NO_SUITABLE_PAGE
;
1293 static int compact_finished(struct zone
*zone
, struct compact_control
*cc
,
1294 const int migratetype
)
1298 ret
= __compact_finished(zone
, cc
, migratetype
);
1299 trace_mm_compaction_finished(zone
, cc
->order
, ret
);
1300 if (ret
== COMPACT_NO_SUITABLE_PAGE
)
1301 ret
= COMPACT_CONTINUE
;
1307 * compaction_suitable: Is this suitable to run compaction on this zone now?
1309 * COMPACT_SKIPPED - If there are too few free pages for compaction
1310 * COMPACT_PARTIAL - If the allocation would succeed without compaction
1311 * COMPACT_CONTINUE - If compaction should run now
1313 static unsigned long __compaction_suitable(struct zone
*zone
, int order
,
1314 int alloc_flags
, int classzone_idx
)
1317 unsigned long watermark
;
1319 if (is_via_compact_memory(order
))
1320 return COMPACT_CONTINUE
;
1322 watermark
= low_wmark_pages(zone
);
1324 * If watermarks for high-order allocation are already met, there
1325 * should be no need for compaction at all.
1327 if (zone_watermark_ok(zone
, order
, watermark
, classzone_idx
,
1329 return COMPACT_PARTIAL
;
1332 * Watermarks for order-0 must be met for compaction. Note the 2UL.
1333 * This is because during migration, copies of pages need to be
1334 * allocated and for a short time, the footprint is higher
1336 watermark
+= (2UL << order
);
1337 if (!zone_watermark_ok(zone
, 0, watermark
, classzone_idx
, alloc_flags
))
1338 return COMPACT_SKIPPED
;
1341 * fragmentation index determines if allocation failures are due to
1342 * low memory or external fragmentation
1344 * index of -1000 would imply allocations might succeed depending on
1345 * watermarks, but we already failed the high-order watermark check
1346 * index towards 0 implies failure is due to lack of memory
1347 * index towards 1000 implies failure is due to fragmentation
1349 * Only compact if a failure would be due to fragmentation.
1351 fragindex
= fragmentation_index(zone
, order
);
1352 if (fragindex
>= 0 && fragindex
<= sysctl_extfrag_threshold
)
1353 return COMPACT_NOT_SUITABLE_ZONE
;
1355 return COMPACT_CONTINUE
;
1358 unsigned long compaction_suitable(struct zone
*zone
, int order
,
1359 int alloc_flags
, int classzone_idx
)
1363 ret
= __compaction_suitable(zone
, order
, alloc_flags
, classzone_idx
);
1364 trace_mm_compaction_suitable(zone
, order
, ret
);
1365 if (ret
== COMPACT_NOT_SUITABLE_ZONE
)
1366 ret
= COMPACT_SKIPPED
;
1371 static int compact_zone(struct zone
*zone
, struct compact_control
*cc
)
1374 unsigned long start_pfn
= zone
->zone_start_pfn
;
1375 unsigned long end_pfn
= zone_end_pfn(zone
);
1376 const int migratetype
= gfpflags_to_migratetype(cc
->gfp_mask
);
1377 const bool sync
= cc
->mode
!= MIGRATE_ASYNC
;
1379 ret
= compaction_suitable(zone
, cc
->order
, cc
->alloc_flags
,
1382 case COMPACT_PARTIAL
:
1383 case COMPACT_SKIPPED
:
1384 /* Compaction is likely to fail */
1386 case COMPACT_CONTINUE
:
1387 /* Fall through to compaction */
1392 * Clear pageblock skip if there were failures recently and compaction
1393 * is about to be retried after being deferred.
1395 if (compaction_restarting(zone
, cc
->order
))
1396 __reset_isolation_suitable(zone
);
1399 * Setup to move all movable pages to the end of the zone. Used cached
1400 * information on where the scanners should start but check that it
1401 * is initialised by ensuring the values are within zone boundaries.
1403 cc
->migrate_pfn
= zone
->compact_cached_migrate_pfn
[sync
];
1404 cc
->free_pfn
= zone
->compact_cached_free_pfn
;
1405 if (cc
->free_pfn
< start_pfn
|| cc
->free_pfn
> end_pfn
) {
1406 cc
->free_pfn
= end_pfn
& ~(pageblock_nr_pages
-1);
1407 zone
->compact_cached_free_pfn
= cc
->free_pfn
;
1409 if (cc
->migrate_pfn
< start_pfn
|| cc
->migrate_pfn
> end_pfn
) {
1410 cc
->migrate_pfn
= start_pfn
;
1411 zone
->compact_cached_migrate_pfn
[0] = cc
->migrate_pfn
;
1412 zone
->compact_cached_migrate_pfn
[1] = cc
->migrate_pfn
;
1414 cc
->last_migrated_pfn
= 0;
1416 trace_mm_compaction_begin(start_pfn
, cc
->migrate_pfn
,
1417 cc
->free_pfn
, end_pfn
, sync
);
1419 migrate_prep_local();
1421 while ((ret
= compact_finished(zone
, cc
, migratetype
)) ==
1425 switch (isolate_migratepages(zone
, cc
)) {
1427 ret
= COMPACT_CONTENDED
;
1428 putback_movable_pages(&cc
->migratepages
);
1429 cc
->nr_migratepages
= 0;
1433 * We haven't isolated and migrated anything, but
1434 * there might still be unflushed migrations from
1435 * previous cc->order aligned block.
1438 case ISOLATE_SUCCESS
:
1442 err
= migrate_pages(&cc
->migratepages
, compaction_alloc
,
1443 compaction_free
, (unsigned long)cc
, cc
->mode
,
1446 trace_mm_compaction_migratepages(cc
->nr_migratepages
, err
,
1449 /* All pages were either migrated or will be released */
1450 cc
->nr_migratepages
= 0;
1452 putback_movable_pages(&cc
->migratepages
);
1454 * migrate_pages() may return -ENOMEM when scanners meet
1455 * and we want compact_finished() to detect it
1457 if (err
== -ENOMEM
&& !compact_scanners_met(cc
)) {
1458 ret
= COMPACT_CONTENDED
;
1465 * Has the migration scanner moved away from the previous
1466 * cc->order aligned block where we migrated from? If yes,
1467 * flush the pages that were freed, so that they can merge and
1468 * compact_finished() can detect immediately if allocation
1471 if (cc
->order
> 0 && cc
->last_migrated_pfn
) {
1473 unsigned long current_block_start
=
1474 cc
->migrate_pfn
& ~((1UL << cc
->order
) - 1);
1476 if (cc
->last_migrated_pfn
< current_block_start
) {
1478 lru_add_drain_cpu(cpu
);
1479 drain_local_pages(zone
);
1481 /* No more flushing until we migrate again */
1482 cc
->last_migrated_pfn
= 0;
1490 * Release free pages and update where the free scanner should restart,
1491 * so we don't leave any returned pages behind in the next attempt.
1493 if (cc
->nr_freepages
> 0) {
1494 unsigned long free_pfn
= release_freepages(&cc
->freepages
);
1496 cc
->nr_freepages
= 0;
1497 VM_BUG_ON(free_pfn
== 0);
1498 /* The cached pfn is always the first in a pageblock */
1499 free_pfn
&= ~(pageblock_nr_pages
-1);
1501 * Only go back, not forward. The cached pfn might have been
1502 * already reset to zone end in compact_finished()
1504 if (free_pfn
> zone
->compact_cached_free_pfn
)
1505 zone
->compact_cached_free_pfn
= free_pfn
;
1508 trace_mm_compaction_end(start_pfn
, cc
->migrate_pfn
,
1509 cc
->free_pfn
, end_pfn
, sync
, ret
);
1511 if (ret
== COMPACT_CONTENDED
)
1512 ret
= COMPACT_PARTIAL
;
1517 static unsigned long compact_zone_order(struct zone
*zone
, int order
,
1518 gfp_t gfp_mask
, enum migrate_mode mode
, int *contended
,
1519 int alloc_flags
, int classzone_idx
)
1522 struct compact_control cc
= {
1524 .nr_migratepages
= 0,
1526 .gfp_mask
= gfp_mask
,
1529 .alloc_flags
= alloc_flags
,
1530 .classzone_idx
= classzone_idx
,
1531 .direct_compaction
= true,
1533 INIT_LIST_HEAD(&cc
.freepages
);
1534 INIT_LIST_HEAD(&cc
.migratepages
);
1536 ret
= compact_zone(zone
, &cc
);
1538 VM_BUG_ON(!list_empty(&cc
.freepages
));
1539 VM_BUG_ON(!list_empty(&cc
.migratepages
));
1541 *contended
= cc
.contended
;
1545 int sysctl_extfrag_threshold
= 500;
1548 * try_to_compact_pages - Direct compact to satisfy a high-order allocation
1549 * @gfp_mask: The GFP mask of the current allocation
1550 * @order: The order of the current allocation
1551 * @alloc_flags: The allocation flags of the current allocation
1552 * @ac: The context of current allocation
1553 * @mode: The migration mode for async, sync light, or sync migration
1554 * @contended: Return value that determines if compaction was aborted due to
1555 * need_resched() or lock contention
1557 * This is the main entry point for direct page compaction.
1559 unsigned long try_to_compact_pages(gfp_t gfp_mask
, unsigned int order
,
1560 int alloc_flags
, const struct alloc_context
*ac
,
1561 enum migrate_mode mode
, int *contended
)
1563 int may_enter_fs
= gfp_mask
& __GFP_FS
;
1564 int may_perform_io
= gfp_mask
& __GFP_IO
;
1567 int rc
= COMPACT_DEFERRED
;
1568 int all_zones_contended
= COMPACT_CONTENDED_LOCK
; /* init for &= op */
1570 *contended
= COMPACT_CONTENDED_NONE
;
1572 /* Check if the GFP flags allow compaction */
1573 if (!order
|| !may_enter_fs
|| !may_perform_io
)
1574 return COMPACT_SKIPPED
;
1576 trace_mm_compaction_try_to_compact_pages(order
, gfp_mask
, mode
);
1578 /* Compact each zone in the list */
1579 for_each_zone_zonelist_nodemask(zone
, z
, ac
->zonelist
, ac
->high_zoneidx
,
1584 if (compaction_deferred(zone
, order
))
1587 status
= compact_zone_order(zone
, order
, gfp_mask
, mode
,
1588 &zone_contended
, alloc_flags
,
1590 rc
= max(status
, rc
);
1592 * It takes at least one zone that wasn't lock contended
1593 * to clear all_zones_contended.
1595 all_zones_contended
&= zone_contended
;
1597 /* If a normal allocation would succeed, stop compacting */
1598 if (zone_watermark_ok(zone
, order
, low_wmark_pages(zone
),
1599 ac
->classzone_idx
, alloc_flags
)) {
1601 * We think the allocation will succeed in this zone,
1602 * but it is not certain, hence the false. The caller
1603 * will repeat this with true if allocation indeed
1604 * succeeds in this zone.
1606 compaction_defer_reset(zone
, order
, false);
1608 * It is possible that async compaction aborted due to
1609 * need_resched() and the watermarks were ok thanks to
1610 * somebody else freeing memory. The allocation can
1611 * however still fail so we better signal the
1612 * need_resched() contention anyway (this will not
1613 * prevent the allocation attempt).
1615 if (zone_contended
== COMPACT_CONTENDED_SCHED
)
1616 *contended
= COMPACT_CONTENDED_SCHED
;
1621 if (mode
!= MIGRATE_ASYNC
&& status
== COMPACT_COMPLETE
) {
1623 * We think that allocation won't succeed in this zone
1624 * so we defer compaction there. If it ends up
1625 * succeeding after all, it will be reset.
1627 defer_compaction(zone
, order
);
1631 * We might have stopped compacting due to need_resched() in
1632 * async compaction, or due to a fatal signal detected. In that
1633 * case do not try further zones and signal need_resched()
1636 if ((zone_contended
== COMPACT_CONTENDED_SCHED
)
1637 || fatal_signal_pending(current
)) {
1638 *contended
= COMPACT_CONTENDED_SCHED
;
1645 * We might not have tried all the zones, so be conservative
1646 * and assume they are not all lock contended.
1648 all_zones_contended
= 0;
1653 * If at least one zone wasn't deferred or skipped, we report if all
1654 * zones that were tried were lock contended.
1656 if (rc
> COMPACT_SKIPPED
&& all_zones_contended
)
1657 *contended
= COMPACT_CONTENDED_LOCK
;
1663 /* Compact all zones within a node */
1664 static void __compact_pgdat(pg_data_t
*pgdat
, struct compact_control
*cc
)
1669 for (zoneid
= 0; zoneid
< MAX_NR_ZONES
; zoneid
++) {
1671 zone
= &pgdat
->node_zones
[zoneid
];
1672 if (!populated_zone(zone
))
1675 cc
->nr_freepages
= 0;
1676 cc
->nr_migratepages
= 0;
1678 INIT_LIST_HEAD(&cc
->freepages
);
1679 INIT_LIST_HEAD(&cc
->migratepages
);
1682 * When called via /proc/sys/vm/compact_memory
1683 * this makes sure we compact the whole zone regardless of
1684 * cached scanner positions.
1686 if (is_via_compact_memory(cc
->order
))
1687 __reset_isolation_suitable(zone
);
1689 if (is_via_compact_memory(cc
->order
) ||
1690 !compaction_deferred(zone
, cc
->order
))
1691 compact_zone(zone
, cc
);
1693 if (cc
->order
> 0) {
1694 if (zone_watermark_ok(zone
, cc
->order
,
1695 low_wmark_pages(zone
), 0, 0))
1696 compaction_defer_reset(zone
, cc
->order
, false);
1699 VM_BUG_ON(!list_empty(&cc
->freepages
));
1700 VM_BUG_ON(!list_empty(&cc
->migratepages
));
1704 void compact_pgdat(pg_data_t
*pgdat
, int order
)
1706 struct compact_control cc
= {
1708 .mode
= MIGRATE_ASYNC
,
1714 __compact_pgdat(pgdat
, &cc
);
1717 static void compact_node(int nid
)
1719 struct compact_control cc
= {
1721 .mode
= MIGRATE_SYNC_LIGHT
,
1722 .ignore_skip_hint
= true,
1725 __compact_pgdat(NODE_DATA(nid
), &cc
);
1728 /* Compact all nodes in the system */
1729 static void compact_nodes(void)
1733 /* Flush pending updates to the LRU lists */
1734 lru_add_drain_all();
1736 for_each_online_node(nid
)
1740 /* The written value is actually unused, all memory is compacted */
1741 int sysctl_compact_memory
;
1743 /* This is the entry point for compacting all nodes via /proc/sys/vm */
1744 int sysctl_compaction_handler(struct ctl_table
*table
, int write
,
1745 void __user
*buffer
, size_t *length
, loff_t
*ppos
)
1748 pr_info("compact_memory start.(%d times so far)\n",
1749 sysctl_compact_memory
);
1750 sysctl_compact_memory
++;
1752 pr_info("compact_memory done.(%d times so far)\n",
1753 sysctl_compact_memory
);
1756 proc_dointvec(table
, write
, buffer
, length
, ppos
);
1761 int sysctl_extfrag_handler(struct ctl_table
*table
, int write
,
1762 void __user
*buffer
, size_t *length
, loff_t
*ppos
)
1764 proc_dointvec_minmax(table
, write
, buffer
, length
, ppos
);
1769 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
1770 static ssize_t
sysfs_compact_node(struct device
*dev
,
1771 struct device_attribute
*attr
,
1772 const char *buf
, size_t count
)
1776 if (nid
>= 0 && nid
< nr_node_ids
&& node_online(nid
)) {
1777 /* Flush pending updates to the LRU lists */
1778 lru_add_drain_all();
1785 static DEVICE_ATTR(compact
, S_IWUSR
, NULL
, sysfs_compact_node
);
1787 int compaction_register_node(struct node
*node
)
1789 return device_create_file(&node
->dev
, &dev_attr_compact
);
1792 void compaction_unregister_node(struct node
*node
)
1794 return device_remove_file(&node
->dev
, &dev_attr_compact
);
1796 #endif /* CONFIG_SYSFS && CONFIG_NUMA */
1798 static inline bool kcompactd_work_requested(pg_data_t
*pgdat
)
1800 return pgdat
->kcompactd_max_order
> 0;
1803 static bool kcompactd_node_suitable(pg_data_t
*pgdat
)
1807 enum zone_type classzone_idx
= pgdat
->kcompactd_classzone_idx
;
1809 for (zoneid
= 0; zoneid
<= classzone_idx
; zoneid
++) {
1810 zone
= &pgdat
->node_zones
[zoneid
];
1812 if (!populated_zone(zone
))
1815 if (compaction_suitable(zone
, pgdat
->kcompactd_max_order
, 0,
1816 classzone_idx
) == COMPACT_CONTINUE
)
1823 static void kcompactd_do_work(pg_data_t
*pgdat
)
1826 * With no special task, compact all zones so that a page of requested
1827 * order is allocatable.
1831 struct compact_control cc
= {
1832 .order
= pgdat
->kcompactd_max_order
,
1833 .classzone_idx
= pgdat
->kcompactd_classzone_idx
,
1834 .mode
= MIGRATE_SYNC_LIGHT
,
1835 .ignore_skip_hint
= true,
1838 bool success
= false;
1840 trace_mm_compaction_kcompactd_wake(pgdat
->node_id
, cc
.order
,
1842 count_vm_event(KCOMPACTD_WAKE
);
1844 for (zoneid
= 0; zoneid
<= cc
.classzone_idx
; zoneid
++) {
1847 zone
= &pgdat
->node_zones
[zoneid
];
1848 if (!populated_zone(zone
))
1851 if (compaction_deferred(zone
, cc
.order
))
1854 if (compaction_suitable(zone
, cc
.order
, 0, zoneid
) !=
1858 cc
.nr_freepages
= 0;
1859 cc
.nr_migratepages
= 0;
1861 INIT_LIST_HEAD(&cc
.freepages
);
1862 INIT_LIST_HEAD(&cc
.migratepages
);
1864 status
= compact_zone(zone
, &cc
);
1866 if (zone_watermark_ok(zone
, cc
.order
, low_wmark_pages(zone
),
1867 cc
.classzone_idx
, 0)) {
1869 compaction_defer_reset(zone
, cc
.order
, false);
1870 } else if (status
== COMPACT_COMPLETE
) {
1872 * We use sync migration mode here, so we defer like
1873 * sync direct compaction does.
1875 defer_compaction(zone
, cc
.order
);
1878 VM_BUG_ON(!list_empty(&cc
.freepages
));
1879 VM_BUG_ON(!list_empty(&cc
.migratepages
));
1883 * Regardless of success, we are done until woken up next. But remember
1884 * the requested order/classzone_idx in case it was higher/tighter than
1887 if (pgdat
->kcompactd_max_order
<= cc
.order
)
1888 pgdat
->kcompactd_max_order
= 0;
1889 if (pgdat
->kcompactd_classzone_idx
>= cc
.classzone_idx
)
1890 pgdat
->kcompactd_classzone_idx
= pgdat
->nr_zones
- 1;
1893 void wakeup_kcompactd(pg_data_t
*pgdat
, int order
, int classzone_idx
)
1898 if (pgdat
->kcompactd_max_order
< order
)
1899 pgdat
->kcompactd_max_order
= order
;
1901 if (pgdat
->kcompactd_classzone_idx
> classzone_idx
)
1902 pgdat
->kcompactd_classzone_idx
= classzone_idx
;
1904 if (!waitqueue_active(&pgdat
->kcompactd_wait
))
1907 if (!kcompactd_node_suitable(pgdat
))
1910 trace_mm_compaction_wakeup_kcompactd(pgdat
->node_id
, order
,
1912 wake_up_interruptible(&pgdat
->kcompactd_wait
);
1916 * The background compaction daemon, started as a kernel thread
1917 * from the init process.
1919 static int kcompactd(void *p
)
1921 pg_data_t
*pgdat
= (pg_data_t
*)p
;
1922 struct task_struct
*tsk
= current
;
1924 const struct cpumask
*cpumask
= cpumask_of_node(pgdat
->node_id
);
1926 if (!cpumask_empty(cpumask
))
1927 set_cpus_allowed_ptr(tsk
, cpumask
);
1931 pgdat
->kcompactd_max_order
= 0;
1932 pgdat
->kcompactd_classzone_idx
= pgdat
->nr_zones
- 1;
1934 while (!kthread_should_stop()) {
1935 trace_mm_compaction_kcompactd_sleep(pgdat
->node_id
);
1936 wait_event_freezable(pgdat
->kcompactd_wait
,
1937 kcompactd_work_requested(pgdat
));
1939 kcompactd_do_work(pgdat
);
1946 * This kcompactd start function will be called by init and node-hot-add.
1947 * On node-hot-add, kcompactd will moved to proper cpus if cpus are hot-added.
1949 int kcompactd_run(int nid
)
1951 pg_data_t
*pgdat
= NODE_DATA(nid
);
1954 if (pgdat
->kcompactd
)
1957 pgdat
->kcompactd
= kthread_run(kcompactd
, pgdat
, "kcompactd%d", nid
);
1958 if (IS_ERR(pgdat
->kcompactd
)) {
1959 pr_err("Failed to start kcompactd on node %d\n", nid
);
1960 ret
= PTR_ERR(pgdat
->kcompactd
);
1961 pgdat
->kcompactd
= NULL
;
1967 * Called by memory hotplug when all memory in a node is offlined. Caller must
1968 * hold mem_hotplug_begin/end().
1970 void kcompactd_stop(int nid
)
1972 struct task_struct
*kcompactd
= NODE_DATA(nid
)->kcompactd
;
1975 kthread_stop(kcompactd
);
1976 NODE_DATA(nid
)->kcompactd
= NULL
;
1981 * It's optimal to keep kcompactd on the same CPUs as their memory, but
1982 * not required for correctness. So if the last cpu in a node goes
1983 * away, we get changed to run anywhere: as the first one comes back,
1984 * restore their cpu bindings.
1986 static int cpu_callback(struct notifier_block
*nfb
, unsigned long action
,
1991 if (action
== CPU_ONLINE
|| action
== CPU_ONLINE_FROZEN
) {
1992 for_each_node_state(nid
, N_MEMORY
) {
1993 pg_data_t
*pgdat
= NODE_DATA(nid
);
1994 const struct cpumask
*mask
;
1996 mask
= cpumask_of_node(pgdat
->node_id
);
1998 if (cpumask_any_and(cpu_online_mask
, mask
) < nr_cpu_ids
)
1999 /* One of our CPUs online: restore mask */
2000 set_cpus_allowed_ptr(pgdat
->kcompactd
, mask
);
2006 static int __init
kcompactd_init(void)
2010 for_each_node_state(nid
, N_MEMORY
)
2012 hotcpu_notifier(cpu_callback
, 0);
2015 subsys_initcall(kcompactd_init
)
2017 #endif /* CONFIG_COMPACTION */