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