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