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 <linux/cpuset.h>
27 #include "internal.h"
28
29 #ifdef CONFIG_COMPACTION
30 /*
31 * Fragmentation score check interval for proactive compaction purposes.
32 */
33 #define HPAGE_FRAG_CHECK_INTERVAL_MSEC (500)
34
count_compact_event(enum vm_event_item item)35 static inline void count_compact_event(enum vm_event_item item)
36 {
37 count_vm_event(item);
38 }
39
count_compact_events(enum vm_event_item item,long delta)40 static inline void count_compact_events(enum vm_event_item item, long delta)
41 {
42 count_vm_events(item, delta);
43 }
44
45 /*
46 * order == -1 is expected when compacting proactively via
47 * 1. /proc/sys/vm/compact_memory
48 * 2. /sys/devices/system/node/nodex/compact
49 * 3. /proc/sys/vm/compaction_proactiveness
50 */
is_via_compact_memory(int order)51 static inline bool is_via_compact_memory(int order)
52 {
53 return order == -1;
54 }
55
56 #else
57 #define count_compact_event(item) do { } while (0)
58 #define count_compact_events(item, delta) do { } while (0)
is_via_compact_memory(int order)59 static inline bool is_via_compact_memory(int order) { return false; }
60 #endif
61
62 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
63
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/compaction.h>
66
67 #define block_start_pfn(pfn, order) round_down(pfn, 1UL << (order))
68 #define block_end_pfn(pfn, order) ALIGN((pfn) + 1, 1UL << (order))
69
70 /*
71 * Page order with-respect-to which proactive compaction
72 * calculates external fragmentation, which is used as
73 * the "fragmentation score" of a node/zone.
74 */
75 #if defined CONFIG_TRANSPARENT_HUGEPAGE
76 #define COMPACTION_HPAGE_ORDER HPAGE_PMD_ORDER
77 #elif defined CONFIG_HUGETLBFS
78 #define COMPACTION_HPAGE_ORDER HUGETLB_PAGE_ORDER
79 #else
80 #define COMPACTION_HPAGE_ORDER (PMD_SHIFT - PAGE_SHIFT)
81 #endif
82
mark_allocated_noprof(struct page * page,unsigned int order,gfp_t gfp_flags)83 static struct page *mark_allocated_noprof(struct page *page, unsigned int order, gfp_t gfp_flags)
84 {
85 post_alloc_hook(page, order, __GFP_MOVABLE);
86 set_page_refcounted(page);
87 return page;
88 }
89 #define mark_allocated(...) alloc_hooks(mark_allocated_noprof(__VA_ARGS__))
90
release_free_list(struct list_head * freepages)91 static unsigned long release_free_list(struct list_head *freepages)
92 {
93 int order;
94 unsigned long high_pfn = 0;
95
96 for (order = 0; order < NR_PAGE_ORDERS; order++) {
97 struct page *page, *next;
98
99 list_for_each_entry_safe(page, next, &freepages[order], lru) {
100 unsigned long pfn = page_to_pfn(page);
101
102 list_del(&page->lru);
103 /*
104 * Convert free pages into post allocation pages, so
105 * that we can free them via __free_page.
106 */
107 mark_allocated(page, order, __GFP_MOVABLE);
108 __free_pages(page, order);
109 if (pfn > high_pfn)
110 high_pfn = pfn;
111 }
112 }
113 return high_pfn;
114 }
115
116 #ifdef CONFIG_COMPACTION
117
118 /* Do not skip compaction more than 64 times */
119 #define COMPACT_MAX_DEFER_SHIFT 6
120
121 /*
122 * Compaction is deferred when compaction fails to result in a page
123 * allocation success. 1 << compact_defer_shift, compactions are skipped up
124 * to a limit of 1 << COMPACT_MAX_DEFER_SHIFT
125 */
defer_compaction(struct zone * zone,int order)126 static void defer_compaction(struct zone *zone, int order)
127 {
128 zone->compact_considered = 0;
129 zone->compact_defer_shift++;
130
131 if (order < zone->compact_order_failed)
132 zone->compact_order_failed = order;
133
134 if (zone->compact_defer_shift > COMPACT_MAX_DEFER_SHIFT)
135 zone->compact_defer_shift = COMPACT_MAX_DEFER_SHIFT;
136
137 trace_mm_compaction_defer_compaction(zone, order);
138 }
139
140 /* Returns true if compaction should be skipped this time */
compaction_deferred(struct zone * zone,int order)141 static bool compaction_deferred(struct zone *zone, int order)
142 {
143 unsigned long defer_limit = 1UL << zone->compact_defer_shift;
144
145 if (order < zone->compact_order_failed)
146 return false;
147
148 /* Avoid possible overflow */
149 if (++zone->compact_considered >= defer_limit) {
150 zone->compact_considered = defer_limit;
151 return false;
152 }
153
154 trace_mm_compaction_deferred(zone, order);
155
156 return true;
157 }
158
159 /*
160 * Update defer tracking counters after successful compaction of given order,
161 * which means an allocation either succeeded (alloc_success == true) or is
162 * expected to succeed.
163 */
compaction_defer_reset(struct zone * zone,int order,bool alloc_success)164 void compaction_defer_reset(struct zone *zone, int order,
165 bool alloc_success)
166 {
167 if (alloc_success) {
168 zone->compact_considered = 0;
169 zone->compact_defer_shift = 0;
170 }
171 if (order >= zone->compact_order_failed)
172 zone->compact_order_failed = order + 1;
173
174 trace_mm_compaction_defer_reset(zone, order);
175 }
176
177 /* Returns true if restarting compaction after many failures */
compaction_restarting(struct zone * zone,int order)178 static bool compaction_restarting(struct zone *zone, int order)
179 {
180 if (order < zone->compact_order_failed)
181 return false;
182
183 return zone->compact_defer_shift == COMPACT_MAX_DEFER_SHIFT &&
184 zone->compact_considered >= 1UL << zone->compact_defer_shift;
185 }
186
187 /* Returns true if the pageblock should be scanned for pages to isolate. */
isolation_suitable(struct compact_control * cc,struct page * page)188 static inline bool isolation_suitable(struct compact_control *cc,
189 struct page *page)
190 {
191 if (cc->ignore_skip_hint)
192 return true;
193
194 return !get_pageblock_skip(page);
195 }
196
reset_cached_positions(struct zone * zone)197 static void reset_cached_positions(struct zone *zone)
198 {
199 zone->compact_cached_migrate_pfn[0] = zone->zone_start_pfn;
200 zone->compact_cached_migrate_pfn[1] = zone->zone_start_pfn;
201 zone->compact_cached_free_pfn =
202 pageblock_start_pfn(zone_end_pfn(zone) - 1);
203 }
204
205 #ifdef CONFIG_SPARSEMEM
206 /*
207 * If the PFN falls into an offline section, return the start PFN of the
208 * next online section. If the PFN falls into an online section or if
209 * there is no next online section, return 0.
210 */
skip_offline_sections(unsigned long start_pfn)211 static unsigned long skip_offline_sections(unsigned long start_pfn)
212 {
213 unsigned long start_nr = pfn_to_section_nr(start_pfn);
214
215 if (online_section_nr(start_nr))
216 return 0;
217
218 while (++start_nr <= __highest_present_section_nr) {
219 if (online_section_nr(start_nr))
220 return section_nr_to_pfn(start_nr);
221 }
222
223 return 0;
224 }
225
226 /*
227 * If the PFN falls into an offline section, return the end PFN of the
228 * next online section in reverse. If the PFN falls into an online section
229 * or if there is no next online section in reverse, return 0.
230 */
skip_offline_sections_reverse(unsigned long start_pfn)231 static unsigned long skip_offline_sections_reverse(unsigned long start_pfn)
232 {
233 unsigned long start_nr = pfn_to_section_nr(start_pfn);
234
235 if (!start_nr || online_section_nr(start_nr))
236 return 0;
237
238 while (start_nr-- > 0) {
239 if (online_section_nr(start_nr))
240 return section_nr_to_pfn(start_nr) + PAGES_PER_SECTION;
241 }
242
243 return 0;
244 }
245 #else
skip_offline_sections(unsigned long start_pfn)246 static unsigned long skip_offline_sections(unsigned long start_pfn)
247 {
248 return 0;
249 }
250
skip_offline_sections_reverse(unsigned long start_pfn)251 static unsigned long skip_offline_sections_reverse(unsigned long start_pfn)
252 {
253 return 0;
254 }
255 #endif
256
257 /*
258 * Compound pages of >= pageblock_order should consistently be skipped until
259 * released. It is always pointless to compact pages of such order (if they are
260 * migratable), and the pageblocks they occupy cannot contain any free pages.
261 */
pageblock_skip_persistent(struct page * page)262 static bool pageblock_skip_persistent(struct page *page)
263 {
264 if (!PageCompound(page))
265 return false;
266
267 page = compound_head(page);
268
269 if (compound_order(page) >= pageblock_order)
270 return true;
271
272 return false;
273 }
274
275 static bool
__reset_isolation_pfn(struct zone * zone,unsigned long pfn,bool check_source,bool check_target)276 __reset_isolation_pfn(struct zone *zone, unsigned long pfn, bool check_source,
277 bool check_target)
278 {
279 struct page *page = pfn_to_online_page(pfn);
280 struct page *block_page;
281 struct page *end_page;
282 unsigned long block_pfn;
283
284 if (!page)
285 return false;
286 if (zone != page_zone(page))
287 return false;
288 if (pageblock_skip_persistent(page))
289 return false;
290
291 /*
292 * If skip is already cleared do no further checking once the
293 * restart points have been set.
294 */
295 if (check_source && check_target && !get_pageblock_skip(page))
296 return true;
297
298 /*
299 * If clearing skip for the target scanner, do not select a
300 * non-movable pageblock as the starting point.
301 */
302 if (!check_source && check_target &&
303 get_pageblock_migratetype(page) != MIGRATE_MOVABLE)
304 return false;
305
306 /* Ensure the start of the pageblock or zone is online and valid */
307 block_pfn = pageblock_start_pfn(pfn);
308 block_pfn = max(block_pfn, zone->zone_start_pfn);
309 block_page = pfn_to_online_page(block_pfn);
310 if (block_page) {
311 page = block_page;
312 pfn = block_pfn;
313 }
314
315 /* Ensure the end of the pageblock or zone is online and valid */
316 block_pfn = pageblock_end_pfn(pfn) - 1;
317 block_pfn = min(block_pfn, zone_end_pfn(zone) - 1);
318 end_page = pfn_to_online_page(block_pfn);
319 if (!end_page)
320 return false;
321
322 /*
323 * Only clear the hint if a sample indicates there is either a
324 * free page or an LRU page in the block. One or other condition
325 * is necessary for the block to be a migration source/target.
326 */
327 do {
328 if (check_source && PageLRU(page)) {
329 clear_pageblock_skip(page);
330 return true;
331 }
332
333 if (check_target && PageBuddy(page)) {
334 clear_pageblock_skip(page);
335 return true;
336 }
337
338 page += (1 << PAGE_ALLOC_COSTLY_ORDER);
339 } while (page <= end_page);
340
341 return false;
342 }
343
344 /*
345 * This function is called to clear all cached information on pageblocks that
346 * should be skipped for page isolation when the migrate and free page scanner
347 * meet.
348 */
__reset_isolation_suitable(struct zone * zone)349 static void __reset_isolation_suitable(struct zone *zone)
350 {
351 unsigned long migrate_pfn = zone->zone_start_pfn;
352 unsigned long free_pfn = zone_end_pfn(zone) - 1;
353 unsigned long reset_migrate = free_pfn;
354 unsigned long reset_free = migrate_pfn;
355 bool source_set = false;
356 bool free_set = false;
357
358 /* Only flush if a full compaction finished recently */
359 if (!zone->compact_blockskip_flush)
360 return;
361
362 zone->compact_blockskip_flush = false;
363
364 /*
365 * Walk the zone and update pageblock skip information. Source looks
366 * for PageLRU while target looks for PageBuddy. When the scanner
367 * is found, both PageBuddy and PageLRU are checked as the pageblock
368 * is suitable as both source and target.
369 */
370 for (; migrate_pfn < free_pfn; migrate_pfn += pageblock_nr_pages,
371 free_pfn -= pageblock_nr_pages) {
372 cond_resched();
373
374 /* Update the migrate PFN */
375 if (__reset_isolation_pfn(zone, migrate_pfn, true, source_set) &&
376 migrate_pfn < reset_migrate) {
377 source_set = true;
378 reset_migrate = migrate_pfn;
379 zone->compact_init_migrate_pfn = reset_migrate;
380 zone->compact_cached_migrate_pfn[0] = reset_migrate;
381 zone->compact_cached_migrate_pfn[1] = reset_migrate;
382 }
383
384 /* Update the free PFN */
385 if (__reset_isolation_pfn(zone, free_pfn, free_set, true) &&
386 free_pfn > reset_free) {
387 free_set = true;
388 reset_free = free_pfn;
389 zone->compact_init_free_pfn = reset_free;
390 zone->compact_cached_free_pfn = reset_free;
391 }
392 }
393
394 /* Leave no distance if no suitable block was reset */
395 if (reset_migrate >= reset_free) {
396 zone->compact_cached_migrate_pfn[0] = migrate_pfn;
397 zone->compact_cached_migrate_pfn[1] = migrate_pfn;
398 zone->compact_cached_free_pfn = free_pfn;
399 }
400 }
401
reset_isolation_suitable(pg_data_t * pgdat)402 void reset_isolation_suitable(pg_data_t *pgdat)
403 {
404 int zoneid;
405
406 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
407 struct zone *zone = &pgdat->node_zones[zoneid];
408 if (!populated_zone(zone))
409 continue;
410
411 __reset_isolation_suitable(zone);
412 }
413 }
414
415 /*
416 * Sets the pageblock skip bit if it was clear. Note that this is a hint as
417 * locks are not required for read/writers. Returns true if it was already set.
418 */
test_and_set_skip(struct compact_control * cc,struct page * page)419 static bool test_and_set_skip(struct compact_control *cc, struct page *page)
420 {
421 bool skip;
422
423 /* Do not update if skip hint is being ignored */
424 if (cc->ignore_skip_hint)
425 return false;
426
427 skip = get_pageblock_skip(page);
428 if (!skip && !cc->no_set_skip_hint)
429 set_pageblock_skip(page);
430
431 return skip;
432 }
433
update_cached_migrate(struct compact_control * cc,unsigned long pfn)434 static void update_cached_migrate(struct compact_control *cc, unsigned long pfn)
435 {
436 struct zone *zone = cc->zone;
437
438 /* Set for isolation rather than compaction */
439 if (cc->no_set_skip_hint)
440 return;
441
442 pfn = pageblock_end_pfn(pfn);
443
444 /* Update where async and sync compaction should restart */
445 if (pfn > zone->compact_cached_migrate_pfn[0])
446 zone->compact_cached_migrate_pfn[0] = pfn;
447 if (cc->mode != MIGRATE_ASYNC &&
448 pfn > zone->compact_cached_migrate_pfn[1])
449 zone->compact_cached_migrate_pfn[1] = pfn;
450 }
451
452 /*
453 * If no pages were isolated then mark this pageblock to be skipped in the
454 * future. The information is later cleared by __reset_isolation_suitable().
455 */
update_pageblock_skip(struct compact_control * cc,struct page * page,unsigned long pfn)456 static void update_pageblock_skip(struct compact_control *cc,
457 struct page *page, unsigned long pfn)
458 {
459 struct zone *zone = cc->zone;
460
461 if (cc->no_set_skip_hint)
462 return;
463
464 set_pageblock_skip(page);
465
466 if (pfn < zone->compact_cached_free_pfn)
467 zone->compact_cached_free_pfn = pfn;
468 }
469 #else
isolation_suitable(struct compact_control * cc,struct page * page)470 static inline bool isolation_suitable(struct compact_control *cc,
471 struct page *page)
472 {
473 return true;
474 }
475
pageblock_skip_persistent(struct page * page)476 static inline bool pageblock_skip_persistent(struct page *page)
477 {
478 return false;
479 }
480
update_pageblock_skip(struct compact_control * cc,struct page * page,unsigned long pfn)481 static inline void update_pageblock_skip(struct compact_control *cc,
482 struct page *page, unsigned long pfn)
483 {
484 }
485
update_cached_migrate(struct compact_control * cc,unsigned long pfn)486 static void update_cached_migrate(struct compact_control *cc, unsigned long pfn)
487 {
488 }
489
test_and_set_skip(struct compact_control * cc,struct page * page)490 static bool test_and_set_skip(struct compact_control *cc, struct page *page)
491 {
492 return false;
493 }
494 #endif /* CONFIG_COMPACTION */
495
496 /*
497 * Compaction requires the taking of some coarse locks that are potentially
498 * very heavily contended. For async compaction, trylock and record if the
499 * lock is contended. The lock will still be acquired but compaction will
500 * abort when the current block is finished regardless of success rate.
501 * Sync compaction acquires the lock.
502 *
503 * Always returns true which makes it easier to track lock state in callers.
504 */
compact_lock_irqsave(spinlock_t * lock,unsigned long * flags,struct compact_control * cc)505 static bool compact_lock_irqsave(spinlock_t *lock, unsigned long *flags,
506 struct compact_control *cc)
507 __acquires(lock)
508 {
509 /* Track if the lock is contended in async mode */
510 if (cc->mode == MIGRATE_ASYNC && !cc->contended) {
511 if (spin_trylock_irqsave(lock, *flags))
512 return true;
513
514 cc->contended = true;
515 }
516
517 spin_lock_irqsave(lock, *flags);
518 return true;
519 }
520
521 static struct lruvec *
compact_folio_lruvec_lock_irqsave(struct folio * folio,unsigned long * flags,struct compact_control * cc)522 compact_folio_lruvec_lock_irqsave(struct folio *folio, unsigned long *flags,
523 struct compact_control *cc)
524 {
525 struct lruvec *lruvec;
526
527 rcu_read_lock();
528 retry:
529 lruvec = folio_lruvec(folio);
530 compact_lock_irqsave(&lruvec->lru_lock, flags, cc);
531 if (unlikely(lruvec_memcg(lruvec) != folio_memcg(folio))) {
532 spin_unlock_irqrestore(&lruvec->lru_lock, *flags);
533 goto retry;
534 }
535
536 return lruvec;
537 }
538
539 /*
540 * Compaction requires the taking of some coarse locks that are potentially
541 * very heavily contended. The lock should be periodically unlocked to avoid
542 * having disabled IRQs for a long time, even when there is nobody waiting on
543 * the lock. It might also be that allowing the IRQs will result in
544 * need_resched() becoming true. If scheduling is needed, compaction schedules.
545 * Either compaction type will also abort if a fatal signal is pending.
546 * In either case if the lock was locked, it is dropped and not regained.
547 *
548 * Returns true if compaction should abort due to fatal signal pending.
549 * Returns false when compaction can continue.
550 */
compact_unlock_should_abort(spinlock_t * lock,unsigned long flags,bool * locked,struct compact_control * cc)551 static bool compact_unlock_should_abort(spinlock_t *lock,
552 unsigned long flags, bool *locked, struct compact_control *cc)
553 {
554 if (*locked) {
555 spin_unlock_irqrestore(lock, flags);
556 *locked = false;
557 }
558
559 if (fatal_signal_pending(current)) {
560 cc->contended = true;
561 return true;
562 }
563
564 cond_resched();
565
566 return false;
567 }
568
569 /*
570 * Isolate free pages onto a private freelist. If @strict is true, will abort
571 * returning 0 on any invalid PFNs or non-free pages inside of the pageblock
572 * (even though it may still end up isolating some pages).
573 */
isolate_freepages_block(struct compact_control * cc,unsigned long * start_pfn,unsigned long end_pfn,struct list_head * freelist,unsigned int stride,bool strict)574 static unsigned long isolate_freepages_block(struct compact_control *cc,
575 unsigned long *start_pfn,
576 unsigned long end_pfn,
577 struct list_head *freelist,
578 unsigned int stride,
579 bool strict)
580 {
581 int nr_scanned = 0, total_isolated = 0;
582 struct page *page;
583 unsigned long flags = 0;
584 bool locked = false;
585 unsigned long blockpfn = *start_pfn;
586 unsigned int order;
587
588 /* Strict mode is for isolation, speed is secondary */
589 if (strict)
590 stride = 1;
591
592 page = pfn_to_page(blockpfn);
593
594 /* Isolate free pages. */
595 for (; blockpfn < end_pfn; blockpfn += stride, page += stride) {
596 int isolated;
597
598 /*
599 * Periodically drop the lock (if held) regardless of its
600 * contention, to give chance to IRQs. Abort if fatal signal
601 * pending.
602 */
603 if (!(blockpfn % COMPACT_CLUSTER_MAX)
604 && compact_unlock_should_abort(&cc->zone->lock, flags,
605 &locked, cc))
606 break;
607
608 nr_scanned++;
609
610 /*
611 * For compound pages such as THP and hugetlbfs, we can save
612 * potentially a lot of iterations if we skip them at once.
613 * The check is racy, but we can consider only valid values
614 * and the only danger is skipping too much.
615 */
616 if (PageCompound(page)) {
617 const unsigned int order = compound_order(page);
618
619 if ((order <= MAX_PAGE_ORDER) &&
620 (blockpfn + (1UL << order) <= end_pfn)) {
621 blockpfn += (1UL << order) - 1;
622 page += (1UL << order) - 1;
623 nr_scanned += (1UL << order) - 1;
624 }
625
626 goto isolate_fail;
627 }
628
629 if (!PageBuddy(page))
630 goto isolate_fail;
631
632 /* If we already hold the lock, we can skip some rechecking. */
633 if (!locked) {
634 locked = compact_lock_irqsave(&cc->zone->lock,
635 &flags, cc);
636
637 /* Recheck this is a buddy page under lock */
638 if (!PageBuddy(page))
639 goto isolate_fail;
640 }
641
642 /* Found a free page, will break it into order-0 pages */
643 order = buddy_order(page);
644 isolated = __isolate_free_page(page, order);
645 if (!isolated)
646 break;
647 set_page_private(page, order);
648
649 nr_scanned += isolated - 1;
650 total_isolated += isolated;
651 cc->nr_freepages += isolated;
652 list_add_tail(&page->lru, &freelist[order]);
653
654 if (!strict && cc->nr_migratepages <= cc->nr_freepages) {
655 blockpfn += isolated;
656 break;
657 }
658 /* Advance to the end of split page */
659 blockpfn += isolated - 1;
660 page += isolated - 1;
661 continue;
662
663 isolate_fail:
664 if (strict)
665 break;
666
667 }
668
669 if (locked)
670 spin_unlock_irqrestore(&cc->zone->lock, flags);
671
672 /*
673 * Be careful to not go outside of the pageblock.
674 */
675 if (unlikely(blockpfn > end_pfn))
676 blockpfn = end_pfn;
677
678 trace_mm_compaction_isolate_freepages(*start_pfn, blockpfn,
679 nr_scanned, total_isolated);
680
681 /* Record how far we have got within the block */
682 *start_pfn = blockpfn;
683
684 /*
685 * If strict isolation is requested by CMA then check that all the
686 * pages requested were isolated. If there were any failures, 0 is
687 * returned and CMA will fail.
688 */
689 if (strict && blockpfn < end_pfn)
690 total_isolated = 0;
691
692 cc->total_free_scanned += nr_scanned;
693 if (total_isolated)
694 count_compact_events(COMPACTISOLATED, total_isolated);
695 return total_isolated;
696 }
697
698 /**
699 * isolate_freepages_range() - isolate free pages.
700 * @cc: Compaction control structure.
701 * @start_pfn: The first PFN to start isolating.
702 * @end_pfn: The one-past-last PFN.
703 *
704 * Non-free pages, invalid PFNs, or zone boundaries within the
705 * [start_pfn, end_pfn) range are considered errors, cause function to
706 * undo its actions and return zero. cc->freepages[] are empty.
707 *
708 * Otherwise, function returns one-past-the-last PFN of isolated page
709 * (which may be greater then end_pfn if end fell in a middle of
710 * a free page). cc->freepages[] contain free pages isolated.
711 */
712 unsigned long
isolate_freepages_range(struct compact_control * cc,unsigned long start_pfn,unsigned long end_pfn)713 isolate_freepages_range(struct compact_control *cc,
714 unsigned long start_pfn, unsigned long end_pfn)
715 {
716 unsigned long isolated, pfn, block_start_pfn, block_end_pfn;
717 int order;
718
719 for (order = 0; order < NR_PAGE_ORDERS; order++)
720 INIT_LIST_HEAD(&cc->freepages[order]);
721
722 pfn = start_pfn;
723 block_start_pfn = pageblock_start_pfn(pfn);
724 if (block_start_pfn < cc->zone->zone_start_pfn)
725 block_start_pfn = cc->zone->zone_start_pfn;
726 block_end_pfn = pageblock_end_pfn(pfn);
727
728 for (; pfn < end_pfn; pfn += isolated,
729 block_start_pfn = block_end_pfn,
730 block_end_pfn += pageblock_nr_pages) {
731 /* Protect pfn from changing by isolate_freepages_block */
732 unsigned long isolate_start_pfn = pfn;
733
734 /*
735 * pfn could pass the block_end_pfn if isolated freepage
736 * is more than pageblock order. In this case, we adjust
737 * scanning range to right one.
738 */
739 if (pfn >= block_end_pfn) {
740 block_start_pfn = pageblock_start_pfn(pfn);
741 block_end_pfn = pageblock_end_pfn(pfn);
742 }
743
744 block_end_pfn = min(block_end_pfn, end_pfn);
745
746 if (!pageblock_pfn_to_page(block_start_pfn,
747 block_end_pfn, cc->zone))
748 break;
749
750 isolated = isolate_freepages_block(cc, &isolate_start_pfn,
751 block_end_pfn, cc->freepages, 0, true);
752
753 /*
754 * In strict mode, isolate_freepages_block() returns 0 if
755 * there are any holes in the block (ie. invalid PFNs or
756 * non-free pages).
757 */
758 if (!isolated)
759 break;
760
761 /*
762 * If we managed to isolate pages, it is always (1 << n) *
763 * pageblock_nr_pages for some non-negative n. (Max order
764 * page may span two pageblocks).
765 */
766 }
767
768 if (pfn < end_pfn) {
769 /* Loop terminated early, cleanup. */
770 release_free_list(cc->freepages);
771 return 0;
772 }
773
774 /* We don't use freelists for anything. */
775 return pfn;
776 }
777
778 /* Similar to reclaim, but different enough that they don't share logic */
too_many_isolated(struct compact_control * cc)779 static bool too_many_isolated(struct compact_control *cc)
780 {
781 pg_data_t *pgdat = cc->zone->zone_pgdat;
782 bool too_many;
783
784 unsigned long active, inactive, isolated;
785
786 inactive = node_page_state(pgdat, NR_INACTIVE_FILE) +
787 node_page_state(pgdat, NR_INACTIVE_ANON);
788 active = node_page_state(pgdat, NR_ACTIVE_FILE) +
789 node_page_state(pgdat, NR_ACTIVE_ANON);
790 isolated = node_page_state(pgdat, NR_ISOLATED_FILE) +
791 node_page_state(pgdat, NR_ISOLATED_ANON);
792
793 /*
794 * Allow GFP_NOFS to isolate past the limit set for regular
795 * compaction runs. This prevents an ABBA deadlock when other
796 * compactors have already isolated to the limit, but are
797 * blocked on filesystem locks held by the GFP_NOFS thread.
798 */
799 if (cc->gfp_mask & __GFP_FS) {
800 inactive >>= 3;
801 active >>= 3;
802 }
803
804 too_many = isolated > (inactive + active) / 2;
805 if (!too_many)
806 wake_throttle_isolated(pgdat);
807
808 return too_many;
809 }
810
811 /**
812 * skip_isolation_on_order() - determine when to skip folio isolation based on
813 * folio order and compaction target order
814 * @order: to-be-isolated folio order
815 * @target_order: compaction target order
816 *
817 * This avoids unnecessary folio isolations during compaction.
818 */
skip_isolation_on_order(int order,int target_order)819 static bool skip_isolation_on_order(int order, int target_order)
820 {
821 /*
822 * Unless we are performing global compaction (i.e.,
823 * is_via_compact_memory), skip any folios that are larger than the
824 * target order: we wouldn't be here if we'd have a free folio with
825 * the desired target_order, so migrating this folio would likely fail
826 * later.
827 */
828 if (!is_via_compact_memory(target_order) && order >= target_order)
829 return true;
830 /*
831 * We limit memory compaction to pageblocks and won't try
832 * creating free blocks of memory that are larger than that.
833 */
834 return order >= pageblock_order;
835 }
836
837 /**
838 * isolate_migratepages_block() - isolate all migrate-able pages within
839 * a single pageblock
840 * @cc: Compaction control structure.
841 * @low_pfn: The first PFN to isolate
842 * @end_pfn: The one-past-the-last PFN to isolate, within same pageblock
843 * @mode: Isolation mode to be used.
844 *
845 * Isolate all pages that can be migrated from the range specified by
846 * [low_pfn, end_pfn). The range is expected to be within same pageblock.
847 * Returns errno, like -EAGAIN or -EINTR in case e.g signal pending or congestion,
848 * -ENOMEM in case we could not allocate a page, or 0.
849 * cc->migrate_pfn will contain the next pfn to scan.
850 *
851 * The pages are isolated on cc->migratepages list (not required to be empty),
852 * and cc->nr_migratepages is updated accordingly.
853 */
854 static int
isolate_migratepages_block(struct compact_control * cc,unsigned long low_pfn,unsigned long end_pfn,isolate_mode_t mode)855 isolate_migratepages_block(struct compact_control *cc, unsigned long low_pfn,
856 unsigned long end_pfn, isolate_mode_t mode)
857 {
858 pg_data_t *pgdat = cc->zone->zone_pgdat;
859 unsigned long nr_scanned = 0, nr_isolated = 0;
860 struct lruvec *lruvec = NULL;
861 unsigned long flags = 0;
862 struct lruvec *locked = NULL;
863 struct folio *folio = NULL;
864 struct page *page = NULL, *valid_page = NULL;
865 struct address_space *mapping;
866 unsigned long start_pfn = low_pfn;
867 bool skip_on_failure = false;
868 unsigned long next_skip_pfn = 0;
869 bool skip_updated = false;
870 int ret = 0;
871
872 cc->migrate_pfn = low_pfn;
873
874 /*
875 * Ensure that there are not too many pages isolated from the LRU
876 * list by either parallel reclaimers or compaction. If there are,
877 * delay for some time until fewer pages are isolated
878 */
879 while (unlikely(too_many_isolated(cc))) {
880 /* stop isolation if there are still pages not migrated */
881 if (cc->nr_migratepages)
882 return -EAGAIN;
883
884 /* async migration should just abort */
885 if (cc->mode == MIGRATE_ASYNC)
886 return -EAGAIN;
887
888 reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
889
890 if (fatal_signal_pending(current))
891 return -EINTR;
892 }
893
894 cond_resched();
895
896 if (cc->direct_compaction && (cc->mode == MIGRATE_ASYNC)) {
897 skip_on_failure = true;
898 next_skip_pfn = block_end_pfn(low_pfn, cc->order);
899 }
900
901 /* Time to isolate some pages for migration */
902 for (; low_pfn < end_pfn; low_pfn++) {
903 bool is_dirty, is_unevictable;
904
905 if (skip_on_failure && low_pfn >= next_skip_pfn) {
906 /*
907 * We have isolated all migration candidates in the
908 * previous order-aligned block, and did not skip it due
909 * to failure. We should migrate the pages now and
910 * hopefully succeed compaction.
911 */
912 if (nr_isolated)
913 break;
914
915 /*
916 * We failed to isolate in the previous order-aligned
917 * block. Set the new boundary to the end of the
918 * current block. Note we can't simply increase
919 * next_skip_pfn by 1 << order, as low_pfn might have
920 * been incremented by a higher number due to skipping
921 * a compound or a high-order buddy page in the
922 * previous loop iteration.
923 */
924 next_skip_pfn = block_end_pfn(low_pfn, cc->order);
925 }
926
927 /*
928 * Periodically drop the lock (if held) regardless of its
929 * contention, to give chance to IRQs. Abort completely if
930 * a fatal signal is pending.
931 */
932 if (!(low_pfn % COMPACT_CLUSTER_MAX)) {
933 if (locked) {
934 lruvec_unlock_irqrestore(locked, flags);
935 locked = NULL;
936 }
937
938 if (fatal_signal_pending(current)) {
939 cc->contended = true;
940 ret = -EINTR;
941
942 goto fatal_pending;
943 }
944
945 cond_resched();
946 }
947
948 nr_scanned++;
949
950 page = pfn_to_page(low_pfn);
951
952 /*
953 * Check if the pageblock has already been marked skipped.
954 * Only the first PFN is checked as the caller isolates
955 * COMPACT_CLUSTER_MAX at a time so the second call must
956 * not falsely conclude that the block should be skipped.
957 */
958 if (!valid_page && (pageblock_aligned(low_pfn) ||
959 low_pfn == cc->zone->zone_start_pfn)) {
960 if (!isolation_suitable(cc, page)) {
961 low_pfn = end_pfn;
962 folio = NULL;
963 goto isolate_abort;
964 }
965 valid_page = page;
966 }
967
968 if (PageHuge(page)) {
969 const unsigned int order = compound_order(page);
970 /*
971 * skip hugetlbfs if we are not compacting for pages
972 * bigger than its order. THPs and other compound pages
973 * are handled below.
974 */
975 if (!cc->alloc_contig) {
976
977 if (order <= MAX_PAGE_ORDER) {
978 low_pfn += (1UL << order) - 1;
979 nr_scanned += (1UL << order) - 1;
980 }
981 goto isolate_fail;
982 }
983 /* for alloc_contig case */
984 if (locked) {
985 lruvec_unlock_irqrestore(locked, flags);
986 locked = NULL;
987 }
988
989 folio = page_folio(page);
990 ret = isolate_or_dissolve_huge_folio(folio, &cc->migratepages);
991
992 /*
993 * Fail isolation in case isolate_or_dissolve_huge_folio()
994 * reports an error. In case of -ENOMEM, abort right away.
995 */
996 if (ret < 0) {
997 /* Do not report -EBUSY down the chain */
998 if (ret == -EBUSY)
999 ret = 0;
1000 low_pfn += (1UL << order) - 1;
1001 nr_scanned += (1UL << order) - 1;
1002 goto isolate_fail;
1003 }
1004
1005 if (folio_test_hugetlb(folio)) {
1006 /*
1007 * Hugepage was successfully isolated and placed
1008 * on the cc->migratepages list.
1009 */
1010 low_pfn += folio_nr_pages(folio) - folio_page_idx(folio, page) - 1;
1011 goto isolate_success_no_list;
1012 }
1013
1014 /*
1015 * Ok, the hugepage was dissolved. Now these pages are
1016 * Buddy and cannot be re-allocated because they are
1017 * isolated. Fall-through as the check below handles
1018 * Buddy pages.
1019 */
1020 }
1021
1022 /*
1023 * Skip if free. We read page order here without zone lock
1024 * which is generally unsafe, but the race window is small and
1025 * the worst thing that can happen is that we skip some
1026 * potential isolation targets.
1027 */
1028 if (PageBuddy(page)) {
1029 unsigned long freepage_order = buddy_order_unsafe(page);
1030
1031 /*
1032 * Without lock, we cannot be sure that what we got is
1033 * a valid page order. Consider only values in the
1034 * valid order range to prevent low_pfn overflow.
1035 */
1036 if (freepage_order > 0 && freepage_order <= MAX_PAGE_ORDER) {
1037 low_pfn += (1UL << freepage_order) - 1;
1038 nr_scanned += (1UL << freepage_order) - 1;
1039 }
1040 continue;
1041 }
1042
1043 /*
1044 * Regardless of being on LRU, compound pages such as THP
1045 * (hugetlbfs is handled above) are not to be compacted unless
1046 * we are attempting an allocation larger than the compound
1047 * page size. We can potentially save a lot of iterations if we
1048 * skip them at once. The check is racy, but we can consider
1049 * only valid values and the only danger is skipping too much.
1050 */
1051 if (PageCompound(page) && !cc->alloc_contig) {
1052 const unsigned int order = compound_order(page);
1053
1054 /* Skip based on page order and compaction target order. */
1055 if (skip_isolation_on_order(order, cc->order)) {
1056 if (order <= MAX_PAGE_ORDER) {
1057 low_pfn += (1UL << order) - 1;
1058 nr_scanned += (1UL << order) - 1;
1059 }
1060 goto isolate_fail;
1061 }
1062 }
1063
1064 /*
1065 * Check may be lockless but that's ok as we recheck later.
1066 * It's possible to migrate LRU and non-lru movable pages.
1067 * Skip any other type of page
1068 */
1069 if (!PageLRU(page)) {
1070 /* Isolation code will deal with any races. */
1071 if (unlikely(page_has_movable_ops(page)) &&
1072 !PageMovableOpsIsolated(page)) {
1073 if (locked) {
1074 lruvec_unlock_irqrestore(locked, flags);
1075 locked = NULL;
1076 }
1077
1078 if (isolate_movable_ops_page(page, mode)) {
1079 folio = page_folio(page);
1080 goto isolate_success;
1081 }
1082 }
1083
1084 goto isolate_fail;
1085 }
1086
1087 /*
1088 * Be careful not to clear PageLRU until after we're
1089 * sure the page is not being freed elsewhere -- the
1090 * page release code relies on it.
1091 */
1092 folio = folio_get_nontail_page(page);
1093 if (unlikely(!folio))
1094 goto isolate_fail;
1095
1096 /*
1097 * Migration will fail if an anonymous page is pinned in memory,
1098 * so avoid taking lru_lock and isolating it unnecessarily in an
1099 * admittedly racy check.
1100 */
1101 mapping = folio_mapping(folio);
1102 if (!mapping && (folio_ref_count(folio) - 1) > folio_mapcount(folio))
1103 goto isolate_fail_put;
1104
1105 /*
1106 * Only allow to migrate anonymous pages in GFP_NOFS context
1107 * because those do not depend on fs locks.
1108 */
1109 if (!(cc->gfp_mask & __GFP_FS) && mapping)
1110 goto isolate_fail_put;
1111
1112 /* Only take pages on LRU: a check now makes later tests safe */
1113 if (!folio_test_lru(folio))
1114 goto isolate_fail_put;
1115
1116 is_unevictable = folio_test_unevictable(folio);
1117
1118 /* Compaction might skip unevictable pages but CMA takes them */
1119 if (!(mode & ISOLATE_UNEVICTABLE) && is_unevictable)
1120 goto isolate_fail_put;
1121
1122 /*
1123 * To minimise LRU disruption, the caller can indicate with
1124 * ISOLATE_ASYNC_MIGRATE that it only wants to isolate pages
1125 * it will be able to migrate without blocking - clean pages
1126 * for the most part. Writeback would require blocking.
1127 */
1128 if ((mode & ISOLATE_ASYNC_MIGRATE) && folio_test_writeback(folio))
1129 goto isolate_fail_put;
1130
1131 is_dirty = folio_test_dirty(folio);
1132
1133 if (((mode & ISOLATE_ASYNC_MIGRATE) && is_dirty) ||
1134 (mapping && is_unevictable)) {
1135 bool migrate_dirty = true;
1136 bool is_inaccessible;
1137
1138 /*
1139 * Only folios without mappings or that have
1140 * a ->migrate_folio callback are possible to migrate
1141 * without blocking.
1142 *
1143 * Folios from inaccessible mappings are not migratable.
1144 *
1145 * However, we can be racing with truncation, which can
1146 * free the mapping that we need to check. Truncation
1147 * holds the folio lock until after the folio is removed
1148 * from the page so holding it ourselves is sufficient.
1149 *
1150 * To avoid locking the folio just to check inaccessible,
1151 * assume every inaccessible folio is also unevictable,
1152 * which is a cheaper test. If our assumption goes
1153 * wrong, it's not a correctness bug, just potentially
1154 * wasted cycles.
1155 */
1156 if (!folio_trylock(folio))
1157 goto isolate_fail_put;
1158
1159 mapping = folio_mapping(folio);
1160 if ((mode & ISOLATE_ASYNC_MIGRATE) && is_dirty) {
1161 migrate_dirty = !mapping ||
1162 mapping->a_ops->migrate_folio;
1163 }
1164 is_inaccessible = mapping && mapping_inaccessible(mapping);
1165 folio_unlock(folio);
1166 if (!migrate_dirty || is_inaccessible)
1167 goto isolate_fail_put;
1168 }
1169
1170 /* Try isolate the folio */
1171 if (!folio_test_clear_lru(folio))
1172 goto isolate_fail_put;
1173
1174 if (locked)
1175 lruvec = folio_lruvec(folio);
1176
1177 /* If we already hold the lock, we can skip some rechecking */
1178 if (lruvec != locked || !locked) {
1179 if (locked)
1180 lruvec_unlock_irqrestore(locked, flags);
1181
1182 lruvec = compact_folio_lruvec_lock_irqsave(folio, &flags, cc);
1183 locked = lruvec;
1184
1185 /*
1186 * Try get exclusive access under lock. If marked for
1187 * skip, the scan is aborted unless the current context
1188 * is a rescan to reach the end of the pageblock.
1189 */
1190 if (!skip_updated && valid_page) {
1191 skip_updated = true;
1192 if (test_and_set_skip(cc, valid_page) &&
1193 !cc->finish_pageblock) {
1194 low_pfn = end_pfn;
1195 goto isolate_abort;
1196 }
1197 }
1198
1199 /*
1200 * Check LRU folio order under the lock
1201 */
1202 if (unlikely(skip_isolation_on_order(folio_order(folio),
1203 cc->order) &&
1204 !cc->alloc_contig)) {
1205 low_pfn += folio_nr_pages(folio) - 1;
1206 nr_scanned += folio_nr_pages(folio) - 1;
1207 folio_set_lru(folio);
1208 goto isolate_fail_put;
1209 }
1210 }
1211
1212 /* The folio is taken off the LRU */
1213 if (folio_test_large(folio))
1214 low_pfn += folio_nr_pages(folio) - 1;
1215
1216 /* Successfully isolated */
1217 lruvec_del_folio(lruvec, folio);
1218 node_stat_mod_folio(folio,
1219 NR_ISOLATED_ANON + folio_is_file_lru(folio),
1220 folio_nr_pages(folio));
1221
1222 isolate_success:
1223 list_add(&folio->lru, &cc->migratepages);
1224 isolate_success_no_list:
1225 cc->nr_migratepages += folio_nr_pages(folio);
1226 nr_isolated += folio_nr_pages(folio);
1227 nr_scanned += folio_nr_pages(folio) - 1;
1228
1229 /*
1230 * Avoid isolating too much unless this block is being
1231 * fully scanned (e.g. dirty/writeback pages, parallel allocation)
1232 * or a lock is contended. For contention, isolate quickly to
1233 * potentially remove one source of contention.
1234 */
1235 if (cc->nr_migratepages >= COMPACT_CLUSTER_MAX &&
1236 !cc->finish_pageblock && !cc->contended) {
1237 ++low_pfn;
1238 break;
1239 }
1240
1241 continue;
1242
1243 isolate_fail_put:
1244 /* Avoid potential deadlock in freeing page under lru_lock */
1245 if (locked) {
1246 lruvec_unlock_irqrestore(locked, flags);
1247 locked = NULL;
1248 }
1249 folio_put(folio);
1250
1251 isolate_fail:
1252 if (!skip_on_failure && ret != -ENOMEM)
1253 continue;
1254
1255 /*
1256 * We have isolated some pages, but then failed. Release them
1257 * instead of migrating, as we cannot form the cc->order buddy
1258 * page anyway.
1259 */
1260 if (nr_isolated) {
1261 if (locked) {
1262 lruvec_unlock_irqrestore(locked, flags);
1263 locked = NULL;
1264 }
1265 putback_movable_pages(&cc->migratepages);
1266 cc->nr_migratepages = 0;
1267 nr_isolated = 0;
1268 }
1269
1270 if (low_pfn < next_skip_pfn) {
1271 low_pfn = next_skip_pfn - 1;
1272 /*
1273 * The check near the loop beginning would have updated
1274 * next_skip_pfn too, but this is a bit simpler.
1275 */
1276 next_skip_pfn += 1UL << cc->order;
1277 }
1278
1279 if (ret == -ENOMEM)
1280 break;
1281 }
1282
1283 /*
1284 * The PageBuddy() check could have potentially brought us outside
1285 * the range to be scanned.
1286 */
1287 if (unlikely(low_pfn > end_pfn))
1288 low_pfn = end_pfn;
1289
1290 folio = NULL;
1291
1292 isolate_abort:
1293 if (locked)
1294 lruvec_unlock_irqrestore(locked, flags);
1295 if (folio) {
1296 folio_set_lru(folio);
1297 folio_put(folio);
1298 }
1299
1300 /*
1301 * Update the cached scanner pfn once the pageblock has been scanned.
1302 * Pages will either be migrated in which case there is no point
1303 * scanning in the near future or migration failed in which case the
1304 * failure reason may persist. The block is marked for skipping if
1305 * there were no pages isolated in the block or if the block is
1306 * rescanned twice in a row.
1307 */
1308 if (low_pfn == end_pfn && (!nr_isolated || cc->finish_pageblock)) {
1309 if (!cc->no_set_skip_hint && valid_page && !skip_updated)
1310 set_pageblock_skip(valid_page);
1311 update_cached_migrate(cc, low_pfn);
1312 }
1313
1314 trace_mm_compaction_isolate_migratepages(start_pfn, low_pfn,
1315 nr_scanned, nr_isolated);
1316
1317 fatal_pending:
1318 cc->total_migrate_scanned += nr_scanned;
1319 if (nr_isolated)
1320 count_compact_events(COMPACTISOLATED, nr_isolated);
1321
1322 cc->migrate_pfn = low_pfn;
1323
1324 return ret;
1325 }
1326
1327 /**
1328 * isolate_migratepages_range() - isolate migrate-able pages in a PFN range
1329 * @cc: Compaction control structure.
1330 * @start_pfn: The first PFN to start isolating.
1331 * @end_pfn: The one-past-last PFN.
1332 *
1333 * Returns -EAGAIN when contented, -EINTR in case of a signal pending, -ENOMEM
1334 * in case we could not allocate a page, or 0.
1335 */
1336 int
isolate_migratepages_range(struct compact_control * cc,unsigned long start_pfn,unsigned long end_pfn)1337 isolate_migratepages_range(struct compact_control *cc, unsigned long start_pfn,
1338 unsigned long end_pfn)
1339 {
1340 unsigned long pfn, block_start_pfn, block_end_pfn;
1341 int ret = 0;
1342
1343 /* Scan block by block. First and last block may be incomplete */
1344 pfn = start_pfn;
1345 block_start_pfn = pageblock_start_pfn(pfn);
1346 if (block_start_pfn < cc->zone->zone_start_pfn)
1347 block_start_pfn = cc->zone->zone_start_pfn;
1348 block_end_pfn = pageblock_end_pfn(pfn);
1349
1350 for (; pfn < end_pfn; pfn = block_end_pfn,
1351 block_start_pfn = block_end_pfn,
1352 block_end_pfn += pageblock_nr_pages) {
1353
1354 block_end_pfn = min(block_end_pfn, end_pfn);
1355
1356 if (!pageblock_pfn_to_page(block_start_pfn,
1357 block_end_pfn, cc->zone))
1358 continue;
1359
1360 ret = isolate_migratepages_block(cc, pfn, block_end_pfn,
1361 ISOLATE_UNEVICTABLE);
1362
1363 if (ret)
1364 break;
1365
1366 if (cc->nr_migratepages >= COMPACT_CLUSTER_MAX)
1367 break;
1368 }
1369
1370 return ret;
1371 }
1372
1373 #endif /* CONFIG_COMPACTION || CONFIG_CMA */
1374 #ifdef CONFIG_COMPACTION
1375
suitable_migration_source(struct compact_control * cc,struct page * page)1376 static bool suitable_migration_source(struct compact_control *cc,
1377 struct page *page)
1378 {
1379 int block_mt;
1380
1381 if (pageblock_skip_persistent(page))
1382 return false;
1383
1384 if ((cc->mode != MIGRATE_ASYNC) || !cc->direct_compaction)
1385 return true;
1386
1387 block_mt = get_pageblock_migratetype(page);
1388
1389 if (cc->migratetype == MIGRATE_MOVABLE)
1390 return is_migrate_movable(block_mt);
1391 else
1392 return block_mt == cc->migratetype;
1393 }
1394
1395 /* Returns true if the page is within a block suitable for migration to */
suitable_migration_target(struct compact_control * cc,struct page * page)1396 static bool suitable_migration_target(struct compact_control *cc,
1397 struct page *page)
1398 {
1399 /* If the page is a large free page, then disallow migration */
1400 if (PageBuddy(page)) {
1401 int order = cc->order > 0 ? cc->order : pageblock_order;
1402
1403 /*
1404 * We are checking page_order without zone->lock taken. But
1405 * the only small danger is that we skip a potentially suitable
1406 * pageblock, so it's not worth to check order for valid range.
1407 */
1408 if (buddy_order_unsafe(page) >= order)
1409 return false;
1410 }
1411
1412 if (cc->ignore_block_suitable)
1413 return true;
1414
1415 /* If the block is MIGRATE_MOVABLE or MIGRATE_CMA, allow migration */
1416 if (is_migrate_movable(get_pageblock_migratetype(page)))
1417 return true;
1418
1419 /* Otherwise skip the block */
1420 return false;
1421 }
1422
1423 static inline unsigned int
freelist_scan_limit(struct compact_control * cc)1424 freelist_scan_limit(struct compact_control *cc)
1425 {
1426 unsigned short shift = BITS_PER_LONG - 1;
1427
1428 return (COMPACT_CLUSTER_MAX >> min(shift, cc->fast_search_fail)) + 1;
1429 }
1430
1431 /*
1432 * Test whether the free scanner has reached the same or lower pageblock than
1433 * the migration scanner, and compaction should thus terminate.
1434 */
compact_scanners_met(struct compact_control * cc)1435 static inline bool compact_scanners_met(struct compact_control *cc)
1436 {
1437 return (cc->free_pfn >> pageblock_order)
1438 <= (cc->migrate_pfn >> pageblock_order);
1439 }
1440
1441 /*
1442 * Used when scanning for a suitable migration target which scans freelists
1443 * in reverse. Reorders the list such as the unscanned pages are scanned
1444 * first on the next iteration of the free scanner
1445 */
1446 static void
move_freelist_head(struct list_head * freelist,struct page * freepage)1447 move_freelist_head(struct list_head *freelist, struct page *freepage)
1448 {
1449 LIST_HEAD(sublist);
1450
1451 if (!list_is_first(&freepage->buddy_list, freelist)) {
1452 list_cut_before(&sublist, freelist, &freepage->buddy_list);
1453 list_splice_tail(&sublist, freelist);
1454 }
1455 }
1456
1457 /*
1458 * Similar to move_freelist_head except used by the migration scanner
1459 * when scanning forward. It's possible for these list operations to
1460 * move against each other if they search the free list exactly in
1461 * lockstep.
1462 */
1463 static void
move_freelist_tail(struct list_head * freelist,struct page * freepage)1464 move_freelist_tail(struct list_head *freelist, struct page *freepage)
1465 {
1466 LIST_HEAD(sublist);
1467
1468 if (!list_is_last(&freepage->buddy_list, freelist)) {
1469 list_cut_position(&sublist, freelist, &freepage->buddy_list);
1470 list_splice_tail(&sublist, freelist);
1471 }
1472 }
1473
1474 static void
fast_isolate_around(struct compact_control * cc,unsigned long pfn)1475 fast_isolate_around(struct compact_control *cc, unsigned long pfn)
1476 {
1477 unsigned long start_pfn, end_pfn;
1478 struct page *page;
1479
1480 /* Do not search around if there are enough pages already */
1481 if (cc->nr_freepages >= cc->nr_migratepages)
1482 return;
1483
1484 /* Minimise scanning during async compaction */
1485 if (cc->direct_compaction && cc->mode == MIGRATE_ASYNC)
1486 return;
1487
1488 /* Pageblock boundaries */
1489 start_pfn = max(pageblock_start_pfn(pfn), cc->zone->zone_start_pfn);
1490 end_pfn = min(pageblock_end_pfn(pfn), zone_end_pfn(cc->zone));
1491
1492 page = pageblock_pfn_to_page(start_pfn, end_pfn, cc->zone);
1493 if (!page)
1494 return;
1495
1496 isolate_freepages_block(cc, &start_pfn, end_pfn, cc->freepages, 1, false);
1497
1498 /* Skip this pageblock in the future as it's full or nearly full */
1499 if (start_pfn == end_pfn && !cc->no_set_skip_hint)
1500 set_pageblock_skip(page);
1501 }
1502
1503 /* Search orders in round-robin fashion */
next_search_order(struct compact_control * cc,int order)1504 static int next_search_order(struct compact_control *cc, int order)
1505 {
1506 order--;
1507 if (order < 0)
1508 order = cc->order - 1;
1509
1510 /* Search wrapped around? */
1511 if (order == cc->search_order) {
1512 cc->search_order--;
1513 if (cc->search_order < 0)
1514 cc->search_order = cc->order - 1;
1515 return -1;
1516 }
1517
1518 return order;
1519 }
1520
fast_isolate_freepages(struct compact_control * cc)1521 static void fast_isolate_freepages(struct compact_control *cc)
1522 {
1523 unsigned int limit = max(1U, freelist_scan_limit(cc) >> 1);
1524 unsigned int nr_scanned = 0, total_isolated = 0;
1525 unsigned long low_pfn, min_pfn, highest = 0;
1526 unsigned long nr_isolated = 0;
1527 unsigned long distance;
1528 struct page *page = NULL;
1529 bool scan_start = false;
1530 int order;
1531
1532 /* Full compaction passes in a negative order */
1533 if (cc->order <= 0)
1534 return;
1535
1536 /*
1537 * If starting the scan, use a deeper search and use the highest
1538 * PFN found if a suitable one is not found.
1539 */
1540 if (cc->free_pfn >= cc->zone->compact_init_free_pfn) {
1541 limit = pageblock_nr_pages >> 1;
1542 scan_start = true;
1543 }
1544
1545 /*
1546 * Preferred point is in the top quarter of the scan space but take
1547 * a pfn from the top half if the search is problematic.
1548 */
1549 distance = (cc->free_pfn - cc->migrate_pfn);
1550 low_pfn = pageblock_start_pfn(cc->free_pfn - (distance >> 2));
1551 min_pfn = pageblock_start_pfn(cc->free_pfn - (distance >> 1));
1552
1553 if (WARN_ON_ONCE(min_pfn > low_pfn))
1554 low_pfn = min_pfn;
1555
1556 /*
1557 * Search starts from the last successful isolation order or the next
1558 * order to search after a previous failure
1559 */
1560 cc->search_order = min_t(unsigned int, cc->order - 1, cc->search_order);
1561
1562 for (order = cc->search_order;
1563 !page && order >= 0;
1564 order = next_search_order(cc, order)) {
1565 struct free_area *area = &cc->zone->free_area[order];
1566 struct list_head *freelist;
1567 struct page *freepage;
1568 unsigned long flags;
1569 unsigned int order_scanned = 0;
1570 unsigned long high_pfn = 0;
1571
1572 if (!area->nr_free)
1573 continue;
1574
1575 spin_lock_irqsave(&cc->zone->lock, flags);
1576 freelist = &area->free_list[MIGRATE_MOVABLE];
1577 list_for_each_entry_reverse(freepage, freelist, buddy_list) {
1578 unsigned long pfn;
1579
1580 order_scanned++;
1581 nr_scanned++;
1582 pfn = page_to_pfn(freepage);
1583
1584 if (pfn >= highest)
1585 highest = max(pageblock_start_pfn(pfn),
1586 cc->zone->zone_start_pfn);
1587
1588 if (pfn >= low_pfn) {
1589 cc->fast_search_fail = 0;
1590 cc->search_order = order;
1591 page = freepage;
1592 break;
1593 }
1594
1595 if (pfn >= min_pfn && pfn > high_pfn) {
1596 high_pfn = pfn;
1597
1598 /* Shorten the scan if a candidate is found */
1599 limit >>= 1;
1600 }
1601
1602 if (order_scanned >= limit)
1603 break;
1604 }
1605
1606 /* Use a maximum candidate pfn if a preferred one was not found */
1607 if (!page && high_pfn) {
1608 page = pfn_to_page(high_pfn);
1609
1610 /* Update freepage for the list reorder below */
1611 freepage = page;
1612 }
1613
1614 /* Reorder to so a future search skips recent pages */
1615 move_freelist_head(freelist, freepage);
1616
1617 /* Isolate the page if available */
1618 if (page) {
1619 if (__isolate_free_page(page, order)) {
1620 set_page_private(page, order);
1621 nr_isolated = 1 << order;
1622 nr_scanned += nr_isolated - 1;
1623 total_isolated += nr_isolated;
1624 cc->nr_freepages += nr_isolated;
1625 list_add_tail(&page->lru, &cc->freepages[order]);
1626 count_compact_events(COMPACTISOLATED, nr_isolated);
1627 } else {
1628 /* If isolation fails, abort the search */
1629 order = cc->search_order + 1;
1630 page = NULL;
1631 }
1632 }
1633
1634 spin_unlock_irqrestore(&cc->zone->lock, flags);
1635
1636 /* Skip fast search if enough freepages isolated */
1637 if (cc->nr_freepages >= cc->nr_migratepages)
1638 break;
1639
1640 /*
1641 * Smaller scan on next order so the total scan is related
1642 * to freelist_scan_limit.
1643 */
1644 if (order_scanned >= limit)
1645 limit = max(1U, limit >> 1);
1646 }
1647
1648 trace_mm_compaction_fast_isolate_freepages(min_pfn, cc->free_pfn,
1649 nr_scanned, total_isolated);
1650
1651 if (!page) {
1652 cc->fast_search_fail++;
1653 if (scan_start) {
1654 /*
1655 * Use the highest PFN found above min. If one was
1656 * not found, be pessimistic for direct compaction
1657 * and use the min mark.
1658 */
1659 if (highest >= min_pfn) {
1660 page = pfn_to_page(highest);
1661 cc->free_pfn = highest;
1662 } else {
1663 if (cc->direct_compaction && pfn_valid(min_pfn)) {
1664 page = pageblock_pfn_to_page(min_pfn,
1665 min(pageblock_end_pfn(min_pfn),
1666 zone_end_pfn(cc->zone)),
1667 cc->zone);
1668 if (page && !suitable_migration_target(cc, page))
1669 page = NULL;
1670
1671 cc->free_pfn = min_pfn;
1672 }
1673 }
1674 }
1675 }
1676
1677 if (highest && highest >= cc->zone->compact_cached_free_pfn) {
1678 highest -= pageblock_nr_pages;
1679 cc->zone->compact_cached_free_pfn = highest;
1680 }
1681
1682 cc->total_free_scanned += nr_scanned;
1683 if (!page)
1684 return;
1685
1686 low_pfn = page_to_pfn(page);
1687 fast_isolate_around(cc, low_pfn);
1688 }
1689
1690 /*
1691 * Based on information in the current compact_control, find blocks
1692 * suitable for isolating free pages from and then isolate them.
1693 */
isolate_freepages(struct compact_control * cc)1694 static void isolate_freepages(struct compact_control *cc)
1695 {
1696 struct zone *zone = cc->zone;
1697 struct page *page;
1698 unsigned long block_start_pfn; /* start of current pageblock */
1699 unsigned long isolate_start_pfn; /* exact pfn we start at */
1700 unsigned long block_end_pfn; /* end of current pageblock */
1701 unsigned long low_pfn; /* lowest pfn scanner is able to scan */
1702 unsigned int stride;
1703
1704 /* Try a small search of the free lists for a candidate */
1705 fast_isolate_freepages(cc);
1706 if (cc->nr_freepages)
1707 return;
1708
1709 /*
1710 * Initialise the free scanner. The starting point is where we last
1711 * successfully isolated from, zone-cached value, or the end of the
1712 * zone when isolating for the first time. For looping we also need
1713 * this pfn aligned down to the pageblock boundary, because we do
1714 * block_start_pfn -= pageblock_nr_pages in the for loop.
1715 * For ending point, take care when isolating in last pageblock of a
1716 * zone which ends in the middle of a pageblock.
1717 * The low boundary is the end of the pageblock the migration scanner
1718 * is using.
1719 */
1720 isolate_start_pfn = cc->free_pfn;
1721 block_start_pfn = pageblock_start_pfn(isolate_start_pfn);
1722 block_end_pfn = min(block_start_pfn + pageblock_nr_pages,
1723 zone_end_pfn(zone));
1724 low_pfn = pageblock_end_pfn(cc->migrate_pfn);
1725 stride = cc->mode == MIGRATE_ASYNC ? COMPACT_CLUSTER_MAX : 1;
1726
1727 /*
1728 * Isolate free pages until enough are available to migrate the
1729 * pages on cc->migratepages. We stop searching if the migrate
1730 * and free page scanners meet or enough free pages are isolated.
1731 */
1732 for (; block_start_pfn >= low_pfn;
1733 block_end_pfn = block_start_pfn,
1734 block_start_pfn -= pageblock_nr_pages,
1735 isolate_start_pfn = block_start_pfn) {
1736 unsigned long nr_isolated;
1737
1738 /*
1739 * This can iterate a massively long zone without finding any
1740 * suitable migration targets, so periodically check resched.
1741 */
1742 if (!(block_start_pfn % (COMPACT_CLUSTER_MAX * pageblock_nr_pages)))
1743 cond_resched();
1744
1745 page = pageblock_pfn_to_page(block_start_pfn, block_end_pfn,
1746 zone);
1747 if (!page) {
1748 unsigned long next_pfn;
1749
1750 next_pfn = skip_offline_sections_reverse(block_start_pfn);
1751 if (next_pfn)
1752 block_start_pfn = max(next_pfn, low_pfn);
1753
1754 continue;
1755 }
1756
1757 /* Check the block is suitable for migration */
1758 if (!suitable_migration_target(cc, page))
1759 continue;
1760
1761 /* If isolation recently failed, do not retry */
1762 if (!isolation_suitable(cc, page))
1763 continue;
1764
1765 /* Found a block suitable for isolating free pages from. */
1766 nr_isolated = isolate_freepages_block(cc, &isolate_start_pfn,
1767 block_end_pfn, cc->freepages, stride, false);
1768
1769 /* Update the skip hint if the full pageblock was scanned */
1770 if (isolate_start_pfn == block_end_pfn)
1771 update_pageblock_skip(cc, page, block_start_pfn -
1772 pageblock_nr_pages);
1773
1774 /* Are enough freepages isolated? */
1775 if (cc->nr_freepages >= cc->nr_migratepages) {
1776 if (isolate_start_pfn >= block_end_pfn) {
1777 /*
1778 * Restart at previous pageblock if more
1779 * freepages can be isolated next time.
1780 */
1781 isolate_start_pfn =
1782 block_start_pfn - pageblock_nr_pages;
1783 }
1784 break;
1785 } else if (isolate_start_pfn < block_end_pfn) {
1786 /*
1787 * If isolation failed early, do not continue
1788 * needlessly.
1789 */
1790 break;
1791 }
1792
1793 /* Adjust stride depending on isolation */
1794 if (nr_isolated) {
1795 stride = 1;
1796 continue;
1797 }
1798 stride = min_t(unsigned int, COMPACT_CLUSTER_MAX, stride << 1);
1799 }
1800
1801 /*
1802 * Record where the free scanner will restart next time. Either we
1803 * broke from the loop and set isolate_start_pfn based on the last
1804 * call to isolate_freepages_block(), or we met the migration scanner
1805 * and the loop terminated due to isolate_start_pfn < low_pfn
1806 */
1807 cc->free_pfn = isolate_start_pfn;
1808 }
1809
1810 /*
1811 * This is a migrate-callback that "allocates" freepages by taking pages
1812 * from the isolated freelists in the block we are migrating to.
1813 */
compaction_alloc_noprof(struct folio * src,unsigned long data)1814 static struct folio *compaction_alloc_noprof(struct folio *src, unsigned long data)
1815 {
1816 struct compact_control *cc = (struct compact_control *)data;
1817 struct folio *dst;
1818 int order = folio_order(src);
1819 bool has_isolated_pages = false;
1820 int start_order;
1821 struct page *freepage;
1822 unsigned long size;
1823
1824 again:
1825 for (start_order = order; start_order < NR_PAGE_ORDERS; start_order++)
1826 if (!list_empty(&cc->freepages[start_order]))
1827 break;
1828
1829 /* no free pages in the list */
1830 if (start_order == NR_PAGE_ORDERS) {
1831 if (has_isolated_pages)
1832 return NULL;
1833 isolate_freepages(cc);
1834 has_isolated_pages = true;
1835 goto again;
1836 }
1837
1838 freepage = list_first_entry(&cc->freepages[start_order], struct page,
1839 lru);
1840 size = 1 << start_order;
1841
1842 list_del(&freepage->lru);
1843
1844 while (start_order > order) {
1845 start_order--;
1846 size >>= 1;
1847
1848 list_add(&freepage[size].lru, &cc->freepages[start_order]);
1849 set_page_private(&freepage[size], start_order);
1850 }
1851 dst = (struct folio *)freepage;
1852
1853 post_alloc_hook(&dst->page, order, __GFP_MOVABLE);
1854 set_page_refcounted(&dst->page);
1855 if (order)
1856 prep_compound_page(&dst->page, order);
1857 cc->nr_freepages -= 1 << order;
1858 cc->nr_migratepages -= 1 << order;
1859 return page_rmappable_folio(&dst->page);
1860 }
1861
compaction_alloc(struct folio * src,unsigned long data)1862 static struct folio *compaction_alloc(struct folio *src, unsigned long data)
1863 {
1864 return alloc_hooks(compaction_alloc_noprof(src, data));
1865 }
1866
1867 /*
1868 * This is a migrate-callback that "frees" freepages back to the isolated
1869 * freelist. All pages on the freelist are from the same zone, so there is no
1870 * special handling needed for NUMA.
1871 */
compaction_free(struct folio * dst,unsigned long data)1872 static void compaction_free(struct folio *dst, unsigned long data)
1873 {
1874 struct compact_control *cc = (struct compact_control *)data;
1875 int order = folio_order(dst);
1876 struct page *page = &dst->page;
1877
1878 if (folio_put_testzero(dst) && free_pages_prepare(page, order)) {
1879 list_add(&dst->lru, &cc->freepages[order]);
1880 cc->nr_freepages += 1 << order;
1881 }
1882 cc->nr_migratepages += 1 << order;
1883 /*
1884 * someone else has referenced the page or free_pages_prepare() fails,
1885 * we cannot take it back to our free list.
1886 */
1887 }
1888
1889 /* possible outcome of isolate_migratepages */
1890 typedef enum {
1891 ISOLATE_ABORT, /* Abort compaction now */
1892 ISOLATE_NONE, /* No pages isolated, continue scanning */
1893 ISOLATE_SUCCESS, /* Pages isolated, migrate */
1894 } isolate_migrate_t;
1895
1896 /*
1897 * Allow userspace to control policy on scanning the unevictable LRU for
1898 * compactable pages.
1899 */
1900 static int sysctl_compact_unevictable_allowed __read_mostly = CONFIG_COMPACT_UNEVICTABLE_DEFAULT;
1901 /*
1902 * Tunable for proactive compaction. It determines how
1903 * aggressively the kernel should compact memory in the
1904 * background. It takes values in the range [0, 100].
1905 */
1906 static unsigned int __read_mostly sysctl_compaction_proactiveness = 20;
1907 static int sysctl_extfrag_threshold = 500;
1908 static int __read_mostly sysctl_compact_memory;
1909
1910 static inline void
update_fast_start_pfn(struct compact_control * cc,unsigned long pfn)1911 update_fast_start_pfn(struct compact_control *cc, unsigned long pfn)
1912 {
1913 if (cc->fast_start_pfn == ULONG_MAX)
1914 return;
1915
1916 if (!cc->fast_start_pfn)
1917 cc->fast_start_pfn = pfn;
1918
1919 cc->fast_start_pfn = min(cc->fast_start_pfn, pfn);
1920 }
1921
1922 static inline unsigned long
reinit_migrate_pfn(struct compact_control * cc)1923 reinit_migrate_pfn(struct compact_control *cc)
1924 {
1925 if (!cc->fast_start_pfn || cc->fast_start_pfn == ULONG_MAX)
1926 return cc->migrate_pfn;
1927
1928 cc->migrate_pfn = cc->fast_start_pfn;
1929 cc->fast_start_pfn = ULONG_MAX;
1930
1931 return cc->migrate_pfn;
1932 }
1933
1934 /*
1935 * Briefly search the free lists for a migration source that already has
1936 * some free pages to reduce the number of pages that need migration
1937 * before a pageblock is free.
1938 */
fast_find_migrateblock(struct compact_control * cc)1939 static unsigned long fast_find_migrateblock(struct compact_control *cc)
1940 {
1941 unsigned int limit = freelist_scan_limit(cc);
1942 unsigned int nr_scanned = 0;
1943 unsigned long distance;
1944 unsigned long pfn = cc->migrate_pfn;
1945 unsigned long high_pfn;
1946 int order;
1947 bool found_block = false;
1948
1949 /* Skip hints are relied on to avoid repeats on the fast search */
1950 if (cc->ignore_skip_hint)
1951 return pfn;
1952
1953 /*
1954 * If the pageblock should be finished then do not select a different
1955 * pageblock.
1956 */
1957 if (cc->finish_pageblock)
1958 return pfn;
1959
1960 /*
1961 * If the migrate_pfn is not at the start of a zone or the start
1962 * of a pageblock then assume this is a continuation of a previous
1963 * scan restarted due to COMPACT_CLUSTER_MAX.
1964 */
1965 if (pfn != cc->zone->zone_start_pfn && pfn != pageblock_start_pfn(pfn))
1966 return pfn;
1967
1968 /*
1969 * For smaller orders, just linearly scan as the number of pages
1970 * to migrate should be relatively small and does not necessarily
1971 * justify freeing up a large block for a small allocation.
1972 */
1973 if (cc->order <= PAGE_ALLOC_COSTLY_ORDER)
1974 return pfn;
1975
1976 /*
1977 * Only allow kcompactd and direct requests for movable pages to
1978 * quickly clear out a MOVABLE pageblock for allocation. This
1979 * reduces the risk that a large movable pageblock is freed for
1980 * an unmovable/reclaimable small allocation.
1981 */
1982 if (cc->direct_compaction && cc->migratetype != MIGRATE_MOVABLE)
1983 return pfn;
1984
1985 /*
1986 * When starting the migration scanner, pick any pageblock within the
1987 * first half of the search space. Otherwise try and pick a pageblock
1988 * within the first eighth to reduce the chances that a migration
1989 * target later becomes a source.
1990 */
1991 distance = (cc->free_pfn - cc->migrate_pfn) >> 1;
1992 if (cc->migrate_pfn != cc->zone->zone_start_pfn)
1993 distance >>= 2;
1994 high_pfn = pageblock_start_pfn(cc->migrate_pfn + distance);
1995
1996 for (order = cc->order - 1;
1997 order >= PAGE_ALLOC_COSTLY_ORDER && !found_block && nr_scanned < limit;
1998 order--) {
1999 struct free_area *area = &cc->zone->free_area[order];
2000 struct list_head *freelist;
2001 unsigned long flags;
2002 struct page *freepage;
2003
2004 if (!area->nr_free)
2005 continue;
2006
2007 spin_lock_irqsave(&cc->zone->lock, flags);
2008 freelist = &area->free_list[MIGRATE_MOVABLE];
2009 list_for_each_entry(freepage, freelist, buddy_list) {
2010 unsigned long free_pfn;
2011
2012 if (nr_scanned++ >= limit) {
2013 move_freelist_tail(freelist, freepage);
2014 break;
2015 }
2016
2017 free_pfn = page_to_pfn(freepage);
2018 if (free_pfn < high_pfn) {
2019 /*
2020 * Avoid if skipped recently. Ideally it would
2021 * move to the tail but even safe iteration of
2022 * the list assumes an entry is deleted, not
2023 * reordered.
2024 */
2025 if (get_pageblock_skip(freepage))
2026 continue;
2027
2028 /* Reorder to so a future search skips recent pages */
2029 move_freelist_tail(freelist, freepage);
2030
2031 update_fast_start_pfn(cc, free_pfn);
2032 pfn = pageblock_start_pfn(free_pfn);
2033 if (pfn < cc->zone->zone_start_pfn)
2034 pfn = cc->zone->zone_start_pfn;
2035 cc->fast_search_fail = 0;
2036 found_block = true;
2037 break;
2038 }
2039 }
2040 spin_unlock_irqrestore(&cc->zone->lock, flags);
2041 }
2042
2043 cc->total_migrate_scanned += nr_scanned;
2044
2045 /*
2046 * If fast scanning failed then use a cached entry for a page block
2047 * that had free pages as the basis for starting a linear scan.
2048 */
2049 if (!found_block) {
2050 cc->fast_search_fail++;
2051 pfn = reinit_migrate_pfn(cc);
2052 }
2053 return pfn;
2054 }
2055
2056 /*
2057 * Isolate all pages that can be migrated from the first suitable block,
2058 * starting at the block pointed to by the migrate scanner pfn within
2059 * compact_control.
2060 */
isolate_migratepages(struct compact_control * cc)2061 static isolate_migrate_t isolate_migratepages(struct compact_control *cc)
2062 {
2063 unsigned long block_start_pfn;
2064 unsigned long block_end_pfn;
2065 unsigned long low_pfn;
2066 struct page *page;
2067 const isolate_mode_t isolate_mode =
2068 (sysctl_compact_unevictable_allowed ? ISOLATE_UNEVICTABLE : 0) |
2069 (cc->mode != MIGRATE_SYNC ? ISOLATE_ASYNC_MIGRATE : 0);
2070 bool fast_find_block;
2071
2072 /*
2073 * Start at where we last stopped, or beginning of the zone as
2074 * initialized by compact_zone(). The first failure will use
2075 * the lowest PFN as the starting point for linear scanning.
2076 */
2077 low_pfn = fast_find_migrateblock(cc);
2078 block_start_pfn = pageblock_start_pfn(low_pfn);
2079 if (block_start_pfn < cc->zone->zone_start_pfn)
2080 block_start_pfn = cc->zone->zone_start_pfn;
2081
2082 /*
2083 * fast_find_migrateblock() has already ensured the pageblock is not
2084 * set with a skipped flag, so to avoid the isolation_suitable check
2085 * below again, check whether the fast search was successful.
2086 */
2087 fast_find_block = low_pfn != cc->migrate_pfn && !cc->fast_search_fail;
2088
2089 /* Only scan within a pageblock boundary */
2090 block_end_pfn = pageblock_end_pfn(low_pfn);
2091
2092 /*
2093 * Iterate over whole pageblocks until we find the first suitable.
2094 * Do not cross the free scanner.
2095 */
2096 for (; block_end_pfn <= cc->free_pfn;
2097 fast_find_block = false,
2098 cc->migrate_pfn = low_pfn = block_end_pfn,
2099 block_start_pfn = block_end_pfn,
2100 block_end_pfn += pageblock_nr_pages) {
2101
2102 /*
2103 * This can potentially iterate a massively long zone with
2104 * many pageblocks unsuitable, so periodically check if we
2105 * need to schedule.
2106 */
2107 if (!(low_pfn % (COMPACT_CLUSTER_MAX * pageblock_nr_pages)))
2108 cond_resched();
2109
2110 page = pageblock_pfn_to_page(block_start_pfn,
2111 block_end_pfn, cc->zone);
2112 if (!page) {
2113 unsigned long next_pfn;
2114
2115 next_pfn = skip_offline_sections(block_start_pfn);
2116 if (next_pfn)
2117 block_end_pfn = min(next_pfn, cc->free_pfn);
2118 continue;
2119 }
2120
2121 /*
2122 * If isolation recently failed, do not retry. Only check the
2123 * pageblock once. COMPACT_CLUSTER_MAX causes a pageblock
2124 * to be visited multiple times. Assume skip was checked
2125 * before making it "skip" so other compaction instances do
2126 * not scan the same block.
2127 */
2128 if ((pageblock_aligned(low_pfn) ||
2129 low_pfn == cc->zone->zone_start_pfn) &&
2130 !fast_find_block && !isolation_suitable(cc, page))
2131 continue;
2132
2133 /*
2134 * For async direct compaction, only scan the pageblocks of the
2135 * same migratetype without huge pages. Async direct compaction
2136 * is optimistic to see if the minimum amount of work satisfies
2137 * the allocation. The cached PFN is updated as it's possible
2138 * that all remaining blocks between source and target are
2139 * unsuitable and the compaction scanners fail to meet.
2140 */
2141 if (!suitable_migration_source(cc, page)) {
2142 update_cached_migrate(cc, block_end_pfn);
2143 continue;
2144 }
2145
2146 /* Perform the isolation */
2147 if (isolate_migratepages_block(cc, low_pfn, block_end_pfn,
2148 isolate_mode))
2149 return ISOLATE_ABORT;
2150
2151 /*
2152 * Either we isolated something and proceed with migration. Or
2153 * we failed and compact_zone should decide if we should
2154 * continue or not.
2155 */
2156 break;
2157 }
2158
2159 return cc->nr_migratepages ? ISOLATE_SUCCESS : ISOLATE_NONE;
2160 }
2161
2162 /*
2163 * Determine whether kswapd is (or recently was!) running on this node.
2164 *
2165 * pgdat_kswapd_lock() pins pgdat->kswapd, so a concurrent kswapd_stop() can't
2166 * zero it.
2167 */
kswapd_is_running(pg_data_t * pgdat)2168 static bool kswapd_is_running(pg_data_t *pgdat)
2169 {
2170 bool running;
2171
2172 pgdat_kswapd_lock(pgdat);
2173 running = pgdat->kswapd && task_is_running(pgdat->kswapd);
2174 pgdat_kswapd_unlock(pgdat);
2175
2176 return running;
2177 }
2178
2179 /*
2180 * A zone's fragmentation score is the external fragmentation wrt to the
2181 * COMPACTION_HPAGE_ORDER. It returns a value in the range [0, 100].
2182 */
fragmentation_score_zone(struct zone * zone)2183 static unsigned int fragmentation_score_zone(struct zone *zone)
2184 {
2185 return extfrag_for_order(zone, COMPACTION_HPAGE_ORDER);
2186 }
2187
2188 /*
2189 * A weighted zone's fragmentation score is the external fragmentation
2190 * wrt to the COMPACTION_HPAGE_ORDER scaled by the zone's size. It
2191 * returns a value in the range [0, 100].
2192 *
2193 * The scaling factor ensures that proactive compaction focuses on larger
2194 * zones like ZONE_NORMAL, rather than smaller, specialized zones like
2195 * ZONE_DMA32. For smaller zones, the score value remains close to zero,
2196 * and thus never exceeds the high threshold for proactive compaction.
2197 */
fragmentation_score_zone_weighted(struct zone * zone)2198 static unsigned int fragmentation_score_zone_weighted(struct zone *zone)
2199 {
2200 unsigned long score;
2201
2202 score = zone->present_pages * fragmentation_score_zone(zone);
2203 return div64_ul(score, zone->zone_pgdat->node_present_pages + 1);
2204 }
2205
2206 /*
2207 * The per-node proactive (background) compaction process is started by its
2208 * corresponding kcompactd thread when the node's fragmentation score
2209 * exceeds the high threshold. The compaction process remains active till
2210 * the node's score falls below the low threshold, or one of the back-off
2211 * conditions is met.
2212 */
fragmentation_score_node(pg_data_t * pgdat)2213 static unsigned int fragmentation_score_node(pg_data_t *pgdat)
2214 {
2215 unsigned int score = 0;
2216 int zoneid;
2217
2218 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
2219 struct zone *zone;
2220
2221 zone = &pgdat->node_zones[zoneid];
2222 if (!populated_zone(zone))
2223 continue;
2224 score += fragmentation_score_zone_weighted(zone);
2225 }
2226
2227 return score;
2228 }
2229
fragmentation_score_wmark(bool low)2230 static unsigned int fragmentation_score_wmark(bool low)
2231 {
2232 unsigned int wmark_low, leeway;
2233
2234 wmark_low = 100U - sysctl_compaction_proactiveness;
2235 leeway = min(10U, wmark_low / 2);
2236 return low ? wmark_low : min(wmark_low + leeway, 100U);
2237 }
2238
should_proactive_compact_node(pg_data_t * pgdat)2239 static bool should_proactive_compact_node(pg_data_t *pgdat)
2240 {
2241 int wmark_high;
2242
2243 if (!sysctl_compaction_proactiveness || kswapd_is_running(pgdat))
2244 return false;
2245
2246 wmark_high = fragmentation_score_wmark(false);
2247 return fragmentation_score_node(pgdat) > wmark_high;
2248 }
2249
__compact_finished(struct compact_control * cc)2250 static enum compact_result __compact_finished(struct compact_control *cc)
2251 {
2252 unsigned int order;
2253 const int migratetype = cc->migratetype;
2254 int ret;
2255
2256 /* Compaction run completes if the migrate and free scanner meet */
2257 if (compact_scanners_met(cc)) {
2258 /* Let the next compaction start anew. */
2259 reset_cached_positions(cc->zone);
2260
2261 /*
2262 * Mark that the PG_migrate_skip information should be cleared
2263 * by kswapd when it goes to sleep. kcompactd does not set the
2264 * flag itself as the decision to be clear should be directly
2265 * based on an allocation request.
2266 */
2267 if (cc->direct_compaction)
2268 cc->zone->compact_blockskip_flush = true;
2269
2270 if (cc->whole_zone)
2271 return COMPACT_COMPLETE;
2272 else
2273 return COMPACT_PARTIAL_SKIPPED;
2274 }
2275
2276 if (cc->proactive_compaction) {
2277 int score, wmark_low;
2278 pg_data_t *pgdat;
2279
2280 pgdat = cc->zone->zone_pgdat;
2281 if (kswapd_is_running(pgdat))
2282 return COMPACT_PARTIAL_SKIPPED;
2283
2284 score = fragmentation_score_zone(cc->zone);
2285 wmark_low = fragmentation_score_wmark(true);
2286
2287 if (score > wmark_low)
2288 ret = COMPACT_CONTINUE;
2289 else
2290 ret = COMPACT_SUCCESS;
2291
2292 goto out;
2293 }
2294
2295 if (is_via_compact_memory(cc->order))
2296 return COMPACT_CONTINUE;
2297
2298 /*
2299 * Always finish scanning a pageblock to reduce the possibility of
2300 * fallbacks in the future. This is particularly important when
2301 * migration source is unmovable/reclaimable but it's not worth
2302 * special casing.
2303 */
2304 if (!pageblock_aligned(cc->migrate_pfn))
2305 return COMPACT_CONTINUE;
2306
2307 /*
2308 * When defrag_mode is enabled, make kcompactd target
2309 * watermarks in whole pageblocks. Because they can be stolen
2310 * without polluting, no further fallback checks are needed.
2311 */
2312 if (defrag_mode && !cc->direct_compaction) {
2313 if (__zone_watermark_ok(cc->zone, cc->order,
2314 high_wmark_pages(cc->zone),
2315 cc->highest_zoneidx, cc->alloc_flags,
2316 zone_page_state(cc->zone,
2317 NR_FREE_PAGES_BLOCKS)))
2318 return COMPACT_SUCCESS;
2319
2320 return COMPACT_CONTINUE;
2321 }
2322
2323 /* Direct compactor: Is a suitable page free? */
2324 ret = COMPACT_NO_SUITABLE_PAGE;
2325 for (order = cc->order; order < NR_PAGE_ORDERS; order++) {
2326 struct free_area *area = &cc->zone->free_area[order];
2327
2328 /* Job done if page is free of the right migratetype */
2329 if (!free_area_empty(area, migratetype))
2330 return COMPACT_SUCCESS;
2331
2332 #ifdef CONFIG_CMA
2333 /* MIGRATE_MOVABLE can fallback on MIGRATE_CMA */
2334 if (migratetype == MIGRATE_MOVABLE &&
2335 !free_area_empty(area, MIGRATE_CMA))
2336 return COMPACT_SUCCESS;
2337 #endif
2338 /*
2339 * Job done if allocation would steal freepages from
2340 * other migratetype buddy lists.
2341 */
2342 if (find_suitable_fallback(area, order, migratetype, true, NULL)
2343 == FALLBACK_FOUND)
2344 /*
2345 * Movable pages are OK in any pageblock. If we are
2346 * stealing for a non-movable allocation, make sure
2347 * we finish compacting the current pageblock first
2348 * (which is assured by the above migrate_pfn align
2349 * check) so it is as free as possible and we won't
2350 * have to steal another one soon.
2351 */
2352 return COMPACT_SUCCESS;
2353 }
2354
2355 out:
2356 if (cc->contended || fatal_signal_pending(current))
2357 ret = COMPACT_CONTENDED;
2358
2359 return ret;
2360 }
2361
compact_finished(struct compact_control * cc)2362 static enum compact_result compact_finished(struct compact_control *cc)
2363 {
2364 int ret;
2365
2366 ret = __compact_finished(cc);
2367 trace_mm_compaction_finished(cc->zone, cc->order, ret);
2368 if (ret == COMPACT_NO_SUITABLE_PAGE)
2369 ret = COMPACT_CONTINUE;
2370
2371 return ret;
2372 }
2373
__compaction_suitable(struct zone * zone,int order,unsigned long watermark,int highest_zoneidx,unsigned long free_pages)2374 static bool __compaction_suitable(struct zone *zone, int order,
2375 unsigned long watermark, int highest_zoneidx,
2376 unsigned long free_pages)
2377 {
2378 /*
2379 * Watermarks for order-0 must be met for compaction to be able to
2380 * isolate free pages for migration targets. This means that the
2381 * watermark have to match, or be more pessimistic than the check in
2382 * __isolate_free_page().
2383 *
2384 * For costly orders, we require a higher watermark for compaction to
2385 * proceed to increase its chances.
2386 *
2387 * We use the direct compactor's highest_zoneidx to skip over zones
2388 * where lowmem reserves would prevent allocation even if compaction
2389 * succeeds.
2390 *
2391 * ALLOC_CMA is used, as pages in CMA pageblocks are considered
2392 * suitable migration targets.
2393 */
2394 watermark += compact_gap(order);
2395 if (order > PAGE_ALLOC_COSTLY_ORDER)
2396 watermark += low_wmark_pages(zone) - min_wmark_pages(zone);
2397 return __zone_watermark_ok(zone, 0, watermark, highest_zoneidx,
2398 ALLOC_CMA, free_pages);
2399 }
2400
2401 /*
2402 * compaction_suitable: Is this suitable to run compaction on this zone now?
2403 */
compaction_suitable(struct zone * zone,int order,unsigned long watermark,int highest_zoneidx)2404 bool compaction_suitable(struct zone *zone, int order, unsigned long watermark,
2405 int highest_zoneidx)
2406 {
2407 enum compact_result compact_result;
2408 bool suitable;
2409
2410 suitable = __compaction_suitable(zone, order, watermark, highest_zoneidx,
2411 zone_page_state(zone, NR_FREE_PAGES));
2412 /*
2413 * fragmentation index determines if allocation failures are due to
2414 * low memory or external fragmentation
2415 *
2416 * index of -1000 would imply allocations might succeed depending on
2417 * watermarks, but we already failed the high-order watermark check
2418 * index towards 0 implies failure is due to lack of memory
2419 * index towards 1000 implies failure is due to fragmentation
2420 *
2421 * Only compact if a failure would be due to fragmentation. Also
2422 * ignore fragindex for non-costly orders where the alternative to
2423 * a successful reclaim/compaction is OOM. Fragindex and the
2424 * vm.extfrag_threshold sysctl is meant as a heuristic to prevent
2425 * excessive compaction for costly orders, but it should not be at the
2426 * expense of system stability.
2427 */
2428 if (suitable) {
2429 compact_result = COMPACT_CONTINUE;
2430 if (order > PAGE_ALLOC_COSTLY_ORDER) {
2431 int fragindex = fragmentation_index(zone, order);
2432
2433 if (fragindex >= 0 &&
2434 fragindex <= sysctl_extfrag_threshold) {
2435 suitable = false;
2436 compact_result = COMPACT_NOT_SUITABLE_ZONE;
2437 }
2438 }
2439 } else {
2440 compact_result = COMPACT_SKIPPED;
2441 }
2442
2443 trace_mm_compaction_suitable(zone, order, compact_result);
2444
2445 return suitable;
2446 }
2447
2448 /* Used by direct reclaimers */
compaction_zonelist_suitable(struct alloc_context * ac,int order,int alloc_flags,gfp_t gfp_mask)2449 bool compaction_zonelist_suitable(struct alloc_context *ac, int order,
2450 int alloc_flags, gfp_t gfp_mask)
2451 {
2452 struct zone *zone;
2453 struct zoneref *z;
2454
2455 /*
2456 * Make sure at least one zone would pass __compaction_suitable if we continue
2457 * retrying the reclaim.
2458 */
2459 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
2460 ac->highest_zoneidx, ac->nodemask) {
2461 unsigned long available;
2462
2463 if (cpusets_enabled() && (alloc_flags & ALLOC_CPUSET) &&
2464 !__cpuset_zone_allowed(zone, gfp_mask))
2465 continue;
2466
2467 /*
2468 * Do not consider all the reclaimable memory because we do not
2469 * want to trash just for a single high order allocation which
2470 * is even not guaranteed to appear even if __compaction_suitable
2471 * is happy about the watermark check.
2472 */
2473 available = zone_reclaimable_pages(zone) / order;
2474 available += zone_page_state_snapshot(zone, NR_FREE_PAGES);
2475 if (__compaction_suitable(zone, order, min_wmark_pages(zone),
2476 ac->highest_zoneidx, available))
2477 return true;
2478 }
2479
2480 return false;
2481 }
2482
2483 /*
2484 * Should we do compaction for target allocation order.
2485 * Return COMPACT_SUCCESS if allocation for target order can be already
2486 * satisfied
2487 * Return COMPACT_SKIPPED if compaction for target order is likely to fail
2488 * Return COMPACT_CONTINUE if compaction for target order should be ran
2489 */
2490 static enum compact_result
compaction_suit_allocation_order(struct zone * zone,unsigned int order,int highest_zoneidx,unsigned int alloc_flags,bool async,bool kcompactd)2491 compaction_suit_allocation_order(struct zone *zone, unsigned int order,
2492 int highest_zoneidx, unsigned int alloc_flags,
2493 bool async, bool kcompactd)
2494 {
2495 unsigned long free_pages;
2496 unsigned long watermark;
2497
2498 if (kcompactd && defrag_mode)
2499 free_pages = zone_page_state(zone, NR_FREE_PAGES_BLOCKS);
2500 else
2501 free_pages = zone_page_state(zone, NR_FREE_PAGES);
2502
2503 watermark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK);
2504 if (__zone_watermark_ok(zone, order, watermark, highest_zoneidx,
2505 alloc_flags, free_pages))
2506 return COMPACT_SUCCESS;
2507
2508 /*
2509 * For unmovable allocations (without ALLOC_CMA), check if there is enough
2510 * free memory in the non-CMA pageblocks. Otherwise compaction could form
2511 * the high-order page in CMA pageblocks, which would not help the
2512 * allocation to succeed. However, limit the check to costly order async
2513 * compaction (such as opportunistic THP attempts) because there is the
2514 * possibility that compaction would migrate pages from non-CMA to CMA
2515 * pageblock.
2516 */
2517 if (order > PAGE_ALLOC_COSTLY_ORDER && async &&
2518 !(alloc_flags & ALLOC_CMA)) {
2519 if (!__zone_watermark_ok(zone, 0, watermark + compact_gap(order),
2520 highest_zoneidx, 0,
2521 zone_page_state(zone, NR_FREE_PAGES)))
2522 return COMPACT_SKIPPED;
2523 }
2524
2525 if (!compaction_suitable(zone, order, watermark, highest_zoneidx))
2526 return COMPACT_SKIPPED;
2527
2528 return COMPACT_CONTINUE;
2529 }
2530
2531 static enum compact_result
compact_zone(struct compact_control * cc,struct capture_control * capc)2532 compact_zone(struct compact_control *cc, struct capture_control *capc)
2533 {
2534 enum compact_result ret;
2535 unsigned long start_pfn = cc->zone->zone_start_pfn;
2536 unsigned long end_pfn = zone_end_pfn(cc->zone);
2537 unsigned long last_migrated_pfn;
2538 const bool sync = cc->mode != MIGRATE_ASYNC;
2539 bool update_cached;
2540 unsigned int nr_succeeded = 0, nr_migratepages;
2541 int order;
2542
2543 /*
2544 * These counters track activities during zone compaction. Initialize
2545 * them before compacting a new zone.
2546 */
2547 cc->total_migrate_scanned = 0;
2548 cc->total_free_scanned = 0;
2549 cc->nr_migratepages = 0;
2550 cc->nr_freepages = 0;
2551 for (order = 0; order < NR_PAGE_ORDERS; order++)
2552 INIT_LIST_HEAD(&cc->freepages[order]);
2553 INIT_LIST_HEAD(&cc->migratepages);
2554
2555 cc->migratetype = gfp_migratetype(cc->gfp_mask);
2556
2557 if (!is_via_compact_memory(cc->order)) {
2558 ret = compaction_suit_allocation_order(cc->zone, cc->order,
2559 cc->highest_zoneidx,
2560 cc->alloc_flags,
2561 cc->mode == MIGRATE_ASYNC,
2562 !cc->direct_compaction);
2563 if (ret != COMPACT_CONTINUE)
2564 return ret;
2565 }
2566
2567 /*
2568 * Clear pageblock skip if there were failures recently and compaction
2569 * is about to be retried after being deferred.
2570 */
2571 if (compaction_restarting(cc->zone, cc->order))
2572 __reset_isolation_suitable(cc->zone);
2573
2574 /*
2575 * Setup to move all movable pages to the end of the zone. Used cached
2576 * information on where the scanners should start (unless we explicitly
2577 * want to compact the whole zone), but check that it is initialised
2578 * by ensuring the values are within zone boundaries.
2579 */
2580 cc->fast_start_pfn = 0;
2581 if (cc->whole_zone) {
2582 cc->migrate_pfn = start_pfn;
2583 cc->free_pfn = pageblock_start_pfn(end_pfn - 1);
2584 } else {
2585 cc->migrate_pfn = cc->zone->compact_cached_migrate_pfn[sync];
2586 cc->free_pfn = cc->zone->compact_cached_free_pfn;
2587 if (cc->free_pfn < start_pfn || cc->free_pfn >= end_pfn) {
2588 cc->free_pfn = pageblock_start_pfn(end_pfn - 1);
2589 cc->zone->compact_cached_free_pfn = cc->free_pfn;
2590 }
2591 if (cc->migrate_pfn < start_pfn || cc->migrate_pfn >= end_pfn) {
2592 cc->migrate_pfn = start_pfn;
2593 cc->zone->compact_cached_migrate_pfn[0] = cc->migrate_pfn;
2594 cc->zone->compact_cached_migrate_pfn[1] = cc->migrate_pfn;
2595 }
2596
2597 if (cc->migrate_pfn <= cc->zone->compact_init_migrate_pfn)
2598 cc->whole_zone = true;
2599 }
2600
2601 last_migrated_pfn = 0;
2602
2603 /*
2604 * Migrate has separate cached PFNs for ASYNC and SYNC* migration on
2605 * the basis that some migrations will fail in ASYNC mode. However,
2606 * if the cached PFNs match and pageblocks are skipped due to having
2607 * no isolation candidates, then the sync state does not matter.
2608 * Until a pageblock with isolation candidates is found, keep the
2609 * cached PFNs in sync to avoid revisiting the same blocks.
2610 */
2611 update_cached = !sync &&
2612 cc->zone->compact_cached_migrate_pfn[0] == cc->zone->compact_cached_migrate_pfn[1];
2613
2614 trace_mm_compaction_begin(cc, start_pfn, end_pfn, sync);
2615
2616 /* lru_add_drain_all could be expensive with involving other CPUs */
2617 lru_add_drain();
2618
2619 while ((ret = compact_finished(cc)) == COMPACT_CONTINUE) {
2620 int err;
2621 unsigned long iteration_start_pfn = cc->migrate_pfn;
2622
2623 /*
2624 * Avoid multiple rescans of the same pageblock which can
2625 * happen if a page cannot be isolated (dirty/writeback in
2626 * async mode) or if the migrated pages are being allocated
2627 * before the pageblock is cleared. The first rescan will
2628 * capture the entire pageblock for migration. If it fails,
2629 * it'll be marked skip and scanning will proceed as normal.
2630 */
2631 cc->finish_pageblock = false;
2632 if (pageblock_start_pfn(last_migrated_pfn) ==
2633 pageblock_start_pfn(iteration_start_pfn)) {
2634 cc->finish_pageblock = true;
2635 }
2636
2637 rescan:
2638 switch (isolate_migratepages(cc)) {
2639 case ISOLATE_ABORT:
2640 ret = COMPACT_CONTENDED;
2641 putback_movable_pages(&cc->migratepages);
2642 cc->nr_migratepages = 0;
2643 goto out;
2644 case ISOLATE_NONE:
2645 if (update_cached) {
2646 cc->zone->compact_cached_migrate_pfn[1] =
2647 cc->zone->compact_cached_migrate_pfn[0];
2648 }
2649
2650 /*
2651 * We haven't isolated and migrated anything, but
2652 * there might still be unflushed migrations from
2653 * previous cc->order aligned block.
2654 */
2655 goto check_drain;
2656 case ISOLATE_SUCCESS:
2657 update_cached = false;
2658 last_migrated_pfn = max(cc->zone->zone_start_pfn,
2659 pageblock_start_pfn(cc->migrate_pfn - 1));
2660 }
2661
2662 /*
2663 * Record the number of pages to migrate since the
2664 * compaction_alloc/free() will update cc->nr_migratepages
2665 * properly.
2666 */
2667 nr_migratepages = cc->nr_migratepages;
2668 err = migrate_pages(&cc->migratepages, compaction_alloc,
2669 compaction_free, (unsigned long)cc, cc->mode,
2670 MR_COMPACTION, &nr_succeeded);
2671
2672 trace_mm_compaction_migratepages(nr_migratepages, nr_succeeded);
2673
2674 /* All pages were either migrated or will be released */
2675 cc->nr_migratepages = 0;
2676 if (err) {
2677 putback_movable_pages(&cc->migratepages);
2678 /*
2679 * migrate_pages() may return -ENOMEM when scanners meet
2680 * and we want compact_finished() to detect it
2681 */
2682 if (err == -ENOMEM && !compact_scanners_met(cc)) {
2683 ret = COMPACT_CONTENDED;
2684 goto out;
2685 }
2686 /*
2687 * If an ASYNC or SYNC_LIGHT fails to migrate a page
2688 * within the pageblock_order-aligned block and
2689 * fast_find_migrateblock may be used then scan the
2690 * remainder of the pageblock. This will mark the
2691 * pageblock "skip" to avoid rescanning in the near
2692 * future. This will isolate more pages than necessary
2693 * for the request but avoid loops due to
2694 * fast_find_migrateblock revisiting blocks that were
2695 * recently partially scanned.
2696 */
2697 if (!pageblock_aligned(cc->migrate_pfn) &&
2698 !cc->ignore_skip_hint && !cc->finish_pageblock &&
2699 (cc->mode < MIGRATE_SYNC)) {
2700 cc->finish_pageblock = true;
2701
2702 /*
2703 * Draining pcplists does not help THP if
2704 * any page failed to migrate. Even after
2705 * drain, the pageblock will not be free.
2706 */
2707 if (cc->order == COMPACTION_HPAGE_ORDER)
2708 last_migrated_pfn = 0;
2709
2710 goto rescan;
2711 }
2712 }
2713
2714 /* Stop if a page has been captured */
2715 if (capc && capc->page) {
2716 ret = COMPACT_SUCCESS;
2717 break;
2718 }
2719
2720 check_drain:
2721 /*
2722 * Has the migration scanner moved away from the previous
2723 * cc->order aligned block where we migrated from? If yes,
2724 * flush the pages that were freed, so that they can merge and
2725 * compact_finished() can detect immediately if allocation
2726 * would succeed.
2727 */
2728 if (cc->order > 0 && last_migrated_pfn) {
2729 unsigned long current_block_start =
2730 block_start_pfn(cc->migrate_pfn, cc->order);
2731
2732 if (last_migrated_pfn < current_block_start) {
2733 lru_add_drain_cpu_zone(cc->zone);
2734 /* No more flushing until we migrate again */
2735 last_migrated_pfn = 0;
2736 }
2737 }
2738 }
2739
2740 out:
2741 /*
2742 * Release free pages and update where the free scanner should restart,
2743 * so we don't leave any returned pages behind in the next attempt.
2744 */
2745 if (cc->nr_freepages > 0) {
2746 unsigned long free_pfn = release_free_list(cc->freepages);
2747
2748 cc->nr_freepages = 0;
2749 VM_BUG_ON(free_pfn == 0);
2750 /* The cached pfn is always the first in a pageblock */
2751 free_pfn = pageblock_start_pfn(free_pfn);
2752 /*
2753 * Only go back, not forward. The cached pfn might have been
2754 * already reset to zone end in compact_finished()
2755 */
2756 if (free_pfn > cc->zone->compact_cached_free_pfn)
2757 cc->zone->compact_cached_free_pfn = free_pfn;
2758 }
2759
2760 count_compact_events(COMPACTMIGRATE_SCANNED, cc->total_migrate_scanned);
2761 count_compact_events(COMPACTFREE_SCANNED, cc->total_free_scanned);
2762
2763 trace_mm_compaction_end(cc, start_pfn, end_pfn, sync, ret);
2764
2765 VM_BUG_ON(!list_empty(&cc->migratepages));
2766
2767 return ret;
2768 }
2769
compact_zone_order(struct zone * zone,int order,gfp_t gfp_mask,enum compact_priority prio,unsigned int alloc_flags,int highest_zoneidx,struct page ** capture)2770 static enum compact_result compact_zone_order(struct zone *zone, int order,
2771 gfp_t gfp_mask, enum compact_priority prio,
2772 unsigned int alloc_flags, int highest_zoneidx,
2773 struct page **capture)
2774 {
2775 enum compact_result ret;
2776 struct compact_control cc = {
2777 .order = order,
2778 .search_order = order,
2779 .gfp_mask = gfp_mask,
2780 .zone = zone,
2781 .mode = (prio == COMPACT_PRIO_ASYNC) ?
2782 MIGRATE_ASYNC : MIGRATE_SYNC_LIGHT,
2783 .alloc_flags = alloc_flags,
2784 .highest_zoneidx = highest_zoneidx,
2785 .direct_compaction = true,
2786 .whole_zone = (prio == MIN_COMPACT_PRIORITY),
2787 .ignore_skip_hint = (prio == MIN_COMPACT_PRIORITY),
2788 .ignore_block_suitable = (prio == MIN_COMPACT_PRIORITY)
2789 };
2790 struct capture_control capc = {
2791 .cc = &cc,
2792 .page = NULL,
2793 };
2794
2795 /*
2796 * Make sure the structs are really initialized before we expose the
2797 * capture control, in case we are interrupted and the interrupt handler
2798 * frees a page.
2799 */
2800 barrier();
2801 WRITE_ONCE(current->capture_control, &capc);
2802
2803 ret = compact_zone(&cc, &capc);
2804
2805 /*
2806 * Make sure we hide capture control first before we read the captured
2807 * page pointer, otherwise an interrupt could free and capture a page
2808 * and we would leak it.
2809 */
2810 WRITE_ONCE(current->capture_control, NULL);
2811 *capture = READ_ONCE(capc.page);
2812 /*
2813 * Technically, it is also possible that compaction is skipped but
2814 * the page is still captured out of luck(IRQ came and freed the page).
2815 * Returning COMPACT_SUCCESS in such cases helps in properly accounting
2816 * the COMPACT[STALL|FAIL] when compaction is skipped.
2817 */
2818 if (*capture)
2819 ret = COMPACT_SUCCESS;
2820
2821 return ret;
2822 }
2823
2824 /**
2825 * try_to_compact_pages - Direct compact to satisfy a high-order allocation
2826 * @gfp_mask: The GFP mask of the current allocation
2827 * @order: The order of the current allocation
2828 * @alloc_flags: The allocation flags of the current allocation
2829 * @ac: The context of current allocation
2830 * @prio: Determines how hard direct compaction should try to succeed
2831 * @capture: Pointer to free page created by compaction will be stored here
2832 *
2833 * This is the main entry point for direct page compaction.
2834 */
try_to_compact_pages(gfp_t gfp_mask,unsigned int order,unsigned int alloc_flags,const struct alloc_context * ac,enum compact_priority prio,struct page ** capture)2835 enum compact_result try_to_compact_pages(gfp_t gfp_mask, unsigned int order,
2836 unsigned int alloc_flags, const struct alloc_context *ac,
2837 enum compact_priority prio, struct page **capture)
2838 {
2839 struct zoneref *z;
2840 struct zone *zone;
2841 enum compact_result rc = COMPACT_SKIPPED;
2842
2843 if (!gfp_compaction_allowed(gfp_mask))
2844 return COMPACT_SKIPPED;
2845
2846 trace_mm_compaction_try_to_compact_pages(order, gfp_mask, prio);
2847
2848 /* Compact each zone in the list */
2849 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist,
2850 ac->highest_zoneidx, ac->nodemask) {
2851 enum compact_result status;
2852
2853 if (cpusets_enabled() &&
2854 (alloc_flags & ALLOC_CPUSET) &&
2855 !__cpuset_zone_allowed(zone, gfp_mask))
2856 continue;
2857
2858 if (prio > MIN_COMPACT_PRIORITY
2859 && compaction_deferred(zone, order)) {
2860 rc = max_t(enum compact_result, COMPACT_DEFERRED, rc);
2861 continue;
2862 }
2863
2864 status = compact_zone_order(zone, order, gfp_mask, prio,
2865 alloc_flags, ac->highest_zoneidx, capture);
2866 rc = max(status, rc);
2867
2868 /* The allocation should succeed, stop compacting */
2869 if (status == COMPACT_SUCCESS) {
2870 /*
2871 * We think the allocation will succeed in this zone,
2872 * but it is not certain, hence the false. The caller
2873 * will repeat this with true if allocation indeed
2874 * succeeds in this zone.
2875 */
2876 compaction_defer_reset(zone, order, false);
2877
2878 break;
2879 }
2880
2881 if (prio != COMPACT_PRIO_ASYNC && (status == COMPACT_COMPLETE ||
2882 status == COMPACT_PARTIAL_SKIPPED))
2883 /*
2884 * We think that allocation won't succeed in this zone
2885 * so we defer compaction there. If it ends up
2886 * succeeding after all, it will be reset.
2887 */
2888 defer_compaction(zone, order);
2889
2890 /*
2891 * We might have stopped compacting due to need_resched() in
2892 * async compaction, or due to a fatal signal detected. In that
2893 * case do not try further zones
2894 */
2895 if ((prio == COMPACT_PRIO_ASYNC && need_resched())
2896 || fatal_signal_pending(current))
2897 break;
2898 }
2899
2900 return rc;
2901 }
2902
2903 /*
2904 * compact_node() - compact all zones within a node
2905 * @pgdat: The node page data
2906 * @proactive: Whether the compaction is proactive
2907 *
2908 * For proactive compaction, compact till each zone's fragmentation score
2909 * reaches within proactive compaction thresholds (as determined by the
2910 * proactiveness tunable), it is possible that the function returns before
2911 * reaching score targets due to various back-off conditions, such as,
2912 * contention on per-node or per-zone locks.
2913 */
compact_node(pg_data_t * pgdat,bool proactive)2914 static int compact_node(pg_data_t *pgdat, bool proactive)
2915 {
2916 int zoneid;
2917 struct zone *zone;
2918 struct compact_control cc = {
2919 .order = -1,
2920 .mode = proactive ? MIGRATE_SYNC_LIGHT : MIGRATE_SYNC,
2921 .ignore_skip_hint = true,
2922 .whole_zone = true,
2923 .gfp_mask = GFP_KERNEL,
2924 .proactive_compaction = proactive,
2925 };
2926
2927 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) {
2928 zone = &pgdat->node_zones[zoneid];
2929 if (!populated_zone(zone))
2930 continue;
2931
2932 if (fatal_signal_pending(current))
2933 return -EINTR;
2934
2935 cc.zone = zone;
2936
2937 compact_zone(&cc, NULL);
2938
2939 if (proactive) {
2940 count_compact_events(KCOMPACTD_MIGRATE_SCANNED,
2941 cc.total_migrate_scanned);
2942 count_compact_events(KCOMPACTD_FREE_SCANNED,
2943 cc.total_free_scanned);
2944 }
2945 }
2946
2947 return 0;
2948 }
2949
2950 /* Compact all zones of all nodes in the system */
compact_nodes(void)2951 static int compact_nodes(void)
2952 {
2953 int ret, nid;
2954
2955 /* Flush pending updates to the LRU lists */
2956 lru_add_drain_all();
2957
2958 for_each_online_node(nid) {
2959 ret = compact_node(NODE_DATA(nid), false);
2960 if (ret)
2961 return ret;
2962 }
2963
2964 return 0;
2965 }
2966
compaction_proactiveness_sysctl_handler(const struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)2967 static int compaction_proactiveness_sysctl_handler(const struct ctl_table *table, int write,
2968 void *buffer, size_t *length, loff_t *ppos)
2969 {
2970 int rc, nid;
2971
2972 rc = proc_dointvec_minmax(table, write, buffer, length, ppos);
2973 if (rc)
2974 return rc;
2975
2976 if (write && sysctl_compaction_proactiveness) {
2977 for_each_online_node(nid) {
2978 pg_data_t *pgdat = NODE_DATA(nid);
2979
2980 if (pgdat->proactive_compact_trigger)
2981 continue;
2982
2983 pgdat->proactive_compact_trigger = true;
2984 trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, -1,
2985 pgdat->nr_zones - 1);
2986 wake_up_interruptible(&pgdat->kcompactd_wait);
2987 }
2988 }
2989
2990 return 0;
2991 }
2992
2993 /*
2994 * This is the entry point for compacting all nodes via
2995 * /proc/sys/vm/compact_memory
2996 */
sysctl_compaction_handler(const struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)2997 static int sysctl_compaction_handler(const struct ctl_table *table, int write,
2998 void *buffer, size_t *length, loff_t *ppos)
2999 {
3000 int ret;
3001
3002 ret = proc_dointvec(table, write, buffer, length, ppos);
3003 if (ret)
3004 return ret;
3005
3006 if (sysctl_compact_memory != 1)
3007 return -EINVAL;
3008
3009 if (write)
3010 ret = compact_nodes();
3011
3012 return ret;
3013 }
3014
3015 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA)
compact_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)3016 static ssize_t compact_store(struct device *dev,
3017 struct device_attribute *attr,
3018 const char *buf, size_t count)
3019 {
3020 int nid = dev->id;
3021
3022 if (nid >= 0 && nid < nr_node_ids && node_online(nid)) {
3023 /* Flush pending updates to the LRU lists */
3024 lru_add_drain_all();
3025
3026 compact_node(NODE_DATA(nid), false);
3027 }
3028
3029 return count;
3030 }
3031 static DEVICE_ATTR_WO(compact);
3032
compaction_register_node(struct node * node)3033 int compaction_register_node(struct node *node)
3034 {
3035 return device_create_file(&node->dev, &dev_attr_compact);
3036 }
3037
compaction_unregister_node(struct node * node)3038 void compaction_unregister_node(struct node *node)
3039 {
3040 device_remove_file(&node->dev, &dev_attr_compact);
3041 }
3042 #endif /* CONFIG_SYSFS && CONFIG_NUMA */
3043
kcompactd_work_requested(pg_data_t * pgdat)3044 static inline bool kcompactd_work_requested(pg_data_t *pgdat)
3045 {
3046 return pgdat->kcompactd_max_order > 0 || kthread_should_stop() ||
3047 pgdat->proactive_compact_trigger;
3048 }
3049
kcompactd_node_suitable(pg_data_t * pgdat)3050 static bool kcompactd_node_suitable(pg_data_t *pgdat)
3051 {
3052 int zoneid;
3053 struct zone *zone;
3054 enum zone_type highest_zoneidx = pgdat->kcompactd_highest_zoneidx;
3055 enum compact_result ret;
3056 unsigned int alloc_flags = defrag_mode ?
3057 ALLOC_WMARK_HIGH : ALLOC_WMARK_MIN;
3058
3059 for (zoneid = 0; zoneid <= highest_zoneidx; zoneid++) {
3060 zone = &pgdat->node_zones[zoneid];
3061
3062 if (!populated_zone(zone))
3063 continue;
3064
3065 ret = compaction_suit_allocation_order(zone,
3066 pgdat->kcompactd_max_order,
3067 highest_zoneidx, alloc_flags,
3068 false, true);
3069 if (ret == COMPACT_CONTINUE)
3070 return true;
3071 }
3072
3073 return false;
3074 }
3075
kcompactd_do_work(pg_data_t * pgdat)3076 static void kcompactd_do_work(pg_data_t *pgdat)
3077 {
3078 /*
3079 * With no special task, compact all zones so that a page of requested
3080 * order is allocatable.
3081 */
3082 int zoneid;
3083 struct zone *zone;
3084 struct compact_control cc = {
3085 .order = pgdat->kcompactd_max_order,
3086 .search_order = pgdat->kcompactd_max_order,
3087 .highest_zoneidx = pgdat->kcompactd_highest_zoneidx,
3088 .mode = MIGRATE_SYNC_LIGHT,
3089 .ignore_skip_hint = false,
3090 .gfp_mask = GFP_KERNEL,
3091 .alloc_flags = defrag_mode ? ALLOC_WMARK_HIGH : ALLOC_WMARK_MIN,
3092 };
3093 enum compact_result ret;
3094
3095 trace_mm_compaction_kcompactd_wake(pgdat->node_id, cc.order,
3096 cc.highest_zoneidx);
3097 count_compact_event(KCOMPACTD_WAKE);
3098
3099 for (zoneid = 0; zoneid <= cc.highest_zoneidx; zoneid++) {
3100 int status;
3101
3102 zone = &pgdat->node_zones[zoneid];
3103 if (!populated_zone(zone))
3104 continue;
3105
3106 if (compaction_deferred(zone, cc.order))
3107 continue;
3108
3109 ret = compaction_suit_allocation_order(zone,
3110 cc.order, zoneid, cc.alloc_flags,
3111 false, true);
3112 if (ret != COMPACT_CONTINUE)
3113 continue;
3114
3115 if (kthread_should_stop())
3116 return;
3117
3118 cc.zone = zone;
3119 status = compact_zone(&cc, NULL);
3120
3121 if (status == COMPACT_SUCCESS) {
3122 compaction_defer_reset(zone, cc.order, false);
3123 } else if (status == COMPACT_PARTIAL_SKIPPED || status == COMPACT_COMPLETE) {
3124 /*
3125 * Buddy pages may become stranded on pcps that could
3126 * otherwise coalesce on the zone's free area for
3127 * order >= cc.order. This is ratelimited by the
3128 * upcoming deferral.
3129 */
3130 drain_all_pages(zone);
3131
3132 /*
3133 * We use sync migration mode here, so we defer like
3134 * sync direct compaction does.
3135 */
3136 defer_compaction(zone, cc.order);
3137 }
3138
3139 count_compact_events(KCOMPACTD_MIGRATE_SCANNED,
3140 cc.total_migrate_scanned);
3141 count_compact_events(KCOMPACTD_FREE_SCANNED,
3142 cc.total_free_scanned);
3143 }
3144
3145 /*
3146 * Regardless of success, we are done until woken up next. But remember
3147 * the requested order/highest_zoneidx in case it was higher/tighter
3148 * than our current ones
3149 */
3150 if (pgdat->kcompactd_max_order <= cc.order)
3151 pgdat->kcompactd_max_order = 0;
3152 if (pgdat->kcompactd_highest_zoneidx >= cc.highest_zoneidx)
3153 pgdat->kcompactd_highest_zoneidx = pgdat->nr_zones - 1;
3154 }
3155
wakeup_kcompactd(pg_data_t * pgdat,int order,int highest_zoneidx)3156 void wakeup_kcompactd(pg_data_t *pgdat, int order, int highest_zoneidx)
3157 {
3158 if (!order)
3159 return;
3160
3161 if (pgdat->kcompactd_max_order < order)
3162 pgdat->kcompactd_max_order = order;
3163
3164 if (pgdat->kcompactd_highest_zoneidx > highest_zoneidx)
3165 pgdat->kcompactd_highest_zoneidx = highest_zoneidx;
3166
3167 /*
3168 * Pairs with implicit barrier in wait_event_freezable()
3169 * such that wakeups are not missed.
3170 */
3171 if (!wq_has_sleeper(&pgdat->kcompactd_wait))
3172 return;
3173
3174 if (!kcompactd_node_suitable(pgdat))
3175 return;
3176
3177 trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, order,
3178 highest_zoneidx);
3179 wake_up_interruptible(&pgdat->kcompactd_wait);
3180 }
3181
3182 /*
3183 * The background compaction daemon, started as a kernel thread
3184 * from the init process.
3185 */
kcompactd(void * p)3186 static int kcompactd(void *p)
3187 {
3188 pg_data_t *pgdat = (pg_data_t *)p;
3189 long default_timeout = msecs_to_jiffies(HPAGE_FRAG_CHECK_INTERVAL_MSEC);
3190 long timeout = default_timeout;
3191
3192 current->flags |= PF_KCOMPACTD;
3193 set_freezable();
3194
3195 pgdat->kcompactd_max_order = 0;
3196 pgdat->kcompactd_highest_zoneidx = pgdat->nr_zones - 1;
3197
3198 while (!kthread_should_stop()) {
3199 unsigned long pflags;
3200
3201 /*
3202 * Avoid the unnecessary wakeup for proactive compaction
3203 * when it is disabled.
3204 */
3205 if (!sysctl_compaction_proactiveness)
3206 timeout = MAX_SCHEDULE_TIMEOUT;
3207 trace_mm_compaction_kcompactd_sleep(pgdat->node_id);
3208 if (wait_event_freezable_timeout(pgdat->kcompactd_wait,
3209 kcompactd_work_requested(pgdat), timeout) &&
3210 !pgdat->proactive_compact_trigger) {
3211
3212 psi_memstall_enter(&pflags);
3213 kcompactd_do_work(pgdat);
3214 psi_memstall_leave(&pflags);
3215 /*
3216 * Reset the timeout value. The defer timeout from
3217 * proactive compaction is lost here but that is fine
3218 * as the condition of the zone changing substantionally
3219 * then carrying on with the previous defer interval is
3220 * not useful.
3221 */
3222 timeout = default_timeout;
3223 continue;
3224 }
3225
3226 /*
3227 * Start the proactive work with default timeout. Based
3228 * on the fragmentation score, this timeout is updated.
3229 */
3230 timeout = default_timeout;
3231 if (should_proactive_compact_node(pgdat)) {
3232 unsigned int prev_score, score;
3233
3234 prev_score = fragmentation_score_node(pgdat);
3235 compact_node(pgdat, true);
3236 score = fragmentation_score_node(pgdat);
3237 /*
3238 * Defer proactive compaction if the fragmentation
3239 * score did not go down i.e. no progress made.
3240 */
3241 if (unlikely(score >= prev_score))
3242 timeout =
3243 default_timeout << COMPACT_MAX_DEFER_SHIFT;
3244 }
3245 if (unlikely(pgdat->proactive_compact_trigger))
3246 pgdat->proactive_compact_trigger = false;
3247 }
3248
3249 current->flags &= ~PF_KCOMPACTD;
3250
3251 return 0;
3252 }
3253
3254 /*
3255 * This kcompactd start function will be called by init and node-hot-add.
3256 * On node-hot-add, kcompactd will moved to proper cpus if cpus are hot-added.
3257 */
kcompactd_run(int nid)3258 void __meminit kcompactd_run(int nid)
3259 {
3260 pg_data_t *pgdat = NODE_DATA(nid);
3261
3262 if (pgdat->kcompactd)
3263 return;
3264
3265 pgdat->kcompactd = kthread_create_on_node(kcompactd, pgdat, nid, "kcompactd%d", nid);
3266 if (IS_ERR(pgdat->kcompactd)) {
3267 pr_err("Failed to start kcompactd on node %d\n", nid);
3268 pgdat->kcompactd = NULL;
3269 } else {
3270 wake_up_process(pgdat->kcompactd);
3271 }
3272 }
3273
3274 /*
3275 * Called by memory hotplug when all memory in a node is offlined. Caller must
3276 * be holding mem_hotplug_begin/done().
3277 */
kcompactd_stop(int nid)3278 void __meminit kcompactd_stop(int nid)
3279 {
3280 struct task_struct *kcompactd = NODE_DATA(nid)->kcompactd;
3281
3282 if (kcompactd) {
3283 kthread_stop(kcompactd);
3284 NODE_DATA(nid)->kcompactd = NULL;
3285 }
3286 }
3287
proc_dointvec_minmax_warn_RT_change(const struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)3288 static int proc_dointvec_minmax_warn_RT_change(const struct ctl_table *table,
3289 int write, void *buffer, size_t *lenp, loff_t *ppos)
3290 {
3291 int ret, old;
3292
3293 if (!IS_ENABLED(CONFIG_PREEMPT_RT) || !write)
3294 return proc_dointvec_minmax(table, write, buffer, lenp, ppos);
3295
3296 old = *(int *)table->data;
3297 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
3298 if (ret)
3299 return ret;
3300 if (old != *(int *)table->data)
3301 pr_warn_once("sysctl attribute %s changed by %s[%d]\n",
3302 table->procname, current->comm,
3303 task_pid_nr(current));
3304 return ret;
3305 }
3306
3307 static const struct ctl_table vm_compaction[] = {
3308 {
3309 .procname = "compact_memory",
3310 .data = &sysctl_compact_memory,
3311 .maxlen = sizeof(int),
3312 .mode = 0200,
3313 .proc_handler = sysctl_compaction_handler,
3314 },
3315 {
3316 .procname = "compaction_proactiveness",
3317 .data = &sysctl_compaction_proactiveness,
3318 .maxlen = sizeof(sysctl_compaction_proactiveness),
3319 .mode = 0644,
3320 .proc_handler = compaction_proactiveness_sysctl_handler,
3321 .extra1 = SYSCTL_ZERO,
3322 .extra2 = SYSCTL_ONE_HUNDRED,
3323 },
3324 {
3325 .procname = "extfrag_threshold",
3326 .data = &sysctl_extfrag_threshold,
3327 .maxlen = sizeof(int),
3328 .mode = 0644,
3329 .proc_handler = proc_dointvec_minmax,
3330 .extra1 = SYSCTL_ZERO,
3331 .extra2 = SYSCTL_ONE_THOUSAND,
3332 },
3333 {
3334 .procname = "compact_unevictable_allowed",
3335 .data = &sysctl_compact_unevictable_allowed,
3336 .maxlen = sizeof(int),
3337 .mode = 0644,
3338 .proc_handler = proc_dointvec_minmax_warn_RT_change,
3339 .extra1 = SYSCTL_ZERO,
3340 .extra2 = SYSCTL_ONE,
3341 },
3342 };
3343
kcompactd_init(void)3344 static int __init kcompactd_init(void)
3345 {
3346 int nid;
3347
3348 for_each_node_state(nid, N_MEMORY)
3349 kcompactd_run(nid);
3350 register_sysctl_init("vm", vm_compaction);
3351 return 0;
3352 }
3353 subsys_initcall(kcompactd_init)
3354
3355 #endif /* CONFIG_COMPACTION */
3356