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/swap.h>
11 #include <linux/migrate.h>
12 #include <linux/compaction.h>
13 #include <linux/mm_inline.h>
14 #include <linux/backing-dev.h>
15 #include <linux/sysctl.h>
16 #include <linux/sysfs.h>
19 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
21 #define CREATE_TRACE_POINTS
22 #include <trace/events/compaction.h>
24 static unsigned long release_freepages(struct list_head *freelist)
26 struct page *page, *next;
27 unsigned long count = 0;
29 list_for_each_entry_safe(page, next, freelist, lru) {
38 static void map_pages(struct list_head *list)
42 list_for_each_entry(page, list, lru) {
43 arch_alloc_page(page, 0);
44 kernel_map_pages(page, 1, 1);
49 * Isolate free pages onto a private freelist. Caller must hold zone->lock.
50 * If @strict is true, will abort returning 0 on any invalid PFNs or non-free
51 * pages inside of the pageblock (even though it may still end up isolating
54 static unsigned long isolate_freepages_block(unsigned long blockpfn,
55 unsigned long end_pfn,
56 struct list_head *freelist,
59 int nr_scanned = 0, total_isolated = 0;
62 cursor = pfn_to_page(blockpfn);
64 /* Isolate free pages. This assumes the block is valid */
65 for (; blockpfn < end_pfn; blockpfn++, cursor++) {
67 struct page *page = cursor;
69 if (!pfn_valid_within(blockpfn)) {
76 if (!PageBuddy(page)) {
82 /* Found a free page, break it into order-0 pages */
83 isolated = split_free_page(page);
84 if (!isolated && strict)
86 total_isolated += isolated;
87 for (i = 0; i < isolated; i++) {
88 list_add(&page->lru, freelist);
92 /* If a page was split, advance to the end of it */
94 blockpfn += isolated - 1;
95 cursor += isolated - 1;
99 trace_mm_compaction_isolate_freepages(nr_scanned, total_isolated);
100 return total_isolated;
104 * isolate_freepages_range() - isolate free pages.
105 * @start_pfn: The first PFN to start isolating.
106 * @end_pfn: The one-past-last PFN.
108 * Non-free pages, invalid PFNs, or zone boundaries within the
109 * [start_pfn, end_pfn) range are considered errors, cause function to
110 * undo its actions and return zero.
112 * Otherwise, function returns one-past-the-last PFN of isolated page
113 * (which may be greater then end_pfn if end fell in a middle of
117 isolate_freepages_range(unsigned long start_pfn, unsigned long end_pfn)
119 unsigned long isolated, pfn, block_end_pfn, flags;
120 struct zone *zone = NULL;
123 if (pfn_valid(start_pfn))
124 zone = page_zone(pfn_to_page(start_pfn));
126 for (pfn = start_pfn; pfn < end_pfn; pfn += isolated) {
127 if (!pfn_valid(pfn) || zone != page_zone(pfn_to_page(pfn)))
131 * On subsequent iterations ALIGN() is actually not needed,
132 * but we keep it that we not to complicate the code.
134 block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
135 block_end_pfn = min(block_end_pfn, end_pfn);
137 spin_lock_irqsave(&zone->lock, flags);
138 isolated = isolate_freepages_block(pfn, block_end_pfn,
140 spin_unlock_irqrestore(&zone->lock, flags);
143 * In strict mode, isolate_freepages_block() returns 0 if
144 * there are any holes in the block (ie. invalid PFNs or
151 * If we managed to isolate pages, it is always (1 << n) *
152 * pageblock_nr_pages for some non-negative n. (Max order
153 * page may span two pageblocks).
157 /* split_free_page does not map the pages */
158 map_pages(&freelist);
161 /* Loop terminated early, cleanup. */
162 release_freepages(&freelist);
166 /* We don't use freelists for anything. */
170 /* Update the number of anon and file isolated pages in the zone */
171 static void acct_isolated(struct zone *zone, struct compact_control *cc)
174 unsigned int count[2] = { 0, };
176 list_for_each_entry(page, &cc->migratepages, lru)
177 count[!!page_is_file_cache(page)]++;
179 __mod_zone_page_state(zone, NR_ISOLATED_ANON, count[0]);
180 __mod_zone_page_state(zone, NR_ISOLATED_FILE, count[1]);
183 /* Similar to reclaim, but different enough that they don't share logic */
184 static bool too_many_isolated(struct zone *zone)
186 unsigned long active, inactive, isolated;
188 inactive = zone_page_state(zone, NR_INACTIVE_FILE) +
189 zone_page_state(zone, NR_INACTIVE_ANON);
190 active = zone_page_state(zone, NR_ACTIVE_FILE) +
191 zone_page_state(zone, NR_ACTIVE_ANON);
192 isolated = zone_page_state(zone, NR_ISOLATED_FILE) +
193 zone_page_state(zone, NR_ISOLATED_ANON);
195 return isolated > (inactive + active) / 2;
199 * isolate_migratepages_range() - isolate all migrate-able pages in range.
200 * @zone: Zone pages are in.
201 * @cc: Compaction control structure.
202 * @low_pfn: The first PFN of the range.
203 * @end_pfn: The one-past-the-last PFN of the range.
205 * Isolate all pages that can be migrated from the range specified by
206 * [low_pfn, end_pfn). Returns zero if there is a fatal signal
207 * pending), otherwise PFN of the first page that was not scanned
208 * (which may be both less, equal to or more then end_pfn).
210 * Assumes that cc->migratepages is empty and cc->nr_migratepages is
213 * Apart from cc->migratepages and cc->nr_migratetypes this function
214 * does not modify any cc's fields, in particular it does not modify
215 * (or read for that matter) cc->migrate_pfn.
218 isolate_migratepages_range(struct zone *zone, struct compact_control *cc,
219 unsigned long low_pfn, unsigned long end_pfn)
221 unsigned long last_pageblock_nr = 0, pageblock_nr;
222 unsigned long nr_scanned = 0, nr_isolated = 0;
223 struct list_head *migratelist = &cc->migratepages;
224 isolate_mode_t mode = ISOLATE_ACTIVE|ISOLATE_INACTIVE;
227 * Ensure that there are not too many pages isolated from the LRU
228 * list by either parallel reclaimers or compaction. If there are,
229 * delay for some time until fewer pages are isolated
231 while (unlikely(too_many_isolated(zone))) {
232 /* async migration should just abort */
236 congestion_wait(BLK_RW_ASYNC, HZ/10);
238 if (fatal_signal_pending(current))
242 /* Time to isolate some pages for migration */
244 spin_lock_irq(&zone->lru_lock);
245 for (; low_pfn < end_pfn; low_pfn++) {
249 /* give a chance to irqs before checking need_resched() */
250 if (!((low_pfn+1) % SWAP_CLUSTER_MAX)) {
251 spin_unlock_irq(&zone->lru_lock);
254 if (need_resched() || spin_is_contended(&zone->lru_lock)) {
256 spin_unlock_irq(&zone->lru_lock);
258 spin_lock_irq(&zone->lru_lock);
259 if (fatal_signal_pending(current))
262 spin_lock_irq(&zone->lru_lock);
265 * migrate_pfn does not necessarily start aligned to a
266 * pageblock. Ensure that pfn_valid is called when moving
267 * into a new MAX_ORDER_NR_PAGES range in case of large
268 * memory holes within the zone
270 if ((low_pfn & (MAX_ORDER_NR_PAGES - 1)) == 0) {
271 if (!pfn_valid(low_pfn)) {
272 low_pfn += MAX_ORDER_NR_PAGES - 1;
277 if (!pfn_valid_within(low_pfn))
282 * Get the page and ensure the page is within the same zone.
283 * See the comment in isolate_freepages about overlapping
284 * nodes. It is deliberate that the new zone lock is not taken
285 * as memory compaction should not move pages between nodes.
287 page = pfn_to_page(low_pfn);
288 if (page_zone(page) != zone)
296 * For async migration, also only scan in MOVABLE blocks. Async
297 * migration is optimistic to see if the minimum amount of work
298 * satisfies the allocation
300 pageblock_nr = low_pfn >> pageblock_order;
301 if (!cc->sync && last_pageblock_nr != pageblock_nr &&
302 get_pageblock_migratetype(page) != MIGRATE_MOVABLE) {
303 low_pfn += pageblock_nr_pages;
304 low_pfn = ALIGN(low_pfn, pageblock_nr_pages) - 1;
305 last_pageblock_nr = pageblock_nr;
313 * PageLRU is set, and lru_lock excludes isolation,
314 * splitting and collapsing (collapsing has already
315 * happened if PageLRU is set).
317 if (PageTransHuge(page)) {
318 low_pfn += (1 << compound_order(page)) - 1;
323 mode |= ISOLATE_ASYNC_MIGRATE;
325 /* Try isolate the page */
326 if (__isolate_lru_page(page, mode, 0) != 0)
329 VM_BUG_ON(PageTransCompound(page));
331 /* Successfully isolated */
332 del_page_from_lru_list(zone, page, page_lru(page));
333 list_add(&page->lru, migratelist);
334 cc->nr_migratepages++;
337 /* Avoid isolating too much */
338 if (cc->nr_migratepages == COMPACT_CLUSTER_MAX) {
344 acct_isolated(zone, cc);
346 spin_unlock_irq(&zone->lru_lock);
348 trace_mm_compaction_isolate_migratepages(nr_scanned, nr_isolated);
353 #endif /* CONFIG_COMPACTION || CONFIG_CMA */
354 #ifdef CONFIG_COMPACTION
356 /* Returns true if the page is within a block suitable for migration to */
357 static bool suitable_migration_target(struct page *page)
360 int migratetype = get_pageblock_migratetype(page);
362 /* Don't interfere with memory hot-remove or the min_free_kbytes blocks */
363 if (migratetype == MIGRATE_ISOLATE || migratetype == MIGRATE_RESERVE)
366 /* If the page is a large free page, then allow migration */
367 if (PageBuddy(page) && page_order(page) >= pageblock_order)
370 /* If the block is MIGRATE_MOVABLE, allow migration */
371 if (migratetype == MIGRATE_MOVABLE)
374 /* Otherwise skip the block */
379 * Based on information in the current compact_control, find blocks
380 * suitable for isolating free pages from and then isolate them.
382 static void isolate_freepages(struct zone *zone,
383 struct compact_control *cc)
386 unsigned long high_pfn, low_pfn, pfn, zone_end_pfn, end_pfn;
388 int nr_freepages = cc->nr_freepages;
389 struct list_head *freelist = &cc->freepages;
392 * Initialise the free scanner. The starting point is where we last
393 * scanned from (or the end of the zone if starting). The low point
394 * is the end of the pageblock the migration scanner is using.
397 low_pfn = cc->migrate_pfn + pageblock_nr_pages;
400 * Take care that if the migration scanner is at the end of the zone
401 * that the free scanner does not accidentally move to the next zone
402 * in the next isolation cycle.
404 high_pfn = min(low_pfn, pfn);
406 zone_end_pfn = zone->zone_start_pfn + zone->spanned_pages;
409 * Isolate free pages until enough are available to migrate the
410 * pages on cc->migratepages. We stop searching if the migrate
411 * and free page scanners meet or enough free pages are isolated.
413 for (; pfn > low_pfn && cc->nr_migratepages > nr_freepages;
414 pfn -= pageblock_nr_pages) {
415 unsigned long isolated;
421 * Check for overlapping nodes/zones. It's possible on some
422 * configurations to have a setup like
424 * i.e. it's possible that all pages within a zones range of
425 * pages do not belong to a single zone.
427 page = pfn_to_page(pfn);
428 if (page_zone(page) != zone)
431 /* Check the block is suitable for migration */
432 if (!suitable_migration_target(page))
436 * Found a block suitable for isolating free pages from. Now
437 * we disabled interrupts, double check things are ok and
438 * isolate the pages. This is to minimise the time IRQs
442 spin_lock_irqsave(&zone->lock, flags);
443 if (suitable_migration_target(page)) {
444 end_pfn = min(pfn + pageblock_nr_pages, zone_end_pfn);
445 isolated = isolate_freepages_block(pfn, end_pfn,
447 nr_freepages += isolated;
449 spin_unlock_irqrestore(&zone->lock, flags);
452 * Record the highest PFN we isolated pages from. When next
453 * looking for free pages, the search will restart here as
454 * page migration may have returned some pages to the allocator
457 high_pfn = max(high_pfn, pfn);
460 /* split_free_page does not map the pages */
463 cc->free_pfn = high_pfn;
464 cc->nr_freepages = nr_freepages;
468 * This is a migrate-callback that "allocates" freepages by taking pages
469 * from the isolated freelists in the block we are migrating to.
471 static struct page *compaction_alloc(struct page *migratepage,
475 struct compact_control *cc = (struct compact_control *)data;
476 struct page *freepage;
478 /* Isolate free pages if necessary */
479 if (list_empty(&cc->freepages)) {
480 isolate_freepages(cc->zone, cc);
482 if (list_empty(&cc->freepages))
486 freepage = list_entry(cc->freepages.next, struct page, lru);
487 list_del(&freepage->lru);
494 * We cannot control nr_migratepages and nr_freepages fully when migration is
495 * running as migrate_pages() has no knowledge of compact_control. When
496 * migration is complete, we count the number of pages on the lists by hand.
498 static void update_nr_listpages(struct compact_control *cc)
500 int nr_migratepages = 0;
501 int nr_freepages = 0;
504 list_for_each_entry(page, &cc->migratepages, lru)
506 list_for_each_entry(page, &cc->freepages, lru)
509 cc->nr_migratepages = nr_migratepages;
510 cc->nr_freepages = nr_freepages;
513 /* possible outcome of isolate_migratepages */
515 ISOLATE_ABORT, /* Abort compaction now */
516 ISOLATE_NONE, /* No pages isolated, continue scanning */
517 ISOLATE_SUCCESS, /* Pages isolated, migrate */
521 * Isolate all pages that can be migrated from the block pointed to by
522 * the migrate scanner within compact_control.
524 static isolate_migrate_t isolate_migratepages(struct zone *zone,
525 struct compact_control *cc)
527 unsigned long low_pfn, end_pfn;
529 /* Do not scan outside zone boundaries */
530 low_pfn = max(cc->migrate_pfn, zone->zone_start_pfn);
532 /* Only scan within a pageblock boundary */
533 end_pfn = ALIGN(low_pfn + pageblock_nr_pages, pageblock_nr_pages);
535 /* Do not cross the free scanner or scan within a memory hole */
536 if (end_pfn > cc->free_pfn || !pfn_valid(low_pfn)) {
537 cc->migrate_pfn = end_pfn;
541 /* Perform the isolation */
542 low_pfn = isolate_migratepages_range(zone, cc, low_pfn, end_pfn);
544 return ISOLATE_ABORT;
546 cc->migrate_pfn = low_pfn;
548 return ISOLATE_SUCCESS;
551 static int compact_finished(struct zone *zone,
552 struct compact_control *cc)
555 unsigned long watermark;
557 if (fatal_signal_pending(current))
558 return COMPACT_PARTIAL;
560 /* Compaction run completes if the migrate and free scanner meet */
561 if (cc->free_pfn <= cc->migrate_pfn)
562 return COMPACT_COMPLETE;
565 * order == -1 is expected when compacting via
566 * /proc/sys/vm/compact_memory
569 return COMPACT_CONTINUE;
571 /* Compaction run is not finished if the watermark is not met */
572 watermark = low_wmark_pages(zone);
573 watermark += (1 << cc->order);
575 if (!zone_watermark_ok(zone, cc->order, watermark, 0, 0))
576 return COMPACT_CONTINUE;
578 /* Direct compactor: Is a suitable page free? */
579 for (order = cc->order; order < MAX_ORDER; order++) {
580 /* Job done if page is free of the right migratetype */
581 if (!list_empty(&zone->free_area[order].free_list[cc->migratetype]))
582 return COMPACT_PARTIAL;
584 /* Job done if allocation would set block type */
585 if (order >= pageblock_order && zone->free_area[order].nr_free)
586 return COMPACT_PARTIAL;
589 return COMPACT_CONTINUE;
593 * compaction_suitable: Is this suitable to run compaction on this zone now?
595 * COMPACT_SKIPPED - If there are too few free pages for compaction
596 * COMPACT_PARTIAL - If the allocation would succeed without compaction
597 * COMPACT_CONTINUE - If compaction should run now
599 unsigned long compaction_suitable(struct zone *zone, int order)
602 unsigned long watermark;
605 * order == -1 is expected when compacting via
606 * /proc/sys/vm/compact_memory
609 return COMPACT_CONTINUE;
612 * Watermarks for order-0 must be met for compaction. Note the 2UL.
613 * This is because during migration, copies of pages need to be
614 * allocated and for a short time, the footprint is higher
616 watermark = low_wmark_pages(zone) + (2UL << order);
617 if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
618 return COMPACT_SKIPPED;
621 * fragmentation index determines if allocation failures are due to
622 * low memory or external fragmentation
624 * index of -1000 implies allocations might succeed depending on
626 * index towards 0 implies failure is due to lack of memory
627 * index towards 1000 implies failure is due to fragmentation
629 * Only compact if a failure would be due to fragmentation.
631 fragindex = fragmentation_index(zone, order);
632 if (fragindex >= 0 && fragindex <= sysctl_extfrag_threshold)
633 return COMPACT_SKIPPED;
635 if (fragindex == -1000 && zone_watermark_ok(zone, order, watermark,
637 return COMPACT_PARTIAL;
639 return COMPACT_CONTINUE;
642 static int compact_zone(struct zone *zone, struct compact_control *cc)
646 ret = compaction_suitable(zone, cc->order);
648 case COMPACT_PARTIAL:
649 case COMPACT_SKIPPED:
650 /* Compaction is likely to fail */
652 case COMPACT_CONTINUE:
653 /* Fall through to compaction */
657 /* Setup to move all movable pages to the end of the zone */
658 cc->migrate_pfn = zone->zone_start_pfn;
659 cc->free_pfn = cc->migrate_pfn + zone->spanned_pages;
660 cc->free_pfn &= ~(pageblock_nr_pages-1);
662 migrate_prep_local();
664 while ((ret = compact_finished(zone, cc)) == COMPACT_CONTINUE) {
665 unsigned long nr_migrate, nr_remaining;
668 switch (isolate_migratepages(zone, cc)) {
670 ret = COMPACT_PARTIAL;
674 case ISOLATE_SUCCESS:
678 nr_migrate = cc->nr_migratepages;
679 err = migrate_pages(&cc->migratepages, compaction_alloc,
680 (unsigned long)cc, false,
681 cc->sync ? MIGRATE_SYNC_LIGHT : MIGRATE_ASYNC);
682 update_nr_listpages(cc);
683 nr_remaining = cc->nr_migratepages;
685 count_vm_event(COMPACTBLOCKS);
686 count_vm_events(COMPACTPAGES, nr_migrate - nr_remaining);
688 count_vm_events(COMPACTPAGEFAILED, nr_remaining);
689 trace_mm_compaction_migratepages(nr_migrate - nr_remaining,
692 /* Release LRU pages not migrated */
694 putback_lru_pages(&cc->migratepages);
695 cc->nr_migratepages = 0;
701 /* Release free pages and check accounting */
702 cc->nr_freepages -= release_freepages(&cc->freepages);
703 VM_BUG_ON(cc->nr_freepages != 0);
708 static unsigned long compact_zone_order(struct zone *zone,
709 int order, gfp_t gfp_mask,
712 struct compact_control cc = {
714 .nr_migratepages = 0,
716 .migratetype = allocflags_to_migratetype(gfp_mask),
720 INIT_LIST_HEAD(&cc.freepages);
721 INIT_LIST_HEAD(&cc.migratepages);
723 return compact_zone(zone, &cc);
726 int sysctl_extfrag_threshold = 500;
729 * try_to_compact_pages - Direct compact to satisfy a high-order allocation
730 * @zonelist: The zonelist used for the current allocation
731 * @order: The order of the current allocation
732 * @gfp_mask: The GFP mask of the current allocation
733 * @nodemask: The allowed nodes to allocate from
734 * @sync: Whether migration is synchronous or not
736 * This is the main entry point for direct page compaction.
738 unsigned long try_to_compact_pages(struct zonelist *zonelist,
739 int order, gfp_t gfp_mask, nodemask_t *nodemask,
742 enum zone_type high_zoneidx = gfp_zone(gfp_mask);
743 int may_enter_fs = gfp_mask & __GFP_FS;
744 int may_perform_io = gfp_mask & __GFP_IO;
747 int rc = COMPACT_SKIPPED;
750 * Check whether it is worth even starting compaction. The order check is
751 * made because an assumption is made that the page allocator can satisfy
752 * the "cheaper" orders without taking special steps
754 if (!order || !may_enter_fs || !may_perform_io)
757 count_vm_event(COMPACTSTALL);
759 /* Compact each zone in the list */
760 for_each_zone_zonelist_nodemask(zone, z, zonelist, high_zoneidx,
764 status = compact_zone_order(zone, order, gfp_mask, sync);
765 rc = max(status, rc);
767 /* If a normal allocation would succeed, stop compacting */
768 if (zone_watermark_ok(zone, order, low_wmark_pages(zone), 0, 0))
776 /* Compact all zones within a node */
777 static int __compact_pgdat(pg_data_t *pgdat, struct compact_control *cc)
782 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
784 zone = &pgdat->node_zones[zoneid];
785 if (!populated_zone(zone))
788 cc->nr_freepages = 0;
789 cc->nr_migratepages = 0;
791 INIT_LIST_HEAD(&cc->freepages);
792 INIT_LIST_HEAD(&cc->migratepages);
794 if (cc->order == -1 || !compaction_deferred(zone, cc->order))
795 compact_zone(zone, cc);
798 int ok = zone_watermark_ok(zone, cc->order,
799 low_wmark_pages(zone), 0, 0);
800 if (ok && cc->order > zone->compact_order_failed)
801 zone->compact_order_failed = cc->order + 1;
802 /* Currently async compaction is never deferred. */
803 else if (!ok && cc->sync)
804 defer_compaction(zone, cc->order);
807 VM_BUG_ON(!list_empty(&cc->freepages));
808 VM_BUG_ON(!list_empty(&cc->migratepages));
814 int compact_pgdat(pg_data_t *pgdat, int order)
816 struct compact_control cc = {
821 return __compact_pgdat(pgdat, &cc);
824 static int compact_node(int nid)
826 struct compact_control cc = {
831 return __compact_pgdat(NODE_DATA(nid), &cc);
834 /* Compact all nodes in the system */
835 static int compact_nodes(void)
839 /* Flush pending updates to the LRU lists */
842 for_each_online_node(nid)
845 return COMPACT_COMPLETE;
848 /* The written value is actually unused, all memory is compacted */
849 int sysctl_compact_memory;
851 /* This is the entry point for compacting all nodes via /proc/sys/vm */
852 int sysctl_compaction_handler(struct ctl_table *table, int write,
853 void __user *buffer, size_t *length, loff_t *ppos)
856 return compact_nodes();
861 int sysctl_extfrag_handler(struct ctl_table *table, int write,
862 void __user *buffer, size_t *length, loff_t *ppos)
864 proc_dointvec_minmax(table, write, buffer, length, ppos);
869 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
870 ssize_t sysfs_compact_node(struct device *dev,
871 struct device_attribute *attr,
872 const char *buf, size_t count)
876 if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
877 /* Flush pending updates to the LRU lists */
885 static DEVICE_ATTR(compact, S_IWUSR, NULL, sysfs_compact_node);
887 int compaction_register_node(struct node *node)
889 return device_create_file(&node->dev, &dev_attr_compact);
892 void compaction_unregister_node(struct node *node)
894 return device_remove_file(&node->dev, &dev_attr_compact);
896 #endif /* CONFIG_SYSFS && CONFIG_NUMA */
898 #endif /* CONFIG_COMPACTION */