]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - mm/compaction.c
aoe: update driver-internal version to 64+
[karo-tx-linux.git] / mm / compaction.c
1 /*
2  * linux/mm/compaction.c
3  *
4  * Memory compaction for the reduction of external fragmentation. Note that
5  * this heavily depends upon page migration to do all the real heavy
6  * lifting
7  *
8  * Copyright IBM Corp. 2007-2010 Mel Gorman <mel@csn.ul.ie>
9  */
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>
17 #include <linux/balloon_compaction.h>
18 #include "internal.h"
19
20 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
21
22 #define CREATE_TRACE_POINTS
23 #include <trace/events/compaction.h>
24
25 static unsigned long release_freepages(struct list_head *freelist)
26 {
27         struct page *page, *next;
28         unsigned long count = 0;
29
30         list_for_each_entry_safe(page, next, freelist, lru) {
31                 list_del(&page->lru);
32                 __free_page(page);
33                 count++;
34         }
35
36         return count;
37 }
38
39 static void map_pages(struct list_head *list)
40 {
41         struct page *page;
42
43         list_for_each_entry(page, list, lru) {
44                 arch_alloc_page(page, 0);
45                 kernel_map_pages(page, 1, 1);
46         }
47 }
48
49 static inline bool migrate_async_suitable(int migratetype)
50 {
51         return is_migrate_cma(migratetype) || migratetype == MIGRATE_MOVABLE;
52 }
53
54 #ifdef CONFIG_COMPACTION
55 /* Returns true if the pageblock should be scanned for pages to isolate. */
56 static inline bool isolation_suitable(struct compact_control *cc,
57                                         struct page *page)
58 {
59         if (cc->ignore_skip_hint)
60                 return true;
61
62         return !get_pageblock_skip(page);
63 }
64
65 /*
66  * This function is called to clear all cached information on pageblocks that
67  * should be skipped for page isolation when the migrate and free page scanner
68  * meet.
69  */
70 static void __reset_isolation_suitable(struct zone *zone)
71 {
72         unsigned long start_pfn = zone->zone_start_pfn;
73         unsigned long end_pfn = zone->zone_start_pfn + zone->spanned_pages;
74         unsigned long pfn;
75
76         zone->compact_cached_migrate_pfn = start_pfn;
77         zone->compact_cached_free_pfn = end_pfn;
78         zone->compact_blockskip_flush = false;
79
80         /* Walk the zone and mark every pageblock as suitable for isolation */
81         for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
82                 struct page *page;
83
84                 cond_resched();
85
86                 if (!pfn_valid(pfn))
87                         continue;
88
89                 page = pfn_to_page(pfn);
90                 if (zone != page_zone(page))
91                         continue;
92
93                 clear_pageblock_skip(page);
94         }
95 }
96
97 void reset_isolation_suitable(pg_data_t *pgdat)
98 {
99         int zoneid;
100
101         for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
102                 struct zone *zone = &pgdat->node_zones[zoneid];
103                 if (!populated_zone(zone))
104                         continue;
105
106                 /* Only flush if a full compaction finished recently */
107                 if (zone->compact_blockskip_flush)
108                         __reset_isolation_suitable(zone);
109         }
110 }
111
112 /*
113  * If no pages were isolated then mark this pageblock to be skipped in the
114  * future. The information is later cleared by __reset_isolation_suitable().
115  */
116 static void update_pageblock_skip(struct compact_control *cc,
117                         struct page *page, unsigned long nr_isolated,
118                         bool migrate_scanner)
119 {
120         struct zone *zone = cc->zone;
121         if (!page)
122                 return;
123
124         if (!nr_isolated) {
125                 unsigned long pfn = page_to_pfn(page);
126                 set_pageblock_skip(page);
127
128                 /* Update where compaction should restart */
129                 if (migrate_scanner) {
130                         if (!cc->finished_update_migrate &&
131                             pfn > zone->compact_cached_migrate_pfn)
132                                 zone->compact_cached_migrate_pfn = pfn;
133                 } else {
134                         if (!cc->finished_update_free &&
135                             pfn < zone->compact_cached_free_pfn)
136                                 zone->compact_cached_free_pfn = pfn;
137                 }
138         }
139 }
140 #else
141 static inline bool isolation_suitable(struct compact_control *cc,
142                                         struct page *page)
143 {
144         return true;
145 }
146
147 static void update_pageblock_skip(struct compact_control *cc,
148                         struct page *page, unsigned long nr_isolated,
149                         bool migrate_scanner)
150 {
151 }
152 #endif /* CONFIG_COMPACTION */
153
154 static inline bool should_release_lock(spinlock_t *lock)
155 {
156         return need_resched() || spin_is_contended(lock);
157 }
158
159 /*
160  * Compaction requires the taking of some coarse locks that are potentially
161  * very heavily contended. Check if the process needs to be scheduled or
162  * if the lock is contended. For async compaction, back out in the event
163  * if contention is severe. For sync compaction, schedule.
164  *
165  * Returns true if the lock is held.
166  * Returns false if the lock is released and compaction should abort
167  */
168 static bool compact_checklock_irqsave(spinlock_t *lock, unsigned long *flags,
169                                       bool locked, struct compact_control *cc)
170 {
171         if (should_release_lock(lock)) {
172                 if (locked) {
173                         spin_unlock_irqrestore(lock, *flags);
174                         locked = false;
175                 }
176
177                 /* async aborts if taking too long or contended */
178                 if (!cc->sync) {
179                         cc->contended = true;
180                         return false;
181                 }
182
183                 cond_resched();
184         }
185
186         if (!locked)
187                 spin_lock_irqsave(lock, *flags);
188         return true;
189 }
190
191 static inline bool compact_trylock_irqsave(spinlock_t *lock,
192                         unsigned long *flags, struct compact_control *cc)
193 {
194         return compact_checklock_irqsave(lock, flags, false, cc);
195 }
196
197 /* Returns true if the page is within a block suitable for migration to */
198 static bool suitable_migration_target(struct page *page)
199 {
200         int migratetype = get_pageblock_migratetype(page);
201
202         /* Don't interfere with memory hot-remove or the min_free_kbytes blocks */
203         if (migratetype == MIGRATE_ISOLATE || migratetype == MIGRATE_RESERVE)
204                 return false;
205
206         /* If the page is a large free page, then allow migration */
207         if (PageBuddy(page) && page_order(page) >= pageblock_order)
208                 return true;
209
210         /* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */
211         if (migrate_async_suitable(migratetype))
212                 return true;
213
214         /* Otherwise skip the block */
215         return false;
216 }
217
218 /*
219  * Isolate free pages onto a private freelist. Caller must hold zone->lock.
220  * If @strict is true, will abort returning 0 on any invalid PFNs or non-free
221  * pages inside of the pageblock (even though it may still end up isolating
222  * some pages).
223  */
224 static unsigned long isolate_freepages_block(struct compact_control *cc,
225                                 unsigned long blockpfn,
226                                 unsigned long end_pfn,
227                                 struct list_head *freelist,
228                                 bool strict)
229 {
230         int nr_scanned = 0, total_isolated = 0;
231         struct page *cursor, *valid_page = NULL;
232         unsigned long nr_strict_required = end_pfn - blockpfn;
233         unsigned long flags;
234         bool locked = false;
235
236         cursor = pfn_to_page(blockpfn);
237
238         /* Isolate free pages. */
239         for (; blockpfn < end_pfn; blockpfn++, cursor++) {
240                 int isolated, i;
241                 struct page *page = cursor;
242
243                 nr_scanned++;
244                 if (!pfn_valid_within(blockpfn))
245                         continue;
246                 if (!valid_page)
247                         valid_page = page;
248                 if (!PageBuddy(page))
249                         continue;
250
251                 /*
252                  * The zone lock must be held to isolate freepages.
253                  * Unfortunately this is a very coarse lock and can be
254                  * heavily contended if there are parallel allocations
255                  * or parallel compactions. For async compaction do not
256                  * spin on the lock and we acquire the lock as late as
257                  * possible.
258                  */
259                 locked = compact_checklock_irqsave(&cc->zone->lock, &flags,
260                                                                 locked, cc);
261                 if (!locked)
262                         break;
263
264                 /* Recheck this is a suitable migration target under lock */
265                 if (!strict && !suitable_migration_target(page))
266                         break;
267
268                 /* Recheck this is a buddy page under lock */
269                 if (!PageBuddy(page))
270                         continue;
271
272                 /* Found a free page, break it into order-0 pages */
273                 isolated = split_free_page(page);
274                 if (!isolated && strict)
275                         break;
276                 total_isolated += isolated;
277                 for (i = 0; i < isolated; i++) {
278                         list_add(&page->lru, freelist);
279                         page++;
280                 }
281
282                 /* If a page was split, advance to the end of it */
283                 if (isolated) {
284                         blockpfn += isolated - 1;
285                         cursor += isolated - 1;
286                 }
287         }
288
289         trace_mm_compaction_isolate_freepages(nr_scanned, total_isolated);
290
291         /*
292          * If strict isolation is requested by CMA then check that all the
293          * pages requested were isolated. If there were any failures, 0 is
294          * returned and CMA will fail.
295          */
296         if (strict && nr_strict_required > total_isolated)
297                 total_isolated = 0;
298
299         if (locked)
300                 spin_unlock_irqrestore(&cc->zone->lock, flags);
301
302         /* Update the pageblock-skip if the whole pageblock was scanned */
303         if (blockpfn == end_pfn)
304                 update_pageblock_skip(cc, valid_page, total_isolated, false);
305
306         return total_isolated;
307 }
308
309 /**
310  * isolate_freepages_range() - isolate free pages.
311  * @start_pfn: The first PFN to start isolating.
312  * @end_pfn:   The one-past-last PFN.
313  *
314  * Non-free pages, invalid PFNs, or zone boundaries within the
315  * [start_pfn, end_pfn) range are considered errors, cause function to
316  * undo its actions and return zero.
317  *
318  * Otherwise, function returns one-past-the-last PFN of isolated page
319  * (which may be greater then end_pfn if end fell in a middle of
320  * a free page).
321  */
322 unsigned long
323 isolate_freepages_range(struct compact_control *cc,
324                         unsigned long start_pfn, unsigned long end_pfn)
325 {
326         unsigned long isolated, pfn, block_end_pfn;
327         LIST_HEAD(freelist);
328
329         for (pfn = start_pfn; pfn < end_pfn; pfn += isolated) {
330                 if (!pfn_valid(pfn) || cc->zone != page_zone(pfn_to_page(pfn)))
331                         break;
332
333                 /*
334                  * On subsequent iterations ALIGN() is actually not needed,
335                  * but we keep it that we not to complicate the code.
336                  */
337                 block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
338                 block_end_pfn = min(block_end_pfn, end_pfn);
339
340                 isolated = isolate_freepages_block(cc, pfn, block_end_pfn,
341                                                    &freelist, true);
342
343                 /*
344                  * In strict mode, isolate_freepages_block() returns 0 if
345                  * there are any holes in the block (ie. invalid PFNs or
346                  * non-free pages).
347                  */
348                 if (!isolated)
349                         break;
350
351                 /*
352                  * If we managed to isolate pages, it is always (1 << n) *
353                  * pageblock_nr_pages for some non-negative n.  (Max order
354                  * page may span two pageblocks).
355                  */
356         }
357
358         /* split_free_page does not map the pages */
359         map_pages(&freelist);
360
361         if (pfn < end_pfn) {
362                 /* Loop terminated early, cleanup. */
363                 release_freepages(&freelist);
364                 return 0;
365         }
366
367         /* We don't use freelists for anything. */
368         return pfn;
369 }
370
371 /* Update the number of anon and file isolated pages in the zone */
372 static void acct_isolated(struct zone *zone, bool locked, struct compact_control *cc)
373 {
374         struct page *page;
375         unsigned int count[2] = { 0, };
376
377         list_for_each_entry(page, &cc->migratepages, lru)
378                 count[!!page_is_file_cache(page)]++;
379
380         /* If locked we can use the interrupt unsafe versions */
381         if (locked) {
382                 __mod_zone_page_state(zone, NR_ISOLATED_ANON, count[0]);
383                 __mod_zone_page_state(zone, NR_ISOLATED_FILE, count[1]);
384         } else {
385                 mod_zone_page_state(zone, NR_ISOLATED_ANON, count[0]);
386                 mod_zone_page_state(zone, NR_ISOLATED_FILE, count[1]);
387         }
388 }
389
390 /* Similar to reclaim, but different enough that they don't share logic */
391 static bool too_many_isolated(struct zone *zone)
392 {
393         unsigned long active, inactive, isolated;
394
395         inactive = zone_page_state(zone, NR_INACTIVE_FILE) +
396                                         zone_page_state(zone, NR_INACTIVE_ANON);
397         active = zone_page_state(zone, NR_ACTIVE_FILE) +
398                                         zone_page_state(zone, NR_ACTIVE_ANON);
399         isolated = zone_page_state(zone, NR_ISOLATED_FILE) +
400                                         zone_page_state(zone, NR_ISOLATED_ANON);
401
402         return isolated > (inactive + active) / 2;
403 }
404
405 /**
406  * isolate_migratepages_range() - isolate all migrate-able pages in range.
407  * @zone:       Zone pages are in.
408  * @cc:         Compaction control structure.
409  * @low_pfn:    The first PFN of the range.
410  * @end_pfn:    The one-past-the-last PFN of the range.
411  * @unevictable: true if it allows to isolate unevictable pages
412  *
413  * Isolate all pages that can be migrated from the range specified by
414  * [low_pfn, end_pfn).  Returns zero if there is a fatal signal
415  * pending), otherwise PFN of the first page that was not scanned
416  * (which may be both less, equal to or more then end_pfn).
417  *
418  * Assumes that cc->migratepages is empty and cc->nr_migratepages is
419  * zero.
420  *
421  * Apart from cc->migratepages and cc->nr_migratetypes this function
422  * does not modify any cc's fields, in particular it does not modify
423  * (or read for that matter) cc->migrate_pfn.
424  */
425 unsigned long
426 isolate_migratepages_range(struct zone *zone, struct compact_control *cc,
427                 unsigned long low_pfn, unsigned long end_pfn, bool unevictable)
428 {
429         unsigned long last_pageblock_nr = 0, pageblock_nr;
430         unsigned long nr_scanned = 0, nr_isolated = 0;
431         struct list_head *migratelist = &cc->migratepages;
432         isolate_mode_t mode = 0;
433         struct lruvec *lruvec;
434         unsigned long flags;
435         bool locked = false;
436         struct page *page = NULL, *valid_page = NULL;
437
438         /*
439          * Ensure that there are not too many pages isolated from the LRU
440          * list by either parallel reclaimers or compaction. If there are,
441          * delay for some time until fewer pages are isolated
442          */
443         while (unlikely(too_many_isolated(zone))) {
444                 /* async migration should just abort */
445                 if (!cc->sync)
446                         return 0;
447
448                 congestion_wait(BLK_RW_ASYNC, HZ/10);
449
450                 if (fatal_signal_pending(current))
451                         return 0;
452         }
453
454         /* Time to isolate some pages for migration */
455         cond_resched();
456         for (; low_pfn < end_pfn; low_pfn++) {
457                 /* give a chance to irqs before checking need_resched() */
458                 if (locked && !((low_pfn+1) % SWAP_CLUSTER_MAX)) {
459                         if (should_release_lock(&zone->lru_lock)) {
460                                 spin_unlock_irqrestore(&zone->lru_lock, flags);
461                                 locked = false;
462                         }
463                 }
464
465                 /*
466                  * migrate_pfn does not necessarily start aligned to a
467                  * pageblock. Ensure that pfn_valid is called when moving
468                  * into a new MAX_ORDER_NR_PAGES range in case of large
469                  * memory holes within the zone
470                  */
471                 if ((low_pfn & (MAX_ORDER_NR_PAGES - 1)) == 0) {
472                         if (!pfn_valid(low_pfn)) {
473                                 low_pfn += MAX_ORDER_NR_PAGES - 1;
474                                 continue;
475                         }
476                 }
477
478                 if (!pfn_valid_within(low_pfn))
479                         continue;
480                 nr_scanned++;
481
482                 /*
483                  * Get the page and ensure the page is within the same zone.
484                  * See the comment in isolate_freepages about overlapping
485                  * nodes. It is deliberate that the new zone lock is not taken
486                  * as memory compaction should not move pages between nodes.
487                  */
488                 page = pfn_to_page(low_pfn);
489                 if (page_zone(page) != zone)
490                         continue;
491
492                 if (!valid_page)
493                         valid_page = page;
494
495                 /* If isolation recently failed, do not retry */
496                 pageblock_nr = low_pfn >> pageblock_order;
497                 if (!isolation_suitable(cc, page))
498                         goto next_pageblock;
499
500                 /* Skip if free */
501                 if (PageBuddy(page))
502                         continue;
503
504                 /*
505                  * For async migration, also only scan in MOVABLE blocks. Async
506                  * migration is optimistic to see if the minimum amount of work
507                  * satisfies the allocation
508                  */
509                 if (!cc->sync && last_pageblock_nr != pageblock_nr &&
510                     !migrate_async_suitable(get_pageblock_migratetype(page))) {
511                         cc->finished_update_migrate = true;
512                         goto next_pageblock;
513                 }
514
515                 /*
516                  * Check may be lockless but that's ok as we recheck later.
517                  * It's possible to migrate LRU pages and balloon pages
518                  * Skip any other type of page
519                  */
520                 if (!PageLRU(page)) {
521                         if (unlikely(balloon_page_movable(page))) {
522                                 if (locked && balloon_page_isolate(page)) {
523                                         /* Successfully isolated */
524                                         cc->finished_update_migrate = true;
525                                         list_add(&page->lru, migratelist);
526                                         cc->nr_migratepages++;
527                                         nr_isolated++;
528                                         goto check_compact_cluster;
529                                 }
530                         }
531                         continue;
532                 }
533
534                 /*
535                  * PageLRU is set. lru_lock normally excludes isolation
536                  * splitting and collapsing (collapsing has already happened
537                  * if PageLRU is set) but the lock is not necessarily taken
538                  * here and it is wasteful to take it just to check transhuge.
539                  * Check TransHuge without lock and skip the whole pageblock if
540                  * it's either a transhuge or hugetlbfs page, as calling
541                  * compound_order() without preventing THP from splitting the
542                  * page underneath us may return surprising results.
543                  */
544                 if (PageTransHuge(page)) {
545                         if (!locked)
546                                 goto next_pageblock;
547                         low_pfn += (1 << compound_order(page)) - 1;
548                         continue;
549                 }
550
551                 /* Check if it is ok to still hold the lock */
552                 locked = compact_checklock_irqsave(&zone->lru_lock, &flags,
553                                                                 locked, cc);
554                 if (!locked || fatal_signal_pending(current))
555                         break;
556
557                 /* Recheck PageLRU and PageTransHuge under lock */
558                 if (!PageLRU(page))
559                         continue;
560                 if (PageTransHuge(page)) {
561                         low_pfn += (1 << compound_order(page)) - 1;
562                         continue;
563                 }
564
565                 if (!cc->sync)
566                         mode |= ISOLATE_ASYNC_MIGRATE;
567
568                 if (unevictable)
569                         mode |= ISOLATE_UNEVICTABLE;
570
571                 lruvec = mem_cgroup_page_lruvec(page, zone);
572
573                 /* Try isolate the page */
574                 if (__isolate_lru_page(page, mode) != 0)
575                         continue;
576
577                 VM_BUG_ON(PageTransCompound(page));
578
579                 /* Successfully isolated */
580                 cc->finished_update_migrate = true;
581                 del_page_from_lru_list(page, lruvec, page_lru(page));
582                 list_add(&page->lru, migratelist);
583                 cc->nr_migratepages++;
584                 nr_isolated++;
585
586 check_compact_cluster:
587                 /* Avoid isolating too much */
588                 if (cc->nr_migratepages == COMPACT_CLUSTER_MAX) {
589                         ++low_pfn;
590                         break;
591                 }
592
593                 continue;
594
595 next_pageblock:
596                 low_pfn += pageblock_nr_pages;
597                 low_pfn = ALIGN(low_pfn, pageblock_nr_pages) - 1;
598                 last_pageblock_nr = pageblock_nr;
599         }
600
601         acct_isolated(zone, locked, cc);
602
603         if (locked)
604                 spin_unlock_irqrestore(&zone->lru_lock, flags);
605
606         /* Update the pageblock-skip if the whole pageblock was scanned */
607         if (low_pfn == end_pfn)
608                 update_pageblock_skip(cc, valid_page, nr_isolated, true);
609
610         trace_mm_compaction_isolate_migratepages(nr_scanned, nr_isolated);
611
612         return low_pfn;
613 }
614
615 #endif /* CONFIG_COMPACTION || CONFIG_CMA */
616 #ifdef CONFIG_COMPACTION
617 /*
618  * Based on information in the current compact_control, find blocks
619  * suitable for isolating free pages from and then isolate them.
620  */
621 static void isolate_freepages(struct zone *zone,
622                                 struct compact_control *cc)
623 {
624         struct page *page;
625         unsigned long high_pfn, low_pfn, pfn, zone_end_pfn, end_pfn;
626         int nr_freepages = cc->nr_freepages;
627         struct list_head *freelist = &cc->freepages;
628
629         /*
630          * Initialise the free scanner. The starting point is where we last
631          * scanned from (or the end of the zone if starting). The low point
632          * is the end of the pageblock the migration scanner is using.
633          */
634         pfn = cc->free_pfn;
635         low_pfn = cc->migrate_pfn + pageblock_nr_pages;
636
637         /*
638          * Take care that if the migration scanner is at the end of the zone
639          * that the free scanner does not accidentally move to the next zone
640          * in the next isolation cycle.
641          */
642         high_pfn = min(low_pfn, pfn);
643
644         zone_end_pfn = zone->zone_start_pfn + zone->spanned_pages;
645
646         /*
647          * Isolate free pages until enough are available to migrate the
648          * pages on cc->migratepages. We stop searching if the migrate
649          * and free page scanners meet or enough free pages are isolated.
650          */
651         for (; pfn > low_pfn && cc->nr_migratepages > nr_freepages;
652                                         pfn -= pageblock_nr_pages) {
653                 unsigned long isolated;
654
655                 if (!pfn_valid(pfn))
656                         continue;
657
658                 /*
659                  * Check for overlapping nodes/zones. It's possible on some
660                  * configurations to have a setup like
661                  * node0 node1 node0
662                  * i.e. it's possible that all pages within a zones range of
663                  * pages do not belong to a single zone.
664                  */
665                 page = pfn_to_page(pfn);
666                 if (page_zone(page) != zone)
667                         continue;
668
669                 /* Check the block is suitable for migration */
670                 if (!suitable_migration_target(page))
671                         continue;
672
673                 /* If isolation recently failed, do not retry */
674                 if (!isolation_suitable(cc, page))
675                         continue;
676
677                 /* Found a block suitable for isolating free pages from */
678                 isolated = 0;
679                 end_pfn = min(pfn + pageblock_nr_pages, zone_end_pfn);
680                 isolated = isolate_freepages_block(cc, pfn, end_pfn,
681                                                    freelist, false);
682                 nr_freepages += isolated;
683
684                 /*
685                  * Record the highest PFN we isolated pages from. When next
686                  * looking for free pages, the search will restart here as
687                  * page migration may have returned some pages to the allocator
688                  */
689                 if (isolated) {
690                         cc->finished_update_free = true;
691                         high_pfn = max(high_pfn, pfn);
692                 }
693         }
694
695         /* split_free_page does not map the pages */
696         map_pages(freelist);
697
698         cc->free_pfn = high_pfn;
699         cc->nr_freepages = nr_freepages;
700 }
701
702 /*
703  * This is a migrate-callback that "allocates" freepages by taking pages
704  * from the isolated freelists in the block we are migrating to.
705  */
706 static struct page *compaction_alloc(struct page *migratepage,
707                                         unsigned long data,
708                                         int **result)
709 {
710         struct compact_control *cc = (struct compact_control *)data;
711         struct page *freepage;
712
713         /* Isolate free pages if necessary */
714         if (list_empty(&cc->freepages)) {
715                 isolate_freepages(cc->zone, cc);
716
717                 if (list_empty(&cc->freepages))
718                         return NULL;
719         }
720
721         freepage = list_entry(cc->freepages.next, struct page, lru);
722         list_del(&freepage->lru);
723         cc->nr_freepages--;
724
725         return freepage;
726 }
727
728 /*
729  * We cannot control nr_migratepages and nr_freepages fully when migration is
730  * running as migrate_pages() has no knowledge of compact_control. When
731  * migration is complete, we count the number of pages on the lists by hand.
732  */
733 static void update_nr_listpages(struct compact_control *cc)
734 {
735         int nr_migratepages = 0;
736         int nr_freepages = 0;
737         struct page *page;
738
739         list_for_each_entry(page, &cc->migratepages, lru)
740                 nr_migratepages++;
741         list_for_each_entry(page, &cc->freepages, lru)
742                 nr_freepages++;
743
744         cc->nr_migratepages = nr_migratepages;
745         cc->nr_freepages = nr_freepages;
746 }
747
748 /* possible outcome of isolate_migratepages */
749 typedef enum {
750         ISOLATE_ABORT,          /* Abort compaction now */
751         ISOLATE_NONE,           /* No pages isolated, continue scanning */
752         ISOLATE_SUCCESS,        /* Pages isolated, migrate */
753 } isolate_migrate_t;
754
755 /*
756  * Isolate all pages that can be migrated from the block pointed to by
757  * the migrate scanner within compact_control.
758  */
759 static isolate_migrate_t isolate_migratepages(struct zone *zone,
760                                         struct compact_control *cc)
761 {
762         unsigned long low_pfn, end_pfn;
763
764         /* Do not scan outside zone boundaries */
765         low_pfn = max(cc->migrate_pfn, zone->zone_start_pfn);
766
767         /* Only scan within a pageblock boundary */
768         end_pfn = ALIGN(low_pfn + pageblock_nr_pages, pageblock_nr_pages);
769
770         /* Do not cross the free scanner or scan within a memory hole */
771         if (end_pfn > cc->free_pfn || !pfn_valid(low_pfn)) {
772                 cc->migrate_pfn = end_pfn;
773                 return ISOLATE_NONE;
774         }
775
776         /* Perform the isolation */
777         low_pfn = isolate_migratepages_range(zone, cc, low_pfn, end_pfn, false);
778         if (!low_pfn || cc->contended)
779                 return ISOLATE_ABORT;
780
781         cc->migrate_pfn = low_pfn;
782
783         return ISOLATE_SUCCESS;
784 }
785
786 static int compact_finished(struct zone *zone,
787                             struct compact_control *cc)
788 {
789         unsigned long watermark;
790
791         if (fatal_signal_pending(current))
792                 return COMPACT_PARTIAL;
793
794         /* Compaction run completes if the migrate and free scanner meet */
795         if (cc->free_pfn <= cc->migrate_pfn) {
796                 /*
797                  * Mark that the PG_migrate_skip information should be cleared
798                  * by kswapd when it goes to sleep. kswapd does not set the
799                  * flag itself as the decision to be clear should be directly
800                  * based on an allocation request.
801                  */
802                 if (!current_is_kswapd())
803                         zone->compact_blockskip_flush = true;
804
805                 return COMPACT_COMPLETE;
806         }
807
808         /*
809          * order == -1 is expected when compacting via
810          * /proc/sys/vm/compact_memory
811          */
812         if (cc->order == -1)
813                 return COMPACT_CONTINUE;
814
815         /* Compaction run is not finished if the watermark is not met */
816         watermark = low_wmark_pages(zone);
817         watermark += (1 << cc->order);
818
819         if (!zone_watermark_ok(zone, cc->order, watermark, 0, 0))
820                 return COMPACT_CONTINUE;
821
822         /* Direct compactor: Is a suitable page free? */
823         if (cc->page) {
824                 /* Was a suitable page captured? */
825                 if (*cc->page)
826                         return COMPACT_PARTIAL;
827         } else {
828                 unsigned int order;
829                 for (order = cc->order; order < MAX_ORDER; order++) {
830                         struct free_area *area = &zone->free_area[cc->order];
831                         /* Job done if page is free of the right migratetype */
832                         if (!list_empty(&area->free_list[cc->migratetype]))
833                                 return COMPACT_PARTIAL;
834
835                         /* Job done if allocation would set block type */
836                         if (cc->order >= pageblock_order && area->nr_free)
837                                 return COMPACT_PARTIAL;
838                 }
839         }
840
841         return COMPACT_CONTINUE;
842 }
843
844 /*
845  * compaction_suitable: Is this suitable to run compaction on this zone now?
846  * Returns
847  *   COMPACT_SKIPPED  - If there are too few free pages for compaction
848  *   COMPACT_PARTIAL  - If the allocation would succeed without compaction
849  *   COMPACT_CONTINUE - If compaction should run now
850  */
851 unsigned long compaction_suitable(struct zone *zone, int order)
852 {
853         int fragindex;
854         unsigned long watermark;
855
856         /*
857          * order == -1 is expected when compacting via
858          * /proc/sys/vm/compact_memory
859          */
860         if (order == -1)
861                 return COMPACT_CONTINUE;
862
863         /*
864          * Watermarks for order-0 must be met for compaction. Note the 2UL.
865          * This is because during migration, copies of pages need to be
866          * allocated and for a short time, the footprint is higher
867          */
868         watermark = low_wmark_pages(zone) + (2UL << order);
869         if (!zone_watermark_ok(zone, 0, watermark, 0, 0))
870                 return COMPACT_SKIPPED;
871
872         /*
873          * fragmentation index determines if allocation failures are due to
874          * low memory or external fragmentation
875          *
876          * index of -1000 implies allocations might succeed depending on
877          * watermarks
878          * index towards 0 implies failure is due to lack of memory
879          * index towards 1000 implies failure is due to fragmentation
880          *
881          * Only compact if a failure would be due to fragmentation.
882          */
883         fragindex = fragmentation_index(zone, order);
884         if (fragindex >= 0 && fragindex <= sysctl_extfrag_threshold)
885                 return COMPACT_SKIPPED;
886
887         if (fragindex == -1000 && zone_watermark_ok(zone, order, watermark,
888             0, 0))
889                 return COMPACT_PARTIAL;
890
891         return COMPACT_CONTINUE;
892 }
893
894 static void compact_capture_page(struct compact_control *cc)
895 {
896         unsigned long flags;
897         int mtype, mtype_low, mtype_high;
898
899         if (!cc->page || *cc->page)
900                 return;
901
902         /*
903          * For MIGRATE_MOVABLE allocations we capture a suitable page ASAP
904          * regardless of the migratetype of the freelist is is captured from.
905          * This is fine because the order for a high-order MIGRATE_MOVABLE
906          * allocation is typically at least a pageblock size and overall
907          * fragmentation is not impaired. Other allocation types must
908          * capture pages from their own migratelist because otherwise they
909          * could pollute other pageblocks like MIGRATE_MOVABLE with
910          * difficult to move pages and making fragmentation worse overall.
911          */
912         if (cc->migratetype == MIGRATE_MOVABLE) {
913                 mtype_low = 0;
914                 mtype_high = MIGRATE_PCPTYPES;
915         } else {
916                 mtype_low = cc->migratetype;
917                 mtype_high = cc->migratetype + 1;
918         }
919
920         /* Speculatively examine the free lists without zone lock */
921         for (mtype = mtype_low; mtype < mtype_high; mtype++) {
922                 int order;
923                 for (order = cc->order; order < MAX_ORDER; order++) {
924                         struct page *page;
925                         struct free_area *area;
926                         area = &(cc->zone->free_area[order]);
927                         if (list_empty(&area->free_list[mtype]))
928                                 continue;
929
930                         /* Take the lock and attempt capture of the page */
931                         if (!compact_trylock_irqsave(&cc->zone->lock, &flags, cc))
932                                 return;
933                         if (!list_empty(&area->free_list[mtype])) {
934                                 page = list_entry(area->free_list[mtype].next,
935                                                         struct page, lru);
936                                 if (capture_free_page(page, cc->order, mtype)) {
937                                         spin_unlock_irqrestore(&cc->zone->lock,
938                                                                         flags);
939                                         *cc->page = page;
940                                         return;
941                                 }
942                         }
943                         spin_unlock_irqrestore(&cc->zone->lock, flags);
944                 }
945         }
946 }
947
948 static int compact_zone(struct zone *zone, struct compact_control *cc)
949 {
950         int ret;
951         unsigned long start_pfn = zone->zone_start_pfn;
952         unsigned long end_pfn = zone->zone_start_pfn + zone->spanned_pages;
953
954         ret = compaction_suitable(zone, cc->order);
955         switch (ret) {
956         case COMPACT_PARTIAL:
957         case COMPACT_SKIPPED:
958                 /* Compaction is likely to fail */
959                 return ret;
960         case COMPACT_CONTINUE:
961                 /* Fall through to compaction */
962                 ;
963         }
964
965         /*
966          * Setup to move all movable pages to the end of the zone. Used cached
967          * information on where the scanners should start but check that it
968          * is initialised by ensuring the values are within zone boundaries.
969          */
970         cc->migrate_pfn = zone->compact_cached_migrate_pfn;
971         cc->free_pfn = zone->compact_cached_free_pfn;
972         if (cc->free_pfn < start_pfn || cc->free_pfn > end_pfn) {
973                 cc->free_pfn = end_pfn & ~(pageblock_nr_pages-1);
974                 zone->compact_cached_free_pfn = cc->free_pfn;
975         }
976         if (cc->migrate_pfn < start_pfn || cc->migrate_pfn > end_pfn) {
977                 cc->migrate_pfn = start_pfn;
978                 zone->compact_cached_migrate_pfn = cc->migrate_pfn;
979         }
980
981         /*
982          * Clear pageblock skip if there were failures recently and compaction
983          * is about to be retried after being deferred. kswapd does not do
984          * this reset as it'll reset the cached information when going to sleep.
985          */
986         if (compaction_restarting(zone, cc->order) && !current_is_kswapd())
987                 __reset_isolation_suitable(zone);
988
989         migrate_prep_local();
990
991         while ((ret = compact_finished(zone, cc)) == COMPACT_CONTINUE) {
992                 unsigned long nr_migrate, nr_remaining;
993                 int err;
994
995                 switch (isolate_migratepages(zone, cc)) {
996                 case ISOLATE_ABORT:
997                         ret = COMPACT_PARTIAL;
998                         putback_movable_pages(&cc->migratepages);
999                         cc->nr_migratepages = 0;
1000                         goto out;
1001                 case ISOLATE_NONE:
1002                         continue;
1003                 case ISOLATE_SUCCESS:
1004                         ;
1005                 }
1006
1007                 nr_migrate = cc->nr_migratepages;
1008                 err = migrate_pages(&cc->migratepages, compaction_alloc,
1009                                 (unsigned long)cc, false,
1010                                 cc->sync ? MIGRATE_SYNC_LIGHT : MIGRATE_ASYNC);
1011                 update_nr_listpages(cc);
1012                 nr_remaining = cc->nr_migratepages;
1013
1014                 count_vm_event(COMPACTBLOCKS);
1015                 count_vm_events(COMPACTPAGES, nr_migrate - nr_remaining);
1016                 if (nr_remaining)
1017                         count_vm_events(COMPACTPAGEFAILED, nr_remaining);
1018                 trace_mm_compaction_migratepages(nr_migrate - nr_remaining,
1019                                                 nr_remaining);
1020
1021                 /* Release isolated pages not migrated */
1022                 if (err) {
1023                         putback_movable_pages(&cc->migratepages);
1024                         cc->nr_migratepages = 0;
1025                         if (err == -ENOMEM) {
1026                                 ret = COMPACT_PARTIAL;
1027                                 goto out;
1028                         }
1029                 }
1030
1031                 /* Capture a page now if it is a suitable size */
1032                 compact_capture_page(cc);
1033         }
1034
1035 out:
1036         /* Release free pages and check accounting */
1037         cc->nr_freepages -= release_freepages(&cc->freepages);
1038         VM_BUG_ON(cc->nr_freepages != 0);
1039
1040         return ret;
1041 }
1042
1043 static unsigned long compact_zone_order(struct zone *zone,
1044                                  int order, gfp_t gfp_mask,
1045                                  bool sync, bool *contended,
1046                                  struct page **page)
1047 {
1048         unsigned long ret;
1049         struct compact_control cc = {
1050                 .nr_freepages = 0,
1051                 .nr_migratepages = 0,
1052                 .order = order,
1053                 .migratetype = allocflags_to_migratetype(gfp_mask),
1054                 .zone = zone,
1055                 .sync = sync,
1056                 .page = page,
1057         };
1058         INIT_LIST_HEAD(&cc.freepages);
1059         INIT_LIST_HEAD(&cc.migratepages);
1060
1061         ret = compact_zone(zone, &cc);
1062
1063         VM_BUG_ON(!list_empty(&cc.freepages));
1064         VM_BUG_ON(!list_empty(&cc.migratepages));
1065
1066         *contended = cc.contended;
1067         return ret;
1068 }
1069
1070 int sysctl_extfrag_threshold = 500;
1071
1072 /**
1073  * try_to_compact_pages - Direct compact to satisfy a high-order allocation
1074  * @zonelist: The zonelist used for the current allocation
1075  * @order: The order of the current allocation
1076  * @gfp_mask: The GFP mask of the current allocation
1077  * @nodemask: The allowed nodes to allocate from
1078  * @sync: Whether migration is synchronous or not
1079  * @contended: Return value that is true if compaction was aborted due to lock contention
1080  * @page: Optionally capture a free page of the requested order during compaction
1081  *
1082  * This is the main entry point for direct page compaction.
1083  */
1084 unsigned long try_to_compact_pages(struct zonelist *zonelist,
1085                         int order, gfp_t gfp_mask, nodemask_t *nodemask,
1086                         bool sync, bool *contended, struct page **page)
1087 {
1088         enum zone_type high_zoneidx = gfp_zone(gfp_mask);
1089         int may_enter_fs = gfp_mask & __GFP_FS;
1090         int may_perform_io = gfp_mask & __GFP_IO;
1091         struct zoneref *z;
1092         struct zone *zone;
1093         int rc = COMPACT_SKIPPED;
1094         int alloc_flags = 0;
1095
1096         /* Check if the GFP flags allow compaction */
1097         if (!order || !may_enter_fs || !may_perform_io)
1098                 return rc;
1099
1100         count_vm_event(COMPACTSTALL);
1101
1102 #ifdef CONFIG_CMA
1103         if (allocflags_to_migratetype(gfp_mask) == MIGRATE_MOVABLE)
1104                 alloc_flags |= ALLOC_CMA;
1105 #endif
1106         /* Compact each zone in the list */
1107         for_each_zone_zonelist_nodemask(zone, z, zonelist, high_zoneidx,
1108                                                                 nodemask) {
1109                 int status;
1110
1111                 status = compact_zone_order(zone, order, gfp_mask, sync,
1112                                                 contended, page);
1113                 rc = max(status, rc);
1114
1115                 /* If a normal allocation would succeed, stop compacting */
1116                 if (zone_watermark_ok(zone, order, low_wmark_pages(zone), 0,
1117                                       alloc_flags))
1118                         break;
1119         }
1120
1121         return rc;
1122 }
1123
1124
1125 /* Compact all zones within a node */
1126 static int __compact_pgdat(pg_data_t *pgdat, struct compact_control *cc)
1127 {
1128         int zoneid;
1129         struct zone *zone;
1130
1131         for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
1132
1133                 zone = &pgdat->node_zones[zoneid];
1134                 if (!populated_zone(zone))
1135                         continue;
1136
1137                 cc->nr_freepages = 0;
1138                 cc->nr_migratepages = 0;
1139                 cc->zone = zone;
1140                 INIT_LIST_HEAD(&cc->freepages);
1141                 INIT_LIST_HEAD(&cc->migratepages);
1142
1143                 if (cc->order == -1 || !compaction_deferred(zone, cc->order))
1144                         compact_zone(zone, cc);
1145
1146                 if (cc->order > 0) {
1147                         int ok = zone_watermark_ok(zone, cc->order,
1148                                                 low_wmark_pages(zone), 0, 0);
1149                         if (ok && cc->order >= zone->compact_order_failed)
1150                                 zone->compact_order_failed = cc->order + 1;
1151                         /* Currently async compaction is never deferred. */
1152                         else if (!ok && cc->sync)
1153                                 defer_compaction(zone, cc->order);
1154                 }
1155
1156                 VM_BUG_ON(!list_empty(&cc->freepages));
1157                 VM_BUG_ON(!list_empty(&cc->migratepages));
1158         }
1159
1160         return 0;
1161 }
1162
1163 int compact_pgdat(pg_data_t *pgdat, int order)
1164 {
1165         struct compact_control cc = {
1166                 .order = order,
1167                 .sync = false,
1168                 .page = NULL,
1169         };
1170
1171         return __compact_pgdat(pgdat, &cc);
1172 }
1173
1174 static int compact_node(int nid)
1175 {
1176         struct compact_control cc = {
1177                 .order = -1,
1178                 .sync = true,
1179                 .page = NULL,
1180         };
1181
1182         return __compact_pgdat(NODE_DATA(nid), &cc);
1183 }
1184
1185 /* Compact all nodes in the system */
1186 static int compact_nodes(void)
1187 {
1188         int nid;
1189
1190         /* Flush pending updates to the LRU lists */
1191         lru_add_drain_all();
1192
1193         for_each_online_node(nid)
1194                 compact_node(nid);
1195
1196         return COMPACT_COMPLETE;
1197 }
1198
1199 /* The written value is actually unused, all memory is compacted */
1200 int sysctl_compact_memory;
1201
1202 /* This is the entry point for compacting all nodes via /proc/sys/vm */
1203 int sysctl_compaction_handler(struct ctl_table *table, int write,
1204                         void __user *buffer, size_t *length, loff_t *ppos)
1205 {
1206         if (write)
1207                 return compact_nodes();
1208
1209         return 0;
1210 }
1211
1212 int sysctl_extfrag_handler(struct ctl_table *table, int write,
1213                         void __user *buffer, size_t *length, loff_t *ppos)
1214 {
1215         proc_dointvec_minmax(table, write, buffer, length, ppos);
1216
1217         return 0;
1218 }
1219
1220 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
1221 ssize_t sysfs_compact_node(struct device *dev,
1222                         struct device_attribute *attr,
1223                         const char *buf, size_t count)
1224 {
1225         int nid = dev->id;
1226
1227         if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
1228                 /* Flush pending updates to the LRU lists */
1229                 lru_add_drain_all();
1230
1231                 compact_node(nid);
1232         }
1233
1234         return count;
1235 }
1236 static DEVICE_ATTR(compact, S_IWUSR, NULL, sysfs_compact_node);
1237
1238 int compaction_register_node(struct node *node)
1239 {
1240         return device_create_file(&node->dev, &dev_attr_compact);
1241 }
1242
1243 void compaction_unregister_node(struct node *node)
1244 {
1245         return device_remove_file(&node->dev, &dev_attr_compact);
1246 }
1247 #endif /* CONFIG_SYSFS && CONFIG_NUMA */
1248
1249 #endif /* CONFIG_COMPACTION */