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 #define CREATE_TRACE_POINTS
20 #include <trace/events/compaction.h>
23 * compact_control is used to track pages being migrated and the free pages
24 * they are being migrated to during memory compaction. The free_pfn starts
25 * at the end of a zone and migrate_pfn begins at the start. Movable pages
26 * are moved to the end of a zone during a compaction run and the run
27 * completes when free_pfn <= migrate_pfn
29 struct compact_control {
30 struct list_head freepages; /* List of free pages to migrate to */
31 struct list_head migratepages; /* List of pages being migrated */
32 unsigned long nr_freepages; /* Number of isolated free pages */
33 unsigned long nr_migratepages; /* Number of pages to migrate */
34 unsigned long free_pfn; /* isolate_freepages search base */
35 unsigned long migrate_pfn; /* isolate_migratepages search base */
36 bool sync; /* Synchronous migration */
38 int order; /* order a direct compactor needs */
39 int migratetype; /* MOVABLE, RECLAIMABLE etc */
43 static unsigned long release_freepages(struct list_head *freelist)
45 struct page *page, *next;
46 unsigned long count = 0;
48 list_for_each_entry_safe(page, next, freelist, lru) {
57 /* Isolate free pages onto a private freelist. Must hold zone->lock */
58 static unsigned long isolate_freepages_block(struct zone *zone,
59 unsigned long blockpfn,
60 struct list_head *freelist)
62 unsigned long zone_end_pfn, end_pfn;
63 int nr_scanned = 0, total_isolated = 0;
66 /* Get the last PFN we should scan for free pages at */
67 zone_end_pfn = zone->zone_start_pfn + zone->spanned_pages;
68 end_pfn = min(blockpfn + pageblock_nr_pages, zone_end_pfn);
70 /* Find the first usable PFN in the block to initialse page cursor */
71 for (; blockpfn < end_pfn; blockpfn++) {
72 if (pfn_valid_within(blockpfn))
75 cursor = pfn_to_page(blockpfn);
77 /* Isolate free pages. This assumes the block is valid */
78 for (; blockpfn < end_pfn; blockpfn++, cursor++) {
80 struct page *page = cursor;
82 if (!pfn_valid_within(blockpfn))
89 /* Found a free page, break it into order-0 pages */
90 isolated = split_free_page(page);
91 total_isolated += isolated;
92 for (i = 0; i < isolated; i++) {
93 list_add(&page->lru, freelist);
97 /* If a page was split, advance to the end of it */
99 blockpfn += isolated - 1;
100 cursor += isolated - 1;
104 trace_mm_compaction_isolate_freepages(nr_scanned, total_isolated);
105 return total_isolated;
108 /* Returns true if the page is within a block suitable for migration to */
109 static bool suitable_migration_target(struct page *page)
112 int migratetype = get_pageblock_migratetype(page);
114 /* Don't interfere with memory hot-remove or the min_free_kbytes blocks */
115 if (migratetype == MIGRATE_ISOLATE || migratetype == MIGRATE_RESERVE)
118 /* If the page is a large free page, then allow migration */
119 if (PageBuddy(page) && page_order(page) >= pageblock_order)
122 /* If the block is MIGRATE_MOVABLE, allow migration */
123 if (migratetype == MIGRATE_MOVABLE)
126 /* Otherwise skip the block */
130 static void map_pages(struct list_head *list)
134 list_for_each_entry(page, list, lru) {
135 arch_alloc_page(page, 0);
136 kernel_map_pages(page, 1, 1);
141 * Based on information in the current compact_control, find blocks
142 * suitable for isolating free pages from and then isolate them.
144 static void isolate_freepages(struct zone *zone,
145 struct compact_control *cc)
148 unsigned long high_pfn, low_pfn, pfn;
150 int nr_freepages = cc->nr_freepages;
151 struct list_head *freelist = &cc->freepages;
154 * Initialise the free scanner. The starting point is where we last
155 * scanned from (or the end of the zone if starting). The low point
156 * is the end of the pageblock the migration scanner is using.
159 low_pfn = cc->migrate_pfn + pageblock_nr_pages;
162 * Take care that if the migration scanner is at the end of the zone
163 * that the free scanner does not accidentally move to the next zone
164 * in the next isolation cycle.
166 high_pfn = min(low_pfn, pfn);
169 * Isolate free pages until enough are available to migrate the
170 * pages on cc->migratepages. We stop searching if the migrate
171 * and free page scanners meet or enough free pages are isolated.
173 for (; pfn > low_pfn && cc->nr_migratepages > nr_freepages;
174 pfn -= pageblock_nr_pages) {
175 unsigned long isolated;
181 * Check for overlapping nodes/zones. It's possible on some
182 * configurations to have a setup like
184 * i.e. it's possible that all pages within a zones range of
185 * pages do not belong to a single zone.
187 page = pfn_to_page(pfn);
188 if (page_zone(page) != zone)
191 /* Check the block is suitable for migration */
192 if (!suitable_migration_target(page))
196 * Found a block suitable for isolating free pages from. Now
197 * we disabled interrupts, double check things are ok and
198 * isolate the pages. This is to minimise the time IRQs
202 spin_lock_irqsave(&zone->lock, flags);
203 if (suitable_migration_target(page)) {
204 isolated = isolate_freepages_block(zone, pfn, freelist);
205 nr_freepages += isolated;
207 spin_unlock_irqrestore(&zone->lock, flags);
210 * Record the highest PFN we isolated pages from. When next
211 * looking for free pages, the search will restart here as
212 * page migration may have returned some pages to the allocator
215 high_pfn = max(high_pfn, pfn);
218 /* split_free_page does not map the pages */
221 cc->free_pfn = high_pfn;
222 cc->nr_freepages = nr_freepages;
225 /* Update the number of anon and file isolated pages in the zone */
226 static void acct_isolated(struct zone *zone, struct compact_control *cc)
229 unsigned int count[2] = { 0, };
231 list_for_each_entry(page, &cc->migratepages, lru)
232 count[!!page_is_file_cache(page)]++;
234 __mod_zone_page_state(zone, NR_ISOLATED_ANON, count[0]);
235 __mod_zone_page_state(zone, NR_ISOLATED_FILE, count[1]);
238 /* Similar to reclaim, but different enough that they don't share logic */
239 static bool too_many_isolated(struct zone *zone)
241 unsigned long active, inactive, isolated;
243 inactive = zone_page_state(zone, NR_INACTIVE_FILE) +
244 zone_page_state(zone, NR_INACTIVE_ANON);
245 active = zone_page_state(zone, NR_ACTIVE_FILE) +
246 zone_page_state(zone, NR_ACTIVE_ANON);
247 isolated = zone_page_state(zone, NR_ISOLATED_FILE) +
248 zone_page_state(zone, NR_ISOLATED_ANON);
250 return isolated > (inactive + active) / 2;
253 /* possible outcome of isolate_migratepages */
255 ISOLATE_ABORT, /* Abort compaction now */
256 ISOLATE_NONE, /* No pages isolated, continue scanning */
257 ISOLATE_SUCCESS, /* Pages isolated, migrate */
261 * isolate_migratepages_range() - isolate all migrate-able pages in range.
262 * @zone: Zone pages are in.
263 * @cc: Compaction control structure.
264 * @low_pfn: The first PFN of the range.
265 * @end_pfn: The one-past-the-last PFN of the range.
267 * Isolate all pages that can be migrated from the range specified by
268 * [low_pfn, end_pfn). Returns zero if there is a fatal signal
269 * pending), otherwise PFN of the first page that was not scanned
270 * (which may be both less, equal to or more then end_pfn).
272 * Assumes that cc->migratepages is empty and cc->nr_migratepages is
275 * Apart from cc->migratepages and cc->nr_migratetypes this function
276 * does not modify any cc's fields, in particular it does not modify
277 * (or read for that matter) cc->migrate_pfn.
280 isolate_migratepages_range(struct zone *zone, struct compact_control *cc,
281 unsigned long low_pfn, unsigned long end_pfn)
283 unsigned long last_pageblock_nr = 0, pageblock_nr;
284 unsigned long nr_scanned = 0, nr_isolated = 0;
285 struct list_head *migratelist = &cc->migratepages;
286 isolate_mode_t mode = ISOLATE_ACTIVE|ISOLATE_INACTIVE;
289 * Ensure that there are not too many pages isolated from the LRU
290 * list by either parallel reclaimers or compaction. If there are,
291 * delay for some time until fewer pages are isolated
293 while (unlikely(too_many_isolated(zone))) {
294 /* async migration should just abort */
298 congestion_wait(BLK_RW_ASYNC, HZ/10);
300 if (fatal_signal_pending(current))
304 /* Time to isolate some pages for migration */
306 spin_lock_irq(&zone->lru_lock);
307 for (; low_pfn < end_pfn; low_pfn++) {
311 /* give a chance to irqs before checking need_resched() */
312 if (!((low_pfn+1) % SWAP_CLUSTER_MAX)) {
313 spin_unlock_irq(&zone->lru_lock);
316 if (need_resched() || spin_is_contended(&zone->lru_lock)) {
318 spin_unlock_irq(&zone->lru_lock);
320 spin_lock_irq(&zone->lru_lock);
321 if (fatal_signal_pending(current))
324 spin_lock_irq(&zone->lru_lock);
327 * migrate_pfn does not necessarily start aligned to a
328 * pageblock. Ensure that pfn_valid is called when moving
329 * into a new MAX_ORDER_NR_PAGES range in case of large
330 * memory holes within the zone
332 if ((low_pfn & (MAX_ORDER_NR_PAGES - 1)) == 0) {
333 if (!pfn_valid(low_pfn)) {
334 low_pfn += MAX_ORDER_NR_PAGES - 1;
339 if (!pfn_valid_within(low_pfn))
344 * Get the page and ensure the page is within the same zone.
345 * See the comment in isolate_freepages about overlapping
346 * nodes. It is deliberate that the new zone lock is not taken
347 * as memory compaction should not move pages between nodes.
349 page = pfn_to_page(low_pfn);
350 if (page_zone(page) != zone)
358 * For async migration, also only scan in MOVABLE blocks. Async
359 * migration is optimistic to see if the minimum amount of work
360 * satisfies the allocation
362 pageblock_nr = low_pfn >> pageblock_order;
363 if (!cc->sync && last_pageblock_nr != pageblock_nr &&
364 get_pageblock_migratetype(page) != MIGRATE_MOVABLE) {
365 low_pfn += pageblock_nr_pages;
366 low_pfn = ALIGN(low_pfn, pageblock_nr_pages) - 1;
367 last_pageblock_nr = pageblock_nr;
375 * PageLRU is set, and lru_lock excludes isolation,
376 * splitting and collapsing (collapsing has already
377 * happened if PageLRU is set).
379 if (PageTransHuge(page)) {
380 low_pfn += (1 << compound_order(page)) - 1;
385 mode |= ISOLATE_ASYNC_MIGRATE;
387 /* Try isolate the page */
388 if (__isolate_lru_page(page, mode, 0) != 0)
391 VM_BUG_ON(PageTransCompound(page));
393 /* Successfully isolated */
394 del_page_from_lru_list(zone, page, page_lru(page));
395 list_add(&page->lru, migratelist);
396 cc->nr_migratepages++;
399 /* Avoid isolating too much */
400 if (cc->nr_migratepages == COMPACT_CLUSTER_MAX) {
406 acct_isolated(zone, cc);
408 spin_unlock_irq(&zone->lru_lock);
410 trace_mm_compaction_isolate_migratepages(nr_scanned, nr_isolated);
416 * Isolate all pages that can be migrated from the block pointed to by
417 * the migrate scanner within compact_control.
419 static isolate_migrate_t isolate_migratepages(struct zone *zone,
420 struct compact_control *cc)
422 unsigned long low_pfn, end_pfn;
424 /* Do not scan outside zone boundaries */
425 low_pfn = max(cc->migrate_pfn, zone->zone_start_pfn);
427 /* Only scan within a pageblock boundary */
428 end_pfn = ALIGN(low_pfn + pageblock_nr_pages, pageblock_nr_pages);
430 /* Do not cross the free scanner or scan within a memory hole */
431 if (end_pfn > cc->free_pfn || !pfn_valid(low_pfn)) {
432 cc->migrate_pfn = end_pfn;
436 /* Perform the isolation */
437 low_pfn = isolate_migratepages_range(zone, cc, low_pfn, end_pfn);
439 return ISOLATE_ABORT;
441 cc->migrate_pfn = low_pfn;
443 return ISOLATE_SUCCESS;
447 * This is a migrate-callback that "allocates" freepages by taking pages
448 * from the isolated freelists in the block we are migrating to.
450 static struct page *compaction_alloc(struct page *migratepage,
454 struct compact_control *cc = (struct compact_control *)data;
455 struct page *freepage;
457 /* Isolate free pages if necessary */
458 if (list_empty(&cc->freepages)) {
459 isolate_freepages(cc->zone, cc);
461 if (list_empty(&cc->freepages))
465 freepage = list_entry(cc->freepages.next, struct page, lru);
466 list_del(&freepage->lru);
473 * We cannot control nr_migratepages and nr_freepages fully when migration is
474 * running as migrate_pages() has no knowledge of compact_control. When
475 * migration is complete, we count the number of pages on the lists by hand.
477 static void update_nr_listpages(struct compact_control *cc)
479 int nr_migratepages = 0;
480 int nr_freepages = 0;
483 list_for_each_entry(page, &cc->migratepages, lru)
485 list_for_each_entry(page, &cc->freepages, lru)
488 cc->nr_migratepages = nr_migratepages;
489 cc->nr_freepages = nr_freepages;
492 static int compact_finished(struct zone *zone,
493 struct compact_control *cc)
496 unsigned long watermark;
498 if (fatal_signal_pending(current))
499 return COMPACT_PARTIAL;
501 /* Compaction run completes if the migrate and free scanner meet */
502 if (cc->free_pfn <= cc->migrate_pfn)
503 return COMPACT_COMPLETE;
506 * order == -1 is expected when compacting via
507 * /proc/sys/vm/compact_memory
510 return COMPACT_CONTINUE;
512 /* Compaction run is not finished if the watermark is not met */
513 watermark = low_wmark_pages(zone);
514 watermark += (1 << cc->order);
516 if (!zone_watermark_ok(zone, cc->order, watermark, 0, 0))
517 return COMPACT_CONTINUE;
519 /* Direct compactor: Is a suitable page free? */
520 for (order = cc->order; order < MAX_ORDER; order++) {
521 /* Job done if page is free of the right migratetype */
522 if (!list_empty(&zone->free_area[order].free_list[cc->migratetype]))
523 return COMPACT_PARTIAL;
525 /* Job done if allocation would set block type */
526 if (order >= pageblock_order && zone->free_area[order].nr_free)
527 return COMPACT_PARTIAL;
530 return COMPACT_CONTINUE;
534 * compaction_suitable: Is this suitable to run compaction on this zone now?
536 * COMPACT_SKIPPED - If there are too few free pages for compaction
537 * COMPACT_PARTIAL - If the allocation would succeed without compaction
538 * COMPACT_CONTINUE - If compaction should run now
540 unsigned long compaction_suitable(struct zone *zone, int order)
543 unsigned long watermark;
546 * order == -1 is expected when compacting via
547 * /proc/sys/vm/compact_memory
550 return COMPACT_CONTINUE;
553 * Watermarks for order-0 must be met for compaction. Note the 2UL.
554 * This is because during migration, copies of pages need to be
555 * allocated and for a short time, the footprint is higher
557 watermark = low_wmark_pages(zone) + (2UL << order);
558 if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
559 return COMPACT_SKIPPED;
562 * fragmentation index determines if allocation failures are due to
563 * low memory or external fragmentation
565 * index of -1000 implies allocations might succeed depending on
567 * index towards 0 implies failure is due to lack of memory
568 * index towards 1000 implies failure is due to fragmentation
570 * Only compact if a failure would be due to fragmentation.
572 fragindex = fragmentation_index(zone, order);
573 if (fragindex >= 0 && fragindex <= sysctl_extfrag_threshold)
574 return COMPACT_SKIPPED;
576 if (fragindex == -1000 && zone_watermark_ok(zone, order, watermark,
578 return COMPACT_PARTIAL;
580 return COMPACT_CONTINUE;
583 static int compact_zone(struct zone *zone, struct compact_control *cc)
587 ret = compaction_suitable(zone, cc->order);
589 case COMPACT_PARTIAL:
590 case COMPACT_SKIPPED:
591 /* Compaction is likely to fail */
593 case COMPACT_CONTINUE:
594 /* Fall through to compaction */
598 /* Setup to move all movable pages to the end of the zone */
599 cc->migrate_pfn = zone->zone_start_pfn;
600 cc->free_pfn = cc->migrate_pfn + zone->spanned_pages;
601 cc->free_pfn &= ~(pageblock_nr_pages-1);
603 migrate_prep_local();
605 while ((ret = compact_finished(zone, cc)) == COMPACT_CONTINUE) {
606 unsigned long nr_migrate, nr_remaining;
609 switch (isolate_migratepages(zone, cc)) {
611 ret = COMPACT_PARTIAL;
615 case ISOLATE_SUCCESS:
619 nr_migrate = cc->nr_migratepages;
620 err = migrate_pages(&cc->migratepages, compaction_alloc,
621 (unsigned long)cc, false,
622 cc->sync ? MIGRATE_SYNC_LIGHT : MIGRATE_ASYNC);
623 update_nr_listpages(cc);
624 nr_remaining = cc->nr_migratepages;
626 count_vm_event(COMPACTBLOCKS);
627 count_vm_events(COMPACTPAGES, nr_migrate - nr_remaining);
629 count_vm_events(COMPACTPAGEFAILED, nr_remaining);
630 trace_mm_compaction_migratepages(nr_migrate - nr_remaining,
633 /* Release LRU pages not migrated */
635 putback_lru_pages(&cc->migratepages);
636 cc->nr_migratepages = 0;
642 /* Release free pages and check accounting */
643 cc->nr_freepages -= release_freepages(&cc->freepages);
644 VM_BUG_ON(cc->nr_freepages != 0);
649 static unsigned long compact_zone_order(struct zone *zone,
650 int order, gfp_t gfp_mask,
653 struct compact_control cc = {
655 .nr_migratepages = 0,
657 .migratetype = allocflags_to_migratetype(gfp_mask),
661 INIT_LIST_HEAD(&cc.freepages);
662 INIT_LIST_HEAD(&cc.migratepages);
664 return compact_zone(zone, &cc);
667 int sysctl_extfrag_threshold = 500;
670 * try_to_compact_pages - Direct compact to satisfy a high-order allocation
671 * @zonelist: The zonelist used for the current allocation
672 * @order: The order of the current allocation
673 * @gfp_mask: The GFP mask of the current allocation
674 * @nodemask: The allowed nodes to allocate from
675 * @sync: Whether migration is synchronous or not
677 * This is the main entry point for direct page compaction.
679 unsigned long try_to_compact_pages(struct zonelist *zonelist,
680 int order, gfp_t gfp_mask, nodemask_t *nodemask,
683 enum zone_type high_zoneidx = gfp_zone(gfp_mask);
684 int may_enter_fs = gfp_mask & __GFP_FS;
685 int may_perform_io = gfp_mask & __GFP_IO;
688 int rc = COMPACT_SKIPPED;
691 * Check whether it is worth even starting compaction. The order check is
692 * made because an assumption is made that the page allocator can satisfy
693 * the "cheaper" orders without taking special steps
695 if (!order || !may_enter_fs || !may_perform_io)
698 count_vm_event(COMPACTSTALL);
700 /* Compact each zone in the list */
701 for_each_zone_zonelist_nodemask(zone, z, zonelist, high_zoneidx,
705 status = compact_zone_order(zone, order, gfp_mask, sync);
706 rc = max(status, rc);
708 /* If a normal allocation would succeed, stop compacting */
709 if (zone_watermark_ok(zone, order, low_wmark_pages(zone), 0, 0))
717 /* Compact all zones within a node */
718 static int __compact_pgdat(pg_data_t *pgdat, struct compact_control *cc)
723 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
725 zone = &pgdat->node_zones[zoneid];
726 if (!populated_zone(zone))
729 cc->nr_freepages = 0;
730 cc->nr_migratepages = 0;
732 INIT_LIST_HEAD(&cc->freepages);
733 INIT_LIST_HEAD(&cc->migratepages);
735 if (cc->order == -1 || !compaction_deferred(zone, cc->order))
736 compact_zone(zone, cc);
739 int ok = zone_watermark_ok(zone, cc->order,
740 low_wmark_pages(zone), 0, 0);
741 if (ok && cc->order > zone->compact_order_failed)
742 zone->compact_order_failed = cc->order + 1;
743 /* Currently async compaction is never deferred. */
744 else if (!ok && cc->sync)
745 defer_compaction(zone, cc->order);
748 VM_BUG_ON(!list_empty(&cc->freepages));
749 VM_BUG_ON(!list_empty(&cc->migratepages));
755 int compact_pgdat(pg_data_t *pgdat, int order)
757 struct compact_control cc = {
762 return __compact_pgdat(pgdat, &cc);
765 static int compact_node(int nid)
767 struct compact_control cc = {
772 return __compact_pgdat(NODE_DATA(nid), &cc);
775 /* Compact all nodes in the system */
776 static int compact_nodes(void)
780 /* Flush pending updates to the LRU lists */
783 for_each_online_node(nid)
786 return COMPACT_COMPLETE;
789 /* The written value is actually unused, all memory is compacted */
790 int sysctl_compact_memory;
792 /* This is the entry point for compacting all nodes via /proc/sys/vm */
793 int sysctl_compaction_handler(struct ctl_table *table, int write,
794 void __user *buffer, size_t *length, loff_t *ppos)
797 return compact_nodes();
802 int sysctl_extfrag_handler(struct ctl_table *table, int write,
803 void __user *buffer, size_t *length, loff_t *ppos)
805 proc_dointvec_minmax(table, write, buffer, length, ppos);
810 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
811 ssize_t sysfs_compact_node(struct device *dev,
812 struct device_attribute *attr,
813 const char *buf, size_t count)
817 if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
818 /* Flush pending updates to the LRU lists */
826 static DEVICE_ATTR(compact, S_IWUSR, NULL, sysfs_compact_node);
828 int compaction_register_node(struct node *node)
830 return device_create_file(&node->dev, &dev_attr_compact);
833 void compaction_unregister_node(struct node *node)
835 return device_remove_file(&node->dev, &dev_attr_compact);
837 #endif /* CONFIG_SYSFS && CONFIG_NUMA */