OSDN Git Service

Merge "net/packet: fix overflow in check for tp_reserve"
[sagit-ice-cold/kernel_xiaomi_msm8998.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/cpu.h>
11 #include <linux/swap.h>
12 #include <linux/migrate.h>
13 #include <linux/compaction.h>
14 #include <linux/mm_inline.h>
15 #include <linux/backing-dev.h>
16 #include <linux/sysctl.h>
17 #include <linux/sysfs.h>
18 #include <linux/page-isolation.h>
19 #include <linux/kasan.h>
20 #include <linux/kthread.h>
21 #include <linux/freezer.h>
22 #include <linux/page_owner.h>
23 #include "internal.h"
24
25 #ifdef CONFIG_COMPACTION
26 static inline void count_compact_event(enum vm_event_item item)
27 {
28         count_vm_event(item);
29 }
30
31 static inline void count_compact_events(enum vm_event_item item, long delta)
32 {
33         count_vm_events(item, delta);
34 }
35 #else
36 #define count_compact_event(item) do { } while (0)
37 #define count_compact_events(item, delta) do { } while (0)
38 #endif
39
40 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
41
42 #define CREATE_TRACE_POINTS
43 #include <trace/events/compaction.h>
44
45 static unsigned long release_freepages(struct list_head *freelist)
46 {
47         struct page *page, *next;
48         unsigned long high_pfn = 0;
49
50         list_for_each_entry_safe(page, next, freelist, lru) {
51                 unsigned long pfn = page_to_pfn(page);
52                 list_del(&page->lru);
53                 __free_page(page);
54                 if (pfn > high_pfn)
55                         high_pfn = pfn;
56         }
57
58         return high_pfn;
59 }
60
61 static void map_pages(struct list_head *list)
62 {
63         unsigned int i, order, nr_pages;
64         struct page *page, *next;
65         LIST_HEAD(tmp_list);
66
67         list_for_each_entry_safe(page, next, list, lru) {
68                 list_del(&page->lru);
69
70                 order = page_private(page);
71                 nr_pages = 1 << order;
72
73                 post_alloc_hook(page, order, __GFP_MOVABLE);
74                 if (order)
75                         split_page(page, order);
76
77                 for (i = 0; i < nr_pages; i++) {
78                         list_add(&page->lru, &tmp_list);
79                         page++;
80                 }
81         }
82
83         list_splice(&tmp_list, list);
84 }
85
86 static inline bool migrate_async_suitable(int migratetype)
87 {
88         return is_migrate_cma(migratetype) || migratetype == MIGRATE_MOVABLE;
89 }
90
91 /*
92  * Check that the whole (or subset of) a pageblock given by the interval of
93  * [start_pfn, end_pfn) is valid and within the same zone, before scanning it
94  * with the migration of free compaction scanner. The scanners then need to
95  * use only pfn_valid_within() check for arches that allow holes within
96  * pageblocks.
97  *
98  * Return struct page pointer of start_pfn, or NULL if checks were not passed.
99  *
100  * It's possible on some configurations to have a setup like node0 node1 node0
101  * i.e. it's possible that all pages within a zones range of pages do not
102  * belong to a single zone. We assume that a border between node0 and node1
103  * can occur within a single pageblock, but not a node0 node1 node0
104  * interleaving within a single pageblock. It is therefore sufficient to check
105  * the first and last page of a pageblock and avoid checking each individual
106  * page in a pageblock.
107  */
108 static struct page *pageblock_pfn_to_page(unsigned long start_pfn,
109                                 unsigned long end_pfn, struct zone *zone)
110 {
111         struct page *start_page;
112         struct page *end_page;
113
114         /* end_pfn is one past the range we are checking */
115         end_pfn--;
116
117         if (!pfn_valid(start_pfn) || !pfn_valid(end_pfn))
118                 return NULL;
119
120         start_page = pfn_to_page(start_pfn);
121
122         if (page_zone(start_page) != zone)
123                 return NULL;
124
125         end_page = pfn_to_page(end_pfn);
126
127         /* This gives a shorter code than deriving page_zone(end_page) */
128         if (page_zone_id(start_page) != page_zone_id(end_page))
129                 return NULL;
130
131         return start_page;
132 }
133
134 #ifdef CONFIG_COMPACTION
135
136 int PageMovable(struct page *page)
137 {
138         struct address_space *mapping;
139
140         VM_BUG_ON_PAGE(!PageLocked(page), page);
141         if (!__PageMovable(page))
142                 return 0;
143
144         mapping = page_mapping(page);
145         if (mapping && mapping->a_ops && mapping->a_ops->isolate_page)
146                 return 1;
147
148         return 0;
149 }
150 EXPORT_SYMBOL(PageMovable);
151
152 void __SetPageMovable(struct page *page, struct address_space *mapping)
153 {
154         VM_BUG_ON_PAGE(!PageLocked(page), page);
155         VM_BUG_ON_PAGE((unsigned long)mapping & PAGE_MAPPING_MOVABLE, page);
156         page->mapping = (void *)((unsigned long)mapping | PAGE_MAPPING_MOVABLE);
157 }
158 EXPORT_SYMBOL(__SetPageMovable);
159
160 void __ClearPageMovable(struct page *page)
161 {
162         VM_BUG_ON_PAGE(!PageLocked(page), page);
163         VM_BUG_ON_PAGE(!PageMovable(page), page);
164         /*
165          * Clear registered address_space val with keeping PAGE_MAPPING_MOVABLE
166          * flag so that VM can catch up released page by driver after isolation.
167          * With it, VM migration doesn't try to put it back.
168          */
169         page->mapping = (void *)((unsigned long)page->mapping &
170                                 PAGE_MAPPING_MOVABLE);
171 }
172 EXPORT_SYMBOL(__ClearPageMovable);
173
174 /* Do not skip compaction more than 64 times */
175 #define COMPACT_MAX_DEFER_SHIFT 6
176
177 /*
178  * Compaction is deferred when compaction fails to result in a page
179  * allocation success. 1 << compact_defer_limit compactions are skipped up
180  * to a limit of 1 << COMPACT_MAX_DEFER_SHIFT
181  */
182 void defer_compaction(struct zone *zone, int order)
183 {
184         zone->compact_considered = 0;
185         zone->compact_defer_shift++;
186
187         if (order < zone->compact_order_failed)
188                 zone->compact_order_failed = order;
189
190         if (zone->compact_defer_shift > COMPACT_MAX_DEFER_SHIFT)
191                 zone->compact_defer_shift = COMPACT_MAX_DEFER_SHIFT;
192
193         trace_mm_compaction_defer_compaction(zone, order);
194 }
195
196 /* Returns true if compaction should be skipped this time */
197 bool compaction_deferred(struct zone *zone, int order)
198 {
199         unsigned long defer_limit = 1UL << zone->compact_defer_shift;
200
201         if (order < zone->compact_order_failed)
202                 return false;
203
204         /* Avoid possible overflow */
205         if (++zone->compact_considered > defer_limit)
206                 zone->compact_considered = defer_limit;
207
208         if (zone->compact_considered >= defer_limit)
209                 return false;
210
211         trace_mm_compaction_deferred(zone, order);
212
213         return true;
214 }
215
216 /*
217  * Update defer tracking counters after successful compaction of given order,
218  * which means an allocation either succeeded (alloc_success == true) or is
219  * expected to succeed.
220  */
221 void compaction_defer_reset(struct zone *zone, int order,
222                 bool alloc_success)
223 {
224         if (alloc_success) {
225                 zone->compact_considered = 0;
226                 zone->compact_defer_shift = 0;
227         }
228         if (order >= zone->compact_order_failed)
229                 zone->compact_order_failed = order + 1;
230
231         trace_mm_compaction_defer_reset(zone, order);
232 }
233
234 /* Returns true if restarting compaction after many failures */
235 bool compaction_restarting(struct zone *zone, int order)
236 {
237         if (order < zone->compact_order_failed)
238                 return false;
239
240         return zone->compact_defer_shift == COMPACT_MAX_DEFER_SHIFT &&
241                 zone->compact_considered >= 1UL << zone->compact_defer_shift;
242 }
243
244 /* Returns true if the pageblock should be scanned for pages to isolate. */
245 static inline bool isolation_suitable(struct compact_control *cc,
246                                         struct page *page)
247 {
248         if (cc->ignore_skip_hint)
249                 return true;
250
251         return !get_pageblock_skip(page);
252 }
253
254 static void reset_cached_positions(struct zone *zone)
255 {
256         zone->compact_cached_migrate_pfn[0] = zone->zone_start_pfn;
257         zone->compact_cached_migrate_pfn[1] = zone->zone_start_pfn;
258         zone->compact_cached_free_pfn = zone_end_pfn(zone);
259 }
260
261 /*
262  * This function is called to clear all cached information on pageblocks that
263  * should be skipped for page isolation when the migrate and free page scanner
264  * meet.
265  */
266 static void __reset_isolation_suitable(struct zone *zone)
267 {
268         unsigned long start_pfn = zone->zone_start_pfn;
269         unsigned long end_pfn = zone_end_pfn(zone);
270         unsigned long pfn;
271
272         zone->compact_blockskip_flush = false;
273
274         /* Walk the zone and mark every pageblock as suitable for isolation */
275         for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) {
276                 struct page *page;
277
278                 cond_resched();
279
280                 if (!pfn_valid(pfn))
281                         continue;
282
283                 page = pfn_to_page(pfn);
284                 if (zone != page_zone(page))
285                         continue;
286
287                 clear_pageblock_skip(page);
288         }
289
290         reset_cached_positions(zone);
291 }
292
293 void reset_isolation_suitable(pg_data_t *pgdat)
294 {
295         int zoneid;
296
297         for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
298                 struct zone *zone = &pgdat->node_zones[zoneid];
299                 if (!populated_zone(zone))
300                         continue;
301
302                 /* Only flush if a full compaction finished recently */
303                 if (zone->compact_blockskip_flush)
304                         __reset_isolation_suitable(zone);
305         }
306 }
307
308 /*
309  * If no pages were isolated then mark this pageblock to be skipped in the
310  * future. The information is later cleared by __reset_isolation_suitable().
311  */
312 static void update_pageblock_skip(struct compact_control *cc,
313                         struct page *page, unsigned long nr_isolated,
314                         bool migrate_scanner)
315 {
316         struct zone *zone = cc->zone;
317         unsigned long pfn;
318
319         if (cc->ignore_skip_hint)
320                 return;
321
322         if (!page)
323                 return;
324
325         if (nr_isolated)
326                 return;
327
328         set_pageblock_skip(page);
329
330         pfn = page_to_pfn(page);
331
332         /* Update where async and sync compaction should restart */
333         if (migrate_scanner) {
334                 if (pfn > zone->compact_cached_migrate_pfn[0])
335                         zone->compact_cached_migrate_pfn[0] = pfn;
336                 if (cc->mode != MIGRATE_ASYNC &&
337                     pfn > zone->compact_cached_migrate_pfn[1])
338                         zone->compact_cached_migrate_pfn[1] = pfn;
339         } else {
340                 if (pfn < zone->compact_cached_free_pfn)
341                         zone->compact_cached_free_pfn = pfn;
342         }
343 }
344 #else
345 static inline bool isolation_suitable(struct compact_control *cc,
346                                         struct page *page)
347 {
348         return true;
349 }
350
351 static void update_pageblock_skip(struct compact_control *cc,
352                         struct page *page, unsigned long nr_isolated,
353                         bool migrate_scanner)
354 {
355 }
356 #endif /* CONFIG_COMPACTION */
357
358 /*
359  * Compaction requires the taking of some coarse locks that are potentially
360  * very heavily contended. For async compaction, back out if the lock cannot
361  * be taken immediately. For sync compaction, spin on the lock if needed.
362  *
363  * Returns true if the lock is held
364  * Returns false if the lock is not held and compaction should abort
365  */
366 static bool compact_trylock_irqsave(spinlock_t *lock, unsigned long *flags,
367                                                 struct compact_control *cc)
368 {
369         if (cc->mode == MIGRATE_ASYNC) {
370                 if (!spin_trylock_irqsave(lock, *flags)) {
371                         cc->contended = COMPACT_CONTENDED_LOCK;
372                         return false;
373                 }
374         } else {
375                 spin_lock_irqsave(lock, *flags);
376         }
377
378         return true;
379 }
380
381 /*
382  * Compaction requires the taking of some coarse locks that are potentially
383  * very heavily contended. The lock should be periodically unlocked to avoid
384  * having disabled IRQs for a long time, even when there is nobody waiting on
385  * the lock. It might also be that allowing the IRQs will result in
386  * need_resched() becoming true. If scheduling is needed, async compaction
387  * aborts. Sync compaction schedules.
388  * Either compaction type will also abort if a fatal signal is pending.
389  * In either case if the lock was locked, it is dropped and not regained.
390  *
391  * Returns true if compaction should abort due to fatal signal pending, or
392  *              async compaction due to need_resched()
393  * Returns false when compaction can continue (sync compaction might have
394  *              scheduled)
395  */
396 static bool compact_unlock_should_abort(spinlock_t *lock,
397                 unsigned long flags, bool *locked, struct compact_control *cc)
398 {
399         if (*locked) {
400                 spin_unlock_irqrestore(lock, flags);
401                 *locked = false;
402         }
403
404         if (fatal_signal_pending(current)) {
405                 cc->contended = COMPACT_CONTENDED_SCHED;
406                 return true;
407         }
408
409         if (need_resched()) {
410                 if (cc->mode == MIGRATE_ASYNC) {
411                         cc->contended = COMPACT_CONTENDED_SCHED;
412                         return true;
413                 }
414                 cond_resched();
415         }
416
417         return false;
418 }
419
420 /*
421  * Aside from avoiding lock contention, compaction also periodically checks
422  * need_resched() and either schedules in sync compaction or aborts async
423  * compaction. This is similar to what compact_unlock_should_abort() does, but
424  * is used where no lock is concerned.
425  *
426  * Returns false when no scheduling was needed, or sync compaction scheduled.
427  * Returns true when async compaction should abort.
428  */
429 static inline bool compact_should_abort(struct compact_control *cc)
430 {
431         /* async compaction aborts if contended */
432         if (need_resched()) {
433                 if (cc->mode == MIGRATE_ASYNC) {
434                         cc->contended = COMPACT_CONTENDED_SCHED;
435                         return true;
436                 }
437
438                 cond_resched();
439         }
440
441         return false;
442 }
443
444 /*
445  * Isolate free pages onto a private freelist. If @strict is true, will abort
446  * returning 0 on any invalid PFNs or non-free pages inside of the pageblock
447  * (even though it may still end up isolating some pages).
448  */
449 static unsigned long isolate_freepages_block(struct compact_control *cc,
450                                 unsigned long *start_pfn,
451                                 unsigned long end_pfn,
452                                 struct list_head *freelist,
453                                 bool strict)
454 {
455         int nr_scanned = 0, total_isolated = 0;
456         struct page *cursor, *valid_page = NULL;
457         unsigned long flags = 0;
458         bool locked = false;
459         unsigned long blockpfn = *start_pfn;
460         unsigned int order;
461
462         cursor = pfn_to_page(blockpfn);
463
464         /* Isolate free pages. */
465         for (; blockpfn < end_pfn; blockpfn++, cursor++) {
466                 int isolated;
467                 struct page *page = cursor;
468
469                 /*
470                  * Periodically drop the lock (if held) regardless of its
471                  * contention, to give chance to IRQs. Abort if fatal signal
472                  * pending or async compaction detects need_resched()
473                  */
474                 if (!(blockpfn % SWAP_CLUSTER_MAX)
475                     && compact_unlock_should_abort(&cc->zone->lock, flags,
476                                                                 &locked, cc))
477                         break;
478
479                 nr_scanned++;
480                 if (!pfn_valid_within(blockpfn))
481                         goto isolate_fail;
482
483                 if (!valid_page)
484                         valid_page = page;
485
486                 /*
487                  * For compound pages such as THP and hugetlbfs, we can save
488                  * potentially a lot of iterations if we skip them at once.
489                  * The check is racy, but we can consider only valid values
490                  * and the only danger is skipping too much.
491                  */
492                 if (PageCompound(page)) {
493                         unsigned int comp_order = compound_order(page);
494
495                         if (likely(comp_order < MAX_ORDER)) {
496                                 blockpfn += (1UL << comp_order) - 1;
497                                 cursor += (1UL << comp_order) - 1;
498                         }
499
500                         goto isolate_fail;
501                 }
502
503                 if (!PageBuddy(page))
504                         goto isolate_fail;
505
506                 /*
507                  * If we already hold the lock, we can skip some rechecking.
508                  * Note that if we hold the lock now, checked_pageblock was
509                  * already set in some previous iteration (or strict is true),
510                  * so it is correct to skip the suitable migration target
511                  * recheck as well.
512                  */
513                 if (!locked) {
514                         /*
515                          * The zone lock must be held to isolate freepages.
516                          * Unfortunately this is a very coarse lock and can be
517                          * heavily contended if there are parallel allocations
518                          * or parallel compactions. For async compaction do not
519                          * spin on the lock and we acquire the lock as late as
520                          * possible.
521                          */
522                         locked = compact_trylock_irqsave(&cc->zone->lock,
523                                                                 &flags, cc);
524                         if (!locked)
525                                 break;
526
527                         /* Recheck this is a buddy page under lock */
528                         if (!PageBuddy(page))
529                                 goto isolate_fail;
530                 }
531
532                 /* Found a free page, will break it into order-0 pages */
533                 order = page_order(page);
534                 isolated = __isolate_free_page(page, order);
535                 if (!isolated)
536                         break;
537                 set_page_private(page, order);
538
539                 total_isolated += isolated;
540                 cc->nr_freepages += isolated;
541                 list_add_tail(&page->lru, freelist);
542
543                 if (!strict && cc->nr_migratepages <= cc->nr_freepages) {
544                         blockpfn += isolated;
545                         break;
546                 }
547                 /* Advance to the end of split page */
548                 blockpfn += isolated - 1;
549                 cursor += isolated - 1;
550                 continue;
551
552 isolate_fail:
553                 if (strict)
554                         break;
555                 else
556                         continue;
557
558         }
559
560         if (locked)
561                 spin_unlock_irqrestore(&cc->zone->lock, flags);
562
563         /*
564          * There is a tiny chance that we have read bogus compound_order(),
565          * so be careful to not go outside of the pageblock.
566          */
567         if (unlikely(blockpfn > end_pfn))
568                 blockpfn = end_pfn;
569
570         trace_mm_compaction_isolate_freepages(*start_pfn, blockpfn,
571                                         nr_scanned, total_isolated);
572
573         /* Record how far we have got within the block */
574         *start_pfn = blockpfn;
575
576         /*
577          * If strict isolation is requested by CMA then check that all the
578          * pages requested were isolated. If there were any failures, 0 is
579          * returned and CMA will fail.
580          */
581         if (strict && blockpfn < end_pfn)
582                 total_isolated = 0;
583
584         /* Update the pageblock-skip if the whole pageblock was scanned */
585         if (blockpfn == end_pfn)
586                 update_pageblock_skip(cc, valid_page, total_isolated, false);
587
588         count_compact_events(COMPACTFREE_SCANNED, nr_scanned);
589         if (total_isolated)
590                 count_compact_events(COMPACTISOLATED, total_isolated);
591         return total_isolated;
592 }
593
594 /**
595  * isolate_freepages_range() - isolate free pages.
596  * @start_pfn: The first PFN to start isolating.
597  * @end_pfn:   The one-past-last PFN.
598  *
599  * Non-free pages, invalid PFNs, or zone boundaries within the
600  * [start_pfn, end_pfn) range are considered errors, cause function to
601  * undo its actions and return zero.
602  *
603  * Otherwise, function returns one-past-the-last PFN of isolated page
604  * (which may be greater then end_pfn if end fell in a middle of
605  * a free page).
606  */
607 unsigned long
608 isolate_freepages_range(struct compact_control *cc,
609                         unsigned long start_pfn, unsigned long end_pfn)
610 {
611         unsigned long isolated, pfn, block_end_pfn;
612         LIST_HEAD(freelist);
613
614         pfn = start_pfn;
615         block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
616
617         for (; pfn < end_pfn; pfn += isolated,
618                                 block_end_pfn += pageblock_nr_pages) {
619                 /* Protect pfn from changing by isolate_freepages_block */
620                 unsigned long isolate_start_pfn = pfn;
621
622                 block_end_pfn = min(block_end_pfn, end_pfn);
623
624                 /*
625                  * pfn could pass the block_end_pfn if isolated freepage
626                  * is more than pageblock order. In this case, we adjust
627                  * scanning range to right one.
628                  */
629                 if (pfn >= block_end_pfn) {
630                         block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
631                         block_end_pfn = min(block_end_pfn, end_pfn);
632                 }
633
634                 if (!pageblock_pfn_to_page(pfn, block_end_pfn, cc->zone))
635                         break;
636
637                 isolated = isolate_freepages_block(cc, &isolate_start_pfn,
638                                                 block_end_pfn, &freelist, true);
639
640                 /*
641                  * In strict mode, isolate_freepages_block() returns 0 if
642                  * there are any holes in the block (ie. invalid PFNs or
643                  * non-free pages).
644                  */
645                 if (!isolated)
646                         break;
647
648                 /*
649                  * If we managed to isolate pages, it is always (1 << n) *
650                  * pageblock_nr_pages for some non-negative n.  (Max order
651                  * page may span two pageblocks).
652                  */
653         }
654
655         /* __isolate_free_page() does not map the pages */
656         map_pages(&freelist);
657
658         if (pfn < end_pfn) {
659                 /* Loop terminated early, cleanup. */
660                 release_freepages(&freelist);
661                 return 0;
662         }
663
664         /* We don't use freelists for anything. */
665         return pfn;
666 }
667
668 /* Update the number of anon and file isolated pages in the zone */
669 static void acct_isolated(struct zone *zone, struct compact_control *cc)
670 {
671         struct page *page;
672         unsigned int count[2] = { 0, };
673
674         if (list_empty(&cc->migratepages))
675                 return;
676
677         list_for_each_entry(page, &cc->migratepages, lru)
678                 count[!!page_is_file_cache(page)]++;
679
680         mod_zone_page_state(zone, NR_ISOLATED_ANON, count[0]);
681         mod_zone_page_state(zone, NR_ISOLATED_FILE, count[1]);
682 }
683
684 static bool __too_many_isolated(struct zone *zone, int safe)
685 {
686         unsigned long active, inactive, isolated;
687
688         if (safe) {
689                 inactive = zone_page_state_snapshot(zone, NR_INACTIVE_FILE) +
690                         zone_page_state_snapshot(zone, NR_INACTIVE_ANON);
691                 active = zone_page_state_snapshot(zone, NR_ACTIVE_FILE) +
692                         zone_page_state_snapshot(zone, NR_ACTIVE_ANON);
693                 isolated = zone_page_state_snapshot(zone, NR_ISOLATED_FILE) +
694                         zone_page_state_snapshot(zone, NR_ISOLATED_ANON);
695         } else {
696                 inactive = zone_page_state(zone, NR_INACTIVE_FILE) +
697                         zone_page_state(zone, NR_INACTIVE_ANON);
698                 active = zone_page_state(zone, NR_ACTIVE_FILE) +
699                         zone_page_state(zone, NR_ACTIVE_ANON);
700                 isolated = zone_page_state(zone, NR_ISOLATED_FILE) +
701                         zone_page_state(zone, NR_ISOLATED_ANON);
702         }
703
704         return isolated > (inactive + active) / 2;
705 }
706
707 /* Similar to reclaim, but different enough that they don't share logic */
708 static bool too_many_isolated(struct compact_control *cc)
709 {
710         /*
711          * __too_many_isolated(safe=0) is fast but inaccurate, because it
712          * doesn't account for the vm_stat_diff[] counters.  So if it looks
713          * like too_many_isolated() is about to return true, fall back to the
714          * slower, more accurate zone_page_state_snapshot().
715          */
716         if (unlikely(__too_many_isolated(cc->zone, 0))) {
717                 if (cc->mode != MIGRATE_ASYNC)
718                         return __too_many_isolated(cc->zone, 1);
719         }
720
721         return false;
722 }
723
724 /**
725  * isolate_migratepages_block() - isolate all migrate-able pages within
726  *                                a single pageblock
727  * @cc:         Compaction control structure.
728  * @low_pfn:    The first PFN to isolate
729  * @end_pfn:    The one-past-the-last PFN to isolate, within same pageblock
730  * @isolate_mode: Isolation mode to be used.
731  *
732  * Isolate all pages that can be migrated from the range specified by
733  * [low_pfn, end_pfn). The range is expected to be within same pageblock.
734  * Returns zero if there is a fatal signal pending, otherwise PFN of the
735  * first page that was not scanned (which may be both less, equal to or more
736  * than end_pfn).
737  *
738  * The pages are isolated on cc->migratepages list (not required to be empty),
739  * and cc->nr_migratepages is updated accordingly. The cc->migrate_pfn field
740  * is neither read nor updated.
741  */
742 static unsigned long
743 isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
744                         unsigned long end_pfn, isolate_mode_t isolate_mode)
745 {
746         struct zone *zone = cc->zone;
747         unsigned long nr_scanned = 0, nr_isolated = 0;
748         struct list_head *migratelist = &cc->migratepages;
749         struct lruvec *lruvec;
750         unsigned long flags = 0;
751         bool locked = false;
752         struct page *page = NULL, *valid_page = NULL;
753         unsigned long start_pfn = low_pfn;
754
755         /*
756          * Ensure that there are not too many pages isolated from the LRU
757          * list by either parallel reclaimers or compaction. If there are,
758          * delay for some time until fewer pages are isolated
759          */
760         while (unlikely(too_many_isolated(cc))) {
761                 /* async migration should just abort */
762                 if (cc->mode == MIGRATE_ASYNC)
763                         return 0;
764
765                 congestion_wait(BLK_RW_ASYNC, HZ/10);
766
767                 if (fatal_signal_pending(current))
768                         return 0;
769         }
770
771         if (compact_should_abort(cc))
772                 return 0;
773
774         /* Time to isolate some pages for migration */
775         for (; low_pfn < end_pfn; low_pfn++) {
776
777                 /*
778                  * Periodically drop the lock (if held) regardless of its
779                  * contention, to give chance to IRQs. Abort async compaction
780                  * if contended.
781                  */
782                 if (!(low_pfn % SWAP_CLUSTER_MAX)
783                     && compact_unlock_should_abort(&zone->lru_lock, flags,
784                                                                 &locked, cc))
785                         break;
786
787                 if (!pfn_valid_within(low_pfn))
788                         continue;
789                 nr_scanned++;
790
791                 page = pfn_to_page(low_pfn);
792
793                 if (!valid_page)
794                         valid_page = page;
795
796                 /*
797                  * Skip if free. We read page order here without zone lock
798                  * which is generally unsafe, but the race window is small and
799                  * the worst thing that can happen is that we skip some
800                  * potential isolation targets.
801                  */
802                 if (PageBuddy(page)) {
803                         unsigned long freepage_order = page_order_unsafe(page);
804
805                         /*
806                          * Without lock, we cannot be sure that what we got is
807                          * a valid page order. Consider only values in the
808                          * valid order range to prevent low_pfn overflow.
809                          */
810                         if (freepage_order > 0 && freepage_order < MAX_ORDER)
811                                 low_pfn += (1UL << freepage_order) - 1;
812                         continue;
813                 }
814
815                 /*
816                  * Regardless of being on LRU, compound pages such as THP and
817                  * hugetlbfs are not to be compacted. We can potentially save
818                  * a lot of iterations if we skip them at once. The check is
819                  * racy, but we can consider only valid values and the only
820                  * danger is skipping too much.
821                  */
822                 if (PageCompound(page)) {
823                         unsigned int comp_order = compound_order(page);
824
825                         if (likely(comp_order < MAX_ORDER))
826                                 low_pfn += (1UL << comp_order) - 1;
827
828                         continue;
829                 }
830
831                 /*
832                  * Check may be lockless but that's ok as we recheck later.
833                  * It's possible to migrate LRU and non-lru movable pages.
834                  * Skip any other type of page
835                  */
836                 if (!PageLRU(page)) {
837                         /*
838                          * __PageMovable can return false positive so we need
839                          * to verify it under page_lock.
840                          */
841                         if (unlikely(__PageMovable(page)) &&
842                                         !PageIsolated(page)) {
843                                 if (locked) {
844                                         spin_unlock_irqrestore(&zone->lru_lock,
845                                                                         flags);
846                                         locked = false;
847                                 }
848
849                                 if (isolate_movable_page(page, isolate_mode))
850                                         goto isolate_success;
851                         }
852
853                         continue;
854                 }
855
856                 /*
857                  * Migration will fail if an anonymous page is pinned in memory,
858                  * so avoid taking lru_lock and isolating it unnecessarily in an
859                  * admittedly racy check.
860                  */
861                 if (!page_mapping(page) &&
862                     page_count(page) > page_mapcount(page))
863                         continue;
864
865                 /* If we already hold the lock, we can skip some rechecking */
866                 if (!locked) {
867                         locked = compact_trylock_irqsave(&zone->lru_lock,
868                                                                 &flags, cc);
869                         if (!locked)
870                                 break;
871
872                         /* Recheck PageLRU and PageCompound under lock */
873                         if (!PageLRU(page))
874                                 continue;
875
876                         /*
877                          * Page become compound since the non-locked check,
878                          * and it's on LRU. It can only be a THP so the order
879                          * is safe to read and it's 0 for tail pages.
880                          */
881                         if (unlikely(PageCompound(page))) {
882                                 low_pfn += (1UL << compound_order(page)) - 1;
883                                 continue;
884                         }
885                 }
886
887                 lruvec = mem_cgroup_page_lruvec(page, zone);
888
889                 /* Try isolate the page */
890                 if (__isolate_lru_page(page, isolate_mode) != 0)
891                         continue;
892
893                 VM_BUG_ON_PAGE(PageCompound(page), page);
894
895                 /* Successfully isolated */
896                 del_page_from_lru_list(page, lruvec, page_lru(page));
897
898 isolate_success:
899                 list_add(&page->lru, migratelist);
900                 cc->nr_migratepages++;
901                 nr_isolated++;
902
903                 /* Avoid isolating too much */
904                 if (cc->nr_migratepages == COMPACT_CLUSTER_MAX) {
905                         ++low_pfn;
906                         break;
907                 }
908         }
909
910         /*
911          * The PageBuddy() check could have potentially brought us outside
912          * the range to be scanned.
913          */
914         if (unlikely(low_pfn > end_pfn))
915                 low_pfn = end_pfn;
916
917         if (locked)
918                 spin_unlock_irqrestore(&zone->lru_lock, flags);
919
920         /*
921          * Update the pageblock-skip information and cached scanner pfn,
922          * if the whole pageblock was scanned without isolating any page.
923          */
924         if (low_pfn == end_pfn)
925                 update_pageblock_skip(cc, valid_page, nr_isolated, true);
926
927         trace_mm_compaction_isolate_migratepages(start_pfn, low_pfn,
928                                                 nr_scanned, nr_isolated);
929
930         count_compact_events(COMPACTMIGRATE_SCANNED, nr_scanned);
931         if (nr_isolated)
932                 count_compact_events(COMPACTISOLATED, nr_isolated);
933
934         return low_pfn;
935 }
936
937 /**
938  * isolate_migratepages_range() - isolate migrate-able pages in a PFN range
939  * @cc:        Compaction control structure.
940  * @start_pfn: The first PFN to start isolating.
941  * @end_pfn:   The one-past-last PFN.
942  *
943  * Returns zero if isolation fails fatally due to e.g. pending signal.
944  * Otherwise, function returns one-past-the-last PFN of isolated page
945  * (which may be greater than end_pfn if end fell in a middle of a THP page).
946  */
947 unsigned long
948 isolate_migratepages_range(struct compact_control *cc, unsigned long start_pfn,
949                                                         unsigned long end_pfn)
950 {
951         unsigned long pfn, block_end_pfn;
952
953         /* Scan block by block. First and last block may be incomplete */
954         pfn = start_pfn;
955         block_end_pfn = ALIGN(pfn + 1, pageblock_nr_pages);
956
957         for (; pfn < end_pfn; pfn = block_end_pfn,
958                                 block_end_pfn += pageblock_nr_pages) {
959
960                 block_end_pfn = min(block_end_pfn, end_pfn);
961
962                 if (!pageblock_pfn_to_page(pfn, block_end_pfn, cc->zone))
963                         continue;
964
965                 pfn = isolate_migratepages_block(cc, pfn, block_end_pfn,
966                                                         ISOLATE_UNEVICTABLE);
967
968                 if (!pfn)
969                         break;
970
971                 if (cc->nr_migratepages == COMPACT_CLUSTER_MAX)
972                         break;
973         }
974         acct_isolated(cc->zone, cc);
975
976         return pfn;
977 }
978
979 #endif /* CONFIG_COMPACTION || CONFIG_CMA */
980 #ifdef CONFIG_COMPACTION
981
982 /* Returns true if the page is within a block suitable for migration to */
983 static bool suitable_migration_target(struct page *page)
984 {
985         /* If the page is a large free page, then disallow migration */
986         if (PageBuddy(page)) {
987                 /*
988                  * We are checking page_order without zone->lock taken. But
989                  * the only small danger is that we skip a potentially suitable
990                  * pageblock, so it's not worth to check order for valid range.
991                  */
992                 if (page_order_unsafe(page) >= pageblock_order)
993                         return false;
994         }
995
996         /* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */
997         if (migrate_async_suitable(get_pageblock_migratetype(page)))
998                 return true;
999
1000         /* Otherwise skip the block */
1001         return false;
1002 }
1003
1004 /*
1005  * Test whether the free scanner has reached the same or lower pageblock than
1006  * the migration scanner, and compaction should thus terminate.
1007  */
1008 static inline bool compact_scanners_met(struct compact_control *cc)
1009 {
1010         return (cc->free_pfn >> pageblock_order)
1011                 <= (cc->migrate_pfn >> pageblock_order);
1012 }
1013
1014 /*
1015  * Based on information in the current compact_control, find blocks
1016  * suitable for isolating free pages from and then isolate them.
1017  */
1018 static void isolate_freepages(struct compact_control *cc)
1019 {
1020         struct zone *zone = cc->zone;
1021         struct page *page;
1022         unsigned long block_start_pfn;  /* start of current pageblock */
1023         unsigned long isolate_start_pfn; /* exact pfn we start at */
1024         unsigned long block_end_pfn;    /* end of current pageblock */
1025         unsigned long low_pfn;       /* lowest pfn scanner is able to scan */
1026         struct list_head *freelist = &cc->freepages;
1027
1028         /*
1029          * Initialise the free scanner. The starting point is where we last
1030          * successfully isolated from, zone-cached value, or the end of the
1031          * zone when isolating for the first time. For looping we also need
1032          * this pfn aligned down to the pageblock boundary, because we do
1033          * block_start_pfn -= pageblock_nr_pages in the for loop.
1034          * For ending point, take care when isolating in last pageblock of a
1035          * a zone which ends in the middle of a pageblock.
1036          * The low boundary is the end of the pageblock the migration scanner
1037          * is using.
1038          */
1039         isolate_start_pfn = cc->free_pfn;
1040         block_start_pfn = cc->free_pfn & ~(pageblock_nr_pages-1);
1041         block_end_pfn = min(block_start_pfn + pageblock_nr_pages,
1042                                                 zone_end_pfn(zone));
1043         low_pfn = ALIGN(cc->migrate_pfn + 1, pageblock_nr_pages);
1044
1045         /*
1046          * Isolate free pages until enough are available to migrate the
1047          * pages on cc->migratepages. We stop searching if the migrate
1048          * and free page scanners meet or enough free pages are isolated.
1049          */
1050         for (; block_start_pfn >= low_pfn;
1051                                 block_end_pfn = block_start_pfn,
1052                                 block_start_pfn -= pageblock_nr_pages,
1053                                 isolate_start_pfn = block_start_pfn) {
1054                 /*
1055                  * This can iterate a massively long zone without finding any
1056                  * suitable migration targets, so periodically check if we need
1057                  * to schedule, or even abort async compaction.
1058                  */
1059                 if (!(block_start_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages))
1060                                                 && compact_should_abort(cc))
1061                         break;
1062
1063                 page = pageblock_pfn_to_page(block_start_pfn, block_end_pfn,
1064                                                                         zone);
1065                 if (!page)
1066                         continue;
1067
1068                 /* Check the block is suitable for migration */
1069                 if (!suitable_migration_target(page))
1070                         continue;
1071
1072                 /* If isolation recently failed, do not retry */
1073                 if (!isolation_suitable(cc, page))
1074                         continue;
1075
1076                 /* Found a block suitable for isolating free pages from. */
1077                 isolate_freepages_block(cc, &isolate_start_pfn, block_end_pfn,
1078                                         freelist, false);
1079
1080                 /*
1081                  * If we isolated enough freepages, or aborted due to lock
1082                  * contention, terminate.
1083                  */
1084                 if ((cc->nr_freepages >= cc->nr_migratepages)
1085                                                         || cc->contended) {
1086                         if (isolate_start_pfn >= block_end_pfn) {
1087                                 /*
1088                                  * Restart at previous pageblock if more
1089                                  * freepages can be isolated next time.
1090                                  */
1091                                 isolate_start_pfn =
1092                                         block_start_pfn - pageblock_nr_pages;
1093                         }
1094                         break;
1095                 } else if (isolate_start_pfn < block_end_pfn) {
1096                         /*
1097                          * If isolation failed early, do not continue
1098                          * needlessly.
1099                          */
1100                         break;
1101                 }
1102         }
1103
1104         /* __isolate_free_page() does not map the pages */
1105         map_pages(freelist);
1106
1107         /*
1108          * Record where the free scanner will restart next time. Either we
1109          * broke from the loop and set isolate_start_pfn based on the last
1110          * call to isolate_freepages_block(), or we met the migration scanner
1111          * and the loop terminated due to isolate_start_pfn < low_pfn
1112          */
1113         cc->free_pfn = isolate_start_pfn;
1114 }
1115
1116 /*
1117  * This is a migrate-callback that "allocates" freepages by taking pages
1118  * from the isolated freelists in the block we are migrating to.
1119  */
1120 static struct page *compaction_alloc(struct page *migratepage,
1121                                         unsigned long data,
1122                                         int **result)
1123 {
1124         struct compact_control *cc = (struct compact_control *)data;
1125         struct page *freepage;
1126
1127         /*
1128          * Isolate free pages if necessary, and if we are not aborting due to
1129          * contention.
1130          */
1131         if (list_empty(&cc->freepages)) {
1132                 if (!cc->contended)
1133                         isolate_freepages(cc);
1134
1135                 if (list_empty(&cc->freepages))
1136                         return NULL;
1137         }
1138
1139         freepage = list_entry(cc->freepages.next, struct page, lru);
1140         list_del(&freepage->lru);
1141         cc->nr_freepages--;
1142
1143         return freepage;
1144 }
1145
1146 /*
1147  * This is a migrate-callback that "frees" freepages back to the isolated
1148  * freelist.  All pages on the freelist are from the same zone, so there is no
1149  * special handling needed for NUMA.
1150  */
1151 static void compaction_free(struct page *page, unsigned long data)
1152 {
1153         struct compact_control *cc = (struct compact_control *)data;
1154
1155         list_add(&page->lru, &cc->freepages);
1156         cc->nr_freepages++;
1157 }
1158
1159 /* possible outcome of isolate_migratepages */
1160 typedef enum {
1161         ISOLATE_ABORT,          /* Abort compaction now */
1162         ISOLATE_NONE,           /* No pages isolated, continue scanning */
1163         ISOLATE_SUCCESS,        /* Pages isolated, migrate */
1164 } isolate_migrate_t;
1165
1166 /*
1167  * Allow userspace to control policy on scanning the unevictable LRU for
1168  * compactable pages.
1169  */
1170 int sysctl_compact_unevictable_allowed __read_mostly = 1;
1171
1172 /*
1173  * Isolate all pages that can be migrated from the first suitable block,
1174  * starting at the block pointed to by the migrate scanner pfn within
1175  * compact_control.
1176  */
1177 static isolate_migrate_t isolate_migratepages(struct zone *zone,
1178                                         struct compact_control *cc)
1179 {
1180         unsigned long low_pfn, end_pfn;
1181         unsigned long isolate_start_pfn;
1182         struct page *page;
1183         const isolate_mode_t isolate_mode =
1184                 (sysctl_compact_unevictable_allowed ? ISOLATE_UNEVICTABLE : 0) |
1185                 (cc->mode == MIGRATE_ASYNC ? ISOLATE_ASYNC_MIGRATE : 0);
1186
1187         /*
1188          * Start at where we last stopped, or beginning of the zone as
1189          * initialized by compact_zone()
1190          */
1191         low_pfn = cc->migrate_pfn;
1192
1193         /* Only scan within a pageblock boundary */
1194         end_pfn = ALIGN(low_pfn + 1, pageblock_nr_pages);
1195
1196         /*
1197          * Iterate over whole pageblocks until we find the first suitable.
1198          * Do not cross the free scanner.
1199          */
1200         for (; end_pfn <= cc->free_pfn;
1201                         low_pfn = end_pfn, end_pfn += pageblock_nr_pages) {
1202
1203                 /*
1204                  * This can potentially iterate a massively long zone with
1205                  * many pageblocks unsuitable, so periodically check if we
1206                  * need to schedule, or even abort async compaction.
1207                  */
1208                 if (!(low_pfn % (SWAP_CLUSTER_MAX * pageblock_nr_pages))
1209                                                 && compact_should_abort(cc))
1210                         break;
1211
1212                 page = pageblock_pfn_to_page(low_pfn, end_pfn, zone);
1213                 if (!page)
1214                         continue;
1215
1216                 /* If isolation recently failed, do not retry */
1217                 if (!isolation_suitable(cc, page))
1218                         continue;
1219
1220                 /*
1221                  * For async compaction, also only scan in MOVABLE blocks.
1222                  * Async compaction is optimistic to see if the minimum amount
1223                  * of work satisfies the allocation.
1224                  */
1225                 if (cc->mode == MIGRATE_ASYNC &&
1226                     !migrate_async_suitable(get_pageblock_migratetype(page)))
1227                         continue;
1228
1229                 /* Perform the isolation */
1230                 isolate_start_pfn = low_pfn;
1231                 low_pfn = isolate_migratepages_block(cc, low_pfn, end_pfn,
1232                                                                 isolate_mode);
1233
1234                 if (!low_pfn || cc->contended) {
1235                         acct_isolated(zone, cc);
1236                         return ISOLATE_ABORT;
1237                 }
1238
1239                 /*
1240                  * Record where we could have freed pages by migration and not
1241                  * yet flushed them to buddy allocator.
1242                  * - this is the lowest page that could have been isolated and
1243                  * then freed by migration.
1244                  */
1245                 if (cc->nr_migratepages && !cc->last_migrated_pfn)
1246                         cc->last_migrated_pfn = isolate_start_pfn;
1247
1248                 /*
1249                  * Either we isolated something and proceed with migration. Or
1250                  * we failed and compact_zone should decide if we should
1251                  * continue or not.
1252                  */
1253                 break;
1254         }
1255
1256         acct_isolated(zone, cc);
1257         /* Record where migration scanner will be restarted. */
1258         cc->migrate_pfn = low_pfn;
1259
1260         return cc->nr_migratepages ? ISOLATE_SUCCESS : ISOLATE_NONE;
1261 }
1262
1263 /*
1264  * order == -1 is expected when compacting via
1265  * /proc/sys/vm/compact_memory
1266  */
1267 static inline bool is_via_compact_memory(int order)
1268 {
1269         return order == -1;
1270 }
1271
1272 static int __compact_finished(struct zone *zone, struct compact_control *cc,
1273                             const int migratetype)
1274 {
1275         unsigned int order;
1276         unsigned long watermark;
1277
1278         if (cc->contended || fatal_signal_pending(current))
1279                 return COMPACT_CONTENDED;
1280
1281         /* Compaction run completes if the migrate and free scanner meet */
1282         if (compact_scanners_met(cc)) {
1283                 /* Let the next compaction start anew. */
1284                 reset_cached_positions(zone);
1285
1286                 /*
1287                  * Mark that the PG_migrate_skip information should be cleared
1288                  * by kswapd when it goes to sleep. kcompactd does not set the
1289                  * flag itself as the decision to be clear should be directly
1290                  * based on an allocation request.
1291                  */
1292                 if (cc->direct_compaction)
1293                         zone->compact_blockskip_flush = true;
1294
1295                 return COMPACT_COMPLETE;
1296         }
1297
1298         if (is_via_compact_memory(cc->order))
1299                 return COMPACT_CONTINUE;
1300
1301         /* Compaction run is not finished if the watermark is not met */
1302         watermark = low_wmark_pages(zone);
1303
1304         if (!zone_watermark_ok(zone, cc->order, watermark, cc->classzone_idx,
1305                                                         cc->alloc_flags))
1306                 return COMPACT_CONTINUE;
1307
1308         /* Direct compactor: Is a suitable page free? */
1309         for (order = cc->order; order < MAX_ORDER; order++) {
1310                 struct free_area *area = &zone->free_area[order];
1311                 bool can_steal;
1312
1313                 /* Job done if page is free of the right migratetype */
1314                 if (!list_empty(&area->free_list[migratetype]))
1315                         return COMPACT_PARTIAL;
1316
1317 #ifdef CONFIG_CMA
1318                 /* MIGRATE_MOVABLE can fallback on MIGRATE_CMA */
1319                 if (migratetype == MIGRATE_MOVABLE &&
1320                         !list_empty(&area->free_list[MIGRATE_CMA]))
1321                         return COMPACT_PARTIAL;
1322 #endif
1323                 /*
1324                  * Job done if allocation would steal freepages from
1325                  * other migratetype buddy lists.
1326                  */
1327                 if (find_suitable_fallback(area, order, migratetype,
1328                                                 true, &can_steal) != -1)
1329                         return COMPACT_PARTIAL;
1330         }
1331
1332         return COMPACT_NO_SUITABLE_PAGE;
1333 }
1334
1335 static int compact_finished(struct zone *zone, struct compact_control *cc,
1336                             const int migratetype)
1337 {
1338         int ret;
1339
1340         ret = __compact_finished(zone, cc, migratetype);
1341         trace_mm_compaction_finished(zone, cc->order, ret);
1342         if (ret == COMPACT_NO_SUITABLE_PAGE)
1343                 ret = COMPACT_CONTINUE;
1344
1345         return ret;
1346 }
1347
1348 /*
1349  * compaction_suitable: Is this suitable to run compaction on this zone now?
1350  * Returns
1351  *   COMPACT_SKIPPED  - If there are too few free pages for compaction
1352  *   COMPACT_PARTIAL  - If the allocation would succeed without compaction
1353  *   COMPACT_CONTINUE - If compaction should run now
1354  */
1355 static unsigned long __compaction_suitable(struct zone *zone, int order,
1356                                         int alloc_flags, int classzone_idx)
1357 {
1358         int fragindex;
1359         unsigned long watermark;
1360
1361         if (is_via_compact_memory(order))
1362                 return COMPACT_CONTINUE;
1363
1364         watermark = low_wmark_pages(zone);
1365         /*
1366          * If watermarks for high-order allocation are already met, there
1367          * should be no need for compaction at all.
1368          */
1369         if (zone_watermark_ok(zone, order, watermark, classzone_idx,
1370                                                                 alloc_flags))
1371                 return COMPACT_PARTIAL;
1372
1373         /*
1374          * Watermarks for order-0 must be met for compaction. Note the 2UL.
1375          * This is because during migration, copies of pages need to be
1376          * allocated and for a short time, the footprint is higher
1377          */
1378         watermark += (2UL << order);
1379         if (!zone_watermark_ok(zone, 0, watermark, classzone_idx, alloc_flags))
1380                 return COMPACT_SKIPPED;
1381
1382         /*
1383          * fragmentation index determines if allocation failures are due to
1384          * low memory or external fragmentation
1385          *
1386          * index of -1000 would imply allocations might succeed depending on
1387          * watermarks, but we already failed the high-order watermark check
1388          * index towards 0 implies failure is due to lack of memory
1389          * index towards 1000 implies failure is due to fragmentation
1390          *
1391          * Only compact if a failure would be due to fragmentation.
1392          */
1393         fragindex = fragmentation_index(zone, order);
1394         if (fragindex >= 0 && fragindex <= sysctl_extfrag_threshold)
1395                 return COMPACT_NOT_SUITABLE_ZONE;
1396
1397         return COMPACT_CONTINUE;
1398 }
1399
1400 unsigned long compaction_suitable(struct zone *zone, int order,
1401                                         int alloc_flags, int classzone_idx)
1402 {
1403         unsigned long ret;
1404
1405         ret = __compaction_suitable(zone, order, alloc_flags, classzone_idx);
1406         trace_mm_compaction_suitable(zone, order, ret);
1407         if (ret == COMPACT_NOT_SUITABLE_ZONE)
1408                 ret = COMPACT_SKIPPED;
1409
1410         return ret;
1411 }
1412
1413 static int compact_zone(struct zone *zone, struct compact_control *cc)
1414 {
1415         int ret;
1416         unsigned long start_pfn = zone->zone_start_pfn;
1417         unsigned long end_pfn = zone_end_pfn(zone);
1418         const int migratetype = gfpflags_to_migratetype(cc->gfp_mask);
1419         const bool sync = cc->mode != MIGRATE_ASYNC;
1420
1421         ret = compaction_suitable(zone, cc->order, cc->alloc_flags,
1422                                                         cc->classzone_idx);
1423         switch (ret) {
1424         case COMPACT_PARTIAL:
1425         case COMPACT_SKIPPED:
1426                 /* Compaction is likely to fail */
1427                 return ret;
1428         case COMPACT_CONTINUE:
1429                 /* Fall through to compaction */
1430                 ;
1431         }
1432
1433         /*
1434          * Clear pageblock skip if there were failures recently and compaction
1435          * is about to be retried after being deferred.
1436          */
1437         if (compaction_restarting(zone, cc->order))
1438                 __reset_isolation_suitable(zone);
1439
1440         /*
1441          * Setup to move all movable pages to the end of the zone. Used cached
1442          * information on where the scanners should start but check that it
1443          * is initialised by ensuring the values are within zone boundaries.
1444          */
1445         cc->migrate_pfn = zone->compact_cached_migrate_pfn[sync];
1446         cc->free_pfn = zone->compact_cached_free_pfn;
1447         if (cc->free_pfn < start_pfn || cc->free_pfn > end_pfn) {
1448                 cc->free_pfn = end_pfn & ~(pageblock_nr_pages-1);
1449                 zone->compact_cached_free_pfn = cc->free_pfn;
1450         }
1451         if (cc->migrate_pfn < start_pfn || cc->migrate_pfn > end_pfn) {
1452                 cc->migrate_pfn = start_pfn;
1453                 zone->compact_cached_migrate_pfn[0] = cc->migrate_pfn;
1454                 zone->compact_cached_migrate_pfn[1] = cc->migrate_pfn;
1455         }
1456         cc->last_migrated_pfn = 0;
1457
1458         trace_mm_compaction_begin(start_pfn, cc->migrate_pfn,
1459                                 cc->free_pfn, end_pfn, sync);
1460
1461         migrate_prep_local();
1462
1463         while ((ret = compact_finished(zone, cc, migratetype)) ==
1464                                                 COMPACT_CONTINUE) {
1465                 int err;
1466
1467                 switch (isolate_migratepages(zone, cc)) {
1468                 case ISOLATE_ABORT:
1469                         ret = COMPACT_CONTENDED;
1470                         putback_movable_pages(&cc->migratepages);
1471                         cc->nr_migratepages = 0;
1472                         goto out;
1473                 case ISOLATE_NONE:
1474                         /*
1475                          * We haven't isolated and migrated anything, but
1476                          * there might still be unflushed migrations from
1477                          * previous cc->order aligned block.
1478                          */
1479                         goto check_drain;
1480                 case ISOLATE_SUCCESS:
1481                         ;
1482                 }
1483
1484                 err = migrate_pages(&cc->migratepages, compaction_alloc,
1485                                 compaction_free, (unsigned long)cc, cc->mode,
1486                                 MR_COMPACTION);
1487
1488                 trace_mm_compaction_migratepages(cc->nr_migratepages, err,
1489                                                         &cc->migratepages);
1490
1491                 /* All pages were either migrated or will be released */
1492                 cc->nr_migratepages = 0;
1493                 if (err) {
1494                         putback_movable_pages(&cc->migratepages);
1495                         /*
1496                          * migrate_pages() may return -ENOMEM when scanners meet
1497                          * and we want compact_finished() to detect it
1498                          */
1499                         if (err == -ENOMEM && !compact_scanners_met(cc)) {
1500                                 ret = COMPACT_CONTENDED;
1501                                 goto out;
1502                         }
1503                 }
1504
1505 check_drain:
1506                 /*
1507                  * Has the migration scanner moved away from the previous
1508                  * cc->order aligned block where we migrated from? If yes,
1509                  * flush the pages that were freed, so that they can merge and
1510                  * compact_finished() can detect immediately if allocation
1511                  * would succeed.
1512                  */
1513                 if (cc->order > 0 && cc->last_migrated_pfn) {
1514                         int cpu;
1515                         unsigned long current_block_start =
1516                                 cc->migrate_pfn & ~((1UL << cc->order) - 1);
1517
1518                         if (cc->last_migrated_pfn < current_block_start) {
1519                                 cpu = get_cpu();
1520                                 lru_add_drain_cpu(cpu);
1521                                 drain_local_pages(zone);
1522                                 put_cpu();
1523                                 /* No more flushing until we migrate again */
1524                                 cc->last_migrated_pfn = 0;
1525                         }
1526                 }
1527
1528         }
1529
1530 out:
1531         /*
1532          * Release free pages and update where the free scanner should restart,
1533          * so we don't leave any returned pages behind in the next attempt.
1534          */
1535         if (cc->nr_freepages > 0) {
1536                 unsigned long free_pfn = release_freepages(&cc->freepages);
1537
1538                 cc->nr_freepages = 0;
1539                 VM_BUG_ON(free_pfn == 0);
1540                 /* The cached pfn is always the first in a pageblock */
1541                 free_pfn &= ~(pageblock_nr_pages-1);
1542                 /*
1543                  * Only go back, not forward. The cached pfn might have been
1544                  * already reset to zone end in compact_finished()
1545                  */
1546                 if (free_pfn > zone->compact_cached_free_pfn)
1547                         zone->compact_cached_free_pfn = free_pfn;
1548         }
1549
1550         trace_mm_compaction_end(start_pfn, cc->migrate_pfn,
1551                                 cc->free_pfn, end_pfn, sync, ret);
1552
1553         if (ret == COMPACT_CONTENDED)
1554                 ret = COMPACT_PARTIAL;
1555
1556         return ret;
1557 }
1558
1559 static unsigned long compact_zone_order(struct zone *zone, int order,
1560                 gfp_t gfp_mask, enum migrate_mode mode, int *contended,
1561                 int alloc_flags, int classzone_idx)
1562 {
1563         unsigned long ret;
1564         struct compact_control cc = {
1565                 .nr_freepages = 0,
1566                 .nr_migratepages = 0,
1567                 .order = order,
1568                 .gfp_mask = gfp_mask,
1569                 .zone = zone,
1570                 .mode = mode,
1571                 .alloc_flags = alloc_flags,
1572                 .classzone_idx = classzone_idx,
1573                 .direct_compaction = true,
1574         };
1575         INIT_LIST_HEAD(&cc.freepages);
1576         INIT_LIST_HEAD(&cc.migratepages);
1577
1578         ret = compact_zone(zone, &cc);
1579
1580         VM_BUG_ON(!list_empty(&cc.freepages));
1581         VM_BUG_ON(!list_empty(&cc.migratepages));
1582
1583         *contended = cc.contended;
1584         return ret;
1585 }
1586
1587 int sysctl_extfrag_threshold = 500;
1588
1589 /**
1590  * try_to_compact_pages - Direct compact to satisfy a high-order allocation
1591  * @gfp_mask: The GFP mask of the current allocation
1592  * @order: The order of the current allocation
1593  * @alloc_flags: The allocation flags of the current allocation
1594  * @ac: The context of current allocation
1595  * @mode: The migration mode for async, sync light, or sync migration
1596  * @contended: Return value that determines if compaction was aborted due to
1597  *             need_resched() or lock contention
1598  *
1599  * This is the main entry point for direct page compaction.
1600  */
1601 unsigned long try_to_compact_pages(gfp_t gfp_mask, unsigned int order,
1602                         int alloc_flags, const struct alloc_context *ac,
1603                         enum migrate_mode mode, int *contended)
1604 {
1605         int may_enter_fs = gfp_mask & __GFP_FS;
1606         int may_perform_io = gfp_mask & __GFP_IO;
1607         struct zoneref *z;
1608         struct zone *zone;
1609         int rc = COMPACT_DEFERRED;
1610         int all_zones_contended = COMPACT_CONTENDED_LOCK; /* init for &= op */
1611
1612         *contended = COMPACT_CONTENDED_NONE;
1613
1614         /* Check if the GFP flags allow compaction */
1615         if (!order || !may_enter_fs || !may_perform_io)
1616                 return COMPACT_SKIPPED;
1617
1618         trace_mm_compaction_try_to_compact_pages(order, gfp_mask, mode);
1619
1620         /* Compact each zone in the list */
1621         for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, ac->high_zoneidx,
1622                                                                 ac->nodemask) {
1623                 int status;
1624                 int zone_contended;
1625
1626                 if (compaction_deferred(zone, order))
1627                         continue;
1628
1629                 status = compact_zone_order(zone, order, gfp_mask, mode,
1630                                 &zone_contended, alloc_flags,
1631                                 ac->classzone_idx);
1632                 rc = max(status, rc);
1633                 /*
1634                  * It takes at least one zone that wasn't lock contended
1635                  * to clear all_zones_contended.
1636                  */
1637                 all_zones_contended &= zone_contended;
1638
1639                 /* If a normal allocation would succeed, stop compacting */
1640                 if (zone_watermark_ok(zone, order, low_wmark_pages(zone),
1641                                         ac->classzone_idx, alloc_flags)) {
1642                         /*
1643                          * We think the allocation will succeed in this zone,
1644                          * but it is not certain, hence the false. The caller
1645                          * will repeat this with true if allocation indeed
1646                          * succeeds in this zone.
1647                          */
1648                         compaction_defer_reset(zone, order, false);
1649                         /*
1650                          * It is possible that async compaction aborted due to
1651                          * need_resched() and the watermarks were ok thanks to
1652                          * somebody else freeing memory. The allocation can
1653                          * however still fail so we better signal the
1654                          * need_resched() contention anyway (this will not
1655                          * prevent the allocation attempt).
1656                          */
1657                         if (zone_contended == COMPACT_CONTENDED_SCHED)
1658                                 *contended = COMPACT_CONTENDED_SCHED;
1659
1660                         goto break_loop;
1661                 }
1662
1663                 if (mode != MIGRATE_ASYNC && status == COMPACT_COMPLETE) {
1664                         /*
1665                          * We think that allocation won't succeed in this zone
1666                          * so we defer compaction there. If it ends up
1667                          * succeeding after all, it will be reset.
1668                          */
1669                         defer_compaction(zone, order);
1670                 }
1671
1672                 /*
1673                  * We might have stopped compacting due to need_resched() in
1674                  * async compaction, or due to a fatal signal detected. In that
1675                  * case do not try further zones and signal need_resched()
1676                  * contention.
1677                  */
1678                 if ((zone_contended == COMPACT_CONTENDED_SCHED)
1679                                         || fatal_signal_pending(current)) {
1680                         *contended = COMPACT_CONTENDED_SCHED;
1681                         goto break_loop;
1682                 }
1683
1684                 continue;
1685 break_loop:
1686                 /*
1687                  * We might not have tried all the zones, so  be conservative
1688                  * and assume they are not all lock contended.
1689                  */
1690                 all_zones_contended = 0;
1691                 break;
1692         }
1693
1694         /*
1695          * If at least one zone wasn't deferred or skipped, we report if all
1696          * zones that were tried were lock contended.
1697          */
1698         if (rc > COMPACT_SKIPPED && all_zones_contended)
1699                 *contended = COMPACT_CONTENDED_LOCK;
1700
1701         return rc;
1702 }
1703
1704
1705 /* Compact all zones within a node */
1706 static void __compact_pgdat(pg_data_t *pgdat, struct compact_control *cc)
1707 {
1708         int zoneid;
1709         struct zone *zone;
1710
1711         for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
1712
1713                 zone = &pgdat->node_zones[zoneid];
1714                 if (!populated_zone(zone))
1715                         continue;
1716
1717                 cc->nr_freepages = 0;
1718                 cc->nr_migratepages = 0;
1719                 cc->zone = zone;
1720                 INIT_LIST_HEAD(&cc->freepages);
1721                 INIT_LIST_HEAD(&cc->migratepages);
1722
1723                 /*
1724                  * When called via /proc/sys/vm/compact_memory
1725                  * this makes sure we compact the whole zone regardless of
1726                  * cached scanner positions.
1727                  */
1728                 if (is_via_compact_memory(cc->order))
1729                         __reset_isolation_suitable(zone);
1730
1731                 if (is_via_compact_memory(cc->order) ||
1732                                 !compaction_deferred(zone, cc->order))
1733                         compact_zone(zone, cc);
1734
1735                 if (cc->order > 0) {
1736                         if (zone_watermark_ok(zone, cc->order,
1737                                                 low_wmark_pages(zone), 0, 0))
1738                                 compaction_defer_reset(zone, cc->order, false);
1739                 }
1740
1741                 VM_BUG_ON(!list_empty(&cc->freepages));
1742                 VM_BUG_ON(!list_empty(&cc->migratepages));
1743         }
1744 }
1745
1746 void compact_pgdat(pg_data_t *pgdat, int order)
1747 {
1748         struct compact_control cc = {
1749                 .order = order,
1750                 .mode = MIGRATE_ASYNC,
1751         };
1752
1753         if (!order)
1754                 return;
1755
1756         __compact_pgdat(pgdat, &cc);
1757 }
1758
1759 static void compact_node(int nid)
1760 {
1761         struct compact_control cc = {
1762                 .order = -1,
1763                 .mode = MIGRATE_SYNC,
1764                 .ignore_skip_hint = true,
1765         };
1766
1767         __compact_pgdat(NODE_DATA(nid), &cc);
1768 }
1769
1770 /* Compact all nodes in the system */
1771 static void compact_nodes(void)
1772 {
1773         int nid;
1774
1775         /* Flush pending updates to the LRU lists */
1776         lru_add_drain_all();
1777
1778         for_each_online_node(nid)
1779                 compact_node(nid);
1780 }
1781
1782 /* The written value is actually unused, all memory is compacted */
1783 int sysctl_compact_memory;
1784
1785 /* This is the entry point for compacting all nodes via /proc/sys/vm */
1786 int sysctl_compaction_handler(struct ctl_table *table, int write,
1787                         void __user *buffer, size_t *length, loff_t *ppos)
1788 {
1789         if (write)
1790                 compact_nodes();
1791
1792         return 0;
1793 }
1794
1795 int sysctl_extfrag_handler(struct ctl_table *table, int write,
1796                         void __user *buffer, size_t *length, loff_t *ppos)
1797 {
1798         proc_dointvec_minmax(table, write, buffer, length, ppos);
1799
1800         return 0;
1801 }
1802
1803 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
1804 static ssize_t sysfs_compact_node(struct device *dev,
1805                         struct device_attribute *attr,
1806                         const char *buf, size_t count)
1807 {
1808         int nid = dev->id;
1809
1810         if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
1811                 /* Flush pending updates to the LRU lists */
1812                 lru_add_drain_all();
1813
1814                 compact_node(nid);
1815         }
1816
1817         return count;
1818 }
1819 static DEVICE_ATTR(compact, S_IWUSR, NULL, sysfs_compact_node);
1820
1821 int compaction_register_node(struct node *node)
1822 {
1823         return device_create_file(&node->dev, &dev_attr_compact);
1824 }
1825
1826 void compaction_unregister_node(struct node *node)
1827 {
1828         return device_remove_file(&node->dev, &dev_attr_compact);
1829 }
1830 #endif /* CONFIG_SYSFS && CONFIG_NUMA */
1831
1832 static inline bool kcompactd_work_requested(pg_data_t *pgdat)
1833 {
1834         return pgdat->kcompactd_max_order > 0 || kthread_should_stop();
1835 }
1836
1837 static bool kcompactd_node_suitable(pg_data_t *pgdat)
1838 {
1839         int zoneid;
1840         struct zone *zone;
1841         enum zone_type classzone_idx = pgdat->kcompactd_classzone_idx;
1842
1843         for (zoneid = 0; zoneid <= classzone_idx; zoneid++) {
1844                 zone = &pgdat->node_zones[zoneid];
1845
1846                 if (!populated_zone(zone))
1847                         continue;
1848
1849                 if (compaction_suitable(zone, pgdat->kcompactd_max_order, 0,
1850                                         classzone_idx) == COMPACT_CONTINUE)
1851                         return true;
1852         }
1853
1854         return false;
1855 }
1856
1857 static void kcompactd_do_work(pg_data_t *pgdat)
1858 {
1859         /*
1860          * With no special task, compact all zones so that a page of requested
1861          * order is allocatable.
1862          */
1863         int zoneid;
1864         struct zone *zone;
1865         struct compact_control cc = {
1866                 .order = pgdat->kcompactd_max_order,
1867                 .classzone_idx = pgdat->kcompactd_classzone_idx,
1868                 .mode = MIGRATE_SYNC_LIGHT,
1869                 .ignore_skip_hint = true,
1870
1871         };
1872         bool success = false;
1873
1874         trace_mm_compaction_kcompactd_wake(pgdat->node_id, cc.order,
1875                                                         cc.classzone_idx);
1876         count_vm_event(KCOMPACTD_WAKE);
1877
1878         for (zoneid = 0; zoneid <= cc.classzone_idx; zoneid++) {
1879                 int status;
1880
1881                 zone = &pgdat->node_zones[zoneid];
1882                 if (!populated_zone(zone))
1883                         continue;
1884
1885                 if (compaction_deferred(zone, cc.order))
1886                         continue;
1887
1888                 if (compaction_suitable(zone, cc.order, 0, zoneid) !=
1889                                                         COMPACT_CONTINUE)
1890                         continue;
1891
1892                 cc.nr_freepages = 0;
1893                 cc.nr_migratepages = 0;
1894                 cc.zone = zone;
1895                 INIT_LIST_HEAD(&cc.freepages);
1896                 INIT_LIST_HEAD(&cc.migratepages);
1897
1898                 if (kthread_should_stop())
1899                         return;
1900                 status = compact_zone(zone, &cc);
1901
1902                 if (zone_watermark_ok(zone, cc.order, low_wmark_pages(zone),
1903                                                 cc.classzone_idx, 0)) {
1904                         success = true;
1905                         compaction_defer_reset(zone, cc.order, false);
1906                 } else if (status == COMPACT_COMPLETE) {
1907                         /*
1908                          * We use sync migration mode here, so we defer like
1909                          * sync direct compaction does.
1910                          */
1911                         defer_compaction(zone, cc.order);
1912                 }
1913
1914                 VM_BUG_ON(!list_empty(&cc.freepages));
1915                 VM_BUG_ON(!list_empty(&cc.migratepages));
1916         }
1917
1918         /*
1919          * Regardless of success, we are done until woken up next. But remember
1920          * the requested order/classzone_idx in case it was higher/tighter than
1921          * our current ones
1922          */
1923         if (pgdat->kcompactd_max_order <= cc.order)
1924                 pgdat->kcompactd_max_order = 0;
1925         if (pgdat->kcompactd_classzone_idx >= cc.classzone_idx)
1926                 pgdat->kcompactd_classzone_idx = pgdat->nr_zones - 1;
1927 }
1928
1929 void wakeup_kcompactd(pg_data_t *pgdat, int order, int classzone_idx)
1930 {
1931         if (!order)
1932                 return;
1933
1934         if (pgdat->kcompactd_max_order < order)
1935                 pgdat->kcompactd_max_order = order;
1936
1937         if (pgdat->kcompactd_classzone_idx > classzone_idx)
1938                 pgdat->kcompactd_classzone_idx = classzone_idx;
1939
1940         if (!waitqueue_active(&pgdat->kcompactd_wait))
1941                 return;
1942
1943         if (!kcompactd_node_suitable(pgdat))
1944                 return;
1945
1946         trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, order,
1947                                                         classzone_idx);
1948         wake_up_interruptible(&pgdat->kcompactd_wait);
1949 }
1950
1951 /*
1952  * The background compaction daemon, started as a kernel thread
1953  * from the init process.
1954  */
1955 static int kcompactd(void *p)
1956 {
1957         pg_data_t *pgdat = (pg_data_t*)p;
1958         struct task_struct *tsk = current;
1959
1960         const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1961
1962         if (!cpumask_empty(cpumask))
1963                 set_cpus_allowed_ptr(tsk, cpumask);
1964
1965         set_freezable();
1966
1967         pgdat->kcompactd_max_order = 0;
1968         pgdat->kcompactd_classzone_idx = pgdat->nr_zones - 1;
1969
1970         while (!kthread_should_stop()) {
1971                 trace_mm_compaction_kcompactd_sleep(pgdat->node_id);
1972                 wait_event_freezable(pgdat->kcompactd_wait,
1973                                 kcompactd_work_requested(pgdat));
1974
1975                 kcompactd_do_work(pgdat);
1976         }
1977
1978         return 0;
1979 }
1980
1981 /*
1982  * This kcompactd start function will be called by init and node-hot-add.
1983  * On node-hot-add, kcompactd will moved to proper cpus if cpus are hot-added.
1984  */
1985 int kcompactd_run(int nid)
1986 {
1987         pg_data_t *pgdat = NODE_DATA(nid);
1988         int ret = 0;
1989
1990         if (pgdat->kcompactd)
1991                 return 0;
1992
1993         pgdat->kcompactd = kthread_run(kcompactd, pgdat, "kcompactd%d", nid);
1994         if (IS_ERR(pgdat->kcompactd)) {
1995                 pr_err("Failed to start kcompactd on node %d\n", nid);
1996                 ret = PTR_ERR(pgdat->kcompactd);
1997                 pgdat->kcompactd = NULL;
1998         }
1999         return ret;
2000 }
2001
2002 /*
2003  * Called by memory hotplug when all memory in a node is offlined. Caller must
2004  * hold mem_hotplug_begin/end().
2005  */
2006 void kcompactd_stop(int nid)
2007 {
2008         struct task_struct *kcompactd = NODE_DATA(nid)->kcompactd;
2009
2010         if (kcompactd) {
2011                 kthread_stop(kcompactd);
2012                 NODE_DATA(nid)->kcompactd = NULL;
2013         }
2014 }
2015
2016 /*
2017  * It's optimal to keep kcompactd on the same CPUs as their memory, but
2018  * not required for correctness. So if the last cpu in a node goes
2019  * away, we get changed to run anywhere: as the first one comes back,
2020  * restore their cpu bindings.
2021  */
2022 static int cpu_callback(struct notifier_block *nfb, unsigned long action,
2023                         void *hcpu)
2024 {
2025         int nid;
2026
2027         if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
2028                 for_each_node_state(nid, N_MEMORY) {
2029                         pg_data_t *pgdat = NODE_DATA(nid);
2030                         const struct cpumask *mask;
2031
2032                         mask = cpumask_of_node(pgdat->node_id);
2033
2034                         if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
2035                                 /* One of our CPUs online: restore mask */
2036                                 set_cpus_allowed_ptr(pgdat->kcompactd, mask);
2037                 }
2038         }
2039         return NOTIFY_OK;
2040 }
2041
2042 static int __init kcompactd_init(void)
2043 {
2044         int nid;
2045
2046         for_each_node_state(nid, N_MEMORY)
2047                 kcompactd_run(nid);
2048         hotcpu_notifier(cpu_callback, 0);
2049         return 0;
2050 }
2051 subsys_initcall(kcompactd_init)
2052
2053 #endif /* CONFIG_COMPACTION */