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/balloon_compaction.h>
19 #include <linux/page-isolation.h>
20 #include <linux/kasan.h>
21 #include <linux/kthread.h>
22 #include <linux/freezer.h>
23 #include <linux/module.h>
26 #ifdef CONFIG_COMPACTION
27 static inline void count_compact_event(enum vm_event_item item)
32 static inline void count_compact_events(enum vm_event_item item, long delta)
34 count_vm_events(item, delta);
37 #define count_compact_event(item) do { } while (0)
38 #define count_compact_events(item, delta) do { } while (0)
41 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
43 #define CREATE_TRACE_POINTS
44 #include <trace/events/compaction.h>
46 static unsigned long release_freepages(struct list_head *freelist)
48 struct page *page, *next;
49 unsigned long high_pfn = 0;
51 list_for_each_entry_safe(page, next, freelist, lru) {
52 unsigned long pfn = page_to_pfn(page);
62 static void map_pages(struct list_head *list)
66 list_for_each_entry(page, list, lru) {
67 arch_alloc_page(page, 0);
68 kernel_map_pages(page, 1, 1);
69 kasan_alloc_pages(page, 0);
73 static inline bool migrate_async_suitable(int migratetype)
75 return is_migrate_cma(migratetype) || migratetype == MIGRATE_MOVABLE;
78 #ifdef CONFIG_COMPACTION
80 /* Do not skip compaction more than 64 times */
81 #define COMPACT_MAX_DEFER_SHIFT 6
84 * Compaction is deferred when compaction fails to result in a page
85 * allocation success. 1 << compact_defer_limit compactions are skipped up
86 * to a limit of 1 << COMPACT_MAX_DEFER_SHIFT
88 void defer_compaction(struct zone *zone, int order)
90 zone->compact_considered = 0;
91 zone->compact_defer_shift++;
93 if (order < zone->compact_order_failed)
94 zone->compact_order_failed = order;
96 if (zone->compact_defer_shift > COMPACT_MAX_DEFER_SHIFT)
97 zone->compact_defer_shift = COMPACT_MAX_DEFER_SHIFT;
99 trace_mm_compaction_defer_compaction(zone, order);
102 /* Returns true if compaction should be skipped this time */
103 bool compaction_deferred(struct zone *zone, int order)
105 unsigned long defer_limit = 1UL << zone->compact_defer_shift;
107 if (order < zone->compact_order_failed)
110 /* Avoid possible overflow */
111 if (++zone->compact_considered > defer_limit)
112 zone->compact_considered = defer_limit;
114 if (zone->compact_considered >= defer_limit)
117 trace_mm_compaction_deferred(zone, order);
123 * Update defer tracking counters after successful compaction of given order,
124 * which means an allocation either succeeded (alloc_success == true) or is
125 * expected to succeed.
127 void compaction_defer_reset(struct zone *zone, int order,
131 zone->compact_considered = 0;
132 zone->compact_defer_shift = 0;
134 if (order >= zone->compact_order_failed)
135 zone->compact_order_failed = order + 1;
137 trace_mm_compaction_defer_reset(zone, order);
140 /* Returns true if restarting compaction after many failures */
141 bool compaction_restarting(struct zone *zone, int order)
143 if (order < zone->compact_order_failed)
146 return zone->compact_defer_shift == COMPACT_MAX_DEFER_SHIFT &&
147 zone->compact_considered >= 1UL << zone->compact_defer_shift;
150 /* Returns true if the pageblock should be scanned for pages to isolate. */
151 static inline bool isolation_suitable(struct compact_control *cc,
154 if (cc->ignore_skip_hint)
157 return !get_pageblock_skip(page);
160 static void reset_cached_positions(struct zone *zone)
162 zone->compact_cached_migrate_pfn[0] = zone->zone_start_pfn;
163 zone->compact_cached_migrate_pfn[1] = zone->zone_start_pfn;
164 zone->compact_cached_free_pfn =
165 round_down(zone_end_pfn(zone) - 1, pageblock_nr_pages);
169 * This function is called to clear all cached information on pageblocks that
170 * should be skipped for page isolation when the migrate and free page scanner
173 static void __reset_isolation_suitable(struct zone *zone)
175 unsigned long start_pfn = zone->zone_start_pfn;
176 unsigned long end_pfn = zone_end_pfn(zone);
179 zone->compact_blockskip_flush = false;
181 /* Walk the zone and mark every pageblock as suitable for isolation */
182 for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
190 page = pfn_to_page(pfn);
191 if (zone != page_zone(page))
194 clear_pageblock_skip(page);
197 reset_cached_positions(zone);
200 void reset_isolation_suitable(pg_data_t *pgdat)
204 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
205 struct zone *zone = &pgdat->node_zones[zoneid];
206 if (!populated_zone(zone))
209 /* Only flush if a full compaction finished recently */
210 if (zone->compact_blockskip_flush)
211 __reset_isolation_suitable(zone);
216 * If no pages were isolated then mark this pageblock to be skipped in the
217 * future. The information is later cleared by __reset_isolation_suitable().
219 static void update_pageblock_skip(struct compact_control *cc,
220 struct page *page, unsigned long nr_isolated,
221 bool migrate_scanner)
223 struct zone *zone = cc->zone;
226 if (cc->ignore_skip_hint)
235 set_pageblock_skip(page);
237 pfn = page_to_pfn(page);
239 /* Update where async and sync compaction should restart */
240 if (migrate_scanner) {
241 if (pfn > zone->compact_cached_migrate_pfn[0])
242 zone->compact_cached_migrate_pfn[0] = pfn;
243 if (cc->mode != MIGRATE_ASYNC &&
244 pfn > zone->compact_cached_migrate_pfn[1])
245 zone->compact_cached_migrate_pfn[1] = pfn;
247 if (pfn < zone->compact_cached_free_pfn)
248 zone->compact_cached_free_pfn = pfn;
252 static inline bool isolation_suitable(struct compact_control *cc,
258 static void update_pageblock_skip(struct compact_control *cc,
259 struct page *page, unsigned long nr_isolated,
260 bool migrate_scanner)
263 #endif /* CONFIG_COMPACTION */
266 * Compaction requires the taking of some coarse locks that are potentially
267 * very heavily contended. For async compaction, back out if the lock cannot
268 * be taken immediately. For sync compaction, spin on the lock if needed.
270 * Returns true if the lock is held
271 * Returns false if the lock is not held and compaction should abort
273 static bool compact_trylock_irqsave(spinlock_t *lock, unsigned long *flags,
274 struct compact_control *cc)
276 if (cc->mode == MIGRATE_ASYNC) {
277 if (!spin_trylock_irqsave(lock, *flags)) {
278 cc->contended = COMPACT_CONTENDED_LOCK;
282 spin_lock_irqsave(lock, *flags);
289 * Compaction requires the taking of some coarse locks that are potentially
290 * very heavily contended. The lock should be periodically unlocked to avoid
291 * having disabled IRQs for a long time, even when there is nobody waiting on
292 * the lock. It might also be that allowing the IRQs will result in
293 * need_resched() becoming true. If scheduling is needed, async compaction
294 * aborts. Sync compaction schedules.
295 * Either compaction type will also abort if a fatal signal is pending.
296 * In either case if the lock was locked, it is dropped and not regained.
298 * Returns true if compaction should abort due to fatal signal pending, or
299 * async compaction due to need_resched()
300 * Returns false when compaction can continue (sync compaction might have
303 static bool compact_unlock_should_abort(spinlock_t *lock,
304 unsigned long flags, bool *locked, struct compact_control *cc)
307 spin_unlock_irqrestore(lock, flags);
311 if (fatal_signal_pending(current)) {
312 cc->contended = COMPACT_CONTENDED_SCHED;
316 if (need_resched()) {
317 if (cc->mode == MIGRATE_ASYNC) {
318 cc->contended = COMPACT_CONTENDED_SCHED;
328 * Aside from avoiding lock contention, compaction also periodically checks
329 * need_resched() and either schedules in sync compaction or aborts async
330 * compaction. This is similar to what compact_unlock_should_abort() does, but
331 * is used where no lock is concerned.
333 * Returns false when no scheduling was needed, or sync compaction scheduled.
334 * Returns true when async compaction should abort.
336 static inline bool compact_should_abort(struct compact_control *cc)
338 /* async compaction aborts if contended */
339 if (need_resched()) {
340 if (cc->mode == MIGRATE_ASYNC) {
341 cc->contended = COMPACT_CONTENDED_SCHED;
352 * Isolate free pages onto a private freelist. If @strict is true, will abort
353 * returning 0 on any invalid PFNs or non-free pages inside of the pageblock
354 * (even though it may still end up isolating some pages).
356 static unsigned long isolate_freepages_block(struct compact_control *cc,
357 unsigned long *start_pfn,
358 unsigned long end_pfn,
359 struct list_head *freelist,
362 int nr_scanned = 0, total_isolated = 0;
363 struct page *cursor, *valid_page = NULL;
364 unsigned long flags = 0;
366 unsigned long blockpfn = *start_pfn;
368 cursor = pfn_to_page(blockpfn);
370 /* Isolate free pages. */
371 for (; blockpfn < end_pfn; blockpfn++, cursor++) {
373 struct page *page = cursor;
376 * Periodically drop the lock (if held) regardless of its
377 * contention, to give chance to IRQs. Abort if fatal signal
378 * pending or async compaction detects need_resched()
380 if (!(blockpfn % SWAP_CLUSTER_MAX)
381 && compact_unlock_should_abort(&cc->zone->lock, flags,
386 if (!pfn_valid_within(blockpfn))
393 * For compound pages such as THP and hugetlbfs, we can save
394 * potentially a lot of iterations if we skip them at once.
395 * The check is racy, but we can consider only valid values
396 * and the only danger is skipping too much.
398 if (PageCompound(page)) {
399 unsigned int comp_order = compound_order(page);
401 if (likely(comp_order < MAX_ORDER)) {
402 blockpfn += (1UL << comp_order) - 1;
403 cursor += (1UL << comp_order) - 1;
409 if (!PageBuddy(page))
413 * If we already hold the lock, we can skip some rechecking.
414 * Note that if we hold the lock now, checked_pageblock was
415 * already set in some previous iteration (or strict is true),
416 * so it is correct to skip the suitable migration target
421 * The zone lock must be held to isolate freepages.
422 * Unfortunately this is a very coarse lock and can be
423 * heavily contended if there are parallel allocations
424 * or parallel compactions. For async compaction do not
425 * spin on the lock and we acquire the lock as late as
428 locked = compact_trylock_irqsave(&cc->zone->lock,
433 /* Recheck this is a buddy page under lock */
434 if (!PageBuddy(page))
438 /* Found a free page, break it into order-0 pages */
439 isolated = split_free_page(page);
440 total_isolated += isolated;
441 for (i = 0; i < isolated; i++) {
442 list_add(&page->lru, freelist);
446 /* If a page was split, advance to the end of it */
448 cc->nr_freepages += isolated;
450 cc->nr_migratepages <= cc->nr_freepages) {
451 blockpfn += isolated;
455 blockpfn += isolated - 1;
456 cursor += isolated - 1;
469 * There is a tiny chance that we have read bogus compound_order(),
470 * so be careful to not go outside of the pageblock.
472 if (unlikely(blockpfn > end_pfn))
475 trace_mm_compaction_isolate_freepages(*start_pfn, blockpfn,
476 nr_scanned, total_isolated);
478 /* Record how far we have got within the block */
479 *start_pfn = blockpfn;
482 * If strict isolation is requested by CMA then check that all the
483 * pages requested were isolated. If there were any failures, 0 is
484 * returned and CMA will fail.
486 if (strict && blockpfn < end_pfn)
490 spin_unlock_irqrestore(&cc->zone->lock, flags);
492 /* Update the pageblock-skip if the whole pageblock was scanned */
493 if (blockpfn == end_pfn)
494 update_pageblock_skip(cc, valid_page, total_isolated, false);
496 count_compact_events(COMPACTFREE_SCANNED, nr_scanned);
498 count_compact_events(COMPACTISOLATED, total_isolated);
499 return total_isolated;
503 * isolate_freepages_range() - isolate free pages.
504 * @start_pfn: The first PFN to start isolating.
505 * @end_pfn: The one-past-last PFN.
507 * Non-free pages, invalid PFNs, or zone boundaries within the
508 * [start_pfn, end_pfn) range are considered errors, cause function to
509 * undo its actions and return zero.
511 * Otherwise, function returns one-past-the-last PFN of isolated page
512 * (which may be greater then end_pfn if end fell in a middle of
516 isolate_freepages_range(struct compact_control *cc,
517 unsigned long start_pfn, unsigned long end_pfn)
519 unsigned long isolated, pfn, block_start_pfn, block_end_pfn;
523 block_start_pfn = pfn & ~(pageblock_nr_pages - 1);
524 if (block_start_pfn < cc->zone->zone_start_pfn)
525 block_start_pfn = cc->zone->zone_start_pfn;
526 block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
528 for (; pfn < end_pfn; pfn += isolated,
529 block_start_pfn = block_end_pfn,
530 block_end_pfn += pageblock_nr_pages) {
531 /* Protect pfn from changing by isolate_freepages_block */
532 unsigned long isolate_start_pfn = pfn;
534 block_end_pfn = min(block_end_pfn, end_pfn);
537 * pfn could pass the block_end_pfn if isolated freepage
538 * is more than pageblock order. In this case, we adjust
539 * scanning range to right one.
541 if (pfn >= block_end_pfn) {
542 block_start_pfn = pfn & ~(pageblock_nr_pages - 1);
543 block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
544 block_end_pfn = min(block_end_pfn, end_pfn);
547 if (!pageblock_pfn_to_page(block_start_pfn,
548 block_end_pfn, cc->zone))
551 isolated = isolate_freepages_block(cc, &isolate_start_pfn,
552 block_end_pfn, &freelist, true);
555 * In strict mode, isolate_freepages_block() returns 0 if
556 * there are any holes in the block (ie. invalid PFNs or
563 * If we managed to isolate pages, it is always (1 << n) *
564 * pageblock_nr_pages for some non-negative n. (Max order
565 * page may span two pageblocks).
569 /* split_free_page does not map the pages */
570 map_pages(&freelist);
573 /* Loop terminated early, cleanup. */
574 release_freepages(&freelist);
578 /* We don't use freelists for anything. */
582 /* Update the number of anon and file isolated pages in the zone */
583 static void acct_isolated(struct zone *zone, struct compact_control *cc)
586 unsigned int count[2] = { 0, };
588 if (list_empty(&cc->migratepages))
591 list_for_each_entry(page, &cc->migratepages, lru)
592 count[!!page_is_file_cache(page)]++;
594 mod_zone_page_state(zone, NR_ISOLATED_ANON, count[0]);
595 mod_zone_page_state(zone, NR_ISOLATED_FILE, count[1]);
598 /* Similar to reclaim, but different enough that they don't share logic */
599 static bool too_many_isolated(struct zone *zone)
601 unsigned long active, inactive, isolated;
603 inactive = zone_page_state(zone, NR_INACTIVE_FILE) +
604 zone_page_state(zone, NR_INACTIVE_ANON);
605 active = zone_page_state(zone, NR_ACTIVE_FILE) +
606 zone_page_state(zone, NR_ACTIVE_ANON);
607 isolated = zone_page_state(zone, NR_ISOLATED_FILE) +
608 zone_page_state(zone, NR_ISOLATED_ANON);
610 return isolated > (inactive + active) / 2;
614 * isolate_migratepages_block() - isolate all migrate-able pages within
616 * @cc: Compaction control structure.
617 * @low_pfn: The first PFN to isolate
618 * @end_pfn: The one-past-the-last PFN to isolate, within same pageblock
619 * @isolate_mode: Isolation mode to be used.
621 * Isolate all pages that can be migrated from the range specified by
622 * [low_pfn, end_pfn). The range is expected to be within same pageblock.
623 * Returns zero if there is a fatal signal pending, otherwise PFN of the
624 * first page that was not scanned (which may be both less, equal to or more
627 * The pages are isolated on cc->migratepages list (not required to be empty),
628 * and cc->nr_migratepages is updated accordingly. The cc->migrate_pfn field
629 * is neither read nor updated.
632 isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
633 unsigned long end_pfn, isolate_mode_t isolate_mode)
635 struct zone *zone = cc->zone;
636 unsigned long nr_scanned = 0, nr_isolated = 0;
637 struct list_head *migratelist = &cc->migratepages;
638 struct lruvec *lruvec;
639 unsigned long flags = 0;
641 struct page *page = NULL, *valid_page = NULL;
642 unsigned long start_pfn = low_pfn;
645 * Ensure that there are not too many pages isolated from the LRU
646 * list by either parallel reclaimers or compaction. If there are,
647 * delay for some time until fewer pages are isolated
649 while (unlikely(too_many_isolated(zone))) {
650 /* async migration should just abort */
651 if (cc->mode == MIGRATE_ASYNC)
654 congestion_wait(BLK_RW_ASYNC, HZ/10);
656 if (fatal_signal_pending(current))
660 if (compact_should_abort(cc))
663 /* Time to isolate some pages for migration */
664 for (; low_pfn < end_pfn; low_pfn++) {
668 * Periodically drop the lock (if held) regardless of its
669 * contention, to give chance to IRQs. Abort async compaction
672 if (!(low_pfn % SWAP_CLUSTER_MAX)
673 && compact_unlock_should_abort(&zone->lru_lock, flags,
677 if (!pfn_valid_within(low_pfn))
681 page = pfn_to_page(low_pfn);
687 * Skip if free. We read page order here without zone lock
688 * which is generally unsafe, but the race window is small and
689 * the worst thing that can happen is that we skip some
690 * potential isolation targets.
692 if (PageBuddy(page)) {
693 unsigned long freepage_order = page_order_unsafe(page);
696 * Without lock, we cannot be sure that what we got is
697 * a valid page order. Consider only values in the
698 * valid order range to prevent low_pfn overflow.
700 if (freepage_order > 0 && freepage_order < MAX_ORDER)
701 low_pfn += (1UL << freepage_order) - 1;
706 * Check may be lockless but that's ok as we recheck later.
707 * It's possible to migrate LRU pages and balloon pages
708 * Skip any other type of page
710 is_lru = PageLRU(page);
712 if (unlikely(balloon_page_movable(page))) {
713 if (balloon_page_isolate(page)) {
714 /* Successfully isolated */
715 goto isolate_success;
721 * Regardless of being on LRU, compound pages such as THP and
722 * hugetlbfs are not to be compacted. We can potentially save
723 * a lot of iterations if we skip them at once. The check is
724 * racy, but we can consider only valid values and the only
725 * danger is skipping too much.
727 if (PageCompound(page)) {
728 unsigned int comp_order = compound_order(page);
730 if (likely(comp_order < MAX_ORDER))
731 low_pfn += (1UL << comp_order) - 1;
740 * Migration will fail if an anonymous page is pinned in memory,
741 * so avoid taking lru_lock and isolating it unnecessarily in an
742 * admittedly racy check.
744 if (!page_mapping(page) &&
745 page_count(page) > page_mapcount(page))
748 /* If we already hold the lock, we can skip some rechecking */
750 locked = compact_trylock_irqsave(&zone->lru_lock,
755 /* Recheck PageLRU and PageCompound under lock */
760 * Page become compound since the non-locked check,
761 * and it's on LRU. It can only be a THP so the order
762 * is safe to read and it's 0 for tail pages.
764 if (unlikely(PageCompound(page))) {
765 low_pfn += (1UL << compound_order(page)) - 1;
770 lruvec = mem_cgroup_page_lruvec(page, zone);
772 /* Try isolate the page */
773 if (__isolate_lru_page(page, isolate_mode) != 0)
776 VM_BUG_ON_PAGE(PageCompound(page), page);
778 /* Successfully isolated */
779 del_page_from_lru_list(page, lruvec, page_lru(page));
782 list_add(&page->lru, migratelist);
783 cc->nr_migratepages++;
786 /* Avoid isolating too much */
787 if (cc->nr_migratepages == COMPACT_CLUSTER_MAX) {
794 * The PageBuddy() check could have potentially brought us outside
795 * the range to be scanned.
797 if (unlikely(low_pfn > end_pfn))
801 spin_unlock_irqrestore(&zone->lru_lock, flags);
804 * Update the pageblock-skip information and cached scanner pfn,
805 * if the whole pageblock was scanned without isolating any page.
807 if (low_pfn == end_pfn)
808 update_pageblock_skip(cc, valid_page, nr_isolated, true);
810 trace_mm_compaction_isolate_migratepages(start_pfn, low_pfn,
811 nr_scanned, nr_isolated);
813 count_compact_events(COMPACTMIGRATE_SCANNED, nr_scanned);
815 count_compact_events(COMPACTISOLATED, nr_isolated);
821 * isolate_migratepages_range() - isolate migrate-able pages in a PFN range
822 * @cc: Compaction control structure.
823 * @start_pfn: The first PFN to start isolating.
824 * @end_pfn: The one-past-last PFN.
826 * Returns zero if isolation fails fatally due to e.g. pending signal.
827 * Otherwise, function returns one-past-the-last PFN of isolated page
828 * (which may be greater than end_pfn if end fell in a middle of a THP page).
831 isolate_migratepages_range(struct compact_control *cc, unsigned long start_pfn,
832 unsigned long end_pfn)
834 unsigned long pfn, block_start_pfn, block_end_pfn;
836 /* Scan block by block. First and last block may be incomplete */
838 block_start_pfn = pfn & ~(pageblock_nr_pages - 1);
839 if (block_start_pfn < cc->zone->zone_start_pfn)
840 block_start_pfn = cc->zone->zone_start_pfn;
841 block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
843 for (; pfn < end_pfn; pfn = block_end_pfn,
844 block_start_pfn = block_end_pfn,
845 block_end_pfn += pageblock_nr_pages) {
847 block_end_pfn = min(block_end_pfn, end_pfn);
849 if (!pageblock_pfn_to_page(block_start_pfn,
850 block_end_pfn, cc->zone))
853 pfn = isolate_migratepages_block(cc, pfn, block_end_pfn,
854 ISOLATE_UNEVICTABLE);
857 * In case of fatal failure, release everything that might
858 * have been isolated in the previous iteration, and signal
859 * the failure back to caller.
862 putback_movable_pages(&cc->migratepages);
863 cc->nr_migratepages = 0;
867 if (cc->nr_migratepages == COMPACT_CLUSTER_MAX)
870 acct_isolated(cc->zone, cc);
875 #endif /* CONFIG_COMPACTION || CONFIG_CMA */
876 #ifdef CONFIG_COMPACTION
878 /* Returns true if the page is within a block suitable for migration to */
879 static bool suitable_migration_target(struct page *page)
881 /* If the page is a large free page, then disallow migration */
882 if (PageBuddy(page)) {
884 * We are checking page_order without zone->lock taken. But
885 * the only small danger is that we skip a potentially suitable
886 * pageblock, so it's not worth to check order for valid range.
888 if (page_order_unsafe(page) >= pageblock_order)
892 /* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */
893 if (migrate_async_suitable(get_pageblock_migratetype(page)))
896 /* Otherwise skip the block */
901 * Test whether the free scanner has reached the same or lower pageblock than
902 * the migration scanner, and compaction should thus terminate.
904 static inline bool compact_scanners_met(struct compact_control *cc)
906 return (cc->free_pfn >> pageblock_order)
907 <= (cc->migrate_pfn >> pageblock_order);
911 * Based on information in the current compact_control, find blocks
912 * suitable for isolating free pages from and then isolate them.
914 static void isolate_freepages(struct compact_control *cc)
916 struct zone *zone = cc->zone;
918 unsigned long block_start_pfn; /* start of current pageblock */
919 unsigned long isolate_start_pfn; /* exact pfn we start at */
920 unsigned long block_end_pfn; /* end of current pageblock */
921 unsigned long low_pfn; /* lowest pfn scanner is able to scan */
922 struct list_head *freelist = &cc->freepages;
925 * Initialise the free scanner. The starting point is where we last
926 * successfully isolated from, zone-cached value, or the end of the
927 * zone when isolating for the first time. For looping we also need
928 * this pfn aligned down to the pageblock boundary, because we do
929 * block_start_pfn -= pageblock_nr_pages in the for loop.
930 * For ending point, take care when isolating in last pageblock of a
931 * a zone which ends in the middle of a pageblock.
932 * The low boundary is the end of the pageblock the migration scanner
935 isolate_start_pfn = cc->free_pfn;
936 block_start_pfn = cc->free_pfn & ~(pageblock_nr_pages-1);
937 block_end_pfn = min(block_start_pfn + pageblock_nr_pages,
939 low_pfn = ALIGN(cc->migrate_pfn + 1, pageblock_nr_pages);
942 * Isolate free pages until enough are available to migrate the
943 * pages on cc->migratepages. We stop searching if the migrate
944 * and free page scanners meet or enough free pages are isolated.
946 for (; block_start_pfn >= low_pfn;
947 block_end_pfn = block_start_pfn,
948 block_start_pfn -= pageblock_nr_pages,
949 isolate_start_pfn = block_start_pfn) {
952 * This can iterate a massively long zone without finding any
953 * suitable migration targets, so periodically check if we need
954 * to schedule, or even abort async compaction.
956 if (!(block_start_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages))
957 && compact_should_abort(cc))
960 page = pageblock_pfn_to_page(block_start_pfn, block_end_pfn,
965 /* Check the block is suitable for migration */
966 if (!suitable_migration_target(page))
969 /* If isolation recently failed, do not retry */
970 if (!isolation_suitable(cc, page))
973 /* Found a block suitable for isolating free pages from. */
974 isolate_freepages_block(cc, &isolate_start_pfn,
975 block_end_pfn, freelist, false);
978 * If we isolated enough freepages, or aborted due to async
979 * compaction being contended, terminate the loop.
980 * Remember where the free scanner should restart next time,
981 * which is where isolate_freepages_block() left off.
982 * But if it scanned the whole pageblock, isolate_start_pfn
983 * now points at block_end_pfn, which is the start of the next
985 * In that case we will however want to restart at the start
986 * of the previous pageblock.
988 if ((cc->nr_freepages >= cc->nr_migratepages)
990 if (isolate_start_pfn >= block_end_pfn)
992 block_start_pfn - pageblock_nr_pages;
996 * isolate_freepages_block() should not terminate
997 * prematurely unless contended, or isolated enough
999 VM_BUG_ON(isolate_start_pfn < block_end_pfn);
1003 /* split_free_page does not map the pages */
1004 map_pages(freelist);
1007 * Record where the free scanner will restart next time. Either we
1008 * broke from the loop and set isolate_start_pfn based on the last
1009 * call to isolate_freepages_block(), or we met the migration scanner
1010 * and the loop terminated due to isolate_start_pfn < low_pfn
1012 cc->free_pfn = isolate_start_pfn;
1016 * This is a migrate-callback that "allocates" freepages by taking pages
1017 * from the isolated freelists in the block we are migrating to.
1019 static struct page *compaction_alloc(struct page *migratepage,
1023 struct compact_control *cc = (struct compact_control *)data;
1024 struct page *freepage;
1027 * Isolate free pages if necessary, and if we are not aborting due to
1030 if (list_empty(&cc->freepages)) {
1032 isolate_freepages(cc);
1034 if (list_empty(&cc->freepages))
1038 freepage = list_entry(cc->freepages.next, struct page, lru);
1039 list_del(&freepage->lru);
1046 * This is a migrate-callback that "frees" freepages back to the isolated
1047 * freelist. All pages on the freelist are from the same zone, so there is no
1048 * special handling needed for NUMA.
1050 static void compaction_free(struct page *page, unsigned long data)
1052 struct compact_control *cc = (struct compact_control *)data;
1054 list_add(&page->lru, &cc->freepages);
1058 /* possible outcome of isolate_migratepages */
1060 ISOLATE_ABORT, /* Abort compaction now */
1061 ISOLATE_NONE, /* No pages isolated, continue scanning */
1062 ISOLATE_SUCCESS, /* Pages isolated, migrate */
1063 } isolate_migrate_t;
1066 * Allow userspace to control policy on scanning the unevictable LRU for
1067 * compactable pages.
1069 int sysctl_compact_unevictable_allowed __read_mostly = 1;
1072 * Isolate all pages that can be migrated from the first suitable block,
1073 * starting at the block pointed to by the migrate scanner pfn within
1076 static isolate_migrate_t isolate_migratepages(struct zone *zone,
1077 struct compact_control *cc)
1079 unsigned long block_start_pfn;
1080 unsigned long block_end_pfn;
1081 unsigned long low_pfn;
1082 unsigned long isolate_start_pfn;
1084 const isolate_mode_t isolate_mode =
1085 (sysctl_compact_unevictable_allowed ? ISOLATE_UNEVICTABLE : 0) |
1086 (cc->mode == MIGRATE_ASYNC ? ISOLATE_ASYNC_MIGRATE : 0);
1089 * Start at where we last stopped, or beginning of the zone as
1090 * initialized by compact_zone()
1092 low_pfn = cc->migrate_pfn;
1093 block_start_pfn = cc->migrate_pfn & ~(pageblock_nr_pages - 1);
1094 if (block_start_pfn < zone->zone_start_pfn)
1095 block_start_pfn = zone->zone_start_pfn;
1097 /* Only scan within a pageblock boundary */
1098 block_end_pfn = ALIGN(low_pfn + 1, pageblock_nr_pages);
1101 * Iterate over whole pageblocks until we find the first suitable.
1102 * Do not cross the free scanner.
1104 for (; block_end_pfn <= cc->free_pfn;
1105 low_pfn = block_end_pfn,
1106 block_start_pfn = block_end_pfn,
1107 block_end_pfn += pageblock_nr_pages) {
1110 * This can potentially iterate a massively long zone with
1111 * many pageblocks unsuitable, so periodically check if we
1112 * need to schedule, or even abort async compaction.
1114 if (!(low_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages))
1115 && compact_should_abort(cc))
1118 page = pageblock_pfn_to_page(block_start_pfn, block_end_pfn,
1123 /* If isolation recently failed, do not retry */
1124 if (!isolation_suitable(cc, page))
1128 * For async compaction, also only scan in MOVABLE blocks.
1129 * Async compaction is optimistic to see if the minimum amount
1130 * of work satisfies the allocation.
1132 if (cc->mode == MIGRATE_ASYNC &&
1133 !migrate_async_suitable(get_pageblock_migratetype(page)))
1136 /* Perform the isolation */
1137 isolate_start_pfn = low_pfn;
1138 low_pfn = isolate_migratepages_block(cc, low_pfn,
1139 block_end_pfn, isolate_mode);
1141 if (!low_pfn || cc->contended) {
1142 acct_isolated(zone, cc);
1143 return ISOLATE_ABORT;
1147 * Record where we could have freed pages by migration and not
1148 * yet flushed them to buddy allocator.
1149 * - this is the lowest page that could have been isolated and
1150 * then freed by migration.
1152 if (cc->nr_migratepages && !cc->last_migrated_pfn)
1153 cc->last_migrated_pfn = isolate_start_pfn;
1156 * Either we isolated something and proceed with migration. Or
1157 * we failed and compact_zone should decide if we should
1163 acct_isolated(zone, cc);
1164 /* Record where migration scanner will be restarted. */
1165 cc->migrate_pfn = low_pfn;
1167 return cc->nr_migratepages ? ISOLATE_SUCCESS : ISOLATE_NONE;
1171 * order == -1 is expected when compacting via
1172 * /proc/sys/vm/compact_memory
1174 static inline bool is_via_compact_memory(int order)
1179 static int __compact_finished(struct zone *zone, struct compact_control *cc,
1180 const int migratetype)
1183 unsigned long watermark;
1185 if (cc->contended || fatal_signal_pending(current))
1186 return COMPACT_CONTENDED;
1188 /* Compaction run completes if the migrate and free scanner meet */
1189 if (compact_scanners_met(cc)) {
1190 /* Let the next compaction start anew. */
1191 reset_cached_positions(zone);
1194 * Mark that the PG_migrate_skip information should be cleared
1195 * by kswapd when it goes to sleep. kcompactd does not set the
1196 * flag itself as the decision to be clear should be directly
1197 * based on an allocation request.
1199 if (cc->direct_compaction)
1200 zone->compact_blockskip_flush = true;
1202 return COMPACT_COMPLETE;
1205 if (is_via_compact_memory(cc->order))
1206 return COMPACT_CONTINUE;
1208 /* Compaction run is not finished if the watermark is not met */
1209 watermark = low_wmark_pages(zone);
1211 if (!zone_watermark_ok(zone, cc->order, watermark, cc->classzone_idx,
1213 return COMPACT_CONTINUE;
1215 /* Direct compactor: Is a suitable page free? */
1216 for (order = cc->order; order < MAX_ORDER; order++) {
1217 struct free_area *area = &zone->free_area[order];
1220 /* Job done if page is free of the right migratetype */
1221 if (!list_empty(&area->free_list[migratetype]))
1222 return COMPACT_PARTIAL;
1225 /* MIGRATE_MOVABLE can fallback on MIGRATE_CMA */
1226 if (migratetype == MIGRATE_MOVABLE &&
1227 !list_empty(&area->free_list[MIGRATE_CMA]))
1228 return COMPACT_PARTIAL;
1231 * Job done if allocation would steal freepages from
1232 * other migratetype buddy lists.
1234 if (find_suitable_fallback(area, order, migratetype,
1235 true, &can_steal) != -1)
1236 return COMPACT_PARTIAL;
1239 return COMPACT_NO_SUITABLE_PAGE;
1242 static int compact_finished(struct zone *zone, struct compact_control *cc,
1243 const int migratetype)
1247 ret = __compact_finished(zone, cc, migratetype);
1248 trace_mm_compaction_finished(zone, cc->order, ret);
1249 if (ret == COMPACT_NO_SUITABLE_PAGE)
1250 ret = COMPACT_CONTINUE;
1256 * compaction_suitable: Is this suitable to run compaction on this zone now?
1258 * COMPACT_SKIPPED - If there are too few free pages for compaction
1259 * COMPACT_PARTIAL - If the allocation would succeed without compaction
1260 * COMPACT_CONTINUE - If compaction should run now
1262 static unsigned long __compaction_suitable(struct zone *zone, int order,
1263 int alloc_flags, int classzone_idx)
1266 unsigned long watermark;
1268 if (is_via_compact_memory(order))
1269 return COMPACT_CONTINUE;
1271 watermark = low_wmark_pages(zone);
1273 * If watermarks for high-order allocation are already met, there
1274 * should be no need for compaction at all.
1276 if (zone_watermark_ok(zone, order, watermark, classzone_idx,
1278 return COMPACT_PARTIAL;
1281 * Watermarks for order-0 must be met for compaction. Note the 2UL.
1282 * This is because during migration, copies of pages need to be
1283 * allocated and for a short time, the footprint is higher
1285 watermark += (2UL << order);
1286 if (!zone_watermark_ok(zone, 0, watermark, classzone_idx, alloc_flags))
1287 return COMPACT_SKIPPED;
1290 * fragmentation index determines if allocation failures are due to
1291 * low memory or external fragmentation
1293 * index of -1000 would imply allocations might succeed depending on
1294 * watermarks, but we already failed the high-order watermark check
1295 * index towards 0 implies failure is due to lack of memory
1296 * index towards 1000 implies failure is due to fragmentation
1298 * Only compact if a failure would be due to fragmentation.
1300 fragindex = fragmentation_index(zone, order);
1301 if (fragindex >= 0 && fragindex <= sysctl_extfrag_threshold)
1302 return COMPACT_NOT_SUITABLE_ZONE;
1304 return COMPACT_CONTINUE;
1307 unsigned long compaction_suitable(struct zone *zone, int order,
1308 int alloc_flags, int classzone_idx)
1312 ret = __compaction_suitable(zone, order, alloc_flags, classzone_idx);
1313 trace_mm_compaction_suitable(zone, order, ret);
1314 if (ret == COMPACT_NOT_SUITABLE_ZONE)
1315 ret = COMPACT_SKIPPED;
1320 static int compact_zone(struct zone *zone, struct compact_control *cc)
1323 unsigned long start_pfn = zone->zone_start_pfn;
1324 unsigned long end_pfn = zone_end_pfn(zone);
1325 const int migratetype = gfpflags_to_migratetype(cc->gfp_mask);
1326 const bool sync = cc->mode != MIGRATE_ASYNC;
1328 ret = compaction_suitable(zone, cc->order, cc->alloc_flags,
1331 case COMPACT_PARTIAL:
1332 case COMPACT_SKIPPED:
1333 /* Compaction is likely to fail */
1335 case COMPACT_CONTINUE:
1336 /* Fall through to compaction */
1341 * Clear pageblock skip if there were failures recently and compaction
1342 * is about to be retried after being deferred.
1344 if (compaction_restarting(zone, cc->order))
1345 __reset_isolation_suitable(zone);
1348 * Setup to move all movable pages to the end of the zone. Used cached
1349 * information on where the scanners should start but check that it
1350 * is initialised by ensuring the values are within zone boundaries.
1352 cc->migrate_pfn = zone->compact_cached_migrate_pfn[sync];
1353 cc->free_pfn = zone->compact_cached_free_pfn;
1354 if (cc->free_pfn < start_pfn || cc->free_pfn >= end_pfn) {
1355 cc->free_pfn = round_down(end_pfn - 1, pageblock_nr_pages);
1356 zone->compact_cached_free_pfn = cc->free_pfn;
1358 if (cc->migrate_pfn < start_pfn || cc->migrate_pfn >= end_pfn) {
1359 cc->migrate_pfn = start_pfn;
1360 zone->compact_cached_migrate_pfn[0] = cc->migrate_pfn;
1361 zone->compact_cached_migrate_pfn[1] = cc->migrate_pfn;
1363 cc->last_migrated_pfn = 0;
1365 trace_mm_compaction_begin(start_pfn, cc->migrate_pfn,
1366 cc->free_pfn, end_pfn, sync);
1368 migrate_prep_local();
1370 while ((ret = compact_finished(zone, cc, migratetype)) ==
1374 switch (isolate_migratepages(zone, cc)) {
1376 ret = COMPACT_CONTENDED;
1377 putback_movable_pages(&cc->migratepages);
1378 cc->nr_migratepages = 0;
1382 * We haven't isolated and migrated anything, but
1383 * there might still be unflushed migrations from
1384 * previous cc->order aligned block.
1387 case ISOLATE_SUCCESS:
1391 err = migrate_pages(&cc->migratepages, compaction_alloc,
1392 compaction_free, (unsigned long)cc, cc->mode,
1395 trace_mm_compaction_migratepages(cc->nr_migratepages, err,
1398 /* All pages were either migrated or will be released */
1399 cc->nr_migratepages = 0;
1401 putback_movable_pages(&cc->migratepages);
1403 * migrate_pages() may return -ENOMEM when scanners meet
1404 * and we want compact_finished() to detect it
1406 if (err == -ENOMEM && !compact_scanners_met(cc)) {
1407 ret = COMPACT_CONTENDED;
1414 * Has the migration scanner moved away from the previous
1415 * cc->order aligned block where we migrated from? If yes,
1416 * flush the pages that were freed, so that they can merge and
1417 * compact_finished() can detect immediately if allocation
1420 if (cc->order > 0 && cc->last_migrated_pfn) {
1422 unsigned long current_block_start =
1423 cc->migrate_pfn & ~((1UL << cc->order) - 1);
1425 if (cc->last_migrated_pfn < current_block_start) {
1427 lru_add_drain_cpu(cpu);
1428 drain_local_pages(zone);
1430 /* No more flushing until we migrate again */
1431 cc->last_migrated_pfn = 0;
1439 * Release free pages and update where the free scanner should restart,
1440 * so we don't leave any returned pages behind in the next attempt.
1442 if (cc->nr_freepages > 0) {
1443 unsigned long free_pfn = release_freepages(&cc->freepages);
1445 cc->nr_freepages = 0;
1446 VM_BUG_ON(free_pfn == 0);
1447 /* The cached pfn is always the first in a pageblock */
1448 free_pfn &= ~(pageblock_nr_pages-1);
1450 * Only go back, not forward. The cached pfn might have been
1451 * already reset to zone end in compact_finished()
1453 if (free_pfn > zone->compact_cached_free_pfn)
1454 zone->compact_cached_free_pfn = free_pfn;
1457 trace_mm_compaction_end(start_pfn, cc->migrate_pfn,
1458 cc->free_pfn, end_pfn, sync, ret);
1460 if (ret == COMPACT_CONTENDED)
1461 ret = COMPACT_PARTIAL;
1466 static unsigned long compact_zone_order(struct zone *zone, int order,
1467 gfp_t gfp_mask, enum migrate_mode mode, int *contended,
1468 int alloc_flags, int classzone_idx)
1471 struct compact_control cc = {
1473 .nr_migratepages = 0,
1475 .gfp_mask = gfp_mask,
1478 .alloc_flags = alloc_flags,
1479 .classzone_idx = classzone_idx,
1480 .direct_compaction = true,
1482 INIT_LIST_HEAD(&cc.freepages);
1483 INIT_LIST_HEAD(&cc.migratepages);
1485 ret = compact_zone(zone, &cc);
1487 VM_BUG_ON(!list_empty(&cc.freepages));
1488 VM_BUG_ON(!list_empty(&cc.migratepages));
1490 *contended = cc.contended;
1494 int sysctl_extfrag_threshold = 500;
1497 * try_to_compact_pages - Direct compact to satisfy a high-order allocation
1498 * @gfp_mask: The GFP mask of the current allocation
1499 * @order: The order of the current allocation
1500 * @alloc_flags: The allocation flags of the current allocation
1501 * @ac: The context of current allocation
1502 * @mode: The migration mode for async, sync light, or sync migration
1503 * @contended: Return value that determines if compaction was aborted due to
1504 * need_resched() or lock contention
1506 * This is the main entry point for direct page compaction.
1508 unsigned long try_to_compact_pages(gfp_t gfp_mask, unsigned int order,
1509 int alloc_flags, const struct alloc_context *ac,
1510 enum migrate_mode mode, int *contended)
1512 int may_enter_fs = gfp_mask & __GFP_FS;
1513 int may_perform_io = gfp_mask & __GFP_IO;
1516 int rc = COMPACT_DEFERRED;
1517 int all_zones_contended = COMPACT_CONTENDED_LOCK; /* init for &= op */
1519 *contended = COMPACT_CONTENDED_NONE;
1521 /* Check if the GFP flags allow compaction */
1522 if (!order || !may_enter_fs || !may_perform_io)
1523 return COMPACT_SKIPPED;
1525 trace_mm_compaction_try_to_compact_pages(order, gfp_mask, mode);
1527 /* Compact each zone in the list */
1528 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
1533 if (compaction_deferred(zone, order))
1536 status = compact_zone_order(zone, order, gfp_mask, mode,
1537 &zone_contended, alloc_flags,
1539 rc = max(status, rc);
1541 * It takes at least one zone that wasn't lock contended
1542 * to clear all_zones_contended.
1544 all_zones_contended &= zone_contended;
1546 /* If a normal allocation would succeed, stop compacting */
1547 if (zone_watermark_ok(zone, order, low_wmark_pages(zone),
1548 ac->classzone_idx, alloc_flags)) {
1550 * We think the allocation will succeed in this zone,
1551 * but it is not certain, hence the false. The caller
1552 * will repeat this with true if allocation indeed
1553 * succeeds in this zone.
1555 compaction_defer_reset(zone, order, false);
1557 * It is possible that async compaction aborted due to
1558 * need_resched() and the watermarks were ok thanks to
1559 * somebody else freeing memory. The allocation can
1560 * however still fail so we better signal the
1561 * need_resched() contention anyway (this will not
1562 * prevent the allocation attempt).
1564 if (zone_contended == COMPACT_CONTENDED_SCHED)
1565 *contended = COMPACT_CONTENDED_SCHED;
1570 if (mode != MIGRATE_ASYNC && status == COMPACT_COMPLETE) {
1572 * We think that allocation won't succeed in this zone
1573 * so we defer compaction there. If it ends up
1574 * succeeding after all, it will be reset.
1576 defer_compaction(zone, order);
1580 * We might have stopped compacting due to need_resched() in
1581 * async compaction, or due to a fatal signal detected. In that
1582 * case do not try further zones and signal need_resched()
1585 if ((zone_contended == COMPACT_CONTENDED_SCHED)
1586 || fatal_signal_pending(current)) {
1587 *contended = COMPACT_CONTENDED_SCHED;
1594 * We might not have tried all the zones, so be conservative
1595 * and assume they are not all lock contended.
1597 all_zones_contended = 0;
1602 * If at least one zone wasn't deferred or skipped, we report if all
1603 * zones that were tried were lock contended.
1605 if (rc > COMPACT_SKIPPED && all_zones_contended)
1606 *contended = COMPACT_CONTENDED_LOCK;
1612 /* Compact all zones within a node */
1613 static void __compact_pgdat(pg_data_t *pgdat, struct compact_control *cc)
1618 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
1620 zone = &pgdat->node_zones[zoneid];
1621 if (!populated_zone(zone))
1624 cc->nr_freepages = 0;
1625 cc->nr_migratepages = 0;
1627 INIT_LIST_HEAD(&cc->freepages);
1628 INIT_LIST_HEAD(&cc->migratepages);
1631 * When called via /proc/sys/vm/compact_memory
1632 * this makes sure we compact the whole zone regardless of
1633 * cached scanner positions.
1635 if (is_via_compact_memory(cc->order))
1636 __reset_isolation_suitable(zone);
1638 if (is_via_compact_memory(cc->order) ||
1639 !compaction_deferred(zone, cc->order))
1640 compact_zone(zone, cc);
1642 VM_BUG_ON(!list_empty(&cc->freepages));
1643 VM_BUG_ON(!list_empty(&cc->migratepages));
1645 if (is_via_compact_memory(cc->order))
1648 if (zone_watermark_ok(zone, cc->order,
1649 low_wmark_pages(zone), 0, 0))
1650 compaction_defer_reset(zone, cc->order, false);
1654 void compact_pgdat(pg_data_t *pgdat, int order)
1656 struct compact_control cc = {
1658 .mode = MIGRATE_ASYNC,
1664 __compact_pgdat(pgdat, &cc);
1667 static void compact_node(int nid)
1669 struct compact_control cc = {
1671 .mode = MIGRATE_SYNC,
1672 .ignore_skip_hint = true,
1675 __compact_pgdat(NODE_DATA(nid), &cc);
1678 /* Compact all nodes in the system */
1679 static void compact_nodes(void)
1683 /* Flush pending updates to the LRU lists */
1684 lru_add_drain_all();
1686 for_each_online_node(nid)
1690 /* The written value is actually unused, all memory is compacted */
1691 int sysctl_compact_memory;
1694 * This is the entry point for compacting all nodes via
1695 * /proc/sys/vm/compact_memory
1697 int sysctl_compaction_handler(struct ctl_table *table, int write,
1698 void __user *buffer, size_t *length, loff_t *ppos)
1706 int sysctl_extfrag_handler(struct ctl_table *table, int write,
1707 void __user *buffer, size_t *length, loff_t *ppos)
1709 proc_dointvec_minmax(table, write, buffer, length, ppos);
1714 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
1715 static ssize_t sysfs_compact_node(struct device *dev,
1716 struct device_attribute *attr,
1717 const char *buf, size_t count)
1721 if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
1722 /* Flush pending updates to the LRU lists */
1723 lru_add_drain_all();
1730 static DEVICE_ATTR(compact, S_IWUSR, NULL, sysfs_compact_node);
1732 int compaction_register_node(struct node *node)
1734 return device_create_file(&node->dev, &dev_attr_compact);
1737 void compaction_unregister_node(struct node *node)
1739 return device_remove_file(&node->dev, &dev_attr_compact);
1741 #endif /* CONFIG_SYSFS && CONFIG_NUMA */
1743 static inline bool kcompactd_work_requested(pg_data_t *pgdat)
1745 return pgdat->kcompactd_max_order > 0;
1748 static bool kcompactd_node_suitable(pg_data_t *pgdat)
1752 enum zone_type classzone_idx = pgdat->kcompactd_classzone_idx;
1754 for (zoneid = 0; zoneid < classzone_idx; zoneid++) {
1755 zone = &pgdat->node_zones[zoneid];
1757 if (!populated_zone(zone))
1760 if (compaction_suitable(zone, pgdat->kcompactd_max_order, 0,
1761 classzone_idx) == COMPACT_CONTINUE)
1768 static void kcompactd_do_work(pg_data_t *pgdat)
1771 * With no special task, compact all zones so that a page of requested
1772 * order is allocatable.
1776 struct compact_control cc = {
1777 .order = pgdat->kcompactd_max_order,
1778 .classzone_idx = pgdat->kcompactd_classzone_idx,
1779 .mode = MIGRATE_SYNC_LIGHT,
1780 .ignore_skip_hint = true,
1783 bool success = false;
1785 trace_mm_compaction_kcompactd_wake(pgdat->node_id, cc.order,
1787 count_vm_event(KCOMPACTD_WAKE);
1789 for (zoneid = 0; zoneid < cc.classzone_idx; zoneid++) {
1792 zone = &pgdat->node_zones[zoneid];
1793 if (!populated_zone(zone))
1796 if (compaction_deferred(zone, cc.order))
1799 if (compaction_suitable(zone, cc.order, 0, zoneid) !=
1803 cc.nr_freepages = 0;
1804 cc.nr_migratepages = 0;
1806 INIT_LIST_HEAD(&cc.freepages);
1807 INIT_LIST_HEAD(&cc.migratepages);
1809 status = compact_zone(zone, &cc);
1811 if (zone_watermark_ok(zone, cc.order, low_wmark_pages(zone),
1812 cc.classzone_idx, 0)) {
1814 compaction_defer_reset(zone, cc.order, false);
1815 } else if (cc.mode != MIGRATE_ASYNC &&
1816 status == COMPACT_COMPLETE) {
1817 defer_compaction(zone, cc.order);
1820 VM_BUG_ON(!list_empty(&cc.freepages));
1821 VM_BUG_ON(!list_empty(&cc.migratepages));
1825 * Regardless of success, we are done until woken up next. But remember
1826 * the requested order/classzone_idx in case it was higher/tighter than
1829 if (pgdat->kcompactd_max_order <= cc.order)
1830 pgdat->kcompactd_max_order = 0;
1831 if (pgdat->classzone_idx >= cc.classzone_idx)
1832 pgdat->classzone_idx = pgdat->nr_zones - 1;
1835 void wakeup_kcompactd(pg_data_t *pgdat, int order, int classzone_idx)
1840 if (pgdat->kcompactd_max_order < order)
1841 pgdat->kcompactd_max_order = order;
1843 if (pgdat->kcompactd_classzone_idx > classzone_idx)
1844 pgdat->kcompactd_classzone_idx = classzone_idx;
1846 if (!waitqueue_active(&pgdat->kcompactd_wait))
1849 if (!kcompactd_node_suitable(pgdat))
1852 trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, order,
1854 wake_up_interruptible(&pgdat->kcompactd_wait);
1858 * The background compaction daemon, started as a kernel thread
1859 * from the init process.
1861 static int kcompactd(void *p)
1863 pg_data_t *pgdat = (pg_data_t*)p;
1864 struct task_struct *tsk = current;
1866 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1868 if (!cpumask_empty(cpumask))
1869 set_cpus_allowed_ptr(tsk, cpumask);
1873 pgdat->kcompactd_max_order = 0;
1874 pgdat->kcompactd_classzone_idx = pgdat->nr_zones - 1;
1876 while (!kthread_should_stop()) {
1877 trace_mm_compaction_kcompactd_sleep(pgdat->node_id);
1878 wait_event_freezable(pgdat->kcompactd_wait,
1879 kcompactd_work_requested(pgdat));
1881 kcompactd_do_work(pgdat);
1888 * This kcompactd start function will be called by init and node-hot-add.
1889 * On node-hot-add, kcompactd will moved to proper cpus if cpus are hot-added.
1891 int kcompactd_run(int nid)
1893 pg_data_t *pgdat = NODE_DATA(nid);
1896 if (pgdat->kcompactd)
1899 pgdat->kcompactd = kthread_run(kcompactd, pgdat, "kcompactd%d", nid);
1900 if (IS_ERR(pgdat->kcompactd)) {
1901 pr_err("Failed to start kcompactd on node %d\n", nid);
1902 ret = PTR_ERR(pgdat->kcompactd);
1903 pgdat->kcompactd = NULL;
1909 * Called by memory hotplug when all memory in a node is offlined. Caller must
1910 * hold mem_hotplug_begin/end().
1912 void kcompactd_stop(int nid)
1914 struct task_struct *kcompactd = NODE_DATA(nid)->kcompactd;
1917 kthread_stop(kcompactd);
1918 NODE_DATA(nid)->kcompactd = NULL;
1923 * It's optimal to keep kcompactd on the same CPUs as their memory, but
1924 * not required for correctness. So if the last cpu in a node goes
1925 * away, we get changed to run anywhere: as the first one comes back,
1926 * restore their cpu bindings.
1928 static int cpu_callback(struct notifier_block *nfb, unsigned long action,
1933 if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
1934 for_each_node_state(nid, N_MEMORY) {
1935 pg_data_t *pgdat = NODE_DATA(nid);
1936 const struct cpumask *mask;
1938 mask = cpumask_of_node(pgdat->node_id);
1940 if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
1941 /* One of our CPUs online: restore mask */
1942 set_cpus_allowed_ptr(pgdat->kcompactd, mask);
1948 static int __init kcompactd_init(void)
1952 for_each_node_state(nid, N_MEMORY)
1954 hotcpu_notifier(cpu_callback, 0);
1958 module_init(kcompactd_init)
1960 #endif /* CONFIG_COMPACTION */