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