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