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 35 static inline void count_compact_event(enum vm_event_item item) 36 { 37 count_vm_event(item); 38 } 39 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 */ 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) 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 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 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 */ 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 */ 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 */ 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 */ 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. */ 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 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 */ 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 */ 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 246 static unsigned long skip_offline_sections(unsigned long start_pfn) 247 { 248 return 0; 249 } 250 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 */ 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 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 */ 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 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 */ 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 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 */ 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 470 static inline bool isolation_suitable(struct compact_control *cc, 471 struct page *page) 472 { 473 return true; 474 } 475 476 static inline bool pageblock_skip_persistent(struct page *page) 477 { 478 return false; 479 } 480 481 static inline void update_pageblock_skip(struct compact_control *cc, 482 struct page *page, unsigned long pfn) 483 { 484 } 485 486 static void update_cached_migrate(struct compact_control *cc, unsigned long pfn) 487 { 488 } 489 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 */ 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 * 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 */ 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 */ 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 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 */ 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 */ 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 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. PageWriteback 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 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 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 */ 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 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 */ 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 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 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 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 */ 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 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 */ 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 */ 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 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 */ 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)) { 1879 free_pages_prepare(page, order); 1880 list_add(&dst->lru, &cc->freepages[order]); 1881 cc->nr_freepages += 1 << order; 1882 } 1883 cc->nr_migratepages += 1 << order; 1884 /* 1885 * someone else has referenced the page, we cannot take it back to our 1886 * free list. 1887 */ 1888 } 1889 1890 /* possible outcome of isolate_migratepages */ 1891 typedef enum { 1892 ISOLATE_ABORT, /* Abort compaction now */ 1893 ISOLATE_NONE, /* No pages isolated, continue scanning */ 1894 ISOLATE_SUCCESS, /* Pages isolated, migrate */ 1895 } isolate_migrate_t; 1896 1897 /* 1898 * Allow userspace to control policy on scanning the unevictable LRU for 1899 * compactable pages. 1900 */ 1901 static int sysctl_compact_unevictable_allowed __read_mostly = CONFIG_COMPACT_UNEVICTABLE_DEFAULT; 1902 /* 1903 * Tunable for proactive compaction. It determines how 1904 * aggressively the kernel should compact memory in the 1905 * background. It takes values in the range [0, 100]. 1906 */ 1907 static unsigned int __read_mostly sysctl_compaction_proactiveness = 20; 1908 static int sysctl_extfrag_threshold = 500; 1909 static int __read_mostly sysctl_compact_memory; 1910 1911 static inline void 1912 update_fast_start_pfn(struct compact_control *cc, unsigned long pfn) 1913 { 1914 if (cc->fast_start_pfn == ULONG_MAX) 1915 return; 1916 1917 if (!cc->fast_start_pfn) 1918 cc->fast_start_pfn = pfn; 1919 1920 cc->fast_start_pfn = min(cc->fast_start_pfn, pfn); 1921 } 1922 1923 static inline unsigned long 1924 reinit_migrate_pfn(struct compact_control *cc) 1925 { 1926 if (!cc->fast_start_pfn || cc->fast_start_pfn == ULONG_MAX) 1927 return cc->migrate_pfn; 1928 1929 cc->migrate_pfn = cc->fast_start_pfn; 1930 cc->fast_start_pfn = ULONG_MAX; 1931 1932 return cc->migrate_pfn; 1933 } 1934 1935 /* 1936 * Briefly search the free lists for a migration source that already has 1937 * some free pages to reduce the number of pages that need migration 1938 * before a pageblock is free. 1939 */ 1940 static unsigned long fast_find_migrateblock(struct compact_control *cc) 1941 { 1942 unsigned int limit = freelist_scan_limit(cc); 1943 unsigned int nr_scanned = 0; 1944 unsigned long distance; 1945 unsigned long pfn = cc->migrate_pfn; 1946 unsigned long high_pfn; 1947 int order; 1948 bool found_block = false; 1949 1950 /* Skip hints are relied on to avoid repeats on the fast search */ 1951 if (cc->ignore_skip_hint) 1952 return pfn; 1953 1954 /* 1955 * If the pageblock should be finished then do not select a different 1956 * pageblock. 1957 */ 1958 if (cc->finish_pageblock) 1959 return pfn; 1960 1961 /* 1962 * If the migrate_pfn is not at the start of a zone or the start 1963 * of a pageblock then assume this is a continuation of a previous 1964 * scan restarted due to COMPACT_CLUSTER_MAX. 1965 */ 1966 if (pfn != cc->zone->zone_start_pfn && pfn != pageblock_start_pfn(pfn)) 1967 return pfn; 1968 1969 /* 1970 * For smaller orders, just linearly scan as the number of pages 1971 * to migrate should be relatively small and does not necessarily 1972 * justify freeing up a large block for a small allocation. 1973 */ 1974 if (cc->order <= PAGE_ALLOC_COSTLY_ORDER) 1975 return pfn; 1976 1977 /* 1978 * Only allow kcompactd and direct requests for movable pages to 1979 * quickly clear out a MOVABLE pageblock for allocation. This 1980 * reduces the risk that a large movable pageblock is freed for 1981 * an unmovable/reclaimable small allocation. 1982 */ 1983 if (cc->direct_compaction && cc->migratetype != MIGRATE_MOVABLE) 1984 return pfn; 1985 1986 /* 1987 * When starting the migration scanner, pick any pageblock within the 1988 * first half of the search space. Otherwise try and pick a pageblock 1989 * within the first eighth to reduce the chances that a migration 1990 * target later becomes a source. 1991 */ 1992 distance = (cc->free_pfn - cc->migrate_pfn) >> 1; 1993 if (cc->migrate_pfn != cc->zone->zone_start_pfn) 1994 distance >>= 2; 1995 high_pfn = pageblock_start_pfn(cc->migrate_pfn + distance); 1996 1997 for (order = cc->order - 1; 1998 order >= PAGE_ALLOC_COSTLY_ORDER && !found_block && nr_scanned < limit; 1999 order--) { 2000 struct free_area *area = &cc->zone->free_area[order]; 2001 struct list_head *freelist; 2002 unsigned long flags; 2003 struct page *freepage; 2004 2005 if (!area->nr_free) 2006 continue; 2007 2008 spin_lock_irqsave(&cc->zone->lock, flags); 2009 freelist = &area->free_list[MIGRATE_MOVABLE]; 2010 list_for_each_entry(freepage, freelist, buddy_list) { 2011 unsigned long free_pfn; 2012 2013 if (nr_scanned++ >= limit) { 2014 move_freelist_tail(freelist, freepage); 2015 break; 2016 } 2017 2018 free_pfn = page_to_pfn(freepage); 2019 if (free_pfn < high_pfn) { 2020 /* 2021 * Avoid if skipped recently. Ideally it would 2022 * move to the tail but even safe iteration of 2023 * the list assumes an entry is deleted, not 2024 * reordered. 2025 */ 2026 if (get_pageblock_skip(freepage)) 2027 continue; 2028 2029 /* Reorder to so a future search skips recent pages */ 2030 move_freelist_tail(freelist, freepage); 2031 2032 update_fast_start_pfn(cc, free_pfn); 2033 pfn = pageblock_start_pfn(free_pfn); 2034 if (pfn < cc->zone->zone_start_pfn) 2035 pfn = cc->zone->zone_start_pfn; 2036 cc->fast_search_fail = 0; 2037 found_block = true; 2038 break; 2039 } 2040 } 2041 spin_unlock_irqrestore(&cc->zone->lock, flags); 2042 } 2043 2044 cc->total_migrate_scanned += nr_scanned; 2045 2046 /* 2047 * If fast scanning failed then use a cached entry for a page block 2048 * that had free pages as the basis for starting a linear scan. 2049 */ 2050 if (!found_block) { 2051 cc->fast_search_fail++; 2052 pfn = reinit_migrate_pfn(cc); 2053 } 2054 return pfn; 2055 } 2056 2057 /* 2058 * Isolate all pages that can be migrated from the first suitable block, 2059 * starting at the block pointed to by the migrate scanner pfn within 2060 * compact_control. 2061 */ 2062 static isolate_migrate_t isolate_migratepages(struct compact_control *cc) 2063 { 2064 unsigned long block_start_pfn; 2065 unsigned long block_end_pfn; 2066 unsigned long low_pfn; 2067 struct page *page; 2068 const isolate_mode_t isolate_mode = 2069 (sysctl_compact_unevictable_allowed ? ISOLATE_UNEVICTABLE : 0) | 2070 (cc->mode != MIGRATE_SYNC ? ISOLATE_ASYNC_MIGRATE : 0); 2071 bool fast_find_block; 2072 2073 /* 2074 * Start at where we last stopped, or beginning of the zone as 2075 * initialized by compact_zone(). The first failure will use 2076 * the lowest PFN as the starting point for linear scanning. 2077 */ 2078 low_pfn = fast_find_migrateblock(cc); 2079 block_start_pfn = pageblock_start_pfn(low_pfn); 2080 if (block_start_pfn < cc->zone->zone_start_pfn) 2081 block_start_pfn = cc->zone->zone_start_pfn; 2082 2083 /* 2084 * fast_find_migrateblock() has already ensured the pageblock is not 2085 * set with a skipped flag, so to avoid the isolation_suitable check 2086 * below again, check whether the fast search was successful. 2087 */ 2088 fast_find_block = low_pfn != cc->migrate_pfn && !cc->fast_search_fail; 2089 2090 /* Only scan within a pageblock boundary */ 2091 block_end_pfn = pageblock_end_pfn(low_pfn); 2092 2093 /* 2094 * Iterate over whole pageblocks until we find the first suitable. 2095 * Do not cross the free scanner. 2096 */ 2097 for (; block_end_pfn <= cc->free_pfn; 2098 fast_find_block = false, 2099 cc->migrate_pfn = low_pfn = block_end_pfn, 2100 block_start_pfn = block_end_pfn, 2101 block_end_pfn += pageblock_nr_pages) { 2102 2103 /* 2104 * This can potentially iterate a massively long zone with 2105 * many pageblocks unsuitable, so periodically check if we 2106 * need to schedule. 2107 */ 2108 if (!(low_pfn % (COMPACT_CLUSTER_MAX * pageblock_nr_pages))) 2109 cond_resched(); 2110 2111 page = pageblock_pfn_to_page(block_start_pfn, 2112 block_end_pfn, cc->zone); 2113 if (!page) { 2114 unsigned long next_pfn; 2115 2116 next_pfn = skip_offline_sections(block_start_pfn); 2117 if (next_pfn) 2118 block_end_pfn = min(next_pfn, cc->free_pfn); 2119 continue; 2120 } 2121 2122 /* 2123 * If isolation recently failed, do not retry. Only check the 2124 * pageblock once. COMPACT_CLUSTER_MAX causes a pageblock 2125 * to be visited multiple times. Assume skip was checked 2126 * before making it "skip" so other compaction instances do 2127 * not scan the same block. 2128 */ 2129 if ((pageblock_aligned(low_pfn) || 2130 low_pfn == cc->zone->zone_start_pfn) && 2131 !fast_find_block && !isolation_suitable(cc, page)) 2132 continue; 2133 2134 /* 2135 * For async direct compaction, only scan the pageblocks of the 2136 * same migratetype without huge pages. Async direct compaction 2137 * is optimistic to see if the minimum amount of work satisfies 2138 * the allocation. The cached PFN is updated as it's possible 2139 * that all remaining blocks between source and target are 2140 * unsuitable and the compaction scanners fail to meet. 2141 */ 2142 if (!suitable_migration_source(cc, page)) { 2143 update_cached_migrate(cc, block_end_pfn); 2144 continue; 2145 } 2146 2147 /* Perform the isolation */ 2148 if (isolate_migratepages_block(cc, low_pfn, block_end_pfn, 2149 isolate_mode)) 2150 return ISOLATE_ABORT; 2151 2152 /* 2153 * Either we isolated something and proceed with migration. Or 2154 * we failed and compact_zone should decide if we should 2155 * continue or not. 2156 */ 2157 break; 2158 } 2159 2160 return cc->nr_migratepages ? ISOLATE_SUCCESS : ISOLATE_NONE; 2161 } 2162 2163 /* 2164 * Determine whether kswapd is (or recently was!) running on this node. 2165 * 2166 * pgdat_kswapd_lock() pins pgdat->kswapd, so a concurrent kswapd_stop() can't 2167 * zero it. 2168 */ 2169 static bool kswapd_is_running(pg_data_t *pgdat) 2170 { 2171 bool running; 2172 2173 pgdat_kswapd_lock(pgdat); 2174 running = pgdat->kswapd && task_is_running(pgdat->kswapd); 2175 pgdat_kswapd_unlock(pgdat); 2176 2177 return running; 2178 } 2179 2180 /* 2181 * A zone's fragmentation score is the external fragmentation wrt to the 2182 * COMPACTION_HPAGE_ORDER. It returns a value in the range [0, 100]. 2183 */ 2184 static unsigned int fragmentation_score_zone(struct zone *zone) 2185 { 2186 return extfrag_for_order(zone, COMPACTION_HPAGE_ORDER); 2187 } 2188 2189 /* 2190 * A weighted zone's fragmentation score is the external fragmentation 2191 * wrt to the COMPACTION_HPAGE_ORDER scaled by the zone's size. It 2192 * returns a value in the range [0, 100]. 2193 * 2194 * The scaling factor ensures that proactive compaction focuses on larger 2195 * zones like ZONE_NORMAL, rather than smaller, specialized zones like 2196 * ZONE_DMA32. For smaller zones, the score value remains close to zero, 2197 * and thus never exceeds the high threshold for proactive compaction. 2198 */ 2199 static unsigned int fragmentation_score_zone_weighted(struct zone *zone) 2200 { 2201 unsigned long score; 2202 2203 score = zone->present_pages * fragmentation_score_zone(zone); 2204 return div64_ul(score, zone->zone_pgdat->node_present_pages + 1); 2205 } 2206 2207 /* 2208 * The per-node proactive (background) compaction process is started by its 2209 * corresponding kcompactd thread when the node's fragmentation score 2210 * exceeds the high threshold. The compaction process remains active till 2211 * the node's score falls below the low threshold, or one of the back-off 2212 * conditions is met. 2213 */ 2214 static unsigned int fragmentation_score_node(pg_data_t *pgdat) 2215 { 2216 unsigned int score = 0; 2217 int zoneid; 2218 2219 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) { 2220 struct zone *zone; 2221 2222 zone = &pgdat->node_zones[zoneid]; 2223 if (!populated_zone(zone)) 2224 continue; 2225 score += fragmentation_score_zone_weighted(zone); 2226 } 2227 2228 return score; 2229 } 2230 2231 static unsigned int fragmentation_score_wmark(bool low) 2232 { 2233 unsigned int wmark_low, leeway; 2234 2235 wmark_low = 100U - sysctl_compaction_proactiveness; 2236 leeway = min(10U, wmark_low / 2); 2237 return low ? wmark_low : min(wmark_low + leeway, 100U); 2238 } 2239 2240 static bool should_proactive_compact_node(pg_data_t *pgdat) 2241 { 2242 int wmark_high; 2243 2244 if (!sysctl_compaction_proactiveness || kswapd_is_running(pgdat)) 2245 return false; 2246 2247 wmark_high = fragmentation_score_wmark(false); 2248 return fragmentation_score_node(pgdat) > wmark_high; 2249 } 2250 2251 static enum compact_result __compact_finished(struct compact_control *cc) 2252 { 2253 unsigned int order; 2254 const int migratetype = cc->migratetype; 2255 int ret; 2256 2257 /* Compaction run completes if the migrate and free scanner meet */ 2258 if (compact_scanners_met(cc)) { 2259 /* Let the next compaction start anew. */ 2260 reset_cached_positions(cc->zone); 2261 2262 /* 2263 * Mark that the PG_migrate_skip information should be cleared 2264 * by kswapd when it goes to sleep. kcompactd does not set the 2265 * flag itself as the decision to be clear should be directly 2266 * based on an allocation request. 2267 */ 2268 if (cc->direct_compaction) 2269 cc->zone->compact_blockskip_flush = true; 2270 2271 if (cc->whole_zone) 2272 return COMPACT_COMPLETE; 2273 else 2274 return COMPACT_PARTIAL_SKIPPED; 2275 } 2276 2277 if (cc->proactive_compaction) { 2278 int score, wmark_low; 2279 pg_data_t *pgdat; 2280 2281 pgdat = cc->zone->zone_pgdat; 2282 if (kswapd_is_running(pgdat)) 2283 return COMPACT_PARTIAL_SKIPPED; 2284 2285 score = fragmentation_score_zone(cc->zone); 2286 wmark_low = fragmentation_score_wmark(true); 2287 2288 if (score > wmark_low) 2289 ret = COMPACT_CONTINUE; 2290 else 2291 ret = COMPACT_SUCCESS; 2292 2293 goto out; 2294 } 2295 2296 if (is_via_compact_memory(cc->order)) 2297 return COMPACT_CONTINUE; 2298 2299 /* 2300 * Always finish scanning a pageblock to reduce the possibility of 2301 * fallbacks in the future. This is particularly important when 2302 * migration source is unmovable/reclaimable but it's not worth 2303 * special casing. 2304 */ 2305 if (!pageblock_aligned(cc->migrate_pfn)) 2306 return COMPACT_CONTINUE; 2307 2308 /* 2309 * When defrag_mode is enabled, make kcompactd target 2310 * watermarks in whole pageblocks. Because they can be stolen 2311 * without polluting, no further fallback checks are needed. 2312 */ 2313 if (defrag_mode && !cc->direct_compaction) { 2314 if (__zone_watermark_ok(cc->zone, cc->order, 2315 high_wmark_pages(cc->zone), 2316 cc->highest_zoneidx, cc->alloc_flags, 2317 zone_page_state(cc->zone, 2318 NR_FREE_PAGES_BLOCKS))) 2319 return COMPACT_SUCCESS; 2320 2321 return COMPACT_CONTINUE; 2322 } 2323 2324 /* Direct compactor: Is a suitable page free? */ 2325 ret = COMPACT_NO_SUITABLE_PAGE; 2326 for (order = cc->order; order < NR_PAGE_ORDERS; order++) { 2327 struct free_area *area = &cc->zone->free_area[order]; 2328 2329 /* Job done if page is free of the right migratetype */ 2330 if (!free_area_empty(area, migratetype)) 2331 return COMPACT_SUCCESS; 2332 2333 #ifdef CONFIG_CMA 2334 /* MIGRATE_MOVABLE can fallback on MIGRATE_CMA */ 2335 if (migratetype == MIGRATE_MOVABLE && 2336 !free_area_empty(area, MIGRATE_CMA)) 2337 return COMPACT_SUCCESS; 2338 #endif 2339 /* 2340 * Job done if allocation would steal freepages from 2341 * other migratetype buddy lists. 2342 */ 2343 if (find_suitable_fallback(area, order, migratetype, true) >= 0) 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 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 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 */ 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 */ 2449 bool compaction_zonelist_suitable(struct alloc_context *ac, int order, 2450 int alloc_flags) 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 /* 2464 * Do not consider all the reclaimable memory because we do not 2465 * want to trash just for a single high order allocation which 2466 * is even not guaranteed to appear even if __compaction_suitable 2467 * is happy about the watermark check. 2468 */ 2469 available = zone_reclaimable_pages(zone) / order; 2470 available += zone_page_state_snapshot(zone, NR_FREE_PAGES); 2471 if (__compaction_suitable(zone, order, min_wmark_pages(zone), 2472 ac->highest_zoneidx, available)) 2473 return true; 2474 } 2475 2476 return false; 2477 } 2478 2479 /* 2480 * Should we do compaction for target allocation order. 2481 * Return COMPACT_SUCCESS if allocation for target order can be already 2482 * satisfied 2483 * Return COMPACT_SKIPPED if compaction for target order is likely to fail 2484 * Return COMPACT_CONTINUE if compaction for target order should be ran 2485 */ 2486 static enum compact_result 2487 compaction_suit_allocation_order(struct zone *zone, unsigned int order, 2488 int highest_zoneidx, unsigned int alloc_flags, 2489 bool async, bool kcompactd) 2490 { 2491 unsigned long free_pages; 2492 unsigned long watermark; 2493 2494 if (kcompactd && defrag_mode) 2495 free_pages = zone_page_state(zone, NR_FREE_PAGES_BLOCKS); 2496 else 2497 free_pages = zone_page_state(zone, NR_FREE_PAGES); 2498 2499 watermark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK); 2500 if (__zone_watermark_ok(zone, order, watermark, highest_zoneidx, 2501 alloc_flags, free_pages)) 2502 return COMPACT_SUCCESS; 2503 2504 /* 2505 * For unmovable allocations (without ALLOC_CMA), check if there is enough 2506 * free memory in the non-CMA pageblocks. Otherwise compaction could form 2507 * the high-order page in CMA pageblocks, which would not help the 2508 * allocation to succeed. However, limit the check to costly order async 2509 * compaction (such as opportunistic THP attempts) because there is the 2510 * possibility that compaction would migrate pages from non-CMA to CMA 2511 * pageblock. 2512 */ 2513 if (order > PAGE_ALLOC_COSTLY_ORDER && async && 2514 !(alloc_flags & ALLOC_CMA)) { 2515 if (!__zone_watermark_ok(zone, 0, watermark + compact_gap(order), 2516 highest_zoneidx, 0, 2517 zone_page_state(zone, NR_FREE_PAGES))) 2518 return COMPACT_SKIPPED; 2519 } 2520 2521 if (!compaction_suitable(zone, order, watermark, highest_zoneidx)) 2522 return COMPACT_SKIPPED; 2523 2524 return COMPACT_CONTINUE; 2525 } 2526 2527 static enum compact_result 2528 compact_zone(struct compact_control *cc, struct capture_control *capc) 2529 { 2530 enum compact_result ret; 2531 unsigned long start_pfn = cc->zone->zone_start_pfn; 2532 unsigned long end_pfn = zone_end_pfn(cc->zone); 2533 unsigned long last_migrated_pfn; 2534 const bool sync = cc->mode != MIGRATE_ASYNC; 2535 bool update_cached; 2536 unsigned int nr_succeeded = 0, nr_migratepages; 2537 int order; 2538 2539 /* 2540 * These counters track activities during zone compaction. Initialize 2541 * them before compacting a new zone. 2542 */ 2543 cc->total_migrate_scanned = 0; 2544 cc->total_free_scanned = 0; 2545 cc->nr_migratepages = 0; 2546 cc->nr_freepages = 0; 2547 for (order = 0; order < NR_PAGE_ORDERS; order++) 2548 INIT_LIST_HEAD(&cc->freepages[order]); 2549 INIT_LIST_HEAD(&cc->migratepages); 2550 2551 cc->migratetype = gfp_migratetype(cc->gfp_mask); 2552 2553 if (!is_via_compact_memory(cc->order)) { 2554 ret = compaction_suit_allocation_order(cc->zone, cc->order, 2555 cc->highest_zoneidx, 2556 cc->alloc_flags, 2557 cc->mode == MIGRATE_ASYNC, 2558 !cc->direct_compaction); 2559 if (ret != COMPACT_CONTINUE) 2560 return ret; 2561 } 2562 2563 /* 2564 * Clear pageblock skip if there were failures recently and compaction 2565 * is about to be retried after being deferred. 2566 */ 2567 if (compaction_restarting(cc->zone, cc->order)) 2568 __reset_isolation_suitable(cc->zone); 2569 2570 /* 2571 * Setup to move all movable pages to the end of the zone. Used cached 2572 * information on where the scanners should start (unless we explicitly 2573 * want to compact the whole zone), but check that it is initialised 2574 * by ensuring the values are within zone boundaries. 2575 */ 2576 cc->fast_start_pfn = 0; 2577 if (cc->whole_zone) { 2578 cc->migrate_pfn = start_pfn; 2579 cc->free_pfn = pageblock_start_pfn(end_pfn - 1); 2580 } else { 2581 cc->migrate_pfn = cc->zone->compact_cached_migrate_pfn[sync]; 2582 cc->free_pfn = cc->zone->compact_cached_free_pfn; 2583 if (cc->free_pfn < start_pfn || cc->free_pfn >= end_pfn) { 2584 cc->free_pfn = pageblock_start_pfn(end_pfn - 1); 2585 cc->zone->compact_cached_free_pfn = cc->free_pfn; 2586 } 2587 if (cc->migrate_pfn < start_pfn || cc->migrate_pfn >= end_pfn) { 2588 cc->migrate_pfn = start_pfn; 2589 cc->zone->compact_cached_migrate_pfn[0] = cc->migrate_pfn; 2590 cc->zone->compact_cached_migrate_pfn[1] = cc->migrate_pfn; 2591 } 2592 2593 if (cc->migrate_pfn <= cc->zone->compact_init_migrate_pfn) 2594 cc->whole_zone = true; 2595 } 2596 2597 last_migrated_pfn = 0; 2598 2599 /* 2600 * Migrate has separate cached PFNs for ASYNC and SYNC* migration on 2601 * the basis that some migrations will fail in ASYNC mode. However, 2602 * if the cached PFNs match and pageblocks are skipped due to having 2603 * no isolation candidates, then the sync state does not matter. 2604 * Until a pageblock with isolation candidates is found, keep the 2605 * cached PFNs in sync to avoid revisiting the same blocks. 2606 */ 2607 update_cached = !sync && 2608 cc->zone->compact_cached_migrate_pfn[0] == cc->zone->compact_cached_migrate_pfn[1]; 2609 2610 trace_mm_compaction_begin(cc, start_pfn, end_pfn, sync); 2611 2612 /* lru_add_drain_all could be expensive with involving other CPUs */ 2613 lru_add_drain(); 2614 2615 while ((ret = compact_finished(cc)) == COMPACT_CONTINUE) { 2616 int err; 2617 unsigned long iteration_start_pfn = cc->migrate_pfn; 2618 2619 /* 2620 * Avoid multiple rescans of the same pageblock which can 2621 * happen if a page cannot be isolated (dirty/writeback in 2622 * async mode) or if the migrated pages are being allocated 2623 * before the pageblock is cleared. The first rescan will 2624 * capture the entire pageblock for migration. If it fails, 2625 * it'll be marked skip and scanning will proceed as normal. 2626 */ 2627 cc->finish_pageblock = false; 2628 if (pageblock_start_pfn(last_migrated_pfn) == 2629 pageblock_start_pfn(iteration_start_pfn)) { 2630 cc->finish_pageblock = true; 2631 } 2632 2633 rescan: 2634 switch (isolate_migratepages(cc)) { 2635 case ISOLATE_ABORT: 2636 ret = COMPACT_CONTENDED; 2637 putback_movable_pages(&cc->migratepages); 2638 cc->nr_migratepages = 0; 2639 goto out; 2640 case ISOLATE_NONE: 2641 if (update_cached) { 2642 cc->zone->compact_cached_migrate_pfn[1] = 2643 cc->zone->compact_cached_migrate_pfn[0]; 2644 } 2645 2646 /* 2647 * We haven't isolated and migrated anything, but 2648 * there might still be unflushed migrations from 2649 * previous cc->order aligned block. 2650 */ 2651 goto check_drain; 2652 case ISOLATE_SUCCESS: 2653 update_cached = false; 2654 last_migrated_pfn = max(cc->zone->zone_start_pfn, 2655 pageblock_start_pfn(cc->migrate_pfn - 1)); 2656 } 2657 2658 /* 2659 * Record the number of pages to migrate since the 2660 * compaction_alloc/free() will update cc->nr_migratepages 2661 * properly. 2662 */ 2663 nr_migratepages = cc->nr_migratepages; 2664 err = migrate_pages(&cc->migratepages, compaction_alloc, 2665 compaction_free, (unsigned long)cc, cc->mode, 2666 MR_COMPACTION, &nr_succeeded); 2667 2668 trace_mm_compaction_migratepages(nr_migratepages, nr_succeeded); 2669 2670 /* All pages were either migrated or will be released */ 2671 cc->nr_migratepages = 0; 2672 if (err) { 2673 putback_movable_pages(&cc->migratepages); 2674 /* 2675 * migrate_pages() may return -ENOMEM when scanners meet 2676 * and we want compact_finished() to detect it 2677 */ 2678 if (err == -ENOMEM && !compact_scanners_met(cc)) { 2679 ret = COMPACT_CONTENDED; 2680 goto out; 2681 } 2682 /* 2683 * If an ASYNC or SYNC_LIGHT fails to migrate a page 2684 * within the pageblock_order-aligned block and 2685 * fast_find_migrateblock may be used then scan the 2686 * remainder of the pageblock. This will mark the 2687 * pageblock "skip" to avoid rescanning in the near 2688 * future. This will isolate more pages than necessary 2689 * for the request but avoid loops due to 2690 * fast_find_migrateblock revisiting blocks that were 2691 * recently partially scanned. 2692 */ 2693 if (!pageblock_aligned(cc->migrate_pfn) && 2694 !cc->ignore_skip_hint && !cc->finish_pageblock && 2695 (cc->mode < MIGRATE_SYNC)) { 2696 cc->finish_pageblock = true; 2697 2698 /* 2699 * Draining pcplists does not help THP if 2700 * any page failed to migrate. Even after 2701 * drain, the pageblock will not be free. 2702 */ 2703 if (cc->order == COMPACTION_HPAGE_ORDER) 2704 last_migrated_pfn = 0; 2705 2706 goto rescan; 2707 } 2708 } 2709 2710 /* Stop if a page has been captured */ 2711 if (capc && capc->page) { 2712 ret = COMPACT_SUCCESS; 2713 break; 2714 } 2715 2716 check_drain: 2717 /* 2718 * Has the migration scanner moved away from the previous 2719 * cc->order aligned block where we migrated from? If yes, 2720 * flush the pages that were freed, so that they can merge and 2721 * compact_finished() can detect immediately if allocation 2722 * would succeed. 2723 */ 2724 if (cc->order > 0 && last_migrated_pfn) { 2725 unsigned long current_block_start = 2726 block_start_pfn(cc->migrate_pfn, cc->order); 2727 2728 if (last_migrated_pfn < current_block_start) { 2729 lru_add_drain_cpu_zone(cc->zone); 2730 /* No more flushing until we migrate again */ 2731 last_migrated_pfn = 0; 2732 } 2733 } 2734 } 2735 2736 out: 2737 /* 2738 * Release free pages and update where the free scanner should restart, 2739 * so we don't leave any returned pages behind in the next attempt. 2740 */ 2741 if (cc->nr_freepages > 0) { 2742 unsigned long free_pfn = release_free_list(cc->freepages); 2743 2744 cc->nr_freepages = 0; 2745 VM_BUG_ON(free_pfn == 0); 2746 /* The cached pfn is always the first in a pageblock */ 2747 free_pfn = pageblock_start_pfn(free_pfn); 2748 /* 2749 * Only go back, not forward. The cached pfn might have been 2750 * already reset to zone end in compact_finished() 2751 */ 2752 if (free_pfn > cc->zone->compact_cached_free_pfn) 2753 cc->zone->compact_cached_free_pfn = free_pfn; 2754 } 2755 2756 count_compact_events(COMPACTMIGRATE_SCANNED, cc->total_migrate_scanned); 2757 count_compact_events(COMPACTFREE_SCANNED, cc->total_free_scanned); 2758 2759 trace_mm_compaction_end(cc, start_pfn, end_pfn, sync, ret); 2760 2761 VM_BUG_ON(!list_empty(&cc->migratepages)); 2762 2763 return ret; 2764 } 2765 2766 static enum compact_result compact_zone_order(struct zone *zone, int order, 2767 gfp_t gfp_mask, enum compact_priority prio, 2768 unsigned int alloc_flags, int highest_zoneidx, 2769 struct page **capture) 2770 { 2771 enum compact_result ret; 2772 struct compact_control cc = { 2773 .order = order, 2774 .search_order = order, 2775 .gfp_mask = gfp_mask, 2776 .zone = zone, 2777 .mode = (prio == COMPACT_PRIO_ASYNC) ? 2778 MIGRATE_ASYNC : MIGRATE_SYNC_LIGHT, 2779 .alloc_flags = alloc_flags, 2780 .highest_zoneidx = highest_zoneidx, 2781 .direct_compaction = true, 2782 .whole_zone = (prio == MIN_COMPACT_PRIORITY), 2783 .ignore_skip_hint = (prio == MIN_COMPACT_PRIORITY), 2784 .ignore_block_suitable = (prio == MIN_COMPACT_PRIORITY) 2785 }; 2786 struct capture_control capc = { 2787 .cc = &cc, 2788 .page = NULL, 2789 }; 2790 2791 /* 2792 * Make sure the structs are really initialized before we expose the 2793 * capture control, in case we are interrupted and the interrupt handler 2794 * frees a page. 2795 */ 2796 barrier(); 2797 WRITE_ONCE(current->capture_control, &capc); 2798 2799 ret = compact_zone(&cc, &capc); 2800 2801 /* 2802 * Make sure we hide capture control first before we read the captured 2803 * page pointer, otherwise an interrupt could free and capture a page 2804 * and we would leak it. 2805 */ 2806 WRITE_ONCE(current->capture_control, NULL); 2807 *capture = READ_ONCE(capc.page); 2808 /* 2809 * Technically, it is also possible that compaction is skipped but 2810 * the page is still captured out of luck(IRQ came and freed the page). 2811 * Returning COMPACT_SUCCESS in such cases helps in properly accounting 2812 * the COMPACT[STALL|FAIL] when compaction is skipped. 2813 */ 2814 if (*capture) 2815 ret = COMPACT_SUCCESS; 2816 2817 return ret; 2818 } 2819 2820 /** 2821 * try_to_compact_pages - Direct compact to satisfy a high-order allocation 2822 * @gfp_mask: The GFP mask of the current allocation 2823 * @order: The order of the current allocation 2824 * @alloc_flags: The allocation flags of the current allocation 2825 * @ac: The context of current allocation 2826 * @prio: Determines how hard direct compaction should try to succeed 2827 * @capture: Pointer to free page created by compaction will be stored here 2828 * 2829 * This is the main entry point for direct page compaction. 2830 */ 2831 enum compact_result try_to_compact_pages(gfp_t gfp_mask, unsigned int order, 2832 unsigned int alloc_flags, const struct alloc_context *ac, 2833 enum compact_priority prio, struct page **capture) 2834 { 2835 struct zoneref *z; 2836 struct zone *zone; 2837 enum compact_result rc = COMPACT_SKIPPED; 2838 2839 if (!gfp_compaction_allowed(gfp_mask)) 2840 return COMPACT_SKIPPED; 2841 2842 trace_mm_compaction_try_to_compact_pages(order, gfp_mask, prio); 2843 2844 /* Compact each zone in the list */ 2845 for_each_zone_zonelist_nodemask(zone, z, ac->zonelist, 2846 ac->highest_zoneidx, ac->nodemask) { 2847 enum compact_result status; 2848 2849 if (cpusets_enabled() && 2850 (alloc_flags & ALLOC_CPUSET) && 2851 !__cpuset_zone_allowed(zone, gfp_mask)) 2852 continue; 2853 2854 if (prio > MIN_COMPACT_PRIORITY 2855 && compaction_deferred(zone, order)) { 2856 rc = max_t(enum compact_result, COMPACT_DEFERRED, rc); 2857 continue; 2858 } 2859 2860 status = compact_zone_order(zone, order, gfp_mask, prio, 2861 alloc_flags, ac->highest_zoneidx, capture); 2862 rc = max(status, rc); 2863 2864 /* The allocation should succeed, stop compacting */ 2865 if (status == COMPACT_SUCCESS) { 2866 /* 2867 * We think the allocation will succeed in this zone, 2868 * but it is not certain, hence the false. The caller 2869 * will repeat this with true if allocation indeed 2870 * succeeds in this zone. 2871 */ 2872 compaction_defer_reset(zone, order, false); 2873 2874 break; 2875 } 2876 2877 if (prio != COMPACT_PRIO_ASYNC && (status == COMPACT_COMPLETE || 2878 status == COMPACT_PARTIAL_SKIPPED)) 2879 /* 2880 * We think that allocation won't succeed in this zone 2881 * so we defer compaction there. If it ends up 2882 * succeeding after all, it will be reset. 2883 */ 2884 defer_compaction(zone, order); 2885 2886 /* 2887 * We might have stopped compacting due to need_resched() in 2888 * async compaction, or due to a fatal signal detected. In that 2889 * case do not try further zones 2890 */ 2891 if ((prio == COMPACT_PRIO_ASYNC && need_resched()) 2892 || fatal_signal_pending(current)) 2893 break; 2894 } 2895 2896 return rc; 2897 } 2898 2899 /* 2900 * compact_node() - compact all zones within a node 2901 * @pgdat: The node page data 2902 * @proactive: Whether the compaction is proactive 2903 * 2904 * For proactive compaction, compact till each zone's fragmentation score 2905 * reaches within proactive compaction thresholds (as determined by the 2906 * proactiveness tunable), it is possible that the function returns before 2907 * reaching score targets due to various back-off conditions, such as, 2908 * contention on per-node or per-zone locks. 2909 */ 2910 static int compact_node(pg_data_t *pgdat, bool proactive) 2911 { 2912 int zoneid; 2913 struct zone *zone; 2914 struct compact_control cc = { 2915 .order = -1, 2916 .mode = proactive ? MIGRATE_SYNC_LIGHT : MIGRATE_SYNC, 2917 .ignore_skip_hint = true, 2918 .whole_zone = true, 2919 .gfp_mask = GFP_KERNEL, 2920 .proactive_compaction = proactive, 2921 }; 2922 2923 for (zoneid = 0; zoneid < MAX_NR_ZONES; zoneid++) { 2924 zone = &pgdat->node_zones[zoneid]; 2925 if (!populated_zone(zone)) 2926 continue; 2927 2928 if (fatal_signal_pending(current)) 2929 return -EINTR; 2930 2931 cc.zone = zone; 2932 2933 compact_zone(&cc, NULL); 2934 2935 if (proactive) { 2936 count_compact_events(KCOMPACTD_MIGRATE_SCANNED, 2937 cc.total_migrate_scanned); 2938 count_compact_events(KCOMPACTD_FREE_SCANNED, 2939 cc.total_free_scanned); 2940 } 2941 } 2942 2943 return 0; 2944 } 2945 2946 /* Compact all zones of all nodes in the system */ 2947 static int compact_nodes(void) 2948 { 2949 int ret, nid; 2950 2951 /* Flush pending updates to the LRU lists */ 2952 lru_add_drain_all(); 2953 2954 for_each_online_node(nid) { 2955 ret = compact_node(NODE_DATA(nid), false); 2956 if (ret) 2957 return ret; 2958 } 2959 2960 return 0; 2961 } 2962 2963 static int compaction_proactiveness_sysctl_handler(const struct ctl_table *table, int write, 2964 void *buffer, size_t *length, loff_t *ppos) 2965 { 2966 int rc, nid; 2967 2968 rc = proc_dointvec_minmax(table, write, buffer, length, ppos); 2969 if (rc) 2970 return rc; 2971 2972 if (write && sysctl_compaction_proactiveness) { 2973 for_each_online_node(nid) { 2974 pg_data_t *pgdat = NODE_DATA(nid); 2975 2976 if (pgdat->proactive_compact_trigger) 2977 continue; 2978 2979 pgdat->proactive_compact_trigger = true; 2980 trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, -1, 2981 pgdat->nr_zones - 1); 2982 wake_up_interruptible(&pgdat->kcompactd_wait); 2983 } 2984 } 2985 2986 return 0; 2987 } 2988 2989 /* 2990 * This is the entry point for compacting all nodes via 2991 * /proc/sys/vm/compact_memory 2992 */ 2993 static int sysctl_compaction_handler(const struct ctl_table *table, int write, 2994 void *buffer, size_t *length, loff_t *ppos) 2995 { 2996 int ret; 2997 2998 ret = proc_dointvec(table, write, buffer, length, ppos); 2999 if (ret) 3000 return ret; 3001 3002 if (sysctl_compact_memory != 1) 3003 return -EINVAL; 3004 3005 if (write) 3006 ret = compact_nodes(); 3007 3008 return ret; 3009 } 3010 3011 #if defined(CONFIG_SYSFS) && defined(CONFIG_NUMA) 3012 static ssize_t compact_store(struct device *dev, 3013 struct device_attribute *attr, 3014 const char *buf, size_t count) 3015 { 3016 int nid = dev->id; 3017 3018 if (nid >= 0 && nid < nr_node_ids && node_online(nid)) { 3019 /* Flush pending updates to the LRU lists */ 3020 lru_add_drain_all(); 3021 3022 compact_node(NODE_DATA(nid), false); 3023 } 3024 3025 return count; 3026 } 3027 static DEVICE_ATTR_WO(compact); 3028 3029 int compaction_register_node(struct node *node) 3030 { 3031 return device_create_file(&node->dev, &dev_attr_compact); 3032 } 3033 3034 void compaction_unregister_node(struct node *node) 3035 { 3036 device_remove_file(&node->dev, &dev_attr_compact); 3037 } 3038 #endif /* CONFIG_SYSFS && CONFIG_NUMA */ 3039 3040 static inline bool kcompactd_work_requested(pg_data_t *pgdat) 3041 { 3042 return pgdat->kcompactd_max_order > 0 || kthread_should_stop() || 3043 pgdat->proactive_compact_trigger; 3044 } 3045 3046 static bool kcompactd_node_suitable(pg_data_t *pgdat) 3047 { 3048 int zoneid; 3049 struct zone *zone; 3050 enum zone_type highest_zoneidx = pgdat->kcompactd_highest_zoneidx; 3051 enum compact_result ret; 3052 unsigned int alloc_flags = defrag_mode ? 3053 ALLOC_WMARK_HIGH : ALLOC_WMARK_MIN; 3054 3055 for (zoneid = 0; zoneid <= highest_zoneidx; zoneid++) { 3056 zone = &pgdat->node_zones[zoneid]; 3057 3058 if (!populated_zone(zone)) 3059 continue; 3060 3061 ret = compaction_suit_allocation_order(zone, 3062 pgdat->kcompactd_max_order, 3063 highest_zoneidx, alloc_flags, 3064 false, true); 3065 if (ret == COMPACT_CONTINUE) 3066 return true; 3067 } 3068 3069 return false; 3070 } 3071 3072 static void kcompactd_do_work(pg_data_t *pgdat) 3073 { 3074 /* 3075 * With no special task, compact all zones so that a page of requested 3076 * order is allocatable. 3077 */ 3078 int zoneid; 3079 struct zone *zone; 3080 struct compact_control cc = { 3081 .order = pgdat->kcompactd_max_order, 3082 .search_order = pgdat->kcompactd_max_order, 3083 .highest_zoneidx = pgdat->kcompactd_highest_zoneidx, 3084 .mode = MIGRATE_SYNC_LIGHT, 3085 .ignore_skip_hint = false, 3086 .gfp_mask = GFP_KERNEL, 3087 .alloc_flags = defrag_mode ? ALLOC_WMARK_HIGH : ALLOC_WMARK_MIN, 3088 }; 3089 enum compact_result ret; 3090 3091 trace_mm_compaction_kcompactd_wake(pgdat->node_id, cc.order, 3092 cc.highest_zoneidx); 3093 count_compact_event(KCOMPACTD_WAKE); 3094 3095 for (zoneid = 0; zoneid <= cc.highest_zoneidx; zoneid++) { 3096 int status; 3097 3098 zone = &pgdat->node_zones[zoneid]; 3099 if (!populated_zone(zone)) 3100 continue; 3101 3102 if (compaction_deferred(zone, cc.order)) 3103 continue; 3104 3105 ret = compaction_suit_allocation_order(zone, 3106 cc.order, zoneid, cc.alloc_flags, 3107 false, true); 3108 if (ret != COMPACT_CONTINUE) 3109 continue; 3110 3111 if (kthread_should_stop()) 3112 return; 3113 3114 cc.zone = zone; 3115 status = compact_zone(&cc, NULL); 3116 3117 if (status == COMPACT_SUCCESS) { 3118 compaction_defer_reset(zone, cc.order, false); 3119 } else if (status == COMPACT_PARTIAL_SKIPPED || status == COMPACT_COMPLETE) { 3120 /* 3121 * Buddy pages may become stranded on pcps that could 3122 * otherwise coalesce on the zone's free area for 3123 * order >= cc.order. This is ratelimited by the 3124 * upcoming deferral. 3125 */ 3126 drain_all_pages(zone); 3127 3128 /* 3129 * We use sync migration mode here, so we defer like 3130 * sync direct compaction does. 3131 */ 3132 defer_compaction(zone, cc.order); 3133 } 3134 3135 count_compact_events(KCOMPACTD_MIGRATE_SCANNED, 3136 cc.total_migrate_scanned); 3137 count_compact_events(KCOMPACTD_FREE_SCANNED, 3138 cc.total_free_scanned); 3139 } 3140 3141 /* 3142 * Regardless of success, we are done until woken up next. But remember 3143 * the requested order/highest_zoneidx in case it was higher/tighter 3144 * than our current ones 3145 */ 3146 if (pgdat->kcompactd_max_order <= cc.order) 3147 pgdat->kcompactd_max_order = 0; 3148 if (pgdat->kcompactd_highest_zoneidx >= cc.highest_zoneidx) 3149 pgdat->kcompactd_highest_zoneidx = pgdat->nr_zones - 1; 3150 } 3151 3152 void wakeup_kcompactd(pg_data_t *pgdat, int order, int highest_zoneidx) 3153 { 3154 if (!order) 3155 return; 3156 3157 if (pgdat->kcompactd_max_order < order) 3158 pgdat->kcompactd_max_order = order; 3159 3160 if (pgdat->kcompactd_highest_zoneidx > highest_zoneidx) 3161 pgdat->kcompactd_highest_zoneidx = highest_zoneidx; 3162 3163 /* 3164 * Pairs with implicit barrier in wait_event_freezable() 3165 * such that wakeups are not missed. 3166 */ 3167 if (!wq_has_sleeper(&pgdat->kcompactd_wait)) 3168 return; 3169 3170 if (!kcompactd_node_suitable(pgdat)) 3171 return; 3172 3173 trace_mm_compaction_wakeup_kcompactd(pgdat->node_id, order, 3174 highest_zoneidx); 3175 wake_up_interruptible(&pgdat->kcompactd_wait); 3176 } 3177 3178 /* 3179 * The background compaction daemon, started as a kernel thread 3180 * from the init process. 3181 */ 3182 static int kcompactd(void *p) 3183 { 3184 pg_data_t *pgdat = (pg_data_t *)p; 3185 long default_timeout = msecs_to_jiffies(HPAGE_FRAG_CHECK_INTERVAL_MSEC); 3186 long timeout = default_timeout; 3187 3188 current->flags |= PF_KCOMPACTD; 3189 set_freezable(); 3190 3191 pgdat->kcompactd_max_order = 0; 3192 pgdat->kcompactd_highest_zoneidx = pgdat->nr_zones - 1; 3193 3194 while (!kthread_should_stop()) { 3195 unsigned long pflags; 3196 3197 /* 3198 * Avoid the unnecessary wakeup for proactive compaction 3199 * when it is disabled. 3200 */ 3201 if (!sysctl_compaction_proactiveness) 3202 timeout = MAX_SCHEDULE_TIMEOUT; 3203 trace_mm_compaction_kcompactd_sleep(pgdat->node_id); 3204 if (wait_event_freezable_timeout(pgdat->kcompactd_wait, 3205 kcompactd_work_requested(pgdat), timeout) && 3206 !pgdat->proactive_compact_trigger) { 3207 3208 psi_memstall_enter(&pflags); 3209 kcompactd_do_work(pgdat); 3210 psi_memstall_leave(&pflags); 3211 /* 3212 * Reset the timeout value. The defer timeout from 3213 * proactive compaction is lost here but that is fine 3214 * as the condition of the zone changing substantionally 3215 * then carrying on with the previous defer interval is 3216 * not useful. 3217 */ 3218 timeout = default_timeout; 3219 continue; 3220 } 3221 3222 /* 3223 * Start the proactive work with default timeout. Based 3224 * on the fragmentation score, this timeout is updated. 3225 */ 3226 timeout = default_timeout; 3227 if (should_proactive_compact_node(pgdat)) { 3228 unsigned int prev_score, score; 3229 3230 prev_score = fragmentation_score_node(pgdat); 3231 compact_node(pgdat, true); 3232 score = fragmentation_score_node(pgdat); 3233 /* 3234 * Defer proactive compaction if the fragmentation 3235 * score did not go down i.e. no progress made. 3236 */ 3237 if (unlikely(score >= prev_score)) 3238 timeout = 3239 default_timeout << COMPACT_MAX_DEFER_SHIFT; 3240 } 3241 if (unlikely(pgdat->proactive_compact_trigger)) 3242 pgdat->proactive_compact_trigger = false; 3243 } 3244 3245 current->flags &= ~PF_KCOMPACTD; 3246 3247 return 0; 3248 } 3249 3250 /* 3251 * This kcompactd start function will be called by init and node-hot-add. 3252 * On node-hot-add, kcompactd will moved to proper cpus if cpus are hot-added. 3253 */ 3254 void __meminit kcompactd_run(int nid) 3255 { 3256 pg_data_t *pgdat = NODE_DATA(nid); 3257 3258 if (pgdat->kcompactd) 3259 return; 3260 3261 pgdat->kcompactd = kthread_create_on_node(kcompactd, pgdat, nid, "kcompactd%d", nid); 3262 if (IS_ERR(pgdat->kcompactd)) { 3263 pr_err("Failed to start kcompactd on node %d\n", nid); 3264 pgdat->kcompactd = NULL; 3265 } else { 3266 wake_up_process(pgdat->kcompactd); 3267 } 3268 } 3269 3270 /* 3271 * Called by memory hotplug when all memory in a node is offlined. Caller must 3272 * be holding mem_hotplug_begin/done(). 3273 */ 3274 void __meminit kcompactd_stop(int nid) 3275 { 3276 struct task_struct *kcompactd = NODE_DATA(nid)->kcompactd; 3277 3278 if (kcompactd) { 3279 kthread_stop(kcompactd); 3280 NODE_DATA(nid)->kcompactd = NULL; 3281 } 3282 } 3283 3284 static int proc_dointvec_minmax_warn_RT_change(const struct ctl_table *table, 3285 int write, void *buffer, size_t *lenp, loff_t *ppos) 3286 { 3287 int ret, old; 3288 3289 if (!IS_ENABLED(CONFIG_PREEMPT_RT) || !write) 3290 return proc_dointvec_minmax(table, write, buffer, lenp, ppos); 3291 3292 old = *(int *)table->data; 3293 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); 3294 if (ret) 3295 return ret; 3296 if (old != *(int *)table->data) 3297 pr_warn_once("sysctl attribute %s changed by %s[%d]\n", 3298 table->procname, current->comm, 3299 task_pid_nr(current)); 3300 return ret; 3301 } 3302 3303 static const struct ctl_table vm_compaction[] = { 3304 { 3305 .procname = "compact_memory", 3306 .data = &sysctl_compact_memory, 3307 .maxlen = sizeof(int), 3308 .mode = 0200, 3309 .proc_handler = sysctl_compaction_handler, 3310 }, 3311 { 3312 .procname = "compaction_proactiveness", 3313 .data = &sysctl_compaction_proactiveness, 3314 .maxlen = sizeof(sysctl_compaction_proactiveness), 3315 .mode = 0644, 3316 .proc_handler = compaction_proactiveness_sysctl_handler, 3317 .extra1 = SYSCTL_ZERO, 3318 .extra2 = SYSCTL_ONE_HUNDRED, 3319 }, 3320 { 3321 .procname = "extfrag_threshold", 3322 .data = &sysctl_extfrag_threshold, 3323 .maxlen = sizeof(int), 3324 .mode = 0644, 3325 .proc_handler = proc_dointvec_minmax, 3326 .extra1 = SYSCTL_ZERO, 3327 .extra2 = SYSCTL_ONE_THOUSAND, 3328 }, 3329 { 3330 .procname = "compact_unevictable_allowed", 3331 .data = &sysctl_compact_unevictable_allowed, 3332 .maxlen = sizeof(int), 3333 .mode = 0644, 3334 .proc_handler = proc_dointvec_minmax_warn_RT_change, 3335 .extra1 = SYSCTL_ZERO, 3336 .extra2 = SYSCTL_ONE, 3337 }, 3338 }; 3339 3340 static int __init kcompactd_init(void) 3341 { 3342 int nid; 3343 3344 for_each_node_state(nid, N_MEMORY) 3345 kcompactd_run(nid); 3346 register_sysctl_init("vm", vm_compaction); 3347 return 0; 3348 } 3349 subsys_initcall(kcompactd_init) 3350 3351 #endif /* CONFIG_COMPACTION */ 3352