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