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>
22 #include <linux/page_owner.h>
25 #ifdef CONFIG_COMPACTION
26 static inline void count_compact_event(enum vm_event_item item)
31 static inline void count_compact_events(enum vm_event_item item, long delta)
33 count_vm_events(item, delta);
36 #define count_compact_event(item) do { } while (0)
37 #define count_compact_events(item, delta) do { } while (0)
40 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
42 #define CREATE_TRACE_POINTS
43 #include <trace/events/compaction.h>
45 static unsigned long release_freepages(struct list_head *freelist)
47 struct page *page, *next;
48 unsigned long high_pfn = 0;
50 list_for_each_entry_safe(page, next, freelist, lru) {
51 unsigned long pfn = page_to_pfn(page);
61 static void map_pages(struct list_head *list)
63 unsigned int i, order, nr_pages;
64 struct page *page, *next;
67 list_for_each_entry_safe(page, next, list, lru) {
70 order = page_private(page);
71 nr_pages = 1 << order;
73 post_alloc_hook(page, order, __GFP_MOVABLE);
75 split_page(page, order);
77 for (i = 0; i < nr_pages; i++) {
78 list_add(&page->lru, &tmp_list);
83 list_splice(&tmp_list, list);
86 static inline bool migrate_async_suitable(int migratetype)
88 return is_migrate_cma(migratetype) || migratetype == MIGRATE_MOVABLE;
92 * Check that the whole (or subset of) a pageblock given by the interval of
93 * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
94 * with the migration of free compaction scanner. The scanners then need to
95 * use only pfn_valid_within() check for arches that allow holes within
98 * Return struct page pointer of start_pfn, or NULL if checks were not passed.
100 * It's possible on some configurations to have a setup like node0 node1 node0
101 * i.e. it's possible that all pages within a zones range of pages do not
102 * belong to a single zone. We assume that a border between node0 and node1
103 * can occur within a single pageblock, but not a node0 node1 node0
104 * interleaving within a single pageblock. It is therefore sufficient to check
105 * the first and last page of a pageblock and avoid checking each individual
106 * page in a pageblock.
108 static struct page *pageblock_pfn_to_page(unsigned long start_pfn,
109 unsigned long end_pfn, struct zone *zone)
111 struct page *start_page;
112 struct page *end_page;
114 /* end_pfn is one past the range we are checking */
117 if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
120 start_page = pfn_to_page(start_pfn);
122 if (page_zone(start_page) != zone)
125 end_page = pfn_to_page(end_pfn);
127 /* This gives a shorter code than deriving page_zone(end_page) */
128 if (page_zone_id(start_page) != page_zone_id(end_page))
134 #ifdef CONFIG_COMPACTION
136 int PageMovable(struct page *page)
138 struct address_space *mapping;
140 VM_BUG_ON_PAGE(!PageLocked(page), page);
141 if (!__PageMovable(page))
144 mapping = page_mapping(page);
145 if (mapping && mapping->a_ops && mapping->a_ops->isolate_page)
150 EXPORT_SYMBOL(PageMovable);
152 void __SetPageMovable(struct page *page, struct address_space *mapping)
154 VM_BUG_ON_PAGE(!PageLocked(page), page);
155 VM_BUG_ON_PAGE((unsigned long)mapping & PAGE_MAPPING_MOVABLE, page);
156 page->mapping = (void *)((unsigned long)mapping | PAGE_MAPPING_MOVABLE);
158 EXPORT_SYMBOL(__SetPageMovable);
160 void __ClearPageMovable(struct page *page)
162 VM_BUG_ON_PAGE(!PageLocked(page), page);
163 VM_BUG_ON_PAGE(!PageMovable(page), page);
165 * Clear registered address_space val with keeping PAGE_MAPPING_MOVABLE
166 * flag so that VM can catch up released page by driver after isolation.
167 * With it, VM migration doesn't try to put it back.
169 page->mapping = (void *)((unsigned long)page->mapping &
170 PAGE_MAPPING_MOVABLE);
172 EXPORT_SYMBOL(__ClearPageMovable);
174 /* Do not skip compaction more than 64 times */
175 #define COMPACT_MAX_DEFER_SHIFT 6
178 * Compaction is deferred when compaction fails to result in a page
179 * allocation success. 1 << compact_defer_limit compactions are skipped up
180 * to a limit of 1 << COMPACT_MAX_DEFER_SHIFT
182 void defer_compaction(struct zone *zone, int order)
184 zone->compact_considered = 0;
185 zone->compact_defer_shift++;
187 if (order < zone->compact_order_failed)
188 zone->compact_order_failed = order;
190 if (zone->compact_defer_shift > COMPACT_MAX_DEFER_SHIFT)
191 zone->compact_defer_shift = COMPACT_MAX_DEFER_SHIFT;
193 trace_mm_compaction_defer_compaction(zone, order);
196 /* Returns true if compaction should be skipped this time */
197 bool compaction_deferred(struct zone *zone, int order)
199 unsigned long defer_limit = 1UL << zone->compact_defer_shift;
201 if (order < zone->compact_order_failed)
204 /* Avoid possible overflow */
205 if (++zone->compact_considered > defer_limit)
206 zone->compact_considered = defer_limit;
208 if (zone->compact_considered >= defer_limit)
211 trace_mm_compaction_deferred(zone, order);
217 * Update defer tracking counters after successful compaction of given order,
218 * which means an allocation either succeeded (alloc_success == true) or is
219 * expected to succeed.
221 void compaction_defer_reset(struct zone *zone, int order,
225 zone->compact_considered = 0;
226 zone->compact_defer_shift = 0;
228 if (order >= zone->compact_order_failed)
229 zone->compact_order_failed = order + 1;
231 trace_mm_compaction_defer_reset(zone, order);
234 /* Returns true if restarting compaction after many failures */
235 bool compaction_restarting(struct zone *zone, int order)
237 if (order < zone->compact_order_failed)
240 return zone->compact_defer_shift == COMPACT_MAX_DEFER_SHIFT &&
241 zone->compact_considered >= 1UL << zone->compact_defer_shift;
244 /* Returns true if the pageblock should be scanned for pages to isolate. */
245 static inline bool isolation_suitable(struct compact_control *cc,
248 if (cc->ignore_skip_hint)
251 return !get_pageblock_skip(page);
254 static void reset_cached_positions(struct zone *zone)
256 zone->compact_cached_migrate_pfn[0] = zone->zone_start_pfn;
257 zone->compact_cached_migrate_pfn[1] = zone->zone_start_pfn;
258 zone->compact_cached_free_pfn = zone_end_pfn(zone);
262 * This function is called to clear all cached information on pageblocks that
263 * should be skipped for page isolation when the migrate and free page scanner
266 static void __reset_isolation_suitable(struct zone *zone)
268 unsigned long start_pfn = zone->zone_start_pfn;
269 unsigned long end_pfn = zone_end_pfn(zone);
272 zone->compact_blockskip_flush = false;
274 /* Walk the zone and mark every pageblock as suitable for isolation */
275 for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
283 page = pfn_to_page(pfn);
284 if (zone != page_zone(page))
287 clear_pageblock_skip(page);
290 reset_cached_positions(zone);
293 void reset_isolation_suitable(pg_data_t *pgdat)
297 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
298 struct zone *zone = &pgdat->node_zones[zoneid];
299 if (!populated_zone(zone))
302 /* Only flush if a full compaction finished recently */
303 if (zone->compact_blockskip_flush)
304 __reset_isolation_suitable(zone);
309 * If no pages were isolated then mark this pageblock to be skipped in the
310 * future. The information is later cleared by __reset_isolation_suitable().
312 static void update_pageblock_skip(struct compact_control *cc,
313 struct page *page, unsigned long nr_isolated,
314 bool migrate_scanner)
316 struct zone *zone = cc->zone;
319 if (cc->ignore_skip_hint)
328 set_pageblock_skip(page);
330 pfn = page_to_pfn(page);
332 /* Update where async and sync compaction should restart */
333 if (migrate_scanner) {
334 if (pfn > zone->compact_cached_migrate_pfn[0])
335 zone->compact_cached_migrate_pfn[0] = pfn;
336 if (cc->mode != MIGRATE_ASYNC &&
337 pfn > zone->compact_cached_migrate_pfn[1])
338 zone->compact_cached_migrate_pfn[1] = pfn;
340 if (pfn < zone->compact_cached_free_pfn)
341 zone->compact_cached_free_pfn = pfn;
345 static inline bool isolation_suitable(struct compact_control *cc,
351 static void update_pageblock_skip(struct compact_control *cc,
352 struct page *page, unsigned long nr_isolated,
353 bool migrate_scanner)
356 #endif /* CONFIG_COMPACTION */
359 * Compaction requires the taking of some coarse locks that are potentially
360 * very heavily contended. For async compaction, back out if the lock cannot
361 * be taken immediately. For sync compaction, spin on the lock if needed.
363 * Returns true if the lock is held
364 * Returns false if the lock is not held and compaction should abort
366 static bool compact_trylock_irqsave(spinlock_t *lock, unsigned long *flags,
367 struct compact_control *cc)
369 if (cc->mode == MIGRATE_ASYNC) {
370 if (!spin_trylock_irqsave(lock, *flags)) {
371 cc->contended = COMPACT_CONTENDED_LOCK;
375 spin_lock_irqsave(lock, *flags);
382 * Compaction requires the taking of some coarse locks that are potentially
383 * very heavily contended. The lock should be periodically unlocked to avoid
384 * having disabled IRQs for a long time, even when there is nobody waiting on
385 * the lock. It might also be that allowing the IRQs will result in
386 * need_resched() becoming true. If scheduling is needed, async compaction
387 * aborts. Sync compaction schedules.
388 * Either compaction type will also abort if a fatal signal is pending.
389 * In either case if the lock was locked, it is dropped and not regained.
391 * Returns true if compaction should abort due to fatal signal pending, or
392 * async compaction due to need_resched()
393 * Returns false when compaction can continue (sync compaction might have
396 static bool compact_unlock_should_abort(spinlock_t *lock,
397 unsigned long flags, bool *locked, struct compact_control *cc)
400 spin_unlock_irqrestore(lock, flags);
404 if (fatal_signal_pending(current)) {
405 cc->contended = COMPACT_CONTENDED_SCHED;
409 if (need_resched()) {
410 if (cc->mode == MIGRATE_ASYNC) {
411 cc->contended = COMPACT_CONTENDED_SCHED;
421 * Aside from avoiding lock contention, compaction also periodically checks
422 * need_resched() and either schedules in sync compaction or aborts async
423 * compaction. This is similar to what compact_unlock_should_abort() does, but
424 * is used where no lock is concerned.
426 * Returns false when no scheduling was needed, or sync compaction scheduled.
427 * Returns true when async compaction should abort.
429 static inline bool compact_should_abort(struct compact_control *cc)
431 /* async compaction aborts if contended */
432 if (need_resched()) {
433 if (cc->mode == MIGRATE_ASYNC) {
434 cc->contended = COMPACT_CONTENDED_SCHED;
445 * Isolate free pages onto a private freelist. If @strict is true, will abort
446 * returning 0 on any invalid PFNs or non-free pages inside of the pageblock
447 * (even though it may still end up isolating some pages).
449 static unsigned long isolate_freepages_block(struct compact_control *cc,
450 unsigned long *start_pfn,
451 unsigned long end_pfn,
452 struct list_head *freelist,
455 int nr_scanned = 0, total_isolated = 0;
456 struct page *cursor, *valid_page = NULL;
457 unsigned long flags = 0;
459 unsigned long blockpfn = *start_pfn;
462 cursor = pfn_to_page(blockpfn);
464 /* Isolate free pages. */
465 for (; blockpfn < end_pfn; blockpfn++, cursor++) {
467 struct page *page = cursor;
470 * Periodically drop the lock (if held) regardless of its
471 * contention, to give chance to IRQs. Abort if fatal signal
472 * pending or async compaction detects need_resched()
474 if (!(blockpfn % SWAP_CLUSTER_MAX)
475 && compact_unlock_should_abort(&cc->zone->lock, flags,
480 if (!pfn_valid_within(blockpfn))
487 * For compound pages such as THP and hugetlbfs, we can save
488 * potentially a lot of iterations if we skip them at once.
489 * The check is racy, but we can consider only valid values
490 * and the only danger is skipping too much.
492 if (PageCompound(page)) {
493 unsigned int comp_order = compound_order(page);
495 if (likely(comp_order < MAX_ORDER)) {
496 blockpfn += (1UL << comp_order) - 1;
497 cursor += (1UL << comp_order) - 1;
503 if (!PageBuddy(page))
507 * If we already hold the lock, we can skip some rechecking.
508 * Note that if we hold the lock now, checked_pageblock was
509 * already set in some previous iteration (or strict is true),
510 * so it is correct to skip the suitable migration target
515 * The zone lock must be held to isolate freepages.
516 * Unfortunately this is a very coarse lock and can be
517 * heavily contended if there are parallel allocations
518 * or parallel compactions. For async compaction do not
519 * spin on the lock and we acquire the lock as late as
522 locked = compact_trylock_irqsave(&cc->zone->lock,
527 /* Recheck this is a buddy page under lock */
528 if (!PageBuddy(page))
532 /* Found a free page, will break it into order-0 pages */
533 order = page_order(page);
534 isolated = __isolate_free_page(page, order);
537 set_page_private(page, order);
539 total_isolated += isolated;
540 cc->nr_freepages += isolated;
541 list_add_tail(&page->lru, freelist);
543 if (!strict && cc->nr_migratepages <= cc->nr_freepages) {
544 blockpfn += isolated;
547 /* Advance to the end of split page */
548 blockpfn += isolated - 1;
549 cursor += isolated - 1;
561 spin_unlock_irqrestore(&cc->zone->lock, flags);
564 * There is a tiny chance that we have read bogus compound_order(),
565 * so be careful to not go outside of the pageblock.
567 if (unlikely(blockpfn > end_pfn))
570 trace_mm_compaction_isolate_freepages(*start_pfn, blockpfn,
571 nr_scanned, total_isolated);
573 /* Record how far we have got within the block */
574 *start_pfn = blockpfn;
577 * If strict isolation is requested by CMA then check that all the
578 * pages requested were isolated. If there were any failures, 0 is
579 * returned and CMA will fail.
581 if (strict && blockpfn < end_pfn)
584 /* Update the pageblock-skip if the whole pageblock was scanned */
585 if (blockpfn == end_pfn)
586 update_pageblock_skip(cc, valid_page, total_isolated, false);
588 count_compact_events(COMPACTFREE_SCANNED, nr_scanned);
590 count_compact_events(COMPACTISOLATED, total_isolated);
591 return total_isolated;
595 * isolate_freepages_range() - isolate free pages.
596 * @start_pfn: The first PFN to start isolating.
597 * @end_pfn: The one-past-last PFN.
599 * Non-free pages, invalid PFNs, or zone boundaries within the
600 * [start_pfn, end_pfn) range are considered errors, cause function to
601 * undo its actions and return zero.
603 * Otherwise, function returns one-past-the-last PFN of isolated page
604 * (which may be greater then end_pfn if end fell in a middle of
608 isolate_freepages_range(struct compact_control *cc,
609 unsigned long start_pfn, unsigned long end_pfn)
611 unsigned long isolated, pfn, block_end_pfn;
615 block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
617 for (; pfn < end_pfn; pfn += isolated,
618 block_end_pfn += pageblock_nr_pages) {
619 /* Protect pfn from changing by isolate_freepages_block */
620 unsigned long isolate_start_pfn = pfn;
622 block_end_pfn = min(block_end_pfn, end_pfn);
625 * pfn could pass the block_end_pfn if isolated freepage
626 * is more than pageblock order. In this case, we adjust
627 * scanning range to right one.
629 if (pfn >= block_end_pfn) {
630 block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
631 block_end_pfn = min(block_end_pfn, end_pfn);
634 if (!pageblock_pfn_to_page(pfn, block_end_pfn, cc->zone))
637 isolated = isolate_freepages_block(cc, &isolate_start_pfn,
638 block_end_pfn, &freelist, true);
641 * In strict mode, isolate_freepages_block() returns 0 if
642 * there are any holes in the block (ie. invalid PFNs or
649 * If we managed to isolate pages, it is always (1 << n) *
650 * pageblock_nr_pages for some non-negative n. (Max order
651 * page may span two pageblocks).
655 /* __isolate_free_page() does not map the pages */
656 map_pages(&freelist);
659 /* Loop terminated early, cleanup. */
660 release_freepages(&freelist);
664 /* We don't use freelists for anything. */
668 /* Update the number of anon and file isolated pages in the zone */
669 static void acct_isolated(struct zone *zone, struct compact_control *cc)
672 unsigned int count[2] = { 0, };
674 if (list_empty(&cc->migratepages))
677 list_for_each_entry(page, &cc->migratepages, lru)
678 count[!!page_is_file_cache(page)]++;
680 mod_zone_page_state(zone, NR_ISOLATED_ANON, count[0]);
681 mod_zone_page_state(zone, NR_ISOLATED_FILE, count[1]);
684 static bool __too_many_isolated(struct zone *zone, int safe)
686 unsigned long active, inactive, isolated;
689 inactive = zone_page_state_snapshot(zone, NR_INACTIVE_FILE) +
690 zone_page_state_snapshot(zone, NR_INACTIVE_ANON);
691 active = zone_page_state_snapshot(zone, NR_ACTIVE_FILE) +
692 zone_page_state_snapshot(zone, NR_ACTIVE_ANON);
693 isolated = zone_page_state_snapshot(zone, NR_ISOLATED_FILE) +
694 zone_page_state_snapshot(zone, NR_ISOLATED_ANON);
696 inactive = zone_page_state(zone, NR_INACTIVE_FILE) +
697 zone_page_state(zone, NR_INACTIVE_ANON);
698 active = zone_page_state(zone, NR_ACTIVE_FILE) +
699 zone_page_state(zone, NR_ACTIVE_ANON);
700 isolated = zone_page_state(zone, NR_ISOLATED_FILE) +
701 zone_page_state(zone, NR_ISOLATED_ANON);
704 return isolated > (inactive + active) / 2;
707 /* Similar to reclaim, but different enough that they don't share logic */
708 static bool too_many_isolated(struct compact_control *cc)
711 * __too_many_isolated(safe=0) is fast but inaccurate, because it
712 * doesn't account for the vm_stat_diff[] counters. So if it looks
713 * like too_many_isolated() is about to return true, fall back to the
714 * slower, more accurate zone_page_state_snapshot().
716 if (unlikely(__too_many_isolated(cc->zone, 0))) {
717 if (cc->mode != MIGRATE_ASYNC)
718 return __too_many_isolated(cc->zone, 1);
725 * isolate_migratepages_block() - isolate all migrate-able pages within
727 * @cc: Compaction control structure.
728 * @low_pfn: The first PFN to isolate
729 * @end_pfn: The one-past-the-last PFN to isolate, within same pageblock
730 * @isolate_mode: Isolation mode to be used.
732 * Isolate all pages that can be migrated from the range specified by
733 * [low_pfn, end_pfn). The range is expected to be within same pageblock.
734 * Returns zero if there is a fatal signal pending, otherwise PFN of the
735 * first page that was not scanned (which may be both less, equal to or more
738 * The pages are isolated on cc->migratepages list (not required to be empty),
739 * and cc->nr_migratepages is updated accordingly. The cc->migrate_pfn field
740 * is neither read nor updated.
743 isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
744 unsigned long end_pfn, isolate_mode_t isolate_mode)
746 struct zone *zone = cc->zone;
747 unsigned long nr_scanned = 0, nr_isolated = 0;
748 struct list_head *migratelist = &cc->migratepages;
749 struct lruvec *lruvec;
750 unsigned long flags = 0;
752 struct page *page = NULL, *valid_page = NULL;
753 unsigned long start_pfn = low_pfn;
756 * Ensure that there are not too many pages isolated from the LRU
757 * list by either parallel reclaimers or compaction. If there are,
758 * delay for some time until fewer pages are isolated
760 while (unlikely(too_many_isolated(cc))) {
761 /* async migration should just abort */
762 if (cc->mode == MIGRATE_ASYNC)
765 congestion_wait(BLK_RW_ASYNC, HZ/10);
767 if (fatal_signal_pending(current))
771 if (compact_should_abort(cc))
774 /* Time to isolate some pages for migration */
775 for (; low_pfn < end_pfn; low_pfn++) {
778 * Periodically drop the lock (if held) regardless of its
779 * contention, to give chance to IRQs. Abort async compaction
782 if (!(low_pfn % SWAP_CLUSTER_MAX)
783 && compact_unlock_should_abort(&zone->lru_lock, flags,
787 if (!pfn_valid_within(low_pfn))
791 page = pfn_to_page(low_pfn);
797 * Skip if free. We read page order here without zone lock
798 * which is generally unsafe, but the race window is small and
799 * the worst thing that can happen is that we skip some
800 * potential isolation targets.
802 if (PageBuddy(page)) {
803 unsigned long freepage_order = page_order_unsafe(page);
806 * Without lock, we cannot be sure that what we got is
807 * a valid page order. Consider only values in the
808 * valid order range to prevent low_pfn overflow.
810 if (freepage_order > 0 && freepage_order < MAX_ORDER)
811 low_pfn += (1UL << freepage_order) - 1;
816 * Regardless of being on LRU, compound pages such as THP and
817 * hugetlbfs are not to be compacted. We can potentially save
818 * a lot of iterations if we skip them at once. The check is
819 * racy, but we can consider only valid values and the only
820 * danger is skipping too much.
822 if (PageCompound(page)) {
823 unsigned int comp_order = compound_order(page);
825 if (likely(comp_order < MAX_ORDER))
826 low_pfn += (1UL << comp_order) - 1;
832 * Check may be lockless but that's ok as we recheck later.
833 * It's possible to migrate LRU and non-lru movable pages.
834 * Skip any other type of page
836 if (!PageLRU(page)) {
838 * __PageMovable can return false positive so we need
839 * to verify it under page_lock.
841 if (unlikely(__PageMovable(page)) &&
842 !PageIsolated(page)) {
844 spin_unlock_irqrestore(&zone->lru_lock,
849 if (isolate_movable_page(page, isolate_mode))
850 goto isolate_success;
857 * Migration will fail if an anonymous page is pinned in memory,
858 * so avoid taking lru_lock and isolating it unnecessarily in an
859 * admittedly racy check.
861 if (!page_mapping(page) &&
862 page_count(page) > page_mapcount(page))
865 /* If we already hold the lock, we can skip some rechecking */
867 locked = compact_trylock_irqsave(&zone->lru_lock,
872 /* Recheck PageLRU and PageCompound under lock */
877 * Page become compound since the non-locked check,
878 * and it's on LRU. It can only be a THP so the order
879 * is safe to read and it's 0 for tail pages.
881 if (unlikely(PageCompound(page))) {
882 low_pfn += (1UL << compound_order(page)) - 1;
887 lruvec = mem_cgroup_page_lruvec(page, zone);
889 /* Try isolate the page */
890 if (__isolate_lru_page(page, isolate_mode) != 0)
893 VM_BUG_ON_PAGE(PageCompound(page), page);
895 /* Successfully isolated */
896 del_page_from_lru_list(page, lruvec, page_lru(page));
899 list_add(&page->lru, migratelist);
900 cc->nr_migratepages++;
903 /* Avoid isolating too much */
904 if (cc->nr_migratepages == COMPACT_CLUSTER_MAX) {
911 * The PageBuddy() check could have potentially brought us outside
912 * the range to be scanned.
914 if (unlikely(low_pfn > end_pfn))
918 spin_unlock_irqrestore(&zone->lru_lock, flags);
921 * Update the pageblock-skip information and cached scanner pfn,
922 * if the whole pageblock was scanned without isolating any page.
924 if (low_pfn == end_pfn)
925 update_pageblock_skip(cc, valid_page, nr_isolated, true);
927 trace_mm_compaction_isolate_migratepages(start_pfn, low_pfn,
928 nr_scanned, nr_isolated);
930 count_compact_events(COMPACTMIGRATE_SCANNED, nr_scanned);
932 count_compact_events(COMPACTISOLATED, nr_isolated);
938 * isolate_migratepages_range() - isolate migrate-able pages in a PFN range
939 * @cc: Compaction control structure.
940 * @start_pfn: The first PFN to start isolating.
941 * @end_pfn: The one-past-last PFN.
943 * Returns zero if isolation fails fatally due to e.g. pending signal.
944 * Otherwise, function returns one-past-the-last PFN of isolated page
945 * (which may be greater than end_pfn if end fell in a middle of a THP page).
948 isolate_migratepages_range(struct compact_control *cc, unsigned long start_pfn,
949 unsigned long end_pfn)
951 unsigned long pfn, block_end_pfn;
953 /* Scan block by block. First and last block may be incomplete */
955 block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
957 for (; pfn < end_pfn; pfn = block_end_pfn,
958 block_end_pfn += pageblock_nr_pages) {
960 block_end_pfn = min(block_end_pfn, end_pfn);
962 if (!pageblock_pfn_to_page(pfn, block_end_pfn, cc->zone))
965 pfn = isolate_migratepages_block(cc, pfn, block_end_pfn,
966 ISOLATE_UNEVICTABLE);
971 if (cc->nr_migratepages == COMPACT_CLUSTER_MAX)
974 acct_isolated(cc->zone, cc);
979 #endif /* CONFIG_COMPACTION || CONFIG_CMA */
980 #ifdef CONFIG_COMPACTION
982 /* Returns true if the page is within a block suitable for migration to */
983 static bool suitable_migration_target(struct page *page)
985 /* If the page is a large free page, then disallow migration */
986 if (PageBuddy(page)) {
988 * We are checking page_order without zone->lock taken. But
989 * the only small danger is that we skip a potentially suitable
990 * pageblock, so it's not worth to check order for valid range.
992 if (page_order_unsafe(page) >= pageblock_order)
996 /* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */
997 if (migrate_async_suitable(get_pageblock_migratetype(page)))
1000 /* Otherwise skip the block */
1005 * Test whether the free scanner has reached the same or lower pageblock than
1006 * the migration scanner, and compaction should thus terminate.
1008 static inline bool compact_scanners_met(struct compact_control *cc)
1010 return (cc->free_pfn >> pageblock_order)
1011 <= (cc->migrate_pfn >> pageblock_order);
1015 * Based on information in the current compact_control, find blocks
1016 * suitable for isolating free pages from and then isolate them.
1018 static void isolate_freepages(struct compact_control *cc)
1020 struct zone *zone = cc->zone;
1022 unsigned long block_start_pfn; /* start of current pageblock */
1023 unsigned long isolate_start_pfn; /* exact pfn we start at */
1024 unsigned long block_end_pfn; /* end of current pageblock */
1025 unsigned long low_pfn; /* lowest pfn scanner is able to scan */
1026 struct list_head *freelist = &cc->freepages;
1029 * Initialise the free scanner. The starting point is where we last
1030 * successfully isolated from, zone-cached value, or the end of the
1031 * zone when isolating for the first time. For looping we also need
1032 * this pfn aligned down to the pageblock boundary, because we do
1033 * block_start_pfn -= pageblock_nr_pages in the for loop.
1034 * For ending point, take care when isolating in last pageblock of a
1035 * a zone which ends in the middle of a pageblock.
1036 * The low boundary is the end of the pageblock the migration scanner
1039 isolate_start_pfn = cc->free_pfn;
1040 block_start_pfn = cc->free_pfn & ~(pageblock_nr_pages-1);
1041 block_end_pfn = min(block_start_pfn + pageblock_nr_pages,
1042 zone_end_pfn(zone));
1043 low_pfn = ALIGN(cc->migrate_pfn + 1, pageblock_nr_pages);
1046 * Isolate free pages until enough are available to migrate the
1047 * pages on cc->migratepages. We stop searching if the migrate
1048 * and free page scanners meet or enough free pages are isolated.
1050 for (; block_start_pfn >= low_pfn;
1051 block_end_pfn = block_start_pfn,
1052 block_start_pfn -= pageblock_nr_pages,
1053 isolate_start_pfn = block_start_pfn) {
1055 * This can iterate a massively long zone without finding any
1056 * suitable migration targets, so periodically check if we need
1057 * to schedule, or even abort async compaction.
1059 if (!(block_start_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages))
1060 && compact_should_abort(cc))
1063 page = pageblock_pfn_to_page(block_start_pfn, block_end_pfn,
1068 /* Check the block is suitable for migration */
1069 if (!suitable_migration_target(page))
1072 /* If isolation recently failed, do not retry */
1073 if (!isolation_suitable(cc, page))
1076 /* Found a block suitable for isolating free pages from. */
1077 isolate_freepages_block(cc, &isolate_start_pfn, block_end_pfn,
1081 * If we isolated enough freepages, or aborted due to lock
1082 * contention, terminate.
1084 if ((cc->nr_freepages >= cc->nr_migratepages)
1086 if (isolate_start_pfn >= block_end_pfn) {
1088 * Restart at previous pageblock if more
1089 * freepages can be isolated next time.
1092 block_start_pfn - pageblock_nr_pages;
1095 } else if (isolate_start_pfn < block_end_pfn) {
1097 * If isolation failed early, do not continue
1104 /* __isolate_free_page() does not map the pages */
1105 map_pages(freelist);
1108 * Record where the free scanner will restart next time. Either we
1109 * broke from the loop and set isolate_start_pfn based on the last
1110 * call to isolate_freepages_block(), or we met the migration scanner
1111 * and the loop terminated due to isolate_start_pfn < low_pfn
1113 cc->free_pfn = isolate_start_pfn;
1117 * This is a migrate-callback that "allocates" freepages by taking pages
1118 * from the isolated freelists in the block we are migrating to.
1120 static struct page *compaction_alloc(struct page *migratepage,
1124 struct compact_control *cc = (struct compact_control *)data;
1125 struct page *freepage;
1128 * Isolate free pages if necessary, and if we are not aborting due to
1131 if (list_empty(&cc->freepages)) {
1133 isolate_freepages(cc);
1135 if (list_empty(&cc->freepages))
1139 freepage = list_entry(cc->freepages.next, struct page, lru);
1140 list_del(&freepage->lru);
1147 * This is a migrate-callback that "frees" freepages back to the isolated
1148 * freelist. All pages on the freelist are from the same zone, so there is no
1149 * special handling needed for NUMA.
1151 static void compaction_free(struct page *page, unsigned long data)
1153 struct compact_control *cc = (struct compact_control *)data;
1155 list_add(&page->lru, &cc->freepages);
1159 /* possible outcome of isolate_migratepages */
1161 ISOLATE_ABORT, /* Abort compaction now */
1162 ISOLATE_NONE, /* No pages isolated, continue scanning */
1163 ISOLATE_SUCCESS, /* Pages isolated, migrate */
1164 } isolate_migrate_t;
1167 * Allow userspace to control policy on scanning the unevictable LRU for
1168 * compactable pages.
1170 int sysctl_compact_unevictable_allowed __read_mostly = 1;
1173 * Isolate all pages that can be migrated from the first suitable block,
1174 * starting at the block pointed to by the migrate scanner pfn within
1177 static isolate_migrate_t isolate_migratepages(struct zone *zone,
1178 struct compact_control *cc)
1180 unsigned long low_pfn, end_pfn;
1181 unsigned long isolate_start_pfn;
1183 const isolate_mode_t isolate_mode =
1184 (sysctl_compact_unevictable_allowed ? ISOLATE_UNEVICTABLE : 0) |
1185 (cc->mode == MIGRATE_ASYNC ? ISOLATE_ASYNC_MIGRATE : 0);
1188 * Start at where we last stopped, or beginning of the zone as
1189 * initialized by compact_zone()
1191 low_pfn = cc->migrate_pfn;
1193 /* Only scan within a pageblock boundary */
1194 end_pfn = ALIGN(low_pfn + 1, pageblock_nr_pages);
1197 * Iterate over whole pageblocks until we find the first suitable.
1198 * Do not cross the free scanner.
1200 for (; end_pfn <= cc->free_pfn;
1201 low_pfn = end_pfn, end_pfn += pageblock_nr_pages) {
1204 * This can potentially iterate a massively long zone with
1205 * many pageblocks unsuitable, so periodically check if we
1206 * need to schedule, or even abort async compaction.
1208 if (!(low_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages))
1209 && compact_should_abort(cc))
1212 page = pageblock_pfn_to_page(low_pfn, end_pfn, zone);
1216 /* If isolation recently failed, do not retry */
1217 if (!isolation_suitable(cc, page))
1221 * For async compaction, also only scan in MOVABLE blocks.
1222 * Async compaction is optimistic to see if the minimum amount
1223 * of work satisfies the allocation.
1225 if (cc->mode == MIGRATE_ASYNC &&
1226 !migrate_async_suitable(get_pageblock_migratetype(page)))
1229 /* Perform the isolation */
1230 isolate_start_pfn = low_pfn;
1231 low_pfn = isolate_migratepages_block(cc, low_pfn, end_pfn,
1234 if (!low_pfn || cc->contended) {
1235 acct_isolated(zone, cc);
1236 return ISOLATE_ABORT;
1240 * Record where we could have freed pages by migration and not
1241 * yet flushed them to buddy allocator.
1242 * - this is the lowest page that could have been isolated and
1243 * then freed by migration.
1245 if (cc->nr_migratepages && !cc->last_migrated_pfn)
1246 cc->last_migrated_pfn = isolate_start_pfn;
1249 * Either we isolated something and proceed with migration. Or
1250 * we failed and compact_zone should decide if we should
1256 acct_isolated(zone, cc);
1257 /* Record where migration scanner will be restarted. */
1258 cc->migrate_pfn = low_pfn;
1260 return cc->nr_migratepages ? ISOLATE_SUCCESS : ISOLATE_NONE;
1264 * order == -1 is expected when compacting via
1265 * /proc/sys/vm/compact_memory
1267 static inline bool is_via_compact_memory(int order)
1272 static int __compact_finished(struct zone *zone, struct compact_control *cc,
1273 const int migratetype)
1276 unsigned long watermark;
1278 if (cc->contended || fatal_signal_pending(current))
1279 return COMPACT_CONTENDED;
1281 /* Compaction run completes if the migrate and free scanner meet */
1282 if (compact_scanners_met(cc)) {
1283 /* Let the next compaction start anew. */
1284 reset_cached_positions(zone);
1287 * Mark that the PG_migrate_skip information should be cleared
1288 * by kswapd when it goes to sleep. kcompactd does not set the
1289 * flag itself as the decision to be clear should be directly
1290 * based on an allocation request.
1292 if (cc->direct_compaction)
1293 zone->compact_blockskip_flush = true;
1295 return COMPACT_COMPLETE;
1298 if (is_via_compact_memory(cc->order))
1299 return COMPACT_CONTINUE;
1301 /* Compaction run is not finished if the watermark is not met */
1302 watermark = low_wmark_pages(zone);
1304 if (!zone_watermark_ok(zone, cc->order, watermark, cc->classzone_idx,
1306 return COMPACT_CONTINUE;
1308 /* Direct compactor: Is a suitable page free? */
1309 for (order = cc->order; order < MAX_ORDER; order++) {
1310 struct free_area *area = &zone->free_area[order];
1313 /* Job done if page is free of the right migratetype */
1314 if (!list_empty(&area->free_list[migratetype]))
1315 return COMPACT_PARTIAL;
1318 /* MIGRATE_MOVABLE can fallback on MIGRATE_CMA */
1319 if (migratetype == MIGRATE_MOVABLE &&
1320 !list_empty(&area->free_list[MIGRATE_CMA]))
1321 return COMPACT_PARTIAL;
1324 * Job done if allocation would steal freepages from
1325 * other migratetype buddy lists.
1327 if (find_suitable_fallback(area, order, migratetype,
1328 true, &can_steal) != -1)
1329 return COMPACT_PARTIAL;
1332 return COMPACT_NO_SUITABLE_PAGE;
1335 static int compact_finished(struct zone *zone, struct compact_control *cc,
1336 const int migratetype)
1340 ret = __compact_finished(zone, cc, migratetype);
1341 trace_mm_compaction_finished(zone, cc->order, ret);
1342 if (ret == COMPACT_NO_SUITABLE_PAGE)
1343 ret = COMPACT_CONTINUE;
1349 * compaction_suitable: Is this suitable to run compaction on this zone now?
1351 * COMPACT_SKIPPED - If there are too few free pages for compaction
1352 * COMPACT_PARTIAL - If the allocation would succeed without compaction
1353 * COMPACT_CONTINUE - If compaction should run now
1355 static unsigned long __compaction_suitable(struct zone *zone, int order,
1356 int alloc_flags, int classzone_idx)
1359 unsigned long watermark;
1361 if (is_via_compact_memory(order))
1362 return COMPACT_CONTINUE;
1364 watermark = low_wmark_pages(zone);
1366 * If watermarks for high-order allocation are already met, there
1367 * should be no need for compaction at all.
1369 if (zone_watermark_ok(zone, order, watermark, classzone_idx,
1371 return COMPACT_PARTIAL;
1374 * Watermarks for order-0 must be met for compaction. Note the 2UL.
1375 * This is because during migration, copies of pages need to be
1376 * allocated and for a short time, the footprint is higher
1378 watermark += (2UL << order);
1379 if (!zone_watermark_ok(zone, 0, watermark, classzone_idx, alloc_flags))
1380 return COMPACT_SKIPPED;
1383 * fragmentation index determines if allocation failures are due to
1384 * low memory or external fragmentation
1386 * index of -1000 would imply allocations might succeed depending on
1387 * watermarks, but we already failed the high-order watermark check
1388 * index towards 0 implies failure is due to lack of memory
1389 * index towards 1000 implies failure is due to fragmentation
1391 * Only compact if a failure would be due to fragmentation.
1393 fragindex = fragmentation_index(zone, order);
1394 if (fragindex >= 0 && fragindex <= sysctl_extfrag_threshold)
1395 return COMPACT_NOT_SUITABLE_ZONE;
1397 return COMPACT_CONTINUE;
1400 unsigned long compaction_suitable(struct zone *zone, int order,
1401 int alloc_flags, int classzone_idx)
1405 ret = __compaction_suitable(zone, order, alloc_flags, classzone_idx);
1406 trace_mm_compaction_suitable(zone, order, ret);
1407 if (ret == COMPACT_NOT_SUITABLE_ZONE)
1408 ret = COMPACT_SKIPPED;
1413 static int compact_zone(struct zone *zone, struct compact_control *cc)
1416 unsigned long start_pfn = zone->zone_start_pfn;
1417 unsigned long end_pfn = zone_end_pfn(zone);
1418 const int migratetype = gfpflags_to_migratetype(cc->gfp_mask);
1419 const bool sync = cc->mode != MIGRATE_ASYNC;
1421 ret = compaction_suitable(zone, cc->order, cc->alloc_flags,
1424 case COMPACT_PARTIAL:
1425 case COMPACT_SKIPPED:
1426 /* Compaction is likely to fail */
1428 case COMPACT_CONTINUE:
1429 /* Fall through to compaction */
1434 * Clear pageblock skip if there were failures recently and compaction
1435 * is about to be retried after being deferred.
1437 if (compaction_restarting(zone, cc->order))
1438 __reset_isolation_suitable(zone);
1441 * Setup to move all movable pages to the end of the zone. Used cached
1442 * information on where the scanners should start but check that it
1443 * is initialised by ensuring the values are within zone boundaries.
1445 cc->migrate_pfn = zone->compact_cached_migrate_pfn[sync];
1446 cc->free_pfn = zone->compact_cached_free_pfn;
1447 if (cc->free_pfn < start_pfn || cc->free_pfn > end_pfn) {
1448 cc->free_pfn = end_pfn & ~(pageblock_nr_pages-1);
1449 zone->compact_cached_free_pfn = cc->free_pfn;
1451 if (cc->migrate_pfn < start_pfn || cc->migrate_pfn > end_pfn) {
1452 cc->migrate_pfn = start_pfn;
1453 zone->compact_cached_migrate_pfn[0] = cc->migrate_pfn;
1454 zone->compact_cached_migrate_pfn[1] = cc->migrate_pfn;
1456 cc->last_migrated_pfn = 0;
1458 trace_mm_compaction_begin(start_pfn, cc->migrate_pfn,
1459 cc->free_pfn, end_pfn, sync);
1461 migrate_prep_local();
1463 while ((ret = compact_finished(zone, cc, migratetype)) ==
1467 switch (isolate_migratepages(zone, cc)) {
1469 ret = COMPACT_CONTENDED;
1470 putback_movable_pages(&cc->migratepages);
1471 cc->nr_migratepages = 0;
1475 * We haven't isolated and migrated anything, but
1476 * there might still be unflushed migrations from
1477 * previous cc->order aligned block.
1480 case ISOLATE_SUCCESS:
1484 err = migrate_pages(&cc->migratepages, compaction_alloc,
1485 compaction_free, (unsigned long)cc, cc->mode,
1488 trace_mm_compaction_migratepages(cc->nr_migratepages, err,
1491 /* All pages were either migrated or will be released */
1492 cc->nr_migratepages = 0;
1494 putback_movable_pages(&cc->migratepages);
1496 * migrate_pages() may return -ENOMEM when scanners meet
1497 * and we want compact_finished() to detect it
1499 if (err == -ENOMEM && !compact_scanners_met(cc)) {
1500 ret = COMPACT_CONTENDED;
1507 * Has the migration scanner moved away from the previous
1508 * cc->order aligned block where we migrated from? If yes,
1509 * flush the pages that were freed, so that they can merge and
1510 * compact_finished() can detect immediately if allocation
1513 if (cc->order > 0 && cc->last_migrated_pfn) {
1515 unsigned long current_block_start =
1516 cc->migrate_pfn & ~((1UL << cc->order) - 1);
1518 if (cc->last_migrated_pfn < current_block_start) {
1520 lru_add_drain_cpu(cpu);
1521 drain_local_pages(zone);
1523 /* No more flushing until we migrate again */
1524 cc->last_migrated_pfn = 0;
1532 * Release free pages and update where the free scanner should restart,
1533 * so we don't leave any returned pages behind in the next attempt.
1535 if (cc->nr_freepages > 0) {
1536 unsigned long free_pfn = release_freepages(&cc->freepages);
1538 cc->nr_freepages = 0;
1539 VM_BUG_ON(free_pfn == 0);
1540 /* The cached pfn is always the first in a pageblock */
1541 free_pfn &= ~(pageblock_nr_pages-1);
1543 * Only go back, not forward. The cached pfn might have been
1544 * already reset to zone end in compact_finished()
1546 if (free_pfn > zone->compact_cached_free_pfn)
1547 zone->compact_cached_free_pfn = free_pfn;
1550 trace_mm_compaction_end(start_pfn, cc->migrate_pfn,
1551 cc->free_pfn, end_pfn, sync, ret);
1553 if (ret == COMPACT_CONTENDED)
1554 ret = COMPACT_PARTIAL;
1559 static unsigned long compact_zone_order(struct zone *zone, int order,
1560 gfp_t gfp_mask, enum migrate_mode mode, int *contended,
1561 int alloc_flags, int classzone_idx)
1564 struct compact_control cc = {
1566 .nr_migratepages = 0,
1568 .gfp_mask = gfp_mask,
1571 .alloc_flags = alloc_flags,
1572 .classzone_idx = classzone_idx,
1573 .direct_compaction = true,
1575 INIT_LIST_HEAD(&cc.freepages);
1576 INIT_LIST_HEAD(&cc.migratepages);
1578 ret = compact_zone(zone, &cc);
1580 VM_BUG_ON(!list_empty(&cc.freepages));
1581 VM_BUG_ON(!list_empty(&cc.migratepages));
1583 *contended = cc.contended;
1587 int sysctl_extfrag_threshold = 500;
1590 * try_to_compact_pages - Direct compact to satisfy a high-order allocation
1591 * @gfp_mask: The GFP mask of the current allocation
1592 * @order: The order of the current allocation
1593 * @alloc_flags: The allocation flags of the current allocation
1594 * @ac: The context of current allocation
1595 * @mode: The migration mode for async, sync light, or sync migration
1596 * @contended: Return value that determines if compaction was aborted due to
1597 * need_resched() or lock contention
1599 * This is the main entry point for direct page compaction.
1601 unsigned long try_to_compact_pages(gfp_t gfp_mask, unsigned int order,
1602 int alloc_flags, const struct alloc_context *ac,
1603 enum migrate_mode mode, int *contended)
1605 int may_enter_fs = gfp_mask & __GFP_FS;
1606 int may_perform_io = gfp_mask & __GFP_IO;
1609 int rc = COMPACT_DEFERRED;
1610 int all_zones_contended = COMPACT_CONTENDED_LOCK; /* init for &= op */
1612 *contended = COMPACT_CONTENDED_NONE;
1614 /* Check if the GFP flags allow compaction */
1615 if (!order || !may_enter_fs || !may_perform_io)
1616 return COMPACT_SKIPPED;
1618 trace_mm_compaction_try_to_compact_pages(order, gfp_mask, mode);
1620 /* Compact each zone in the list */
1621 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
1626 if (compaction_deferred(zone, order))
1629 status = compact_zone_order(zone, order, gfp_mask, mode,
1630 &zone_contended, alloc_flags,
1632 rc = max(status, rc);
1634 * It takes at least one zone that wasn't lock contended
1635 * to clear all_zones_contended.
1637 all_zones_contended &= zone_contended;
1639 /* If a normal allocation would succeed, stop compacting */
1640 if (zone_watermark_ok(zone, order, low_wmark_pages(zone),
1641 ac->classzone_idx, alloc_flags)) {
1643 * We think the allocation will succeed in this zone,
1644 * but it is not certain, hence the false. The caller
1645 * will repeat this with true if allocation indeed
1646 * succeeds in this zone.
1648 compaction_defer_reset(zone, order, false);
1650 * It is possible that async compaction aborted due to
1651 * need_resched() and the watermarks were ok thanks to
1652 * somebody else freeing memory. The allocation can
1653 * however still fail so we better signal the
1654 * need_resched() contention anyway (this will not
1655 * prevent the allocation attempt).
1657 if (zone_contended == COMPACT_CONTENDED_SCHED)
1658 *contended = COMPACT_CONTENDED_SCHED;
1663 if (mode != MIGRATE_ASYNC && status == COMPACT_COMPLETE) {
1665 * We think that allocation won't succeed in this zone
1666 * so we defer compaction there. If it ends up
1667 * succeeding after all, it will be reset.
1669 defer_compaction(zone, order);
1673 * We might have stopped compacting due to need_resched() in
1674 * async compaction, or due to a fatal signal detected. In that
1675 * case do not try further zones and signal need_resched()
1678 if ((zone_contended == COMPACT_CONTENDED_SCHED)
1679 || fatal_signal_pending(current)) {
1680 *contended = COMPACT_CONTENDED_SCHED;
1687 * We might not have tried all the zones, so be conservative
1688 * and assume they are not all lock contended.
1690 all_zones_contended = 0;
1695 * If at least one zone wasn't deferred or skipped, we report if all
1696 * zones that were tried were lock contended.
1698 if (rc > COMPACT_SKIPPED && all_zones_contended)
1699 *contended = COMPACT_CONTENDED_LOCK;
1705 /* Compact all zones within a node */
1706 static void __compact_pgdat(pg_data_t *pgdat, struct compact_control *cc)
1711 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
1713 zone = &pgdat->node_zones[zoneid];
1714 if (!populated_zone(zone))
1717 cc->nr_freepages = 0;
1718 cc->nr_migratepages = 0;
1720 INIT_LIST_HEAD(&cc->freepages);
1721 INIT_LIST_HEAD(&cc->migratepages);
1724 * When called via /proc/sys/vm/compact_memory
1725 * this makes sure we compact the whole zone regardless of
1726 * cached scanner positions.
1728 if (is_via_compact_memory(cc->order))
1729 __reset_isolation_suitable(zone);
1731 if (is_via_compact_memory(cc->order) ||
1732 !compaction_deferred(zone, cc->order))
1733 compact_zone(zone, cc);
1735 if (cc->order > 0) {
1736 if (zone_watermark_ok(zone, cc->order,
1737 low_wmark_pages(zone), 0, 0))
1738 compaction_defer_reset(zone, cc->order, false);
1741 VM_BUG_ON(!list_empty(&cc->freepages));
1742 VM_BUG_ON(!list_empty(&cc->migratepages));
1746 void compact_pgdat(pg_data_t *pgdat, int order)
1748 struct compact_control cc = {
1750 .mode = MIGRATE_ASYNC,
1756 __compact_pgdat(pgdat, &cc);
1759 static void compact_node(int nid)
1761 struct compact_control cc = {
1763 .mode = MIGRATE_SYNC,
1764 .ignore_skip_hint = true,
1767 __compact_pgdat(NODE_DATA(nid), &cc);
1770 /* Compact all nodes in the system */
1771 static void compact_nodes(void)
1775 /* Flush pending updates to the LRU lists */
1776 lru_add_drain_all();
1778 for_each_online_node(nid)
1782 /* The written value is actually unused, all memory is compacted */
1783 int sysctl_compact_memory;
1785 /* This is the entry point for compacting all nodes via /proc/sys/vm */
1786 int sysctl_compaction_handler(struct ctl_table *table, int write,
1787 void __user *buffer, size_t *length, loff_t *ppos)
1795 int sysctl_extfrag_handler(struct ctl_table *table, int write,
1796 void __user *buffer, size_t *length, loff_t *ppos)
1798 proc_dointvec_minmax(table, write, buffer, length, ppos);
1803 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
1804 static ssize_t sysfs_compact_node(struct device *dev,
1805 struct device_attribute *attr,
1806 const char *buf, size_t count)
1810 if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
1811 /* Flush pending updates to the LRU lists */
1812 lru_add_drain_all();
1819 static DEVICE_ATTR(compact, S_IWUSR, NULL, sysfs_compact_node);
1821 int compaction_register_node(struct node *node)
1823 return device_create_file(&node->dev, &dev_attr_compact);
1826 void compaction_unregister_node(struct node *node)
1828 return device_remove_file(&node->dev, &dev_attr_compact);
1830 #endif /* CONFIG_SYSFS && CONFIG_NUMA */
1832 static inline bool kcompactd_work_requested(pg_data_t *pgdat)
1834 return pgdat->kcompactd_max_order > 0 || kthread_should_stop();
1837 static bool kcompactd_node_suitable(pg_data_t *pgdat)
1841 enum zone_type classzone_idx = pgdat->kcompactd_classzone_idx;
1843 for (zoneid = 0; zoneid <= classzone_idx; zoneid++) {
1844 zone = &pgdat->node_zones[zoneid];
1846 if (!populated_zone(zone))
1849 if (compaction_suitable(zone, pgdat->kcompactd_max_order, 0,
1850 classzone_idx) == COMPACT_CONTINUE)
1857 static void kcompactd_do_work(pg_data_t *pgdat)
1860 * With no special task, compact all zones so that a page of requested
1861 * order is allocatable.
1865 struct compact_control cc = {
1866 .order = pgdat->kcompactd_max_order,
1867 .classzone_idx = pgdat->kcompactd_classzone_idx,
1868 .mode = MIGRATE_SYNC_LIGHT,
1869 .ignore_skip_hint = true,
1872 bool success = false;
1874 trace_mm_compaction_kcompactd_wake(pgdat->node_id, cc.order,
1876 count_vm_event(KCOMPACTD_WAKE);
1878 for (zoneid = 0; zoneid <= cc.classzone_idx; zoneid++) {
1881 zone = &pgdat->node_zones[zoneid];
1882 if (!populated_zone(zone))
1885 if (compaction_deferred(zone, cc.order))
1888 if (compaction_suitable(zone, cc.order, 0, zoneid) !=
1892 cc.nr_freepages = 0;
1893 cc.nr_migratepages = 0;
1895 INIT_LIST_HEAD(&cc.freepages);
1896 INIT_LIST_HEAD(&cc.migratepages);
1898 if (kthread_should_stop())
1900 status = compact_zone(zone, &cc);
1902 if (zone_watermark_ok(zone, cc.order, low_wmark_pages(zone),
1903 cc.classzone_idx, 0)) {
1905 compaction_defer_reset(zone, cc.order, false);
1906 } else if (status == COMPACT_COMPLETE) {
1908 * We use sync migration mode here, so we defer like
1909 * sync direct compaction does.
1911 defer_compaction(zone, cc.order);
1914 VM_BUG_ON(!list_empty(&cc.freepages));
1915 VM_BUG_ON(!list_empty(&cc.migratepages));
1919 * Regardless of success, we are done until woken up next. But remember
1920 * the requested order/classzone_idx in case it was higher/tighter than
1923 if (pgdat->kcompactd_max_order <= cc.order)
1924 pgdat->kcompactd_max_order = 0;
1925 if (pgdat->kcompactd_classzone_idx >= cc.classzone_idx)
1926 pgdat->kcompactd_classzone_idx = pgdat->nr_zones - 1;
1929 void wakeup_kcompactd(pg_data_t *pgdat, int order, int classzone_idx)
1934 if (pgdat->kcompactd_max_order < order)
1935 pgdat->kcompactd_max_order = order;
1937 if (pgdat->kcompactd_classzone_idx > classzone_idx)
1938 pgdat->kcompactd_classzone_idx = classzone_idx;
1940 if (!waitqueue_active(&pgdat->kcompactd_wait))
1943 if (!kcompactd_node_suitable(pgdat))
1946 trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, order,
1948 wake_up_interruptible(&pgdat->kcompactd_wait);
1952 * The background compaction daemon, started as a kernel thread
1953 * from the init process.
1955 static int kcompactd(void *p)
1957 pg_data_t *pgdat = (pg_data_t*)p;
1958 struct task_struct *tsk = current;
1960 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1962 if (!cpumask_empty(cpumask))
1963 set_cpus_allowed_ptr(tsk, cpumask);
1967 pgdat->kcompactd_max_order = 0;
1968 pgdat->kcompactd_classzone_idx = pgdat->nr_zones - 1;
1970 while (!kthread_should_stop()) {
1971 trace_mm_compaction_kcompactd_sleep(pgdat->node_id);
1972 wait_event_freezable(pgdat->kcompactd_wait,
1973 kcompactd_work_requested(pgdat));
1975 kcompactd_do_work(pgdat);
1982 * This kcompactd start function will be called by init and node-hot-add.
1983 * On node-hot-add, kcompactd will moved to proper cpus if cpus are hot-added.
1985 int kcompactd_run(int nid)
1987 pg_data_t *pgdat = NODE_DATA(nid);
1990 if (pgdat->kcompactd)
1993 pgdat->kcompactd = kthread_run(kcompactd, pgdat, "kcompactd%d", nid);
1994 if (IS_ERR(pgdat->kcompactd)) {
1995 pr_err("Failed to start kcompactd on node %d\n", nid);
1996 ret = PTR_ERR(pgdat->kcompactd);
1997 pgdat->kcompactd = NULL;
2003 * Called by memory hotplug when all memory in a node is offlined. Caller must
2004 * hold mem_hotplug_begin/end().
2006 void kcompactd_stop(int nid)
2008 struct task_struct *kcompactd = NODE_DATA(nid)->kcompactd;
2011 kthread_stop(kcompactd);
2012 NODE_DATA(nid)->kcompactd = NULL;
2017 * It's optimal to keep kcompactd on the same CPUs as their memory, but
2018 * not required for correctness. So if the last cpu in a node goes
2019 * away, we get changed to run anywhere: as the first one comes back,
2020 * restore their cpu bindings.
2022 static int cpu_callback(struct notifier_block *nfb, unsigned long action,
2027 if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
2028 for_each_node_state(nid, N_MEMORY) {
2029 pg_data_t *pgdat = NODE_DATA(nid);
2030 const struct cpumask *mask;
2032 mask = cpumask_of_node(pgdat->node_id);
2034 if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
2035 /* One of our CPUs online: restore mask */
2036 set_cpus_allowed_ptr(pgdat->kcompactd, mask);
2042 static int __init kcompactd_init(void)
2046 for_each_node_state(nid, N_MEMORY)
2048 hotcpu_notifier(cpu_callback, 0);
2051 subsys_initcall(kcompactd_init)
2053 #endif /* CONFIG_COMPACTION */