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