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