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 #define block_start_pfn(pfn, order) round_down(pfn, 1UL << (order))
46 #define block_end_pfn(pfn, order) ALIGN((pfn) + 1, 1UL << (order))
47 #define pageblock_start_pfn(pfn) block_start_pfn(pfn, pageblock_order)
48 #define pageblock_end_pfn(pfn) block_end_pfn(pfn, pageblock_order)
50 static unsigned long release_freepages(struct list_head *freelist)
52 struct page *page, *next;
53 unsigned long high_pfn = 0;
55 list_for_each_entry_safe(page, next, freelist, lru) {
56 unsigned long pfn = page_to_pfn(page);
66 static void map_pages(struct list_head *list)
68 unsigned int i, order, nr_pages;
69 struct page *page, *next;
72 list_for_each_entry_safe(page, next, list, lru) {
75 order = page_private(page);
76 nr_pages = 1 << order;
77 set_page_private(page, 0);
78 set_page_refcounted(page);
80 arch_alloc_page(page, order);
81 kernel_map_pages(page, nr_pages, 1);
82 kasan_alloc_pages(page, order);
84 set_page_owner(page, order, __GFP_MOVABLE);
86 split_page(page, order);
88 for (i = 0; i < nr_pages; i++) {
89 list_add(&page->lru, &tmp_list);
94 list_splice(&tmp_list, list);
97 static inline bool migrate_async_suitable(int migratetype)
99 return is_migrate_cma(migratetype) || migratetype == MIGRATE_MOVABLE;
102 #ifdef CONFIG_COMPACTION
104 int PageMovable(struct page *page)
106 struct address_space *mapping;
108 VM_BUG_ON_PAGE(!PageLocked(page), page);
109 if (!__PageMovable(page))
112 mapping = page_mapping(page);
113 if (mapping && mapping->a_ops && mapping->a_ops->isolate_page)
118 EXPORT_SYMBOL(PageMovable);
120 void __SetPageMovable(struct page *page, struct address_space *mapping)
122 VM_BUG_ON_PAGE(!PageLocked(page), page);
123 VM_BUG_ON_PAGE((unsigned long)mapping & PAGE_MAPPING_MOVABLE, page);
124 page->mapping = (void *)((unsigned long)mapping | PAGE_MAPPING_MOVABLE);
126 EXPORT_SYMBOL(__SetPageMovable);
128 void __ClearPageMovable(struct page *page)
130 VM_BUG_ON_PAGE(!PageLocked(page), page);
131 VM_BUG_ON_PAGE(!PageMovable(page), page);
133 * Clear registered address_space val with keeping PAGE_MAPPING_MOVABLE
134 * flag so that VM can catch up released page by driver after isolation.
135 * With it, VM migration doesn't try to put it back.
137 page->mapping = (void *)((unsigned long)page->mapping &
138 PAGE_MAPPING_MOVABLE);
140 EXPORT_SYMBOL(__ClearPageMovable);
142 /* Do not skip compaction more than 64 times */
143 #define COMPACT_MAX_DEFER_SHIFT 6
146 * Compaction is deferred when compaction fails to result in a page
147 * allocation success. 1 << compact_defer_limit compactions are skipped up
148 * to a limit of 1 << COMPACT_MAX_DEFER_SHIFT
150 void defer_compaction(struct zone *zone, int order)
152 zone->compact_considered = 0;
153 zone->compact_defer_shift++;
155 if (order < zone->compact_order_failed)
156 zone->compact_order_failed = order;
158 if (zone->compact_defer_shift > COMPACT_MAX_DEFER_SHIFT)
159 zone->compact_defer_shift = COMPACT_MAX_DEFER_SHIFT;
161 trace_mm_compaction_defer_compaction(zone, order);
164 /* Returns true if compaction should be skipped this time */
165 bool compaction_deferred(struct zone *zone, int order)
167 unsigned long defer_limit = 1UL << zone->compact_defer_shift;
169 if (order < zone->compact_order_failed)
172 /* Avoid possible overflow */
173 if (++zone->compact_considered > defer_limit)
174 zone->compact_considered = defer_limit;
176 if (zone->compact_considered >= defer_limit)
179 trace_mm_compaction_deferred(zone, order);
185 * Update defer tracking counters after successful compaction of given order,
186 * which means an allocation either succeeded (alloc_success == true) or is
187 * expected to succeed.
189 void compaction_defer_reset(struct zone *zone, int order,
193 zone->compact_considered = 0;
194 zone->compact_defer_shift = 0;
196 if (order >= zone->compact_order_failed)
197 zone->compact_order_failed = order + 1;
199 trace_mm_compaction_defer_reset(zone, order);
202 /* Returns true if restarting compaction after many failures */
203 bool compaction_restarting(struct zone *zone, int order)
205 if (order < zone->compact_order_failed)
208 return zone->compact_defer_shift == COMPACT_MAX_DEFER_SHIFT &&
209 zone->compact_considered >= 1UL << zone->compact_defer_shift;
212 /* Returns true if the pageblock should be scanned for pages to isolate. */
213 static inline bool isolation_suitable(struct compact_control *cc,
216 if (cc->ignore_skip_hint)
219 return !get_pageblock_skip(page);
222 static void reset_cached_positions(struct zone *zone)
224 zone->compact_cached_migrate_pfn[0] = zone->zone_start_pfn;
225 zone->compact_cached_migrate_pfn[1] = zone->zone_start_pfn;
226 zone->compact_cached_free_pfn =
227 pageblock_start_pfn(zone_end_pfn(zone) - 1);
231 * This function is called to clear all cached information on pageblocks that
232 * should be skipped for page isolation when the migrate and free page scanner
235 static void __reset_isolation_suitable(struct zone *zone)
237 unsigned long start_pfn = zone->zone_start_pfn;
238 unsigned long end_pfn = zone_end_pfn(zone);
241 zone->compact_blockskip_flush = false;
243 /* Walk the zone and mark every pageblock as suitable for isolation */
244 for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
252 page = pfn_to_page(pfn);
253 if (zone != page_zone(page))
256 clear_pageblock_skip(page);
259 reset_cached_positions(zone);
262 void reset_isolation_suitable(pg_data_t *pgdat)
266 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
267 struct zone *zone = &pgdat->node_zones[zoneid];
268 if (!populated_zone(zone))
271 /* Only flush if a full compaction finished recently */
272 if (zone->compact_blockskip_flush)
273 __reset_isolation_suitable(zone);
278 * If no pages were isolated then mark this pageblock to be skipped in the
279 * future. The information is later cleared by __reset_isolation_suitable().
281 static void update_pageblock_skip(struct compact_control *cc,
282 struct page *page, unsigned long nr_isolated,
283 bool migrate_scanner)
285 struct zone *zone = cc->zone;
288 if (cc->ignore_skip_hint)
297 set_pageblock_skip(page);
299 pfn = page_to_pfn(page);
301 /* Update where async and sync compaction should restart */
302 if (migrate_scanner) {
303 if (pfn > zone->compact_cached_migrate_pfn[0])
304 zone->compact_cached_migrate_pfn[0] = pfn;
305 if (cc->mode != MIGRATE_ASYNC &&
306 pfn > zone->compact_cached_migrate_pfn[1])
307 zone->compact_cached_migrate_pfn[1] = pfn;
309 if (pfn < zone->compact_cached_free_pfn)
310 zone->compact_cached_free_pfn = pfn;
314 static inline bool isolation_suitable(struct compact_control *cc,
320 static void update_pageblock_skip(struct compact_control *cc,
321 struct page *page, unsigned long nr_isolated,
322 bool migrate_scanner)
325 #endif /* CONFIG_COMPACTION */
328 * Compaction requires the taking of some coarse locks that are potentially
329 * very heavily contended. For async compaction, back out if the lock cannot
330 * be taken immediately. For sync compaction, spin on the lock if needed.
332 * Returns true if the lock is held
333 * Returns false if the lock is not held and compaction should abort
335 static bool compact_trylock_irqsave(spinlock_t *lock, unsigned long *flags,
336 struct compact_control *cc)
338 if (cc->mode == MIGRATE_ASYNC) {
339 if (!spin_trylock_irqsave(lock, *flags)) {
340 cc->contended = COMPACT_CONTENDED_LOCK;
344 spin_lock_irqsave(lock, *flags);
351 * Compaction requires the taking of some coarse locks that are potentially
352 * very heavily contended. The lock should be periodically unlocked to avoid
353 * having disabled IRQs for a long time, even when there is nobody waiting on
354 * the lock. It might also be that allowing the IRQs will result in
355 * need_resched() becoming true. If scheduling is needed, async compaction
356 * aborts. Sync compaction schedules.
357 * Either compaction type will also abort if a fatal signal is pending.
358 * In either case if the lock was locked, it is dropped and not regained.
360 * Returns true if compaction should abort due to fatal signal pending, or
361 * async compaction due to need_resched()
362 * Returns false when compaction can continue (sync compaction might have
365 static bool compact_unlock_should_abort(spinlock_t *lock,
366 unsigned long flags, bool *locked, struct compact_control *cc)
369 spin_unlock_irqrestore(lock, flags);
373 if (fatal_signal_pending(current)) {
374 cc->contended = COMPACT_CONTENDED_SCHED;
378 if (need_resched()) {
379 if (cc->mode == MIGRATE_ASYNC) {
380 cc->contended = COMPACT_CONTENDED_SCHED;
390 * Aside from avoiding lock contention, compaction also periodically checks
391 * need_resched() and either schedules in sync compaction or aborts async
392 * compaction. This is similar to what compact_unlock_should_abort() does, but
393 * is used where no lock is concerned.
395 * Returns false when no scheduling was needed, or sync compaction scheduled.
396 * Returns true when async compaction should abort.
398 static inline bool compact_should_abort(struct compact_control *cc)
400 /* async compaction aborts if contended */
401 if (need_resched()) {
402 if (cc->mode == MIGRATE_ASYNC) {
403 cc->contended = COMPACT_CONTENDED_SCHED;
414 * Isolate free pages onto a private freelist. If @strict is true, will abort
415 * returning 0 on any invalid PFNs or non-free pages inside of the pageblock
416 * (even though it may still end up isolating some pages).
418 static unsigned long isolate_freepages_block(struct compact_control *cc,
419 unsigned long *start_pfn,
420 unsigned long end_pfn,
421 struct list_head *freelist,
424 int nr_scanned = 0, total_isolated = 0;
425 struct page *cursor, *valid_page = NULL;
426 unsigned long flags = 0;
428 unsigned long blockpfn = *start_pfn;
431 cursor = pfn_to_page(blockpfn);
433 /* Isolate free pages. */
434 for (; blockpfn < end_pfn; blockpfn++, cursor++) {
436 struct page *page = cursor;
439 * Periodically drop the lock (if held) regardless of its
440 * contention, to give chance to IRQs. Abort if fatal signal
441 * pending or async compaction detects need_resched()
443 if (!(blockpfn % SWAP_CLUSTER_MAX)
444 && compact_unlock_should_abort(&cc->zone->lock, flags,
449 if (!pfn_valid_within(blockpfn))
456 * For compound pages such as THP and hugetlbfs, we can save
457 * potentially a lot of iterations if we skip them at once.
458 * The check is racy, but we can consider only valid values
459 * and the only danger is skipping too much.
461 if (PageCompound(page)) {
462 unsigned int comp_order = compound_order(page);
464 if (likely(comp_order < MAX_ORDER)) {
465 blockpfn += (1UL << comp_order) - 1;
466 cursor += (1UL << comp_order) - 1;
472 if (!PageBuddy(page))
476 * If we already hold the lock, we can skip some rechecking.
477 * Note that if we hold the lock now, checked_pageblock was
478 * already set in some previous iteration (or strict is true),
479 * so it is correct to skip the suitable migration target
484 * The zone lock must be held to isolate freepages.
485 * Unfortunately this is a very coarse lock and can be
486 * heavily contended if there are parallel allocations
487 * or parallel compactions. For async compaction do not
488 * spin on the lock and we acquire the lock as late as
491 locked = compact_trylock_irqsave(&cc->zone->lock,
496 /* Recheck this is a buddy page under lock */
497 if (!PageBuddy(page))
501 /* Found a free page, will break it into order-0 pages */
502 order = page_order(page);
503 isolated = __isolate_free_page(page, order);
506 set_page_private(page, order);
508 total_isolated += isolated;
509 cc->nr_freepages += isolated;
510 list_add_tail(&page->lru, freelist);
512 if (!strict && cc->nr_migratepages <= cc->nr_freepages) {
513 blockpfn += isolated;
516 /* Advance to the end of split page */
517 blockpfn += isolated - 1;
518 cursor += isolated - 1;
530 spin_unlock_irqrestore(&cc->zone->lock, flags);
533 * There is a tiny chance that we have read bogus compound_order(),
534 * so be careful to not go outside of the pageblock.
536 if (unlikely(blockpfn > end_pfn))
539 trace_mm_compaction_isolate_freepages(*start_pfn, blockpfn,
540 nr_scanned, total_isolated);
542 /* Record how far we have got within the block */
543 *start_pfn = blockpfn;
546 * If strict isolation is requested by CMA then check that all the
547 * pages requested were isolated. If there were any failures, 0 is
548 * returned and CMA will fail.
550 if (strict && blockpfn < end_pfn)
553 /* Update the pageblock-skip if the whole pageblock was scanned */
554 if (blockpfn == end_pfn)
555 update_pageblock_skip(cc, valid_page, total_isolated, false);
557 count_compact_events(COMPACTFREE_SCANNED, nr_scanned);
559 count_compact_events(COMPACTISOLATED, total_isolated);
560 return total_isolated;
564 * isolate_freepages_range() - isolate free pages.
565 * @start_pfn: The first PFN to start isolating.
566 * @end_pfn: The one-past-last PFN.
568 * Non-free pages, invalid PFNs, or zone boundaries within the
569 * [start_pfn, end_pfn) range are considered errors, cause function to
570 * undo its actions and return zero.
572 * Otherwise, function returns one-past-the-last PFN of isolated page
573 * (which may be greater then end_pfn if end fell in a middle of
577 isolate_freepages_range(struct compact_control *cc,
578 unsigned long start_pfn, unsigned long end_pfn)
580 unsigned long isolated, pfn, block_start_pfn, block_end_pfn;
584 block_start_pfn = pageblock_start_pfn(pfn);
585 if (block_start_pfn < cc->zone->zone_start_pfn)
586 block_start_pfn = cc->zone->zone_start_pfn;
587 block_end_pfn = pageblock_end_pfn(pfn);
589 for (; pfn < end_pfn; pfn += isolated,
590 block_start_pfn = block_end_pfn,
591 block_end_pfn += pageblock_nr_pages) {
592 /* Protect pfn from changing by isolate_freepages_block */
593 unsigned long isolate_start_pfn = pfn;
595 block_end_pfn = min(block_end_pfn, end_pfn);
598 * pfn could pass the block_end_pfn if isolated freepage
599 * is more than pageblock order. In this case, we adjust
600 * scanning range to right one.
602 if (pfn >= block_end_pfn) {
603 block_start_pfn = pageblock_start_pfn(pfn);
604 block_end_pfn = pageblock_end_pfn(pfn);
605 block_end_pfn = min(block_end_pfn, end_pfn);
608 if (!pageblock_pfn_to_page(block_start_pfn,
609 block_end_pfn, cc->zone))
612 isolated = isolate_freepages_block(cc, &isolate_start_pfn,
613 block_end_pfn, &freelist, true);
616 * In strict mode, isolate_freepages_block() returns 0 if
617 * there are any holes in the block (ie. invalid PFNs or
624 * If we managed to isolate pages, it is always (1 << n) *
625 * pageblock_nr_pages for some non-negative n. (Max order
626 * page may span two pageblocks).
630 /* __isolate_free_page() does not map the pages */
631 map_pages(&freelist);
634 /* Loop terminated early, cleanup. */
635 release_freepages(&freelist);
639 /* We don't use freelists for anything. */
643 /* Update the number of anon and file isolated pages in the zone */
644 static void acct_isolated(struct zone *zone, struct compact_control *cc)
647 unsigned int count[2] = { 0, };
649 if (list_empty(&cc->migratepages))
652 list_for_each_entry(page, &cc->migratepages, lru)
653 count[!!page_is_file_cache(page)]++;
655 mod_zone_page_state(zone, NR_ISOLATED_ANON, count[0]);
656 mod_zone_page_state(zone, NR_ISOLATED_FILE, count[1]);
659 /* Similar to reclaim, but different enough that they don't share logic */
660 static bool too_many_isolated(struct zone *zone)
662 unsigned long active, inactive, isolated;
664 inactive = zone_page_state(zone, NR_INACTIVE_FILE) +
665 zone_page_state(zone, NR_INACTIVE_ANON);
666 active = zone_page_state(zone, NR_ACTIVE_FILE) +
667 zone_page_state(zone, NR_ACTIVE_ANON);
668 isolated = zone_page_state(zone, NR_ISOLATED_FILE) +
669 zone_page_state(zone, NR_ISOLATED_ANON);
671 return isolated > (inactive + active) / 2;
675 * isolate_migratepages_block() - isolate all migrate-able pages within
677 * @cc: Compaction control structure.
678 * @low_pfn: The first PFN to isolate
679 * @end_pfn: The one-past-the-last PFN to isolate, within same pageblock
680 * @isolate_mode: Isolation mode to be used.
682 * Isolate all pages that can be migrated from the range specified by
683 * [low_pfn, end_pfn). The range is expected to be within same pageblock.
684 * Returns zero if there is a fatal signal pending, otherwise PFN of the
685 * first page that was not scanned (which may be both less, equal to or more
688 * The pages are isolated on cc->migratepages list (not required to be empty),
689 * and cc->nr_migratepages is updated accordingly. The cc->migrate_pfn field
690 * is neither read nor updated.
693 isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
694 unsigned long end_pfn, isolate_mode_t isolate_mode)
696 struct zone *zone = cc->zone;
697 unsigned long nr_scanned = 0, nr_isolated = 0;
698 struct lruvec *lruvec;
699 unsigned long flags = 0;
701 struct page *page = NULL, *valid_page = NULL;
702 unsigned long start_pfn = low_pfn;
703 bool skip_on_failure = false;
704 unsigned long next_skip_pfn = 0;
707 * Ensure that there are not too many pages isolated from the LRU
708 * list by either parallel reclaimers or compaction. If there are,
709 * delay for some time until fewer pages are isolated
711 while (unlikely(too_many_isolated(zone))) {
712 /* async migration should just abort */
713 if (cc->mode == MIGRATE_ASYNC)
716 congestion_wait(BLK_RW_ASYNC, HZ/10);
718 if (fatal_signal_pending(current))
722 if (compact_should_abort(cc))
725 if (cc->direct_compaction && (cc->mode == MIGRATE_ASYNC)) {
726 skip_on_failure = true;
727 next_skip_pfn = block_end_pfn(low_pfn, cc->order);
730 /* Time to isolate some pages for migration */
731 for (; low_pfn < end_pfn; low_pfn++) {
733 if (skip_on_failure && low_pfn >= next_skip_pfn) {
735 * We have isolated all migration candidates in the
736 * previous order-aligned block, and did not skip it due
737 * to failure. We should migrate the pages now and
738 * hopefully succeed compaction.
744 * We failed to isolate in the previous order-aligned
745 * block. Set the new boundary to the end of the
746 * current block. Note we can't simply increase
747 * next_skip_pfn by 1 << order, as low_pfn might have
748 * been incremented by a higher number due to skipping
749 * a compound or a high-order buddy page in the
750 * previous loop iteration.
752 next_skip_pfn = block_end_pfn(low_pfn, cc->order);
756 * Periodically drop the lock (if held) regardless of its
757 * contention, to give chance to IRQs. Abort async compaction
760 if (!(low_pfn % SWAP_CLUSTER_MAX)
761 && compact_unlock_should_abort(&zone->lru_lock, flags,
765 if (!pfn_valid_within(low_pfn))
769 page = pfn_to_page(low_pfn);
775 * Skip if free. We read page order here without zone lock
776 * which is generally unsafe, but the race window is small and
777 * the worst thing that can happen is that we skip some
778 * potential isolation targets.
780 if (PageBuddy(page)) {
781 unsigned long freepage_order = page_order_unsafe(page);
784 * Without lock, we cannot be sure that what we got is
785 * a valid page order. Consider only values in the
786 * valid order range to prevent low_pfn overflow.
788 if (freepage_order > 0 && freepage_order < MAX_ORDER)
789 low_pfn += (1UL << freepage_order) - 1;
794 * Regardless of being on LRU, compound pages such as THP and
795 * hugetlbfs are not to be compacted. We can potentially save
796 * a lot of iterations if we skip them at once. The check is
797 * racy, but we can consider only valid values and the only
798 * danger is skipping too much.
800 if (PageCompound(page)) {
801 unsigned int comp_order = compound_order(page);
803 if (likely(comp_order < MAX_ORDER))
804 low_pfn += (1UL << comp_order) - 1;
810 * Check may be lockless but that's ok as we recheck later.
811 * It's possible to migrate LRU and non-lru movable pages.
812 * Skip any other type of page
814 if (!PageLRU(page)) {
816 * __PageMovable can return false positive so we need
817 * to verify it under page_lock.
819 if (unlikely(__PageMovable(page)) &&
820 !PageIsolated(page)) {
822 spin_unlock_irqrestore(&zone->lru_lock,
827 if (isolate_movable_page(page, isolate_mode))
828 goto isolate_success;
835 * Migration will fail if an anonymous page is pinned in memory,
836 * so avoid taking lru_lock and isolating it unnecessarily in an
837 * admittedly racy check.
839 if (!page_mapping(page) &&
840 page_count(page) > page_mapcount(page))
843 /* If we already hold the lock, we can skip some rechecking */
845 locked = compact_trylock_irqsave(&zone->lru_lock,
850 /* Recheck PageLRU and PageCompound under lock */
855 * Page become compound since the non-locked check,
856 * and it's on LRU. It can only be a THP so the order
857 * is safe to read and it's 0 for tail pages.
859 if (unlikely(PageCompound(page))) {
860 low_pfn += (1UL << compound_order(page)) - 1;
865 lruvec = mem_cgroup_page_lruvec(page, zone);
867 /* Try isolate the page */
868 if (__isolate_lru_page(page, isolate_mode) != 0)
871 VM_BUG_ON_PAGE(PageCompound(page), page);
873 /* Successfully isolated */
874 del_page_from_lru_list(page, lruvec, page_lru(page));
877 list_add(&page->lru, &cc->migratepages);
878 cc->nr_migratepages++;
882 * Record where we could have freed pages by migration and not
883 * yet flushed them to buddy allocator.
884 * - this is the lowest page that was isolated and likely be
885 * then freed by migration.
887 if (!cc->last_migrated_pfn)
888 cc->last_migrated_pfn = low_pfn;
890 /* Avoid isolating too much */
891 if (cc->nr_migratepages == COMPACT_CLUSTER_MAX) {
898 if (!skip_on_failure)
902 * We have isolated some pages, but then failed. Release them
903 * instead of migrating, as we cannot form the cc->order buddy
908 spin_unlock_irqrestore(&zone->lru_lock, flags);
911 acct_isolated(zone, cc);
912 putback_movable_pages(&cc->migratepages);
913 cc->nr_migratepages = 0;
914 cc->last_migrated_pfn = 0;
918 if (low_pfn < next_skip_pfn) {
919 low_pfn = next_skip_pfn - 1;
921 * The check near the loop beginning would have updated
922 * next_skip_pfn too, but this is a bit simpler.
924 next_skip_pfn += 1UL << cc->order;
929 * The PageBuddy() check could have potentially brought us outside
930 * the range to be scanned.
932 if (unlikely(low_pfn > end_pfn))
936 spin_unlock_irqrestore(&zone->lru_lock, flags);
939 * Update the pageblock-skip information and cached scanner pfn,
940 * if the whole pageblock was scanned without isolating any page.
942 if (low_pfn == end_pfn)
943 update_pageblock_skip(cc, valid_page, nr_isolated, true);
945 trace_mm_compaction_isolate_migratepages(start_pfn, low_pfn,
946 nr_scanned, nr_isolated);
948 count_compact_events(COMPACTMIGRATE_SCANNED, nr_scanned);
950 count_compact_events(COMPACTISOLATED, nr_isolated);
956 * isolate_migratepages_range() - isolate migrate-able pages in a PFN range
957 * @cc: Compaction control structure.
958 * @start_pfn: The first PFN to start isolating.
959 * @end_pfn: The one-past-last PFN.
961 * Returns zero if isolation fails fatally due to e.g. pending signal.
962 * Otherwise, function returns one-past-the-last PFN of isolated page
963 * (which may be greater than end_pfn if end fell in a middle of a THP page).
966 isolate_migratepages_range(struct compact_control *cc, unsigned long start_pfn,
967 unsigned long end_pfn)
969 unsigned long pfn, block_start_pfn, block_end_pfn;
971 /* Scan block by block. First and last block may be incomplete */
973 block_start_pfn = pageblock_start_pfn(pfn);
974 if (block_start_pfn < cc->zone->zone_start_pfn)
975 block_start_pfn = cc->zone->zone_start_pfn;
976 block_end_pfn = pageblock_end_pfn(pfn);
978 for (; pfn < end_pfn; pfn = block_end_pfn,
979 block_start_pfn = block_end_pfn,
980 block_end_pfn += pageblock_nr_pages) {
982 block_end_pfn = min(block_end_pfn, end_pfn);
984 if (!pageblock_pfn_to_page(block_start_pfn,
985 block_end_pfn, cc->zone))
988 pfn = isolate_migratepages_block(cc, pfn, block_end_pfn,
989 ISOLATE_UNEVICTABLE);
994 if (cc->nr_migratepages == COMPACT_CLUSTER_MAX)
997 acct_isolated(cc->zone, cc);
1002 #endif /* CONFIG_COMPACTION || CONFIG_CMA */
1003 #ifdef CONFIG_COMPACTION
1005 /* Returns true if the page is within a block suitable for migration to */
1006 static bool suitable_migration_target(struct page *page)
1008 /* If the page is a large free page, then disallow migration */
1009 if (PageBuddy(page)) {
1011 * We are checking page_order without zone->lock taken. But
1012 * the only small danger is that we skip a potentially suitable
1013 * pageblock, so it's not worth to check order for valid range.
1015 if (page_order_unsafe(page) >= pageblock_order)
1019 /* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */
1020 if (migrate_async_suitable(get_pageblock_migratetype(page)))
1023 /* Otherwise skip the block */
1028 * Test whether the free scanner has reached the same or lower pageblock than
1029 * the migration scanner, and compaction should thus terminate.
1031 static inline bool compact_scanners_met(struct compact_control *cc)
1033 return (cc->free_pfn >> pageblock_order)
1034 <= (cc->migrate_pfn >> pageblock_order);
1038 * Based on information in the current compact_control, find blocks
1039 * suitable for isolating free pages from and then isolate them.
1041 static void isolate_freepages(struct compact_control *cc)
1043 struct zone *zone = cc->zone;
1045 unsigned long block_start_pfn; /* start of current pageblock */
1046 unsigned long isolate_start_pfn; /* exact pfn we start at */
1047 unsigned long block_end_pfn; /* end of current pageblock */
1048 unsigned long low_pfn; /* lowest pfn scanner is able to scan */
1049 struct list_head *freelist = &cc->freepages;
1052 * Initialise the free scanner. The starting point is where we last
1053 * successfully isolated from, zone-cached value, or the end of the
1054 * zone when isolating for the first time. For looping we also need
1055 * this pfn aligned down to the pageblock boundary, because we do
1056 * block_start_pfn -= pageblock_nr_pages in the for loop.
1057 * For ending point, take care when isolating in last pageblock of a
1058 * a zone which ends in the middle of a pageblock.
1059 * The low boundary is the end of the pageblock the migration scanner
1062 isolate_start_pfn = cc->free_pfn;
1063 block_start_pfn = pageblock_start_pfn(cc->free_pfn);
1064 block_end_pfn = min(block_start_pfn + pageblock_nr_pages,
1065 zone_end_pfn(zone));
1066 low_pfn = pageblock_end_pfn(cc->migrate_pfn);
1069 * Isolate free pages until enough are available to migrate the
1070 * pages on cc->migratepages. We stop searching if the migrate
1071 * and free page scanners meet or enough free pages are isolated.
1073 for (; block_start_pfn >= low_pfn;
1074 block_end_pfn = block_start_pfn,
1075 block_start_pfn -= pageblock_nr_pages,
1076 isolate_start_pfn = block_start_pfn) {
1078 * This can iterate a massively long zone without finding any
1079 * suitable migration targets, so periodically check if we need
1080 * to schedule, or even abort async compaction.
1082 if (!(block_start_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages))
1083 && compact_should_abort(cc))
1086 page = pageblock_pfn_to_page(block_start_pfn, block_end_pfn,
1091 /* Check the block is suitable for migration */
1092 if (!suitable_migration_target(page))
1095 /* If isolation recently failed, do not retry */
1096 if (!isolation_suitable(cc, page))
1099 /* Found a block suitable for isolating free pages from. */
1100 isolate_freepages_block(cc, &isolate_start_pfn, block_end_pfn,
1104 * If we isolated enough freepages, or aborted due to lock
1105 * contention, terminate.
1107 if ((cc->nr_freepages >= cc->nr_migratepages)
1109 if (isolate_start_pfn >= block_end_pfn) {
1111 * Restart at previous pageblock if more
1112 * freepages can be isolated next time.
1115 block_start_pfn - pageblock_nr_pages;
1118 } else if (isolate_start_pfn < block_end_pfn) {
1120 * If isolation failed early, do not continue
1127 /* __isolate_free_page() does not map the pages */
1128 map_pages(freelist);
1131 * Record where the free scanner will restart next time. Either we
1132 * broke from the loop and set isolate_start_pfn based on the last
1133 * call to isolate_freepages_block(), or we met the migration scanner
1134 * and the loop terminated due to isolate_start_pfn < low_pfn
1136 cc->free_pfn = isolate_start_pfn;
1140 * This is a migrate-callback that "allocates" freepages by taking pages
1141 * from the isolated freelists in the block we are migrating to.
1143 static struct page *compaction_alloc(struct page *migratepage,
1147 struct compact_control *cc = (struct compact_control *)data;
1148 struct page *freepage;
1151 * Isolate free pages if necessary, and if we are not aborting due to
1154 if (list_empty(&cc->freepages)) {
1156 isolate_freepages(cc);
1158 if (list_empty(&cc->freepages))
1162 freepage = list_entry(cc->freepages.next, struct page, lru);
1163 list_del(&freepage->lru);
1170 * This is a migrate-callback that "frees" freepages back to the isolated
1171 * freelist. All pages on the freelist are from the same zone, so there is no
1172 * special handling needed for NUMA.
1174 static void compaction_free(struct page *page, unsigned long data)
1176 struct compact_control *cc = (struct compact_control *)data;
1178 list_add(&page->lru, &cc->freepages);
1182 /* possible outcome of isolate_migratepages */
1184 ISOLATE_ABORT, /* Abort compaction now */
1185 ISOLATE_NONE, /* No pages isolated, continue scanning */
1186 ISOLATE_SUCCESS, /* Pages isolated, migrate */
1187 } isolate_migrate_t;
1190 * Allow userspace to control policy on scanning the unevictable LRU for
1191 * compactable pages.
1193 int sysctl_compact_unevictable_allowed __read_mostly = 1;
1196 * Isolate all pages that can be migrated from the first suitable block,
1197 * starting at the block pointed to by the migrate scanner pfn within
1200 static isolate_migrate_t isolate_migratepages(struct zone *zone,
1201 struct compact_control *cc)
1203 unsigned long block_start_pfn;
1204 unsigned long block_end_pfn;
1205 unsigned long low_pfn;
1207 const isolate_mode_t isolate_mode =
1208 (sysctl_compact_unevictable_allowed ? ISOLATE_UNEVICTABLE : 0) |
1209 (cc->mode == MIGRATE_ASYNC ? ISOLATE_ASYNC_MIGRATE : 0);
1212 * Start at where we last stopped, or beginning of the zone as
1213 * initialized by compact_zone()
1215 low_pfn = cc->migrate_pfn;
1216 block_start_pfn = pageblock_start_pfn(low_pfn);
1217 if (block_start_pfn < zone->zone_start_pfn)
1218 block_start_pfn = zone->zone_start_pfn;
1220 /* Only scan within a pageblock boundary */
1221 block_end_pfn = pageblock_end_pfn(low_pfn);
1224 * Iterate over whole pageblocks until we find the first suitable.
1225 * Do not cross the free scanner.
1227 for (; block_end_pfn <= cc->free_pfn;
1228 low_pfn = block_end_pfn,
1229 block_start_pfn = block_end_pfn,
1230 block_end_pfn += pageblock_nr_pages) {
1233 * This can potentially iterate a massively long zone with
1234 * many pageblocks unsuitable, so periodically check if we
1235 * need to schedule, or even abort async compaction.
1237 if (!(low_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages))
1238 && compact_should_abort(cc))
1241 page = pageblock_pfn_to_page(block_start_pfn, block_end_pfn,
1246 /* If isolation recently failed, do not retry */
1247 if (!isolation_suitable(cc, page))
1251 * For async compaction, also only scan in MOVABLE blocks.
1252 * Async compaction is optimistic to see if the minimum amount
1253 * of work satisfies the allocation.
1255 if (cc->mode == MIGRATE_ASYNC &&
1256 !migrate_async_suitable(get_pageblock_migratetype(page)))
1259 /* Perform the isolation */
1260 low_pfn = isolate_migratepages_block(cc, low_pfn,
1261 block_end_pfn, isolate_mode);
1263 if (!low_pfn || cc->contended) {
1264 acct_isolated(zone, cc);
1265 return ISOLATE_ABORT;
1269 * Either we isolated something and proceed with migration. Or
1270 * we failed and compact_zone should decide if we should
1276 acct_isolated(zone, cc);
1277 /* Record where migration scanner will be restarted. */
1278 cc->migrate_pfn = low_pfn;
1280 return cc->nr_migratepages ? ISOLATE_SUCCESS : ISOLATE_NONE;
1284 * order == -1 is expected when compacting via
1285 * /proc/sys/vm/compact_memory
1287 static inline bool is_via_compact_memory(int order)
1292 static enum compact_result __compact_finished(struct zone *zone, struct compact_control *cc,
1293 const int migratetype)
1296 unsigned long watermark;
1298 if (cc->contended || fatal_signal_pending(current))
1299 return COMPACT_CONTENDED;
1301 /* Compaction run completes if the migrate and free scanner meet */
1302 if (compact_scanners_met(cc)) {
1303 /* Let the next compaction start anew. */
1304 reset_cached_positions(zone);
1307 * Mark that the PG_migrate_skip information should be cleared
1308 * by kswapd when it goes to sleep. kcompactd does not set the
1309 * flag itself as the decision to be clear should be directly
1310 * based on an allocation request.
1312 if (cc->direct_compaction)
1313 zone->compact_blockskip_flush = true;
1316 return COMPACT_COMPLETE;
1318 return COMPACT_PARTIAL_SKIPPED;
1321 if (is_via_compact_memory(cc->order))
1322 return COMPACT_CONTINUE;
1324 /* Compaction run is not finished if the watermark is not met */
1325 watermark = low_wmark_pages(zone);
1327 if (!zone_watermark_ok(zone, cc->order, watermark, cc->classzone_idx,
1329 return COMPACT_CONTINUE;
1331 /* Direct compactor: Is a suitable page free? */
1332 for (order = cc->order; order < MAX_ORDER; order++) {
1333 struct free_area *area = &zone->free_area[order];
1336 /* Job done if page is free of the right migratetype */
1337 if (!list_empty(&area->free_list[migratetype]))
1338 return COMPACT_PARTIAL;
1341 /* MIGRATE_MOVABLE can fallback on MIGRATE_CMA */
1342 if (migratetype == MIGRATE_MOVABLE &&
1343 !list_empty(&area->free_list[MIGRATE_CMA]))
1344 return COMPACT_PARTIAL;
1347 * Job done if allocation would steal freepages from
1348 * other migratetype buddy lists.
1350 if (find_suitable_fallback(area, order, migratetype,
1351 true, &can_steal) != -1)
1352 return COMPACT_PARTIAL;
1355 return COMPACT_NO_SUITABLE_PAGE;
1358 static enum compact_result compact_finished(struct zone *zone,
1359 struct compact_control *cc,
1360 const int migratetype)
1364 ret = __compact_finished(zone, cc, migratetype);
1365 trace_mm_compaction_finished(zone, cc->order, ret);
1366 if (ret == COMPACT_NO_SUITABLE_PAGE)
1367 ret = COMPACT_CONTINUE;
1373 * compaction_suitable: Is this suitable to run compaction on this zone now?
1375 * COMPACT_SKIPPED - If there are too few free pages for compaction
1376 * COMPACT_PARTIAL - If the allocation would succeed without compaction
1377 * COMPACT_CONTINUE - If compaction should run now
1379 static enum compact_result __compaction_suitable(struct zone *zone, int order,
1380 unsigned int alloc_flags,
1382 unsigned long wmark_target)
1385 unsigned long watermark;
1387 if (is_via_compact_memory(order))
1388 return COMPACT_CONTINUE;
1390 watermark = low_wmark_pages(zone);
1392 * If watermarks for high-order allocation are already met, there
1393 * should be no need for compaction at all.
1395 if (zone_watermark_ok(zone, order, watermark, classzone_idx,
1397 return COMPACT_PARTIAL;
1400 * Watermarks for order-0 must be met for compaction. Note the 2UL.
1401 * This is because during migration, copies of pages need to be
1402 * allocated and for a short time, the footprint is higher
1404 watermark += (2UL << order);
1405 if (!__zone_watermark_ok(zone, 0, watermark, classzone_idx,
1406 alloc_flags, wmark_target))
1407 return COMPACT_SKIPPED;
1410 * fragmentation index determines if allocation failures are due to
1411 * low memory or external fragmentation
1413 * index of -1000 would imply allocations might succeed depending on
1414 * watermarks, but we already failed the high-order watermark check
1415 * index towards 0 implies failure is due to lack of memory
1416 * index towards 1000 implies failure is due to fragmentation
1418 * Only compact if a failure would be due to fragmentation.
1420 fragindex = fragmentation_index(zone, order);
1421 if (fragindex >= 0 && fragindex <= sysctl_extfrag_threshold)
1422 return COMPACT_NOT_SUITABLE_ZONE;
1424 return COMPACT_CONTINUE;
1427 enum compact_result compaction_suitable(struct zone *zone, int order,
1428 unsigned int alloc_flags,
1431 enum compact_result ret;
1433 ret = __compaction_suitable(zone, order, alloc_flags, classzone_idx,
1434 zone_page_state(zone, NR_FREE_PAGES));
1435 trace_mm_compaction_suitable(zone, order, ret);
1436 if (ret == COMPACT_NOT_SUITABLE_ZONE)
1437 ret = COMPACT_SKIPPED;
1442 bool compaction_zonelist_suitable(struct alloc_context *ac, int order,
1449 * Make sure at least one zone would pass __compaction_suitable if we continue
1450 * retrying the reclaim.
1452 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
1454 unsigned long available;
1455 enum compact_result compact_result;
1458 * Do not consider all the reclaimable memory because we do not
1459 * want to trash just for a single high order allocation which
1460 * is even not guaranteed to appear even if __compaction_suitable
1461 * is happy about the watermark check.
1463 available = zone_reclaimable_pages(zone) / order;
1464 available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
1465 compact_result = __compaction_suitable(zone, order, alloc_flags,
1466 ac_classzone_idx(ac), available);
1467 if (compact_result != COMPACT_SKIPPED &&
1468 compact_result != COMPACT_NOT_SUITABLE_ZONE)
1475 static enum compact_result compact_zone(struct zone *zone, struct compact_control *cc)
1477 enum compact_result ret;
1478 unsigned long start_pfn = zone->zone_start_pfn;
1479 unsigned long end_pfn = zone_end_pfn(zone);
1480 const int migratetype = gfpflags_to_migratetype(cc->gfp_mask);
1481 const bool sync = cc->mode != MIGRATE_ASYNC;
1483 ret = compaction_suitable(zone, cc->order, cc->alloc_flags,
1485 /* Compaction is likely to fail */
1486 if (ret == COMPACT_PARTIAL || ret == COMPACT_SKIPPED)
1489 /* huh, compaction_suitable is returning something unexpected */
1490 VM_BUG_ON(ret != COMPACT_CONTINUE);
1493 * Clear pageblock skip if there were failures recently and compaction
1494 * is about to be retried after being deferred.
1496 if (compaction_restarting(zone, cc->order))
1497 __reset_isolation_suitable(zone);
1500 * Setup to move all movable pages to the end of the zone. Used cached
1501 * information on where the scanners should start but check that it
1502 * is initialised by ensuring the values are within zone boundaries.
1504 cc->migrate_pfn = zone->compact_cached_migrate_pfn[sync];
1505 cc->free_pfn = zone->compact_cached_free_pfn;
1506 if (cc->free_pfn < start_pfn || cc->free_pfn >= end_pfn) {
1507 cc->free_pfn = pageblock_start_pfn(end_pfn - 1);
1508 zone->compact_cached_free_pfn = cc->free_pfn;
1510 if (cc->migrate_pfn < start_pfn || cc->migrate_pfn >= end_pfn) {
1511 cc->migrate_pfn = start_pfn;
1512 zone->compact_cached_migrate_pfn[0] = cc->migrate_pfn;
1513 zone->compact_cached_migrate_pfn[1] = cc->migrate_pfn;
1516 if (cc->migrate_pfn == start_pfn)
1517 cc->whole_zone = true;
1519 cc->last_migrated_pfn = 0;
1521 trace_mm_compaction_begin(start_pfn, cc->migrate_pfn,
1522 cc->free_pfn, end_pfn, sync);
1524 migrate_prep_local();
1526 while ((ret = compact_finished(zone, cc, migratetype)) ==
1530 switch (isolate_migratepages(zone, cc)) {
1532 ret = COMPACT_CONTENDED;
1533 putback_movable_pages(&cc->migratepages);
1534 cc->nr_migratepages = 0;
1538 * We haven't isolated and migrated anything, but
1539 * there might still be unflushed migrations from
1540 * previous cc->order aligned block.
1543 case ISOLATE_SUCCESS:
1547 err = migrate_pages(&cc->migratepages, compaction_alloc,
1548 compaction_free, (unsigned long)cc, cc->mode,
1551 trace_mm_compaction_migratepages(cc->nr_migratepages, err,
1554 /* All pages were either migrated or will be released */
1555 cc->nr_migratepages = 0;
1557 putback_movable_pages(&cc->migratepages);
1559 * migrate_pages() may return -ENOMEM when scanners meet
1560 * and we want compact_finished() to detect it
1562 if (err == -ENOMEM && !compact_scanners_met(cc)) {
1563 ret = COMPACT_CONTENDED;
1567 * We failed to migrate at least one page in the current
1568 * order-aligned block, so skip the rest of it.
1570 if (cc->direct_compaction &&
1571 (cc->mode == MIGRATE_ASYNC)) {
1572 cc->migrate_pfn = block_end_pfn(
1573 cc->migrate_pfn - 1, cc->order);
1574 /* Draining pcplists is useless in this case */
1575 cc->last_migrated_pfn = 0;
1582 * Has the migration scanner moved away from the previous
1583 * cc->order aligned block where we migrated from? If yes,
1584 * flush the pages that were freed, so that they can merge and
1585 * compact_finished() can detect immediately if allocation
1588 if (cc->order > 0 && cc->last_migrated_pfn) {
1590 unsigned long current_block_start =
1591 block_start_pfn(cc->migrate_pfn, cc->order);
1593 if (cc->last_migrated_pfn < current_block_start) {
1595 lru_add_drain_cpu(cpu);
1596 drain_local_pages(zone);
1598 /* No more flushing until we migrate again */
1599 cc->last_migrated_pfn = 0;
1607 * Release free pages and update where the free scanner should restart,
1608 * so we don't leave any returned pages behind in the next attempt.
1610 if (cc->nr_freepages > 0) {
1611 unsigned long free_pfn = release_freepages(&cc->freepages);
1613 cc->nr_freepages = 0;
1614 VM_BUG_ON(free_pfn == 0);
1615 /* The cached pfn is always the first in a pageblock */
1616 free_pfn = pageblock_start_pfn(free_pfn);
1618 * Only go back, not forward. The cached pfn might have been
1619 * already reset to zone end in compact_finished()
1621 if (free_pfn > zone->compact_cached_free_pfn)
1622 zone->compact_cached_free_pfn = free_pfn;
1625 trace_mm_compaction_end(start_pfn, cc->migrate_pfn,
1626 cc->free_pfn, end_pfn, sync, ret);
1628 if (ret == COMPACT_CONTENDED)
1629 ret = COMPACT_PARTIAL;
1634 static enum compact_result compact_zone_order(struct zone *zone, int order,
1635 gfp_t gfp_mask, enum migrate_mode mode, int *contended,
1636 unsigned int alloc_flags, int classzone_idx)
1638 enum compact_result ret;
1639 struct compact_control cc = {
1641 .nr_migratepages = 0,
1643 .gfp_mask = gfp_mask,
1646 .alloc_flags = alloc_flags,
1647 .classzone_idx = classzone_idx,
1648 .direct_compaction = true,
1650 INIT_LIST_HEAD(&cc.freepages);
1651 INIT_LIST_HEAD(&cc.migratepages);
1653 ret = compact_zone(zone, &cc);
1655 VM_BUG_ON(!list_empty(&cc.freepages));
1656 VM_BUG_ON(!list_empty(&cc.migratepages));
1658 *contended = cc.contended;
1662 int sysctl_extfrag_threshold = 500;
1665 * try_to_compact_pages - Direct compact to satisfy a high-order allocation
1666 * @gfp_mask: The GFP mask of the current allocation
1667 * @order: The order of the current allocation
1668 * @alloc_flags: The allocation flags of the current allocation
1669 * @ac: The context of current allocation
1670 * @mode: The migration mode for async, sync light, or sync migration
1671 * @contended: Return value that determines if compaction was aborted due to
1672 * need_resched() or lock contention
1674 * This is the main entry point for direct page compaction.
1676 enum compact_result try_to_compact_pages(gfp_t gfp_mask, unsigned int order,
1677 unsigned int alloc_flags, const struct alloc_context *ac,
1678 enum migrate_mode mode, int *contended)
1680 int may_enter_fs = gfp_mask & __GFP_FS;
1681 int may_perform_io = gfp_mask & __GFP_IO;
1684 enum compact_result rc = COMPACT_SKIPPED;
1685 int all_zones_contended = COMPACT_CONTENDED_LOCK; /* init for &= op */
1687 *contended = COMPACT_CONTENDED_NONE;
1689 /* Check if the GFP flags allow compaction */
1690 if (!order || !may_enter_fs || !may_perform_io)
1691 return COMPACT_SKIPPED;
1693 trace_mm_compaction_try_to_compact_pages(order, gfp_mask, mode);
1695 /* Compact each zone in the list */
1696 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
1698 enum compact_result status;
1701 if (compaction_deferred(zone, order)) {
1702 rc = max_t(enum compact_result, COMPACT_DEFERRED, rc);
1706 status = compact_zone_order(zone, order, gfp_mask, mode,
1707 &zone_contended, alloc_flags,
1708 ac_classzone_idx(ac));
1709 rc = max(status, rc);
1711 * It takes at least one zone that wasn't lock contended
1712 * to clear all_zones_contended.
1714 all_zones_contended &= zone_contended;
1716 /* If a normal allocation would succeed, stop compacting */
1717 if (zone_watermark_ok(zone, order, low_wmark_pages(zone),
1718 ac_classzone_idx(ac), alloc_flags)) {
1720 * We think the allocation will succeed in this zone,
1721 * but it is not certain, hence the false. The caller
1722 * will repeat this with true if allocation indeed
1723 * succeeds in this zone.
1725 compaction_defer_reset(zone, order, false);
1727 * It is possible that async compaction aborted due to
1728 * need_resched() and the watermarks were ok thanks to
1729 * somebody else freeing memory. The allocation can
1730 * however still fail so we better signal the
1731 * need_resched() contention anyway (this will not
1732 * prevent the allocation attempt).
1734 if (zone_contended == COMPACT_CONTENDED_SCHED)
1735 *contended = COMPACT_CONTENDED_SCHED;
1740 if (mode != MIGRATE_ASYNC && (status == COMPACT_COMPLETE ||
1741 status == COMPACT_PARTIAL_SKIPPED)) {
1743 * We think that allocation won't succeed in this zone
1744 * so we defer compaction there. If it ends up
1745 * succeeding after all, it will be reset.
1747 defer_compaction(zone, order);
1751 * We might have stopped compacting due to need_resched() in
1752 * async compaction, or due to a fatal signal detected. In that
1753 * case do not try further zones and signal need_resched()
1756 if ((zone_contended == COMPACT_CONTENDED_SCHED)
1757 || fatal_signal_pending(current)) {
1758 *contended = COMPACT_CONTENDED_SCHED;
1765 * We might not have tried all the zones, so be conservative
1766 * and assume they are not all lock contended.
1768 all_zones_contended = 0;
1773 * If at least one zone wasn't deferred or skipped, we report if all
1774 * zones that were tried were lock contended.
1776 if (rc > COMPACT_INACTIVE && all_zones_contended)
1777 *contended = COMPACT_CONTENDED_LOCK;
1783 /* Compact all zones within a node */
1784 static void __compact_pgdat(pg_data_t *pgdat, struct compact_control *cc)
1789 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
1791 zone = &pgdat->node_zones[zoneid];
1792 if (!populated_zone(zone))
1795 cc->nr_freepages = 0;
1796 cc->nr_migratepages = 0;
1798 INIT_LIST_HEAD(&cc->freepages);
1799 INIT_LIST_HEAD(&cc->migratepages);
1802 * When called via /proc/sys/vm/compact_memory
1803 * this makes sure we compact the whole zone regardless of
1804 * cached scanner positions.
1806 if (is_via_compact_memory(cc->order))
1807 __reset_isolation_suitable(zone);
1809 if (is_via_compact_memory(cc->order) ||
1810 !compaction_deferred(zone, cc->order))
1811 compact_zone(zone, cc);
1813 VM_BUG_ON(!list_empty(&cc->freepages));
1814 VM_BUG_ON(!list_empty(&cc->migratepages));
1816 if (is_via_compact_memory(cc->order))
1819 if (zone_watermark_ok(zone, cc->order,
1820 low_wmark_pages(zone), 0, 0))
1821 compaction_defer_reset(zone, cc->order, false);
1825 void compact_pgdat(pg_data_t *pgdat, int order)
1827 struct compact_control cc = {
1829 .mode = MIGRATE_ASYNC,
1835 __compact_pgdat(pgdat, &cc);
1838 static void compact_node(int nid)
1840 struct compact_control cc = {
1842 .mode = MIGRATE_SYNC,
1843 .ignore_skip_hint = true,
1846 __compact_pgdat(NODE_DATA(nid), &cc);
1849 /* Compact all nodes in the system */
1850 static void compact_nodes(void)
1854 /* Flush pending updates to the LRU lists */
1855 lru_add_drain_all();
1857 for_each_online_node(nid)
1861 /* The written value is actually unused, all memory is compacted */
1862 int sysctl_compact_memory;
1865 * This is the entry point for compacting all nodes via
1866 * /proc/sys/vm/compact_memory
1868 int sysctl_compaction_handler(struct ctl_table *table, int write,
1869 void __user *buffer, size_t *length, loff_t *ppos)
1877 int sysctl_extfrag_handler(struct ctl_table *table, int write,
1878 void __user *buffer, size_t *length, loff_t *ppos)
1880 proc_dointvec_minmax(table, write, buffer, length, ppos);
1885 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
1886 static ssize_t sysfs_compact_node(struct device *dev,
1887 struct device_attribute *attr,
1888 const char *buf, size_t count)
1892 if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
1893 /* Flush pending updates to the LRU lists */
1894 lru_add_drain_all();
1901 static DEVICE_ATTR(compact, S_IWUSR, NULL, sysfs_compact_node);
1903 int compaction_register_node(struct node *node)
1905 return device_create_file(&node->dev, &dev_attr_compact);
1908 void compaction_unregister_node(struct node *node)
1910 return device_remove_file(&node->dev, &dev_attr_compact);
1912 #endif /* CONFIG_SYSFS && CONFIG_NUMA */
1914 static inline bool kcompactd_work_requested(pg_data_t *pgdat)
1916 return pgdat->kcompactd_max_order > 0 || kthread_should_stop();
1919 static bool kcompactd_node_suitable(pg_data_t *pgdat)
1923 enum zone_type classzone_idx = pgdat->kcompactd_classzone_idx;
1925 for (zoneid = 0; zoneid <= classzone_idx; zoneid++) {
1926 zone = &pgdat->node_zones[zoneid];
1928 if (!populated_zone(zone))
1931 if (compaction_suitable(zone, pgdat->kcompactd_max_order, 0,
1932 classzone_idx) == COMPACT_CONTINUE)
1939 static void kcompactd_do_work(pg_data_t *pgdat)
1942 * With no special task, compact all zones so that a page of requested
1943 * order is allocatable.
1947 struct compact_control cc = {
1948 .order = pgdat->kcompactd_max_order,
1949 .classzone_idx = pgdat->kcompactd_classzone_idx,
1950 .mode = MIGRATE_SYNC_LIGHT,
1951 .ignore_skip_hint = true,
1954 bool success = false;
1956 trace_mm_compaction_kcompactd_wake(pgdat->node_id, cc.order,
1958 count_vm_event(KCOMPACTD_WAKE);
1960 for (zoneid = 0; zoneid <= cc.classzone_idx; zoneid++) {
1963 zone = &pgdat->node_zones[zoneid];
1964 if (!populated_zone(zone))
1967 if (compaction_deferred(zone, cc.order))
1970 if (compaction_suitable(zone, cc.order, 0, zoneid) !=
1974 cc.nr_freepages = 0;
1975 cc.nr_migratepages = 0;
1977 INIT_LIST_HEAD(&cc.freepages);
1978 INIT_LIST_HEAD(&cc.migratepages);
1980 if (kthread_should_stop())
1982 status = compact_zone(zone, &cc);
1984 if (zone_watermark_ok(zone, cc.order, low_wmark_pages(zone),
1985 cc.classzone_idx, 0)) {
1987 compaction_defer_reset(zone, cc.order, false);
1988 } else if (status == COMPACT_PARTIAL_SKIPPED || status == COMPACT_COMPLETE) {
1990 * We use sync migration mode here, so we defer like
1991 * sync direct compaction does.
1993 defer_compaction(zone, cc.order);
1996 VM_BUG_ON(!list_empty(&cc.freepages));
1997 VM_BUG_ON(!list_empty(&cc.migratepages));
2001 * Regardless of success, we are done until woken up next. But remember
2002 * the requested order/classzone_idx in case it was higher/tighter than
2005 if (pgdat->kcompactd_max_order <= cc.order)
2006 pgdat->kcompactd_max_order = 0;
2007 if (pgdat->kcompactd_classzone_idx >= cc.classzone_idx)
2008 pgdat->kcompactd_classzone_idx = pgdat->nr_zones - 1;
2011 void wakeup_kcompactd(pg_data_t *pgdat, int order, int classzone_idx)
2016 if (pgdat->kcompactd_max_order < order)
2017 pgdat->kcompactd_max_order = order;
2019 if (pgdat->kcompactd_classzone_idx > classzone_idx)
2020 pgdat->kcompactd_classzone_idx = classzone_idx;
2022 if (!waitqueue_active(&pgdat->kcompactd_wait))
2025 if (!kcompactd_node_suitable(pgdat))
2028 trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, order,
2030 wake_up_interruptible(&pgdat->kcompactd_wait);
2034 * The background compaction daemon, started as a kernel thread
2035 * from the init process.
2037 static int kcompactd(void *p)
2039 pg_data_t *pgdat = (pg_data_t*)p;
2040 struct task_struct *tsk = current;
2042 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
2044 if (!cpumask_empty(cpumask))
2045 set_cpus_allowed_ptr(tsk, cpumask);
2049 pgdat->kcompactd_max_order = 0;
2050 pgdat->kcompactd_classzone_idx = pgdat->nr_zones - 1;
2052 while (!kthread_should_stop()) {
2053 trace_mm_compaction_kcompactd_sleep(pgdat->node_id);
2054 wait_event_freezable(pgdat->kcompactd_wait,
2055 kcompactd_work_requested(pgdat));
2057 kcompactd_do_work(pgdat);
2064 * This kcompactd start function will be called by init and node-hot-add.
2065 * On node-hot-add, kcompactd will moved to proper cpus if cpus are hot-added.
2067 int kcompactd_run(int nid)
2069 pg_data_t *pgdat = NODE_DATA(nid);
2072 if (pgdat->kcompactd)
2075 pgdat->kcompactd = kthread_run(kcompactd, pgdat, "kcompactd%d", nid);
2076 if (IS_ERR(pgdat->kcompactd)) {
2077 pr_err("Failed to start kcompactd on node %d\n", nid);
2078 ret = PTR_ERR(pgdat->kcompactd);
2079 pgdat->kcompactd = NULL;
2085 * Called by memory hotplug when all memory in a node is offlined. Caller must
2086 * hold mem_hotplug_begin/end().
2088 void kcompactd_stop(int nid)
2090 struct task_struct *kcompactd = NODE_DATA(nid)->kcompactd;
2093 kthread_stop(kcompactd);
2094 NODE_DATA(nid)->kcompactd = NULL;
2099 * It's optimal to keep kcompactd on the same CPUs as their memory, but
2100 * not required for correctness. So if the last cpu in a node goes
2101 * away, we get changed to run anywhere: as the first one comes back,
2102 * restore their cpu bindings.
2104 static int cpu_callback(struct notifier_block *nfb, unsigned long action,
2109 if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
2110 for_each_node_state(nid, N_MEMORY) {
2111 pg_data_t *pgdat = NODE_DATA(nid);
2112 const struct cpumask *mask;
2114 mask = cpumask_of_node(pgdat->node_id);
2116 if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
2117 /* One of our CPUs online: restore mask */
2118 set_cpus_allowed_ptr(pgdat->kcompactd, mask);
2124 static int __init kcompactd_init(void)
2128 for_each_node_state(nid, N_MEMORY)
2130 hotcpu_notifier(cpu_callback, 0);
2133 subsys_initcall(kcompactd_init)
2135 #endif /* CONFIG_COMPACTION */