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