1 // SPDX-License-Identifier: GPL-2.0 2 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 3 4 #include <linux/mm.h> 5 #include <linux/sched.h> 6 #include <linux/sched/mm.h> 7 #include <linux/mmu_notifier.h> 8 #include <linux/rmap.h> 9 #include <linux/swap.h> 10 #include <linux/mm_inline.h> 11 #include <linux/kthread.h> 12 #include <linux/khugepaged.h> 13 #include <linux/freezer.h> 14 #include <linux/mman.h> 15 #include <linux/hashtable.h> 16 #include <linux/userfaultfd_k.h> 17 #include <linux/page_idle.h> 18 #include <linux/page_table_check.h> 19 #include <linux/rcupdate_wait.h> 20 #include <linux/leafops.h> 21 #include <linux/shmem_fs.h> 22 #include <linux/dax.h> 23 #include <linux/ksm.h> 24 #include <linux/pgalloc.h> 25 #include <linux/backing-dev.h> 26 27 #include <asm/tlb.h> 28 #include "internal.h" 29 #include "mm_slot.h" 30 31 enum scan_result { 32 SCAN_FAIL, 33 SCAN_SUCCEED, 34 SCAN_NO_PTE_TABLE, 35 SCAN_PMD_MAPPED, 36 SCAN_EXCEED_NONE_PTE, 37 SCAN_EXCEED_SWAP_PTE, 38 SCAN_EXCEED_SHARED_PTE, 39 SCAN_PTE_NON_PRESENT, 40 SCAN_PTE_UFFD_WP, 41 SCAN_PTE_MAPPED_HUGEPAGE, 42 SCAN_LACK_REFERENCED_PAGE, 43 SCAN_PAGE_NULL, 44 SCAN_SCAN_ABORT, 45 SCAN_PAGE_COUNT, 46 SCAN_PAGE_LRU, 47 SCAN_PAGE_LOCK, 48 SCAN_PAGE_ANON, 49 SCAN_PAGE_LAZYFREE, 50 SCAN_PAGE_COMPOUND, 51 SCAN_ANY_PROCESS, 52 SCAN_VMA_NULL, 53 SCAN_VMA_CHECK, 54 SCAN_ADDRESS_RANGE, 55 SCAN_DEL_PAGE_LRU, 56 SCAN_ALLOC_HUGE_PAGE_FAIL, 57 SCAN_CGROUP_CHARGE_FAIL, 58 SCAN_TRUNCATED, 59 SCAN_PAGE_HAS_PRIVATE, 60 SCAN_STORE_FAILED, 61 SCAN_COPY_MC, 62 SCAN_PAGE_FILLED, 63 SCAN_PAGE_DIRTY_OR_WRITEBACK, 64 }; 65 66 #define CREATE_TRACE_POINTS 67 #include <trace/events/huge_memory.h> 68 69 static struct task_struct *khugepaged_thread __read_mostly; 70 static DEFINE_MUTEX(khugepaged_mutex); 71 72 /* 73 * default scan 8*HPAGE_PMD_NR ptes, pte_mapped_hugepage, pmd_mapped, 74 * no_pte_table or vmas every 10 second. 75 */ 76 static unsigned int khugepaged_pages_to_scan __read_mostly; 77 static unsigned int khugepaged_pages_collapsed; 78 static unsigned int khugepaged_full_scans; 79 static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000; 80 /* during fragmentation poll the hugepage allocator once every minute */ 81 static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000; 82 static unsigned long khugepaged_sleep_expire; 83 static DEFINE_SPINLOCK(khugepaged_mm_lock); 84 static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait); 85 /* 86 * default collapse hugepages if there is at least one pte mapped like 87 * it would have happened if the vma was large enough during page 88 * fault. 89 * 90 * Note that these are only respected if collapse was initiated by khugepaged. 91 */ 92 #define KHUGEPAGED_MAX_PTES_LIMIT (HPAGE_PMD_NR - 1) 93 unsigned int khugepaged_max_ptes_none __read_mostly; 94 static unsigned int khugepaged_max_ptes_swap __read_mostly; 95 static unsigned int khugepaged_max_ptes_shared __read_mostly; 96 97 #define MM_SLOTS_HASH_BITS 10 98 static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS); 99 100 static struct kmem_cache *mm_slot_cache __ro_after_init; 101 102 struct collapse_control { 103 bool is_khugepaged; 104 105 /* Num pages scanned per node */ 106 u32 node_load[MAX_NUMNODES]; 107 108 /* Num pages scanned (see khugepaged_pages_to_scan) */ 109 unsigned int progress; 110 111 /* nodemask for allocation fallback */ 112 nodemask_t alloc_nmask; 113 }; 114 115 /** 116 * struct khugepaged_scan - cursor for scanning 117 * @mm_head: the head of the mm list to scan 118 * @mm_slot: the current mm_slot we are scanning 119 * @address: the next address inside that to be scanned 120 * 121 * There is only the one khugepaged_scan instance of this cursor structure. 122 */ 123 struct khugepaged_scan { 124 struct list_head mm_head; 125 struct mm_slot *mm_slot; 126 unsigned long address; 127 }; 128 129 static struct khugepaged_scan khugepaged_scan = { 130 .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head), 131 }; 132 133 #ifdef CONFIG_SYSFS 134 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj, 135 struct kobj_attribute *attr, 136 char *buf) 137 { 138 return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs); 139 } 140 141 static ssize_t __sleep_millisecs_store(const char *buf, size_t count, 142 unsigned int *millisecs) 143 { 144 unsigned int msecs; 145 int err; 146 147 err = kstrtouint(buf, 10, &msecs); 148 if (err) 149 return -EINVAL; 150 151 *millisecs = msecs; 152 khugepaged_sleep_expire = 0; 153 wake_up_interruptible(&khugepaged_wait); 154 155 return count; 156 } 157 158 static ssize_t scan_sleep_millisecs_store(struct kobject *kobj, 159 struct kobj_attribute *attr, 160 const char *buf, size_t count) 161 { 162 return __sleep_millisecs_store(buf, count, &khugepaged_scan_sleep_millisecs); 163 } 164 static struct kobj_attribute scan_sleep_millisecs_attr = 165 __ATTR_RW(scan_sleep_millisecs); 166 167 static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj, 168 struct kobj_attribute *attr, 169 char *buf) 170 { 171 return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs); 172 } 173 174 static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj, 175 struct kobj_attribute *attr, 176 const char *buf, size_t count) 177 { 178 return __sleep_millisecs_store(buf, count, &khugepaged_alloc_sleep_millisecs); 179 } 180 static struct kobj_attribute alloc_sleep_millisecs_attr = 181 __ATTR_RW(alloc_sleep_millisecs); 182 183 static ssize_t pages_to_scan_show(struct kobject *kobj, 184 struct kobj_attribute *attr, 185 char *buf) 186 { 187 return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan); 188 } 189 static ssize_t pages_to_scan_store(struct kobject *kobj, 190 struct kobj_attribute *attr, 191 const char *buf, size_t count) 192 { 193 unsigned int pages; 194 int err; 195 196 err = kstrtouint(buf, 10, &pages); 197 if (err || !pages) 198 return -EINVAL; 199 200 khugepaged_pages_to_scan = pages; 201 202 return count; 203 } 204 static struct kobj_attribute pages_to_scan_attr = 205 __ATTR_RW(pages_to_scan); 206 207 static ssize_t pages_collapsed_show(struct kobject *kobj, 208 struct kobj_attribute *attr, 209 char *buf) 210 { 211 return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed); 212 } 213 static struct kobj_attribute pages_collapsed_attr = 214 __ATTR_RO(pages_collapsed); 215 216 static ssize_t full_scans_show(struct kobject *kobj, 217 struct kobj_attribute *attr, 218 char *buf) 219 { 220 return sysfs_emit(buf, "%u\n", khugepaged_full_scans); 221 } 222 static struct kobj_attribute full_scans_attr = 223 __ATTR_RO(full_scans); 224 225 static ssize_t defrag_show(struct kobject *kobj, 226 struct kobj_attribute *attr, char *buf) 227 { 228 return single_hugepage_flag_show(kobj, attr, buf, 229 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG); 230 } 231 static ssize_t defrag_store(struct kobject *kobj, 232 struct kobj_attribute *attr, 233 const char *buf, size_t count) 234 { 235 return single_hugepage_flag_store(kobj, attr, buf, count, 236 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG); 237 } 238 static struct kobj_attribute khugepaged_defrag_attr = 239 __ATTR_RW(defrag); 240 241 /* 242 * max_ptes_none controls if khugepaged should collapse hugepages over 243 * any unmapped ptes in turn potentially increasing the memory 244 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not 245 * reduce the available free memory in the system as it 246 * runs. Increasing max_ptes_none will instead potentially reduce the 247 * free memory in the system during the khugepaged scan. 248 */ 249 static ssize_t max_ptes_none_show(struct kobject *kobj, 250 struct kobj_attribute *attr, 251 char *buf) 252 { 253 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none); 254 } 255 static ssize_t max_ptes_none_store(struct kobject *kobj, 256 struct kobj_attribute *attr, 257 const char *buf, size_t count) 258 { 259 int err; 260 unsigned long max_ptes_none; 261 262 err = kstrtoul(buf, 10, &max_ptes_none); 263 if (err || max_ptes_none > KHUGEPAGED_MAX_PTES_LIMIT) 264 return -EINVAL; 265 266 khugepaged_max_ptes_none = max_ptes_none; 267 268 return count; 269 } 270 static struct kobj_attribute khugepaged_max_ptes_none_attr = 271 __ATTR_RW(max_ptes_none); 272 273 static ssize_t max_ptes_swap_show(struct kobject *kobj, 274 struct kobj_attribute *attr, 275 char *buf) 276 { 277 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap); 278 } 279 280 static ssize_t max_ptes_swap_store(struct kobject *kobj, 281 struct kobj_attribute *attr, 282 const char *buf, size_t count) 283 { 284 int err; 285 unsigned long max_ptes_swap; 286 287 err = kstrtoul(buf, 10, &max_ptes_swap); 288 if (err || max_ptes_swap > KHUGEPAGED_MAX_PTES_LIMIT) 289 return -EINVAL; 290 291 khugepaged_max_ptes_swap = max_ptes_swap; 292 293 return count; 294 } 295 296 static struct kobj_attribute khugepaged_max_ptes_swap_attr = 297 __ATTR_RW(max_ptes_swap); 298 299 static ssize_t max_ptes_shared_show(struct kobject *kobj, 300 struct kobj_attribute *attr, 301 char *buf) 302 { 303 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_shared); 304 } 305 306 static ssize_t max_ptes_shared_store(struct kobject *kobj, 307 struct kobj_attribute *attr, 308 const char *buf, size_t count) 309 { 310 int err; 311 unsigned long max_ptes_shared; 312 313 err = kstrtoul(buf, 10, &max_ptes_shared); 314 if (err || max_ptes_shared > KHUGEPAGED_MAX_PTES_LIMIT) 315 return -EINVAL; 316 317 khugepaged_max_ptes_shared = max_ptes_shared; 318 319 return count; 320 } 321 322 static struct kobj_attribute khugepaged_max_ptes_shared_attr = 323 __ATTR_RW(max_ptes_shared); 324 325 static struct attribute *khugepaged_attr[] = { 326 &khugepaged_defrag_attr.attr, 327 &khugepaged_max_ptes_none_attr.attr, 328 &khugepaged_max_ptes_swap_attr.attr, 329 &khugepaged_max_ptes_shared_attr.attr, 330 &pages_to_scan_attr.attr, 331 &pages_collapsed_attr.attr, 332 &full_scans_attr.attr, 333 &scan_sleep_millisecs_attr.attr, 334 &alloc_sleep_millisecs_attr.attr, 335 NULL, 336 }; 337 338 struct attribute_group khugepaged_attr_group = { 339 .attrs = khugepaged_attr, 340 .name = "khugepaged", 341 }; 342 #endif /* CONFIG_SYSFS */ 343 344 static bool pte_none_or_zero(pte_t pte) 345 { 346 if (pte_none(pte)) 347 return true; 348 return pte_present(pte) && is_zero_pfn(pte_pfn(pte)); 349 } 350 351 int hugepage_madvise(struct vm_area_struct *vma, 352 vm_flags_t *vm_flags, int advice) 353 { 354 switch (advice) { 355 case MADV_HUGEPAGE: 356 *vm_flags &= ~VM_NOHUGEPAGE; 357 *vm_flags |= VM_HUGEPAGE; 358 /* 359 * If the vma become good for khugepaged to scan, 360 * register it here without waiting a page fault that 361 * may not happen any time soon. 362 */ 363 khugepaged_enter_vma(vma, *vm_flags); 364 break; 365 case MADV_NOHUGEPAGE: 366 *vm_flags &= ~VM_HUGEPAGE; 367 *vm_flags |= VM_NOHUGEPAGE; 368 /* 369 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning 370 * this vma even if we leave the mm registered in khugepaged if 371 * it got registered before VM_NOHUGEPAGE was set. 372 */ 373 break; 374 } 375 376 return 0; 377 } 378 379 int __init khugepaged_init(void) 380 { 381 mm_slot_cache = KMEM_CACHE(mm_slot, 0); 382 if (!mm_slot_cache) 383 return -ENOMEM; 384 385 khugepaged_pages_to_scan = HPAGE_PMD_NR * 8; 386 khugepaged_max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT; 387 khugepaged_max_ptes_swap = HPAGE_PMD_NR / 8; 388 khugepaged_max_ptes_shared = HPAGE_PMD_NR / 2; 389 390 return 0; 391 } 392 393 void __init khugepaged_destroy(void) 394 { 395 kmem_cache_destroy(mm_slot_cache); 396 } 397 398 static inline int collapse_test_exit(struct mm_struct *mm) 399 { 400 return atomic_read(&mm->mm_users) == 0; 401 } 402 403 static inline int collapse_test_exit_or_disable(struct mm_struct *mm) 404 { 405 return collapse_test_exit(mm) || 406 mm_flags_test(MMF_DISABLE_THP_COMPLETELY, mm); 407 } 408 409 static bool hugepage_pmd_enabled(void) 410 { 411 /* 412 * We cover the anon, shmem and the file-backed case here; file-backed 413 * hugepages, when configured in, are determined by the global control. 414 * Anon pmd-sized hugepages are determined by the pmd-size control. 415 * Shmem pmd-sized hugepages are also determined by its pmd-size control, 416 * except when the global shmem_huge is set to SHMEM_HUGE_DENY. 417 */ 418 if (IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && 419 hugepage_global_enabled()) 420 return true; 421 if (test_bit(PMD_ORDER, &huge_anon_orders_always)) 422 return true; 423 if (test_bit(PMD_ORDER, &huge_anon_orders_madvise)) 424 return true; 425 if (test_bit(PMD_ORDER, &huge_anon_orders_inherit) && 426 hugepage_global_enabled()) 427 return true; 428 if (IS_ENABLED(CONFIG_SHMEM) && shmem_hpage_pmd_enabled()) 429 return true; 430 return false; 431 } 432 433 void __khugepaged_enter(struct mm_struct *mm) 434 { 435 struct mm_slot *slot; 436 int wakeup; 437 438 /* __khugepaged_exit() must not run from under us */ 439 VM_BUG_ON_MM(collapse_test_exit(mm), mm); 440 441 slot = mm_slot_alloc(mm_slot_cache); 442 if (!slot) 443 return; 444 445 if (unlikely(mm_flags_test_and_set(MMF_VM_HUGEPAGE, mm))) { 446 mm_slot_free(mm_slot_cache, slot); 447 return; 448 } 449 450 spin_lock(&khugepaged_mm_lock); 451 mm_slot_insert(mm_slots_hash, mm, slot); 452 /* 453 * Insert just behind the scanning cursor, to let the area settle 454 * down a little. 455 */ 456 wakeup = list_empty(&khugepaged_scan.mm_head); 457 list_add_tail(&slot->mm_node, &khugepaged_scan.mm_head); 458 spin_unlock(&khugepaged_mm_lock); 459 460 mmgrab(mm); 461 if (wakeup) 462 wake_up_interruptible(&khugepaged_wait); 463 } 464 465 void khugepaged_enter_vma(struct vm_area_struct *vma, 466 vm_flags_t vm_flags) 467 { 468 if (!mm_flags_test(MMF_VM_HUGEPAGE, vma->vm_mm) && 469 hugepage_pmd_enabled()) { 470 if (thp_vma_allowable_order(vma, vm_flags, TVA_KHUGEPAGED, PMD_ORDER)) 471 __khugepaged_enter(vma->vm_mm); 472 } 473 } 474 475 void __khugepaged_exit(struct mm_struct *mm) 476 { 477 struct mm_slot *slot; 478 int free = 0; 479 480 spin_lock(&khugepaged_mm_lock); 481 slot = mm_slot_lookup(mm_slots_hash, mm); 482 if (slot && khugepaged_scan.mm_slot != slot) { 483 hash_del(&slot->hash); 484 list_del(&slot->mm_node); 485 free = 1; 486 } 487 spin_unlock(&khugepaged_mm_lock); 488 489 if (free) { 490 mm_flags_clear(MMF_VM_HUGEPAGE, mm); 491 mm_slot_free(mm_slot_cache, slot); 492 mmdrop(mm); 493 } else if (slot) { 494 /* 495 * This is required to serialize against 496 * collapse_test_exit() (which is guaranteed to run 497 * under mmap sem read mode). Stop here (after we return all 498 * pagetables will be destroyed) until khugepaged has finished 499 * working on the pagetables under the mmap_lock. 500 */ 501 mmap_write_lock(mm); 502 mmap_write_unlock(mm); 503 } 504 } 505 506 static void release_pte_folio(struct folio *folio) 507 { 508 node_stat_mod_folio(folio, 509 NR_ISOLATED_ANON + folio_is_file_lru(folio), 510 -folio_nr_pages(folio)); 511 folio_unlock(folio); 512 folio_putback_lru(folio); 513 } 514 515 static void release_pte_pages(pte_t *pte, pte_t *_pte, 516 struct list_head *compound_pagelist) 517 { 518 struct folio *folio, *tmp; 519 520 while (--_pte >= pte) { 521 pte_t pteval = ptep_get(_pte); 522 unsigned long pfn; 523 524 if (pte_none(pteval)) 525 continue; 526 VM_WARN_ON_ONCE(!pte_present(pteval)); 527 pfn = pte_pfn(pteval); 528 if (is_zero_pfn(pfn)) 529 continue; 530 folio = pfn_folio(pfn); 531 if (folio_test_large(folio)) 532 continue; 533 release_pte_folio(folio); 534 } 535 536 list_for_each_entry_safe(folio, tmp, compound_pagelist, lru) { 537 list_del(&folio->lru); 538 release_pte_folio(folio); 539 } 540 } 541 542 static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma, 543 unsigned long start_addr, pte_t *pte, struct collapse_control *cc, 544 struct list_head *compound_pagelist) 545 { 546 struct page *page = NULL; 547 struct folio *folio = NULL; 548 unsigned long addr = start_addr; 549 pte_t *_pte; 550 int none_or_zero = 0, shared = 0, referenced = 0; 551 enum scan_result result = SCAN_FAIL; 552 553 for (_pte = pte; _pte < pte + HPAGE_PMD_NR; 554 _pte++, addr += PAGE_SIZE) { 555 pte_t pteval = ptep_get(_pte); 556 if (pte_none_or_zero(pteval)) { 557 ++none_or_zero; 558 if (!userfaultfd_armed(vma) && 559 (!cc->is_khugepaged || 560 none_or_zero <= khugepaged_max_ptes_none)) { 561 continue; 562 } else { 563 result = SCAN_EXCEED_NONE_PTE; 564 count_vm_event(THP_SCAN_EXCEED_NONE_PTE); 565 goto out; 566 } 567 } 568 if (!pte_present(pteval)) { 569 result = SCAN_PTE_NON_PRESENT; 570 goto out; 571 } 572 if (pte_uffd_wp(pteval)) { 573 result = SCAN_PTE_UFFD_WP; 574 goto out; 575 } 576 page = vm_normal_page(vma, addr, pteval); 577 if (unlikely(!page) || unlikely(is_zone_device_page(page))) { 578 result = SCAN_PAGE_NULL; 579 goto out; 580 } 581 582 folio = page_folio(page); 583 VM_BUG_ON_FOLIO(!folio_test_anon(folio), folio); 584 585 /* 586 * If the vma has the VM_DROPPABLE flag, the collapse will 587 * preserve the lazyfree property without needing to skip. 588 */ 589 if (cc->is_khugepaged && !(vma->vm_flags & VM_DROPPABLE) && 590 folio_test_lazyfree(folio) && !pte_dirty(pteval)) { 591 result = SCAN_PAGE_LAZYFREE; 592 goto out; 593 } 594 595 /* See collapse_scan_pmd(). */ 596 if (folio_maybe_mapped_shared(folio)) { 597 ++shared; 598 if (cc->is_khugepaged && 599 shared > khugepaged_max_ptes_shared) { 600 result = SCAN_EXCEED_SHARED_PTE; 601 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE); 602 goto out; 603 } 604 } 605 606 if (folio_test_large(folio)) { 607 struct folio *f; 608 609 /* 610 * Check if we have dealt with the compound page 611 * already 612 */ 613 list_for_each_entry(f, compound_pagelist, lru) { 614 if (folio == f) 615 goto next; 616 } 617 } 618 619 /* 620 * We can do it before folio_isolate_lru because the 621 * folio can't be freed from under us. NOTE: PG_lock 622 * is needed to serialize against split_huge_page 623 * when invoked from the VM. 624 */ 625 if (!folio_trylock(folio)) { 626 result = SCAN_PAGE_LOCK; 627 goto out; 628 } 629 630 /* 631 * Check if the page has any GUP (or other external) pins. 632 * 633 * The page table that maps the page has been already unlinked 634 * from the page table tree and this process cannot get 635 * an additional pin on the page. 636 * 637 * New pins can come later if the page is shared across fork, 638 * but not from this process. The other process cannot write to 639 * the page, only trigger CoW. 640 */ 641 if (folio_expected_ref_count(folio) != folio_ref_count(folio)) { 642 folio_unlock(folio); 643 result = SCAN_PAGE_COUNT; 644 goto out; 645 } 646 647 /* 648 * Isolate the page to avoid collapsing an hugepage 649 * currently in use by the VM. 650 */ 651 if (!folio_isolate_lru(folio)) { 652 folio_unlock(folio); 653 result = SCAN_DEL_PAGE_LRU; 654 goto out; 655 } 656 node_stat_mod_folio(folio, 657 NR_ISOLATED_ANON + folio_is_file_lru(folio), 658 folio_nr_pages(folio)); 659 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 660 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio); 661 662 if (folio_test_large(folio)) 663 list_add_tail(&folio->lru, compound_pagelist); 664 next: 665 /* 666 * If collapse was initiated by khugepaged, check that there is 667 * enough young pte to justify collapsing the page 668 */ 669 if (cc->is_khugepaged && 670 (pte_young(pteval) || folio_test_young(folio) || 671 folio_test_referenced(folio) || 672 mmu_notifier_test_young(vma->vm_mm, addr))) 673 referenced++; 674 } 675 676 if (unlikely(cc->is_khugepaged && !referenced)) { 677 result = SCAN_LACK_REFERENCED_PAGE; 678 } else { 679 result = SCAN_SUCCEED; 680 trace_mm_collapse_huge_page_isolate(folio, none_or_zero, 681 referenced, result); 682 return result; 683 } 684 out: 685 release_pte_pages(pte, _pte, compound_pagelist); 686 trace_mm_collapse_huge_page_isolate(folio, none_or_zero, 687 referenced, result); 688 return result; 689 } 690 691 static void __collapse_huge_page_copy_succeeded(pte_t *pte, 692 struct vm_area_struct *vma, 693 unsigned long address, 694 spinlock_t *ptl, 695 struct list_head *compound_pagelist) 696 { 697 unsigned long end = address + HPAGE_PMD_SIZE; 698 struct folio *src, *tmp; 699 pte_t pteval; 700 pte_t *_pte; 701 unsigned int nr_ptes; 702 703 for (_pte = pte; _pte < pte + HPAGE_PMD_NR; _pte += nr_ptes, 704 address += nr_ptes * PAGE_SIZE) { 705 nr_ptes = 1; 706 pteval = ptep_get(_pte); 707 if (pte_none_or_zero(pteval)) { 708 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1); 709 if (pte_none(pteval)) 710 continue; 711 /* 712 * ptl mostly unnecessary. 713 */ 714 spin_lock(ptl); 715 ptep_clear(vma->vm_mm, address, _pte); 716 spin_unlock(ptl); 717 ksm_might_unmap_zero_page(vma->vm_mm, pteval); 718 } else { 719 struct page *src_page = pte_page(pteval); 720 721 src = page_folio(src_page); 722 723 if (folio_test_large(src)) { 724 unsigned int max_nr_ptes = (end - address) >> PAGE_SHIFT; 725 726 nr_ptes = folio_pte_batch(src, _pte, pteval, max_nr_ptes); 727 } else { 728 release_pte_folio(src); 729 } 730 731 /* 732 * ptl mostly unnecessary, but preempt has to 733 * be disabled to update the per-cpu stats 734 * inside folio_remove_rmap_pte(). 735 */ 736 spin_lock(ptl); 737 clear_ptes(vma->vm_mm, address, _pte, nr_ptes); 738 folio_remove_rmap_ptes(src, src_page, nr_ptes, vma); 739 spin_unlock(ptl); 740 free_swap_cache(src); 741 folio_put_refs(src, nr_ptes); 742 } 743 } 744 745 list_for_each_entry_safe(src, tmp, compound_pagelist, lru) { 746 list_del(&src->lru); 747 node_stat_sub_folio(src, NR_ISOLATED_ANON + 748 folio_is_file_lru(src)); 749 folio_unlock(src); 750 free_swap_cache(src); 751 folio_putback_lru(src); 752 } 753 } 754 755 static void __collapse_huge_page_copy_failed(pte_t *pte, 756 pmd_t *pmd, 757 pmd_t orig_pmd, 758 struct vm_area_struct *vma, 759 struct list_head *compound_pagelist) 760 { 761 spinlock_t *pmd_ptl; 762 763 /* 764 * Re-establish the PMD to point to the original page table 765 * entry. Restoring PMD needs to be done prior to releasing 766 * pages. Since pages are still isolated and locked here, 767 * acquiring anon_vma_lock_write is unnecessary. 768 */ 769 pmd_ptl = pmd_lock(vma->vm_mm, pmd); 770 pmd_populate(vma->vm_mm, pmd, pmd_pgtable(orig_pmd)); 771 spin_unlock(pmd_ptl); 772 /* 773 * Release both raw and compound pages isolated 774 * in __collapse_huge_page_isolate. 775 */ 776 release_pte_pages(pte, pte + HPAGE_PMD_NR, compound_pagelist); 777 } 778 779 /* 780 * __collapse_huge_page_copy - attempts to copy memory contents from raw 781 * pages to a hugepage. Cleans up the raw pages if copying succeeds; 782 * otherwise restores the original page table and releases isolated raw pages. 783 * Returns SCAN_SUCCEED if copying succeeds, otherwise returns SCAN_COPY_MC. 784 * 785 * @pte: starting of the PTEs to copy from 786 * @folio: the new hugepage to copy contents to 787 * @pmd: pointer to the new hugepage's PMD 788 * @orig_pmd: the original raw pages' PMD 789 * @vma: the original raw pages' virtual memory area 790 * @address: starting address to copy 791 * @ptl: lock on raw pages' PTEs 792 * @compound_pagelist: list that stores compound pages 793 */ 794 static enum scan_result __collapse_huge_page_copy(pte_t *pte, struct folio *folio, 795 pmd_t *pmd, pmd_t orig_pmd, struct vm_area_struct *vma, 796 unsigned long address, spinlock_t *ptl, 797 struct list_head *compound_pagelist) 798 { 799 unsigned int i; 800 enum scan_result result = SCAN_SUCCEED; 801 802 /* 803 * Copying pages' contents is subject to memory poison at any iteration. 804 */ 805 for (i = 0; i < HPAGE_PMD_NR; i++) { 806 pte_t pteval = ptep_get(pte + i); 807 struct page *page = folio_page(folio, i); 808 unsigned long src_addr = address + i * PAGE_SIZE; 809 struct page *src_page; 810 811 if (pte_none_or_zero(pteval)) { 812 clear_user_highpage(page, src_addr); 813 continue; 814 } 815 src_page = pte_page(pteval); 816 if (copy_mc_user_highpage(page, src_page, src_addr, vma) > 0) { 817 result = SCAN_COPY_MC; 818 break; 819 } 820 } 821 822 if (likely(result == SCAN_SUCCEED)) 823 __collapse_huge_page_copy_succeeded(pte, vma, address, ptl, 824 compound_pagelist); 825 else 826 __collapse_huge_page_copy_failed(pte, pmd, orig_pmd, vma, 827 compound_pagelist); 828 829 return result; 830 } 831 832 static void khugepaged_alloc_sleep(void) 833 { 834 DEFINE_WAIT(wait); 835 836 add_wait_queue(&khugepaged_wait, &wait); 837 __set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE); 838 schedule_timeout(msecs_to_jiffies(khugepaged_alloc_sleep_millisecs)); 839 remove_wait_queue(&khugepaged_wait, &wait); 840 } 841 842 static struct collapse_control khugepaged_collapse_control = { 843 .is_khugepaged = true, 844 }; 845 846 static bool collapse_scan_abort(int nid, struct collapse_control *cc) 847 { 848 int i; 849 850 /* 851 * If node_reclaim_mode is disabled, then no extra effort is made to 852 * allocate memory locally. 853 */ 854 if (!node_reclaim_enabled()) 855 return false; 856 857 /* If there is a count for this node already, it must be acceptable */ 858 if (cc->node_load[nid]) 859 return false; 860 861 for (i = 0; i < MAX_NUMNODES; i++) { 862 if (!cc->node_load[i]) 863 continue; 864 if (node_distance(nid, i) > node_reclaim_distance) 865 return true; 866 } 867 return false; 868 } 869 870 #define khugepaged_defrag() \ 871 (transparent_hugepage_flags & \ 872 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG)) 873 874 /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */ 875 static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void) 876 { 877 return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT; 878 } 879 880 #ifdef CONFIG_NUMA 881 static int collapse_find_target_node(struct collapse_control *cc) 882 { 883 int nid, target_node = 0, max_value = 0; 884 885 /* find first node with max normal pages hit */ 886 for (nid = 0; nid < MAX_NUMNODES; nid++) 887 if (cc->node_load[nid] > max_value) { 888 max_value = cc->node_load[nid]; 889 target_node = nid; 890 } 891 892 for_each_online_node(nid) { 893 if (max_value == cc->node_load[nid]) 894 node_set(nid, cc->alloc_nmask); 895 } 896 897 return target_node; 898 } 899 #else 900 static int collapse_find_target_node(struct collapse_control *cc) 901 { 902 return 0; 903 } 904 #endif 905 906 /* 907 * If mmap_lock temporarily dropped, revalidate vma 908 * before taking mmap_lock. 909 * Returns enum scan_result value. 910 */ 911 912 static enum scan_result hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address, 913 bool expect_anon, struct vm_area_struct **vmap, struct collapse_control *cc) 914 { 915 struct vm_area_struct *vma; 916 enum tva_type type = cc->is_khugepaged ? TVA_KHUGEPAGED : 917 TVA_FORCED_COLLAPSE; 918 919 if (unlikely(collapse_test_exit_or_disable(mm))) 920 return SCAN_ANY_PROCESS; 921 922 *vmap = vma = find_vma(mm, address); 923 if (!vma) 924 return SCAN_VMA_NULL; 925 926 if (!thp_vma_suitable_order(vma, address, PMD_ORDER)) 927 return SCAN_ADDRESS_RANGE; 928 if (!thp_vma_allowable_order(vma, vma->vm_flags, type, PMD_ORDER)) 929 return SCAN_VMA_CHECK; 930 /* 931 * Anon VMA expected, the address may be unmapped then 932 * remapped to file after khugepaged reaquired the mmap_lock. 933 * 934 * thp_vma_allowable_order may return true for qualified file 935 * vmas. 936 */ 937 if (expect_anon && (!(*vmap)->anon_vma || !vma_is_anonymous(*vmap))) 938 return SCAN_PAGE_ANON; 939 return SCAN_SUCCEED; 940 } 941 942 static inline enum scan_result check_pmd_state(pmd_t *pmd) 943 { 944 pmd_t pmde = pmdp_get_lockless(pmd); 945 946 if (pmd_none(pmde)) 947 return SCAN_NO_PTE_TABLE; 948 949 /* 950 * The folio may be under migration when khugepaged is trying to 951 * collapse it. Migration success or failure will eventually end 952 * up with a present PMD mapping a folio again. 953 */ 954 if (pmd_is_migration_entry(pmde)) 955 return SCAN_PMD_MAPPED; 956 if (!pmd_present(pmde)) 957 return SCAN_NO_PTE_TABLE; 958 if (pmd_trans_huge(pmde)) 959 return SCAN_PMD_MAPPED; 960 if (pmd_bad(pmde)) 961 return SCAN_NO_PTE_TABLE; 962 return SCAN_SUCCEED; 963 } 964 965 static enum scan_result find_pmd_or_thp_or_none(struct mm_struct *mm, 966 unsigned long address, pmd_t **pmd) 967 { 968 *pmd = mm_find_pmd(mm, address); 969 if (!*pmd) 970 return SCAN_NO_PTE_TABLE; 971 972 return check_pmd_state(*pmd); 973 } 974 975 static enum scan_result check_pmd_still_valid(struct mm_struct *mm, 976 unsigned long address, pmd_t *pmd) 977 { 978 pmd_t *new_pmd; 979 enum scan_result result = find_pmd_or_thp_or_none(mm, address, &new_pmd); 980 981 if (result != SCAN_SUCCEED) 982 return result; 983 if (new_pmd != pmd) 984 return SCAN_FAIL; 985 return SCAN_SUCCEED; 986 } 987 988 /* 989 * Bring missing pages in from swap, to complete THP collapse. 990 * Only done if khugepaged_scan_pmd believes it is worthwhile. 991 * 992 * Called and returns without pte mapped or spinlocks held. 993 * Returns result: if not SCAN_SUCCEED, mmap_lock has been released. 994 */ 995 static enum scan_result __collapse_huge_page_swapin(struct mm_struct *mm, 996 struct vm_area_struct *vma, unsigned long start_addr, pmd_t *pmd, 997 int referenced) 998 { 999 int swapped_in = 0; 1000 vm_fault_t ret = 0; 1001 unsigned long addr, end = start_addr + (HPAGE_PMD_NR * PAGE_SIZE); 1002 enum scan_result result; 1003 pte_t *pte = NULL; 1004 spinlock_t *ptl; 1005 1006 for (addr = start_addr; addr < end; addr += PAGE_SIZE) { 1007 struct vm_fault vmf = { 1008 .vma = vma, 1009 .address = addr, 1010 .pgoff = linear_page_index(vma, addr), 1011 .flags = FAULT_FLAG_ALLOW_RETRY, 1012 .pmd = pmd, 1013 }; 1014 1015 if (!pte++) { 1016 /* 1017 * Here the ptl is only used to check pte_same() in 1018 * do_swap_page(), so readonly version is enough. 1019 */ 1020 pte = pte_offset_map_ro_nolock(mm, pmd, addr, &ptl); 1021 if (!pte) { 1022 mmap_read_unlock(mm); 1023 result = SCAN_NO_PTE_TABLE; 1024 goto out; 1025 } 1026 } 1027 1028 vmf.orig_pte = ptep_get_lockless(pte); 1029 if (pte_none(vmf.orig_pte) || 1030 pte_present(vmf.orig_pte)) 1031 continue; 1032 1033 vmf.pte = pte; 1034 vmf.ptl = ptl; 1035 ret = do_swap_page(&vmf); 1036 /* Which unmaps pte (after perhaps re-checking the entry) */ 1037 pte = NULL; 1038 1039 /* 1040 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock. 1041 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because 1042 * we do not retry here and swap entry will remain in pagetable 1043 * resulting in later failure. 1044 */ 1045 if (ret & VM_FAULT_RETRY) { 1046 /* Likely, but not guaranteed, that page lock failed */ 1047 result = SCAN_PAGE_LOCK; 1048 goto out; 1049 } 1050 if (ret & VM_FAULT_ERROR) { 1051 mmap_read_unlock(mm); 1052 result = SCAN_FAIL; 1053 goto out; 1054 } 1055 swapped_in++; 1056 } 1057 1058 if (pte) 1059 pte_unmap(pte); 1060 1061 /* Drain LRU cache to remove extra pin on the swapped in pages */ 1062 if (swapped_in) 1063 lru_add_drain(); 1064 1065 result = SCAN_SUCCEED; 1066 out: 1067 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, result); 1068 return result; 1069 } 1070 1071 static enum scan_result alloc_charge_folio(struct folio **foliop, struct mm_struct *mm, 1072 struct collapse_control *cc) 1073 { 1074 gfp_t gfp = (cc->is_khugepaged ? alloc_hugepage_khugepaged_gfpmask() : 1075 GFP_TRANSHUGE); 1076 int node = collapse_find_target_node(cc); 1077 struct folio *folio; 1078 1079 folio = __folio_alloc(gfp, HPAGE_PMD_ORDER, node, &cc->alloc_nmask); 1080 if (!folio) { 1081 *foliop = NULL; 1082 count_vm_event(THP_COLLAPSE_ALLOC_FAILED); 1083 return SCAN_ALLOC_HUGE_PAGE_FAIL; 1084 } 1085 1086 count_vm_event(THP_COLLAPSE_ALLOC); 1087 if (unlikely(mem_cgroup_charge(folio, mm, gfp))) { 1088 folio_put(folio); 1089 *foliop = NULL; 1090 return SCAN_CGROUP_CHARGE_FAIL; 1091 } 1092 1093 count_memcg_folio_events(folio, THP_COLLAPSE_ALLOC, 1); 1094 1095 *foliop = folio; 1096 return SCAN_SUCCEED; 1097 } 1098 1099 static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long address, 1100 int referenced, int unmapped, struct collapse_control *cc) 1101 { 1102 LIST_HEAD(compound_pagelist); 1103 pmd_t *pmd, _pmd; 1104 pte_t *pte; 1105 pgtable_t pgtable; 1106 struct folio *folio; 1107 spinlock_t *pmd_ptl, *pte_ptl; 1108 enum scan_result result = SCAN_FAIL; 1109 struct vm_area_struct *vma; 1110 struct mmu_notifier_range range; 1111 1112 VM_BUG_ON(address & ~HPAGE_PMD_MASK); 1113 1114 /* 1115 * Before allocating the hugepage, release the mmap_lock read lock. 1116 * The allocation can take potentially a long time if it involves 1117 * sync compaction, and we do not need to hold the mmap_lock during 1118 * that. We will recheck the vma after taking it again in write mode. 1119 */ 1120 mmap_read_unlock(mm); 1121 1122 result = alloc_charge_folio(&folio, mm, cc); 1123 if (result != SCAN_SUCCEED) 1124 goto out_nolock; 1125 1126 if (folio_memcg_alloc_deferred(folio)) { 1127 result = SCAN_ALLOC_HUGE_PAGE_FAIL; 1128 goto out_nolock; 1129 } 1130 1131 mmap_read_lock(mm); 1132 result = hugepage_vma_revalidate(mm, address, true, &vma, cc); 1133 if (result != SCAN_SUCCEED) { 1134 mmap_read_unlock(mm); 1135 goto out_nolock; 1136 } 1137 1138 result = find_pmd_or_thp_or_none(mm, address, &pmd); 1139 if (result != SCAN_SUCCEED) { 1140 mmap_read_unlock(mm); 1141 goto out_nolock; 1142 } 1143 1144 if (unmapped) { 1145 /* 1146 * __collapse_huge_page_swapin will return with mmap_lock 1147 * released when it fails. So we jump out_nolock directly in 1148 * that case. Continuing to collapse causes inconsistency. 1149 */ 1150 result = __collapse_huge_page_swapin(mm, vma, address, pmd, 1151 referenced); 1152 if (result != SCAN_SUCCEED) 1153 goto out_nolock; 1154 } 1155 1156 mmap_read_unlock(mm); 1157 /* 1158 * Prevent all access to pagetables with the exception of 1159 * gup_fast later handled by the ptep_clear_flush and the VM 1160 * handled by the anon_vma lock + PG_lock. 1161 * 1162 * UFFDIO_MOVE is prevented to race as well thanks to the 1163 * mmap_lock. 1164 */ 1165 mmap_write_lock(mm); 1166 result = hugepage_vma_revalidate(mm, address, true, &vma, cc); 1167 if (result != SCAN_SUCCEED) 1168 goto out_up_write; 1169 /* check if the pmd is still valid */ 1170 vma_start_write(vma); 1171 result = check_pmd_still_valid(mm, address, pmd); 1172 if (result != SCAN_SUCCEED) 1173 goto out_up_write; 1174 1175 anon_vma_lock_write(vma->anon_vma); 1176 1177 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, address, 1178 address + HPAGE_PMD_SIZE); 1179 mmu_notifier_invalidate_range_start(&range); 1180 1181 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */ 1182 /* 1183 * This removes any huge TLB entry from the CPU so we won't allow 1184 * huge and small TLB entries for the same virtual address to 1185 * avoid the risk of CPU bugs in that area. 1186 * 1187 * Parallel GUP-fast is fine since GUP-fast will back off when 1188 * it detects PMD is changed. 1189 */ 1190 _pmd = pmdp_collapse_flush(vma, address, pmd); 1191 spin_unlock(pmd_ptl); 1192 mmu_notifier_invalidate_range_end(&range); 1193 tlb_remove_table_sync_one(); 1194 1195 pte = pte_offset_map_lock(mm, &_pmd, address, &pte_ptl); 1196 if (pte) { 1197 result = __collapse_huge_page_isolate(vma, address, pte, cc, 1198 &compound_pagelist); 1199 spin_unlock(pte_ptl); 1200 } else { 1201 result = SCAN_NO_PTE_TABLE; 1202 } 1203 1204 if (unlikely(result != SCAN_SUCCEED)) { 1205 if (pte) 1206 pte_unmap(pte); 1207 spin_lock(pmd_ptl); 1208 BUG_ON(!pmd_none(*pmd)); 1209 /* 1210 * We can only use set_pmd_at when establishing 1211 * hugepmds and never for establishing regular pmds that 1212 * points to regular pagetables. Use pmd_populate for that 1213 */ 1214 pmd_populate(mm, pmd, pmd_pgtable(_pmd)); 1215 spin_unlock(pmd_ptl); 1216 anon_vma_unlock_write(vma->anon_vma); 1217 goto out_up_write; 1218 } 1219 1220 /* 1221 * All pages are isolated and locked so anon_vma rmap 1222 * can't run anymore. 1223 */ 1224 anon_vma_unlock_write(vma->anon_vma); 1225 1226 result = __collapse_huge_page_copy(pte, folio, pmd, _pmd, 1227 vma, address, pte_ptl, 1228 &compound_pagelist); 1229 pte_unmap(pte); 1230 if (unlikely(result != SCAN_SUCCEED)) 1231 goto out_up_write; 1232 1233 /* 1234 * The smp_wmb() inside __folio_mark_uptodate() ensures the 1235 * copy_huge_page writes become visible before the set_pmd_at() 1236 * write. 1237 */ 1238 __folio_mark_uptodate(folio); 1239 pgtable = pmd_pgtable(_pmd); 1240 1241 spin_lock(pmd_ptl); 1242 BUG_ON(!pmd_none(*pmd)); 1243 pgtable_trans_huge_deposit(mm, pmd, pgtable); 1244 map_anon_folio_pmd_nopf(folio, pmd, vma, address); 1245 spin_unlock(pmd_ptl); 1246 1247 folio = NULL; 1248 1249 result = SCAN_SUCCEED; 1250 out_up_write: 1251 mmap_write_unlock(mm); 1252 out_nolock: 1253 if (folio) 1254 folio_put(folio); 1255 trace_mm_collapse_huge_page(mm, result == SCAN_SUCCEED, result); 1256 return result; 1257 } 1258 1259 static enum scan_result collapse_scan_pmd(struct mm_struct *mm, 1260 struct vm_area_struct *vma, unsigned long start_addr, 1261 bool *lock_dropped, struct collapse_control *cc) 1262 { 1263 pmd_t *pmd; 1264 pte_t *pte, *_pte; 1265 int none_or_zero = 0, shared = 0, referenced = 0; 1266 enum scan_result result = SCAN_FAIL; 1267 struct page *page = NULL; 1268 struct folio *folio = NULL; 1269 unsigned long addr; 1270 spinlock_t *ptl; 1271 int node = NUMA_NO_NODE, unmapped = 0; 1272 1273 VM_BUG_ON(start_addr & ~HPAGE_PMD_MASK); 1274 1275 result = find_pmd_or_thp_or_none(mm, start_addr, &pmd); 1276 if (result != SCAN_SUCCEED) { 1277 cc->progress++; 1278 goto out; 1279 } 1280 1281 memset(cc->node_load, 0, sizeof(cc->node_load)); 1282 nodes_clear(cc->alloc_nmask); 1283 pte = pte_offset_map_lock(mm, pmd, start_addr, &ptl); 1284 if (!pte) { 1285 cc->progress++; 1286 result = SCAN_NO_PTE_TABLE; 1287 goto out; 1288 } 1289 1290 for (addr = start_addr, _pte = pte; _pte < pte + HPAGE_PMD_NR; 1291 _pte++, addr += PAGE_SIZE) { 1292 cc->progress++; 1293 1294 pte_t pteval = ptep_get(_pte); 1295 if (pte_none_or_zero(pteval)) { 1296 ++none_or_zero; 1297 if (!userfaultfd_armed(vma) && 1298 (!cc->is_khugepaged || 1299 none_or_zero <= khugepaged_max_ptes_none)) { 1300 continue; 1301 } else { 1302 result = SCAN_EXCEED_NONE_PTE; 1303 count_vm_event(THP_SCAN_EXCEED_NONE_PTE); 1304 goto out_unmap; 1305 } 1306 } 1307 if (!pte_present(pteval)) { 1308 ++unmapped; 1309 if (!cc->is_khugepaged || 1310 unmapped <= khugepaged_max_ptes_swap) { 1311 /* 1312 * Always be strict with uffd-wp 1313 * enabled swap entries. Please see 1314 * comment below for pte_uffd_wp(). 1315 */ 1316 if (pte_swp_uffd_wp_any(pteval)) { 1317 result = SCAN_PTE_UFFD_WP; 1318 goto out_unmap; 1319 } 1320 continue; 1321 } else { 1322 result = SCAN_EXCEED_SWAP_PTE; 1323 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE); 1324 goto out_unmap; 1325 } 1326 } 1327 if (pte_uffd_wp(pteval)) { 1328 /* 1329 * Don't collapse the page if any of the small 1330 * PTEs are armed with uffd write protection. 1331 * Here we can also mark the new huge pmd as 1332 * write protected if any of the small ones is 1333 * marked but that could bring unknown 1334 * userfault messages that falls outside of 1335 * the registered range. So, just be simple. 1336 */ 1337 result = SCAN_PTE_UFFD_WP; 1338 goto out_unmap; 1339 } 1340 1341 page = vm_normal_page(vma, addr, pteval); 1342 if (unlikely(!page) || unlikely(is_zone_device_page(page))) { 1343 result = SCAN_PAGE_NULL; 1344 goto out_unmap; 1345 } 1346 folio = page_folio(page); 1347 1348 /* 1349 * If the vma has the VM_DROPPABLE flag, the collapse will 1350 * preserve the lazyfree property without needing to skip. 1351 */ 1352 if (cc->is_khugepaged && !(vma->vm_flags & VM_DROPPABLE) && 1353 folio_test_lazyfree(folio) && !pte_dirty(pteval)) { 1354 result = SCAN_PAGE_LAZYFREE; 1355 goto out_unmap; 1356 } 1357 1358 if (!folio_test_anon(folio)) { 1359 result = SCAN_PAGE_ANON; 1360 goto out_unmap; 1361 } 1362 1363 /* 1364 * We treat a single page as shared if any part of the THP 1365 * is shared. 1366 */ 1367 if (folio_maybe_mapped_shared(folio)) { 1368 ++shared; 1369 if (cc->is_khugepaged && 1370 shared > khugepaged_max_ptes_shared) { 1371 result = SCAN_EXCEED_SHARED_PTE; 1372 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE); 1373 goto out_unmap; 1374 } 1375 } 1376 1377 /* 1378 * Record which node the original page is from and save this 1379 * information to cc->node_load[]. 1380 * Khugepaged will allocate hugepage from the node has the max 1381 * hit record. 1382 */ 1383 node = folio_nid(folio); 1384 if (collapse_scan_abort(node, cc)) { 1385 result = SCAN_SCAN_ABORT; 1386 goto out_unmap; 1387 } 1388 cc->node_load[node]++; 1389 if (!folio_test_lru(folio)) { 1390 result = SCAN_PAGE_LRU; 1391 goto out_unmap; 1392 } 1393 if (folio_test_locked(folio)) { 1394 result = SCAN_PAGE_LOCK; 1395 goto out_unmap; 1396 } 1397 1398 /* 1399 * Check if the page has any GUP (or other external) pins. 1400 * 1401 * Here the check may be racy: 1402 * it may see folio_mapcount() > folio_ref_count(). 1403 * But such case is ephemeral we could always retry collapse 1404 * later. However it may report false positive if the page 1405 * has excessive GUP pins (i.e. 512). Anyway the same check 1406 * will be done again later the risk seems low. 1407 */ 1408 if (folio_expected_ref_count(folio) != folio_ref_count(folio)) { 1409 result = SCAN_PAGE_COUNT; 1410 goto out_unmap; 1411 } 1412 1413 /* 1414 * If collapse was initiated by khugepaged, check that there is 1415 * enough young pte to justify collapsing the page 1416 */ 1417 if (cc->is_khugepaged && 1418 (pte_young(pteval) || folio_test_young(folio) || 1419 folio_test_referenced(folio) || 1420 mmu_notifier_test_young(vma->vm_mm, addr))) 1421 referenced++; 1422 } 1423 if (cc->is_khugepaged && 1424 (!referenced || 1425 (unmapped && referenced < HPAGE_PMD_NR / 2))) { 1426 result = SCAN_LACK_REFERENCED_PAGE; 1427 } else { 1428 result = SCAN_SUCCEED; 1429 } 1430 out_unmap: 1431 pte_unmap_unlock(pte, ptl); 1432 if (result == SCAN_SUCCEED) { 1433 result = collapse_huge_page(mm, start_addr, referenced, 1434 unmapped, cc); 1435 /* collapse_huge_page will return with the mmap_lock released */ 1436 *lock_dropped = true; 1437 } 1438 out: 1439 trace_mm_khugepaged_scan_pmd(mm, folio, referenced, 1440 none_or_zero, result, unmapped); 1441 return result; 1442 } 1443 1444 static void collect_mm_slot(struct mm_slot *slot) 1445 { 1446 struct mm_struct *mm = slot->mm; 1447 1448 lockdep_assert_held(&khugepaged_mm_lock); 1449 1450 if (collapse_test_exit(mm)) { 1451 /* free mm_slot */ 1452 hash_del(&slot->hash); 1453 list_del(&slot->mm_node); 1454 1455 /* 1456 * Not strictly needed because the mm exited already. 1457 * 1458 * mm_flags_clear(MMF_VM_HUGEPAGE, mm); 1459 */ 1460 1461 /* khugepaged_mm_lock actually not necessary for the below */ 1462 mm_slot_free(mm_slot_cache, slot); 1463 mmdrop(mm); 1464 } 1465 } 1466 1467 /* folio must be locked, and mmap_lock must be held */ 1468 static enum scan_result set_huge_pmd(struct vm_area_struct *vma, unsigned long addr, 1469 pmd_t *pmdp, struct folio *folio, struct page *page) 1470 { 1471 struct mm_struct *mm = vma->vm_mm; 1472 struct vm_fault vmf = { 1473 .vma = vma, 1474 .address = addr, 1475 .flags = 0, 1476 }; 1477 pgd_t *pgdp; 1478 p4d_t *p4dp; 1479 pud_t *pudp; 1480 1481 mmap_assert_locked(vma->vm_mm); 1482 1483 if (!pmdp) { 1484 pgdp = pgd_offset(mm, addr); 1485 p4dp = p4d_alloc(mm, pgdp, addr); 1486 if (!p4dp) 1487 return SCAN_FAIL; 1488 pudp = pud_alloc(mm, p4dp, addr); 1489 if (!pudp) 1490 return SCAN_FAIL; 1491 pmdp = pmd_alloc(mm, pudp, addr); 1492 if (!pmdp) 1493 return SCAN_FAIL; 1494 } 1495 1496 vmf.pmd = pmdp; 1497 if (do_set_pmd(&vmf, folio, page)) 1498 return SCAN_FAIL; 1499 1500 folio_get(folio); 1501 return SCAN_SUCCEED; 1502 } 1503 1504 static enum scan_result try_collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr, 1505 bool install_pmd) 1506 { 1507 enum scan_result result = SCAN_FAIL; 1508 int nr_mapped_ptes = 0; 1509 unsigned int nr_batch_ptes; 1510 struct mmu_notifier_range range; 1511 bool notified = false; 1512 unsigned long haddr = addr & HPAGE_PMD_MASK; 1513 unsigned long end = haddr + HPAGE_PMD_SIZE; 1514 struct vm_area_struct *vma = vma_lookup(mm, haddr); 1515 struct folio *folio; 1516 pte_t *start_pte, *pte; 1517 pmd_t *pmd, pgt_pmd; 1518 spinlock_t *pml = NULL, *ptl; 1519 int i; 1520 1521 mmap_assert_locked(mm); 1522 1523 /* First check VMA found, in case page tables are being torn down */ 1524 if (!vma || !vma->vm_file || 1525 !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE)) 1526 return SCAN_VMA_CHECK; 1527 1528 /* Fast check before locking page if already PMD-mapped */ 1529 result = find_pmd_or_thp_or_none(mm, haddr, &pmd); 1530 if (result == SCAN_PMD_MAPPED) 1531 return result; 1532 1533 /* 1534 * If we are here, we've succeeded in replacing all the native pages 1535 * in the page cache with a single hugepage. If a mm were to fault-in 1536 * this memory (mapped by a suitably aligned VMA), we'd get the hugepage 1537 * and map it by a PMD, regardless of sysfs THP settings. As such, let's 1538 * analogously elide sysfs THP settings here and force collapse. 1539 */ 1540 if (!thp_vma_allowable_order(vma, vma->vm_flags, TVA_FORCED_COLLAPSE, PMD_ORDER)) 1541 return SCAN_VMA_CHECK; 1542 1543 /* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */ 1544 if (userfaultfd_wp(vma)) 1545 return SCAN_PTE_UFFD_WP; 1546 1547 folio = filemap_lock_folio(vma->vm_file->f_mapping, 1548 linear_page_index(vma, haddr)); 1549 if (IS_ERR(folio)) 1550 return SCAN_PAGE_NULL; 1551 1552 if (!is_pmd_order(folio_order(folio))) { 1553 result = SCAN_PAGE_COMPOUND; 1554 goto drop_folio; 1555 } 1556 1557 result = find_pmd_or_thp_or_none(mm, haddr, &pmd); 1558 switch (result) { 1559 case SCAN_SUCCEED: 1560 break; 1561 case SCAN_NO_PTE_TABLE: 1562 /* 1563 * All pte entries have been removed and pmd cleared. 1564 * Skip all the pte checks and just update the pmd mapping. 1565 */ 1566 goto maybe_install_pmd; 1567 default: 1568 goto drop_folio; 1569 } 1570 1571 result = SCAN_FAIL; 1572 start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl); 1573 if (!start_pte) /* mmap_lock + page lock should prevent this */ 1574 goto drop_folio; 1575 1576 /* step 1: check all mapped PTEs are to the right huge page */ 1577 for (i = 0, addr = haddr, pte = start_pte; 1578 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) { 1579 struct page *page; 1580 pte_t ptent = ptep_get(pte); 1581 1582 /* empty pte, skip */ 1583 if (pte_none(ptent)) 1584 continue; 1585 1586 /* page swapped out, abort */ 1587 if (!pte_present(ptent)) { 1588 result = SCAN_PTE_NON_PRESENT; 1589 goto abort; 1590 } 1591 1592 page = vm_normal_page(vma, addr, ptent); 1593 if (WARN_ON_ONCE(page && is_zone_device_page(page))) 1594 page = NULL; 1595 /* 1596 * Note that uprobe, debugger, or MAP_PRIVATE may change the 1597 * page table, but the new page will not be a subpage of hpage. 1598 */ 1599 if (folio_page(folio, i) != page) 1600 goto abort; 1601 } 1602 1603 pte_unmap_unlock(start_pte, ptl); 1604 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, 1605 haddr, haddr + HPAGE_PMD_SIZE); 1606 mmu_notifier_invalidate_range_start(&range); 1607 notified = true; 1608 1609 /* 1610 * pmd_lock covers a wider range than ptl, and (if split from mm's 1611 * page_table_lock) ptl nests inside pml. The less time we hold pml, 1612 * the better; but userfaultfd's mfill_atomic_pte() on a private VMA 1613 * inserts a valid as-if-COWed PTE without even looking up page cache. 1614 * So page lock of folio does not protect from it, so we must not drop 1615 * ptl before pgt_pmd is removed, so uffd private needs pml taken now. 1616 */ 1617 if (userfaultfd_armed(vma) && !(vma->vm_flags & VM_SHARED)) 1618 pml = pmd_lock(mm, pmd); 1619 1620 start_pte = pte_offset_map_rw_nolock(mm, pmd, haddr, &pgt_pmd, &ptl); 1621 if (!start_pte) /* mmap_lock + page lock should prevent this */ 1622 goto abort; 1623 if (!pml) 1624 spin_lock(ptl); 1625 else if (ptl != pml) 1626 spin_lock_nested(ptl, SINGLE_DEPTH_NESTING); 1627 1628 if (unlikely(!pmd_same(pgt_pmd, pmdp_get_lockless(pmd)))) 1629 goto abort; 1630 1631 /* step 2: clear page table and adjust rmap */ 1632 for (i = 0, addr = haddr, pte = start_pte; i < HPAGE_PMD_NR; 1633 i += nr_batch_ptes, addr += nr_batch_ptes * PAGE_SIZE, 1634 pte += nr_batch_ptes) { 1635 unsigned int max_nr_batch_ptes = (end - addr) >> PAGE_SHIFT; 1636 struct page *page; 1637 pte_t ptent = ptep_get(pte); 1638 1639 nr_batch_ptes = 1; 1640 1641 if (pte_none(ptent)) 1642 continue; 1643 /* 1644 * We dropped ptl after the first scan, to do the mmu_notifier: 1645 * page lock stops more PTEs of the folio being faulted in, but 1646 * does not stop write faults COWing anon copies from existing 1647 * PTEs; and does not stop those being swapped out or migrated. 1648 */ 1649 if (!pte_present(ptent)) { 1650 result = SCAN_PTE_NON_PRESENT; 1651 goto abort; 1652 } 1653 page = vm_normal_page(vma, addr, ptent); 1654 1655 if (folio_page(folio, i) != page) 1656 goto abort; 1657 1658 nr_batch_ptes = folio_pte_batch(folio, pte, ptent, max_nr_batch_ptes); 1659 1660 /* 1661 * Must clear entry, or a racing truncate may re-remove it. 1662 * TLB flush can be left until pmdp_collapse_flush() does it. 1663 * PTE dirty? Shmem page is already dirty; file is read-only. 1664 */ 1665 clear_ptes(mm, addr, pte, nr_batch_ptes); 1666 folio_remove_rmap_ptes(folio, page, nr_batch_ptes, vma); 1667 nr_mapped_ptes += nr_batch_ptes; 1668 } 1669 1670 if (!pml) 1671 spin_unlock(ptl); 1672 1673 /* step 3: set proper refcount and mm_counters. */ 1674 if (nr_mapped_ptes) { 1675 folio_ref_sub(folio, nr_mapped_ptes); 1676 add_mm_counter(mm, mm_counter_file(folio), -nr_mapped_ptes); 1677 } 1678 1679 /* step 4: remove empty page table */ 1680 if (!pml) { 1681 pml = pmd_lock(mm, pmd); 1682 if (ptl != pml) { 1683 spin_lock_nested(ptl, SINGLE_DEPTH_NESTING); 1684 if (unlikely(!pmd_same(pgt_pmd, pmdp_get_lockless(pmd)))) { 1685 flush_tlb_mm(mm); 1686 goto unlock; 1687 } 1688 } 1689 } 1690 pgt_pmd = pmdp_collapse_flush(vma, haddr, pmd); 1691 pmdp_get_lockless_sync(); 1692 pte_unmap_unlock(start_pte, ptl); 1693 if (ptl != pml) 1694 spin_unlock(pml); 1695 1696 mmu_notifier_invalidate_range_end(&range); 1697 1698 mm_dec_nr_ptes(mm); 1699 page_table_check_pte_clear_range(mm, haddr, pgt_pmd); 1700 pte_free_defer(mm, pmd_pgtable(pgt_pmd)); 1701 1702 maybe_install_pmd: 1703 /* step 5: install pmd entry */ 1704 result = install_pmd 1705 ? set_huge_pmd(vma, haddr, pmd, folio, &folio->page) 1706 : SCAN_SUCCEED; 1707 goto drop_folio; 1708 abort: 1709 if (nr_mapped_ptes) { 1710 flush_tlb_mm(mm); 1711 folio_ref_sub(folio, nr_mapped_ptes); 1712 add_mm_counter(mm, mm_counter_file(folio), -nr_mapped_ptes); 1713 } 1714 unlock: 1715 if (start_pte) 1716 pte_unmap_unlock(start_pte, ptl); 1717 if (pml && pml != ptl) 1718 spin_unlock(pml); 1719 if (notified) 1720 mmu_notifier_invalidate_range_end(&range); 1721 drop_folio: 1722 folio_unlock(folio); 1723 folio_put(folio); 1724 return result; 1725 } 1726 1727 /** 1728 * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at 1729 * address haddr. 1730 * 1731 * @mm: process address space where collapse happens 1732 * @addr: THP collapse address 1733 * @install_pmd: If a huge PMD should be installed 1734 * 1735 * This function checks whether all the PTEs in the PMD are pointing to the 1736 * right THP. If so, retract the page table so the THP can refault in with 1737 * as pmd-mapped. Possibly install a huge PMD mapping the THP. 1738 */ 1739 void collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr, 1740 bool install_pmd) 1741 { 1742 try_collapse_pte_mapped_thp(mm, addr, install_pmd); 1743 } 1744 1745 /* Can we retract page tables for this file-backed VMA? */ 1746 static bool file_backed_vma_is_retractable(struct vm_area_struct *vma) 1747 { 1748 /* 1749 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that 1750 * got written to. These VMAs are likely not worth removing 1751 * page tables from, as PMD-mapping is likely to be split later. 1752 */ 1753 if (READ_ONCE(vma->anon_vma)) 1754 return false; 1755 1756 /* 1757 * When a vma is registered with uffd-wp, we cannot recycle 1758 * the page table because there may be pte markers installed. 1759 * Other vmas can still have the same file mapped hugely, but 1760 * skip this one: it will always be mapped in small page size 1761 * for uffd-wp registered ranges. 1762 */ 1763 if (userfaultfd_wp(vma)) 1764 return false; 1765 1766 /* 1767 * If the VMA contains guard regions then we can't collapse it. 1768 * 1769 * This is set atomically on guard marker installation under mmap/VMA 1770 * read lock, and here we may not hold any VMA or mmap lock at all. 1771 * 1772 * This is therefore serialised on the PTE page table lock, which is 1773 * obtained on guard region installation after the flag is set, so this 1774 * check being performed under this lock excludes races. 1775 */ 1776 if (vma_test_atomic_flag(vma, VMA_MAYBE_GUARD_BIT)) 1777 return false; 1778 1779 return true; 1780 } 1781 1782 static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff) 1783 { 1784 struct vm_area_struct *vma; 1785 1786 i_mmap_lock_read(mapping); 1787 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) { 1788 struct mmu_notifier_range range; 1789 struct mm_struct *mm; 1790 unsigned long addr; 1791 pmd_t *pmd, pgt_pmd; 1792 spinlock_t *pml; 1793 spinlock_t *ptl; 1794 bool success = false; 1795 1796 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT); 1797 if (addr & ~HPAGE_PMD_MASK || 1798 vma->vm_end < addr + HPAGE_PMD_SIZE) 1799 continue; 1800 1801 mm = vma->vm_mm; 1802 if (find_pmd_or_thp_or_none(mm, addr, &pmd) != SCAN_SUCCEED) 1803 continue; 1804 1805 if (collapse_test_exit(mm)) 1806 continue; 1807 1808 if (!file_backed_vma_is_retractable(vma)) 1809 continue; 1810 1811 /* PTEs were notified when unmapped; but now for the PMD? */ 1812 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, 1813 addr, addr + HPAGE_PMD_SIZE); 1814 mmu_notifier_invalidate_range_start(&range); 1815 1816 pml = pmd_lock(mm, pmd); 1817 /* 1818 * The lock of new_folio is still held, we will be blocked in 1819 * the page fault path, which prevents the pte entries from 1820 * being set again. So even though the old empty PTE page may be 1821 * concurrently freed and a new PTE page is filled into the pmd 1822 * entry, it is still empty and can be removed. 1823 * 1824 * So here we only need to recheck if the state of pmd entry 1825 * still meets our requirements, rather than checking pmd_same() 1826 * like elsewhere. 1827 */ 1828 if (check_pmd_state(pmd) != SCAN_SUCCEED) 1829 goto drop_pml; 1830 ptl = pte_lockptr(mm, pmd); 1831 if (ptl != pml) 1832 spin_lock_nested(ptl, SINGLE_DEPTH_NESTING); 1833 1834 /* 1835 * Huge page lock is still held, so normally the page table must 1836 * remain empty; and we have already skipped anon_vma and 1837 * userfaultfd_wp() vmas. But since the mmap_lock is not held, 1838 * it is still possible for a racing userfaultfd_ioctl() or 1839 * madvise() to have inserted ptes or markers. Now that we hold 1840 * ptlock, repeating the retractable checks protects us from 1841 * races against the prior checks. 1842 */ 1843 if (likely(file_backed_vma_is_retractable(vma))) { 1844 pgt_pmd = pmdp_collapse_flush(vma, addr, pmd); 1845 pmdp_get_lockless_sync(); 1846 success = true; 1847 } 1848 1849 if (ptl != pml) 1850 spin_unlock(ptl); 1851 drop_pml: 1852 spin_unlock(pml); 1853 1854 mmu_notifier_invalidate_range_end(&range); 1855 1856 if (success) { 1857 mm_dec_nr_ptes(mm); 1858 page_table_check_pte_clear_range(mm, addr, pgt_pmd); 1859 pte_free_defer(mm, pmd_pgtable(pgt_pmd)); 1860 } 1861 } 1862 i_mmap_unlock_read(mapping); 1863 } 1864 1865 /** 1866 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one. 1867 * 1868 * @mm: process address space where collapse happens 1869 * @addr: virtual collapse start address 1870 * @file: file that collapse on 1871 * @start: collapse start address 1872 * @cc: collapse context and scratchpad 1873 * 1874 * Basic scheme is simple, details are more complex: 1875 * - allocate and lock a new huge page; 1876 * - scan page cache, locking old pages 1877 * + swap/gup in pages if necessary; 1878 * - copy data to new page 1879 * - handle shmem holes 1880 * + re-validate that holes weren't filled by someone else 1881 * + check for userfaultfd 1882 * - finalize updates to the page cache; 1883 * - if replacing succeeds: 1884 * + unlock huge page; 1885 * + free old pages; 1886 * - if replacing failed; 1887 * + unlock old pages 1888 * + unlock and free huge page; 1889 */ 1890 static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr, 1891 struct file *file, pgoff_t start, struct collapse_control *cc) 1892 { 1893 struct address_space *mapping = file->f_mapping; 1894 struct page *dst; 1895 struct folio *folio, *tmp, *new_folio; 1896 pgoff_t index = 0, end = start + HPAGE_PMD_NR; 1897 LIST_HEAD(pagelist); 1898 XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER); 1899 enum scan_result result = SCAN_SUCCEED; 1900 int nr_none = 0; 1901 bool is_shmem = shmem_file(file); 1902 1903 VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem); 1904 VM_BUG_ON(start & (HPAGE_PMD_NR - 1)); 1905 1906 result = alloc_charge_folio(&new_folio, mm, cc); 1907 if (result != SCAN_SUCCEED) 1908 goto out; 1909 1910 mapping_set_update(&xas, mapping); 1911 1912 __folio_set_locked(new_folio); 1913 if (is_shmem) 1914 __folio_set_swapbacked(new_folio); 1915 new_folio->index = start; 1916 new_folio->mapping = mapping; 1917 1918 /* 1919 * Ensure we have slots for all the pages in the range. This is 1920 * almost certainly a no-op because most of the pages must be present 1921 */ 1922 do { 1923 xas_lock_irq(&xas); 1924 xas_create_range(&xas); 1925 if (!xas_error(&xas)) 1926 break; 1927 xas_unlock_irq(&xas); 1928 if (!xas_nomem(&xas, GFP_KERNEL)) { 1929 result = SCAN_FAIL; 1930 goto rollback; 1931 } 1932 } while (1); 1933 1934 for (index = start; index < end;) { 1935 xas_set(&xas, index); 1936 folio = xas_load(&xas); 1937 1938 VM_BUG_ON(index != xas.xa_index); 1939 if (is_shmem) { 1940 if (!folio) { 1941 /* 1942 * Stop if extent has been truncated or 1943 * hole-punched, and is now completely 1944 * empty. 1945 */ 1946 if (index == start) { 1947 if (!xas_next_entry(&xas, end - 1)) { 1948 result = SCAN_TRUNCATED; 1949 goto xa_locked; 1950 } 1951 } 1952 nr_none++; 1953 index++; 1954 continue; 1955 } 1956 1957 if (xa_is_value(folio) || !folio_test_uptodate(folio)) { 1958 xas_unlock_irq(&xas); 1959 /* swap in or instantiate fallocated page */ 1960 if (shmem_get_folio(mapping->host, index, 0, 1961 &folio, SGP_NOALLOC)) { 1962 result = SCAN_FAIL; 1963 goto xa_unlocked; 1964 } 1965 /* drain lru cache to help folio_isolate_lru() */ 1966 lru_add_drain(); 1967 } else if (folio_trylock(folio)) { 1968 folio_get(folio); 1969 xas_unlock_irq(&xas); 1970 } else { 1971 result = SCAN_PAGE_LOCK; 1972 goto xa_locked; 1973 } 1974 } else { /* !is_shmem */ 1975 if (!folio || xa_is_value(folio)) { 1976 xas_unlock_irq(&xas); 1977 page_cache_sync_readahead(mapping, &file->f_ra, 1978 file, index, 1979 end - index); 1980 /* drain lru cache to help folio_isolate_lru() */ 1981 lru_add_drain(); 1982 folio = filemap_lock_folio(mapping, index); 1983 if (IS_ERR(folio)) { 1984 result = SCAN_FAIL; 1985 goto xa_unlocked; 1986 } 1987 } else if (folio_test_dirty(folio)) { 1988 /* 1989 * khugepaged only works on read-only fd, 1990 * so this page is dirty because it hasn't 1991 * been flushed since first write. There 1992 * won't be new dirty pages. 1993 * 1994 * Trigger async flush here and hope the 1995 * writeback is done when khugepaged 1996 * revisits this page. 1997 * 1998 * This is a one-off situation. We are not 1999 * forcing writeback in loop. 2000 */ 2001 xas_unlock_irq(&xas); 2002 filemap_flush(mapping); 2003 result = SCAN_PAGE_DIRTY_OR_WRITEBACK; 2004 goto xa_unlocked; 2005 } else if (folio_test_writeback(folio)) { 2006 xas_unlock_irq(&xas); 2007 result = SCAN_PAGE_DIRTY_OR_WRITEBACK; 2008 goto xa_unlocked; 2009 } else if (folio_trylock(folio)) { 2010 folio_get(folio); 2011 xas_unlock_irq(&xas); 2012 } else { 2013 result = SCAN_PAGE_LOCK; 2014 goto xa_locked; 2015 } 2016 } 2017 2018 /* 2019 * The folio must be locked, so we can drop the i_pages lock 2020 * without racing with truncate. 2021 */ 2022 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 2023 2024 /* make sure the folio is up to date */ 2025 if (unlikely(!folio_test_uptodate(folio))) { 2026 result = SCAN_FAIL; 2027 goto out_unlock; 2028 } 2029 2030 /* 2031 * If file was truncated then extended, or hole-punched, before 2032 * we locked the first folio, then a THP might be there already. 2033 * This will be discovered on the first iteration. 2034 */ 2035 if (is_pmd_order(folio_order(folio))) { 2036 result = SCAN_PTE_MAPPED_HUGEPAGE; 2037 goto out_unlock; 2038 } 2039 2040 if (folio_mapping(folio) != mapping) { 2041 result = SCAN_TRUNCATED; 2042 goto out_unlock; 2043 } 2044 2045 if (!is_shmem && (folio_test_dirty(folio) || 2046 folio_test_writeback(folio))) { 2047 /* 2048 * khugepaged only works on read-only fd, so this 2049 * folio is dirty because it hasn't been flushed 2050 * since first write. 2051 */ 2052 result = SCAN_PAGE_DIRTY_OR_WRITEBACK; 2053 goto out_unlock; 2054 } 2055 2056 if (!folio_isolate_lru(folio)) { 2057 result = SCAN_DEL_PAGE_LRU; 2058 goto out_unlock; 2059 } 2060 2061 if (!filemap_release_folio(folio, GFP_KERNEL)) { 2062 result = SCAN_PAGE_HAS_PRIVATE; 2063 folio_putback_lru(folio); 2064 goto out_unlock; 2065 } 2066 2067 if (folio_mapped(folio)) 2068 try_to_unmap(folio, 2069 TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH); 2070 2071 xas_lock_irq(&xas); 2072 2073 VM_BUG_ON_FOLIO(folio != xa_load(xas.xa, index), folio); 2074 2075 /* 2076 * We control 2 + nr_pages references to the folio: 2077 * - we hold a pin on it; 2078 * - nr_pages reference from page cache; 2079 * - one from lru_isolate_folio; 2080 * If those are the only references, then any new usage 2081 * of the folio will have to fetch it from the page 2082 * cache. That requires locking the folio to handle 2083 * truncate, so any new usage will be blocked until we 2084 * unlock folio after collapse/during rollback. 2085 */ 2086 if (folio_ref_count(folio) != 2 + folio_nr_pages(folio)) { 2087 result = SCAN_PAGE_COUNT; 2088 xas_unlock_irq(&xas); 2089 folio_putback_lru(folio); 2090 goto out_unlock; 2091 } 2092 2093 /* 2094 * Accumulate the folios that are being collapsed. 2095 */ 2096 list_add_tail(&folio->lru, &pagelist); 2097 index += folio_nr_pages(folio); 2098 continue; 2099 out_unlock: 2100 folio_unlock(folio); 2101 folio_put(folio); 2102 goto xa_unlocked; 2103 } 2104 2105 if (!is_shmem) { 2106 filemap_nr_thps_inc(mapping); 2107 /* 2108 * Paired with the fence in do_dentry_open() -> get_write_access() 2109 * to ensure i_writecount is up to date and the update to nr_thps 2110 * is visible. Ensures the page cache will be truncated if the 2111 * file is opened writable. 2112 */ 2113 smp_mb(); 2114 if (inode_is_open_for_write(mapping->host)) { 2115 result = SCAN_FAIL; 2116 filemap_nr_thps_dec(mapping); 2117 } 2118 } 2119 2120 xa_locked: 2121 xas_unlock_irq(&xas); 2122 xa_unlocked: 2123 2124 /* 2125 * If collapse is successful, flush must be done now before copying. 2126 * If collapse is unsuccessful, does flush actually need to be done? 2127 * Do it anyway, to clear the state. 2128 */ 2129 try_to_unmap_flush(); 2130 2131 if (result == SCAN_SUCCEED && nr_none && 2132 !shmem_charge(mapping->host, nr_none)) 2133 result = SCAN_FAIL; 2134 if (result != SCAN_SUCCEED) { 2135 nr_none = 0; 2136 goto rollback; 2137 } 2138 2139 /* 2140 * The old folios are locked, so they won't change anymore. 2141 */ 2142 index = start; 2143 dst = folio_page(new_folio, 0); 2144 list_for_each_entry(folio, &pagelist, lru) { 2145 int i, nr_pages = folio_nr_pages(folio); 2146 2147 while (index < folio->index) { 2148 clear_highpage(dst); 2149 index++; 2150 dst++; 2151 } 2152 2153 for (i = 0; i < nr_pages; i++) { 2154 if (copy_mc_highpage(dst, folio_page(folio, i)) > 0) { 2155 result = SCAN_COPY_MC; 2156 goto rollback; 2157 } 2158 index++; 2159 dst++; 2160 } 2161 } 2162 while (index < end) { 2163 clear_highpage(dst); 2164 index++; 2165 dst++; 2166 } 2167 2168 if (nr_none) { 2169 struct vm_area_struct *vma; 2170 int nr_none_check = 0; 2171 2172 i_mmap_lock_read(mapping); 2173 xas_lock_irq(&xas); 2174 2175 xas_set(&xas, start); 2176 for (index = start; index < end; index++) { 2177 if (!xas_next(&xas)) { 2178 xas_store(&xas, XA_RETRY_ENTRY); 2179 if (xas_error(&xas)) { 2180 result = SCAN_STORE_FAILED; 2181 goto immap_locked; 2182 } 2183 nr_none_check++; 2184 } 2185 } 2186 2187 if (nr_none != nr_none_check) { 2188 result = SCAN_PAGE_FILLED; 2189 goto immap_locked; 2190 } 2191 2192 /* 2193 * If userspace observed a missing page in a VMA with 2194 * a MODE_MISSING userfaultfd, then it might expect a 2195 * UFFD_EVENT_PAGEFAULT for that page. If so, we need to 2196 * roll back to avoid suppressing such an event. Since 2197 * wp/minor userfaultfds don't give userspace any 2198 * guarantees that the kernel doesn't fill a missing 2199 * page with a zero page, so they don't matter here. 2200 * 2201 * Any userfaultfds registered after this point will 2202 * not be able to observe any missing pages due to the 2203 * previously inserted retry entries. 2204 */ 2205 vma_interval_tree_foreach(vma, &mapping->i_mmap, start, end) { 2206 if (userfaultfd_missing(vma)) { 2207 result = SCAN_EXCEED_NONE_PTE; 2208 goto immap_locked; 2209 } 2210 } 2211 2212 immap_locked: 2213 i_mmap_unlock_read(mapping); 2214 if (result != SCAN_SUCCEED) { 2215 xas_set(&xas, start); 2216 for (index = start; index < end; index++) { 2217 if (xas_next(&xas) == XA_RETRY_ENTRY) 2218 xas_store(&xas, NULL); 2219 } 2220 2221 xas_unlock_irq(&xas); 2222 goto rollback; 2223 } 2224 } else { 2225 xas_lock_irq(&xas); 2226 } 2227 2228 if (is_shmem) { 2229 lruvec_stat_mod_folio(new_folio, NR_SHMEM, HPAGE_PMD_NR); 2230 lruvec_stat_mod_folio(new_folio, NR_SHMEM_THPS, HPAGE_PMD_NR); 2231 } else { 2232 lruvec_stat_mod_folio(new_folio, NR_FILE_THPS, HPAGE_PMD_NR); 2233 } 2234 lruvec_stat_mod_folio(new_folio, NR_FILE_PAGES, HPAGE_PMD_NR); 2235 2236 /* 2237 * Mark new_folio as uptodate before inserting it into the 2238 * page cache so that it isn't mistaken for an fallocated but 2239 * unwritten page. 2240 */ 2241 folio_mark_uptodate(new_folio); 2242 folio_ref_add(new_folio, HPAGE_PMD_NR - 1); 2243 2244 if (is_shmem) 2245 folio_mark_dirty(new_folio); 2246 folio_add_lru(new_folio); 2247 2248 /* Join all the small entries into a single multi-index entry. */ 2249 xas_set_order(&xas, start, HPAGE_PMD_ORDER); 2250 xas_store(&xas, new_folio); 2251 WARN_ON_ONCE(xas_error(&xas)); 2252 xas_unlock_irq(&xas); 2253 2254 /* 2255 * Remove pte page tables, so we can re-fault the page as huge. 2256 * If MADV_COLLAPSE, adjust result to call try_collapse_pte_mapped_thp(). 2257 */ 2258 retract_page_tables(mapping, start); 2259 if (cc && !cc->is_khugepaged) 2260 result = SCAN_PTE_MAPPED_HUGEPAGE; 2261 folio_unlock(new_folio); 2262 2263 /* 2264 * The collapse has succeeded, so free the old folios. 2265 */ 2266 list_for_each_entry_safe(folio, tmp, &pagelist, lru) { 2267 list_del(&folio->lru); 2268 lruvec_stat_mod_folio(folio, NR_FILE_PAGES, 2269 -folio_nr_pages(folio)); 2270 if (is_shmem) 2271 lruvec_stat_mod_folio(folio, NR_SHMEM, 2272 -folio_nr_pages(folio)); 2273 folio->mapping = NULL; 2274 folio_clear_active(folio); 2275 folio_clear_unevictable(folio); 2276 folio_unlock(folio); 2277 folio_put_refs(folio, 2 + folio_nr_pages(folio)); 2278 } 2279 2280 goto out; 2281 2282 rollback: 2283 /* Something went wrong: roll back page cache changes */ 2284 if (nr_none) { 2285 xas_lock_irq(&xas); 2286 mapping->nrpages -= nr_none; 2287 xas_unlock_irq(&xas); 2288 shmem_uncharge(mapping->host, nr_none); 2289 } 2290 2291 list_for_each_entry_safe(folio, tmp, &pagelist, lru) { 2292 list_del(&folio->lru); 2293 folio_unlock(folio); 2294 folio_putback_lru(folio); 2295 folio_put(folio); 2296 } 2297 /* 2298 * Undo the updates of filemap_nr_thps_inc for non-SHMEM 2299 * file only. This undo is not needed unless failure is 2300 * due to SCAN_COPY_MC. 2301 */ 2302 if (!is_shmem && result == SCAN_COPY_MC) { 2303 filemap_nr_thps_dec(mapping); 2304 /* 2305 * Paired with the fence in do_dentry_open() -> get_write_access() 2306 * to ensure the update to nr_thps is visible. 2307 */ 2308 smp_mb(); 2309 } 2310 2311 new_folio->mapping = NULL; 2312 2313 folio_unlock(new_folio); 2314 folio_put(new_folio); 2315 out: 2316 VM_BUG_ON(!list_empty(&pagelist)); 2317 trace_mm_khugepaged_collapse_file(mm, new_folio, index, addr, is_shmem, file, HPAGE_PMD_NR, result); 2318 return result; 2319 } 2320 2321 static enum scan_result collapse_scan_file(struct mm_struct *mm, 2322 unsigned long addr, struct file *file, pgoff_t start, 2323 struct collapse_control *cc) 2324 { 2325 struct folio *folio = NULL; 2326 struct address_space *mapping = file->f_mapping; 2327 XA_STATE(xas, &mapping->i_pages, start); 2328 int present, swap; 2329 int node = NUMA_NO_NODE; 2330 enum scan_result result = SCAN_SUCCEED; 2331 2332 present = 0; 2333 swap = 0; 2334 memset(cc->node_load, 0, sizeof(cc->node_load)); 2335 nodes_clear(cc->alloc_nmask); 2336 rcu_read_lock(); 2337 xas_for_each(&xas, folio, start + HPAGE_PMD_NR - 1) { 2338 if (xas_retry(&xas, folio)) 2339 continue; 2340 2341 if (xa_is_value(folio)) { 2342 swap += 1 << xas_get_order(&xas); 2343 if (cc->is_khugepaged && 2344 swap > khugepaged_max_ptes_swap) { 2345 result = SCAN_EXCEED_SWAP_PTE; 2346 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE); 2347 break; 2348 } 2349 continue; 2350 } 2351 2352 if (!folio_try_get(folio)) { 2353 xas_reset(&xas); 2354 continue; 2355 } 2356 2357 if (unlikely(folio != xas_reload(&xas))) { 2358 folio_put(folio); 2359 xas_reset(&xas); 2360 continue; 2361 } 2362 2363 if (is_pmd_order(folio_order(folio))) { 2364 result = SCAN_PTE_MAPPED_HUGEPAGE; 2365 /* 2366 * PMD-sized THP implies that we can only try 2367 * retracting the PTE table. 2368 */ 2369 folio_put(folio); 2370 break; 2371 } 2372 2373 node = folio_nid(folio); 2374 if (collapse_scan_abort(node, cc)) { 2375 result = SCAN_SCAN_ABORT; 2376 folio_put(folio); 2377 break; 2378 } 2379 cc->node_load[node]++; 2380 2381 if (!folio_test_lru(folio)) { 2382 result = SCAN_PAGE_LRU; 2383 folio_put(folio); 2384 break; 2385 } 2386 2387 if (folio_expected_ref_count(folio) + 1 != folio_ref_count(folio)) { 2388 result = SCAN_PAGE_COUNT; 2389 folio_put(folio); 2390 break; 2391 } 2392 2393 /* 2394 * We probably should check if the folio is referenced 2395 * here, but nobody would transfer pte_young() to 2396 * folio_test_referenced() for us. And rmap walk here 2397 * is just too costly... 2398 */ 2399 2400 present += folio_nr_pages(folio); 2401 folio_put(folio); 2402 2403 if (need_resched()) { 2404 xas_pause(&xas); 2405 cond_resched_rcu(); 2406 } 2407 } 2408 rcu_read_unlock(); 2409 if (result == SCAN_PTE_MAPPED_HUGEPAGE) 2410 cc->progress++; 2411 else 2412 cc->progress += HPAGE_PMD_NR; 2413 2414 if (result == SCAN_SUCCEED) { 2415 if (cc->is_khugepaged && 2416 present < HPAGE_PMD_NR - khugepaged_max_ptes_none) { 2417 result = SCAN_EXCEED_NONE_PTE; 2418 count_vm_event(THP_SCAN_EXCEED_NONE_PTE); 2419 } else { 2420 result = collapse_file(mm, addr, file, start, cc); 2421 } 2422 } 2423 2424 trace_mm_khugepaged_scan_file(mm, folio, file, present, swap, result); 2425 return result; 2426 } 2427 2428 /* 2429 * Try to collapse a single PMD starting at a PMD aligned addr, and return 2430 * the results. 2431 */ 2432 static enum scan_result collapse_single_pmd(unsigned long addr, 2433 struct vm_area_struct *vma, bool *lock_dropped, 2434 struct collapse_control *cc) 2435 { 2436 struct mm_struct *mm = vma->vm_mm; 2437 bool triggered_wb = false; 2438 enum scan_result result; 2439 struct file *file; 2440 pgoff_t pgoff; 2441 2442 mmap_assert_locked(mm); 2443 2444 if (vma_is_anonymous(vma)) { 2445 result = collapse_scan_pmd(mm, vma, addr, lock_dropped, cc); 2446 goto end; 2447 } 2448 2449 file = get_file(vma->vm_file); 2450 pgoff = linear_page_index(vma, addr); 2451 2452 mmap_read_unlock(mm); 2453 *lock_dropped = true; 2454 retry: 2455 result = collapse_scan_file(mm, addr, file, pgoff, cc); 2456 2457 /* 2458 * For MADV_COLLAPSE, when encountering dirty pages, try to writeback, 2459 * then retry the collapse one time. 2460 */ 2461 if (!cc->is_khugepaged && result == SCAN_PAGE_DIRTY_OR_WRITEBACK && 2462 !triggered_wb && mapping_can_writeback(file->f_mapping)) { 2463 const loff_t lstart = (loff_t)pgoff << PAGE_SHIFT; 2464 const loff_t lend = lstart + HPAGE_PMD_SIZE - 1; 2465 2466 filemap_write_and_wait_range(file->f_mapping, lstart, lend); 2467 triggered_wb = true; 2468 goto retry; 2469 } 2470 fput(file); 2471 2472 if (result == SCAN_PTE_MAPPED_HUGEPAGE) { 2473 mmap_read_lock(mm); 2474 if (collapse_test_exit_or_disable(mm)) 2475 result = SCAN_ANY_PROCESS; 2476 else 2477 result = try_collapse_pte_mapped_thp(mm, addr, 2478 !cc->is_khugepaged); 2479 if (result == SCAN_PMD_MAPPED) 2480 result = SCAN_SUCCEED; 2481 mmap_read_unlock(mm); 2482 } 2483 end: 2484 if (cc->is_khugepaged && result == SCAN_SUCCEED) 2485 ++khugepaged_pages_collapsed; 2486 return result; 2487 } 2488 2489 static void collapse_scan_mm_slot(unsigned int progress_max, 2490 enum scan_result *result, struct collapse_control *cc) 2491 __releases(&khugepaged_mm_lock) 2492 __acquires(&khugepaged_mm_lock) 2493 { 2494 struct vma_iterator vmi; 2495 struct mm_slot *slot; 2496 struct mm_struct *mm; 2497 struct vm_area_struct *vma; 2498 unsigned int progress_prev = cc->progress; 2499 2500 lockdep_assert_held(&khugepaged_mm_lock); 2501 *result = SCAN_FAIL; 2502 2503 if (khugepaged_scan.mm_slot) { 2504 slot = khugepaged_scan.mm_slot; 2505 } else { 2506 slot = list_first_entry(&khugepaged_scan.mm_head, 2507 struct mm_slot, mm_node); 2508 khugepaged_scan.address = 0; 2509 khugepaged_scan.mm_slot = slot; 2510 } 2511 spin_unlock(&khugepaged_mm_lock); 2512 2513 mm = slot->mm; 2514 /* 2515 * Don't wait for semaphore (to avoid long wait times). Just move to 2516 * the next mm on the list. 2517 */ 2518 vma = NULL; 2519 if (unlikely(!mmap_read_trylock(mm))) 2520 goto breakouterloop_mmap_lock; 2521 2522 cc->progress++; 2523 if (unlikely(collapse_test_exit_or_disable(mm))) 2524 goto breakouterloop; 2525 2526 vma_iter_init(&vmi, mm, khugepaged_scan.address); 2527 for_each_vma(vmi, vma) { 2528 unsigned long hstart, hend; 2529 2530 cond_resched(); 2531 if (unlikely(collapse_test_exit_or_disable(mm))) { 2532 cc->progress++; 2533 break; 2534 } 2535 if (!thp_vma_allowable_order(vma, vma->vm_flags, TVA_KHUGEPAGED, PMD_ORDER)) { 2536 cc->progress++; 2537 continue; 2538 } 2539 hstart = ALIGN(vma->vm_start, HPAGE_PMD_SIZE); 2540 hend = ALIGN_DOWN(vma->vm_end, HPAGE_PMD_SIZE); 2541 if (khugepaged_scan.address > hend) { 2542 cc->progress++; 2543 continue; 2544 } 2545 if (khugepaged_scan.address < hstart) 2546 khugepaged_scan.address = hstart; 2547 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK); 2548 2549 while (khugepaged_scan.address < hend) { 2550 bool lock_dropped = false; 2551 2552 cond_resched(); 2553 if (unlikely(collapse_test_exit_or_disable(mm))) 2554 goto breakouterloop; 2555 2556 VM_WARN_ON_ONCE(khugepaged_scan.address < hstart || 2557 khugepaged_scan.address + HPAGE_PMD_SIZE > 2558 hend); 2559 2560 *result = collapse_single_pmd(khugepaged_scan.address, 2561 vma, &lock_dropped, cc); 2562 /* move to next address */ 2563 khugepaged_scan.address += HPAGE_PMD_SIZE; 2564 if (lock_dropped) 2565 /* 2566 * We released mmap_lock so break loop. Note 2567 * that we drop mmap_lock before all hugepage 2568 * allocations, so if allocation fails, we are 2569 * guaranteed to break here and report the 2570 * correct result back to caller. 2571 */ 2572 goto breakouterloop_mmap_lock; 2573 if (cc->progress >= progress_max) 2574 goto breakouterloop; 2575 } 2576 } 2577 breakouterloop: 2578 mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */ 2579 breakouterloop_mmap_lock: 2580 2581 spin_lock(&khugepaged_mm_lock); 2582 VM_BUG_ON(khugepaged_scan.mm_slot != slot); 2583 /* 2584 * Release the current mm_slot if this mm is about to die, or 2585 * if we scanned all vmas of this mm, or THP got disabled. 2586 */ 2587 if (collapse_test_exit_or_disable(mm) || !vma) { 2588 /* 2589 * Make sure that if mm_users is reaching zero while 2590 * khugepaged runs here, khugepaged_exit will find 2591 * mm_slot not pointing to the exiting mm. 2592 */ 2593 if (!list_is_last(&slot->mm_node, &khugepaged_scan.mm_head)) { 2594 khugepaged_scan.mm_slot = list_next_entry(slot, mm_node); 2595 khugepaged_scan.address = 0; 2596 } else { 2597 khugepaged_scan.mm_slot = NULL; 2598 khugepaged_full_scans++; 2599 } 2600 2601 collect_mm_slot(slot); 2602 } 2603 2604 trace_mm_khugepaged_scan(mm, cc->progress - progress_prev, 2605 khugepaged_scan.mm_slot == NULL); 2606 } 2607 2608 static int khugepaged_has_work(void) 2609 { 2610 return !list_empty(&khugepaged_scan.mm_head) && hugepage_pmd_enabled(); 2611 } 2612 2613 static int khugepaged_wait_event(void) 2614 { 2615 return !list_empty(&khugepaged_scan.mm_head) || 2616 kthread_should_stop(); 2617 } 2618 2619 static void khugepaged_do_scan(struct collapse_control *cc) 2620 { 2621 const unsigned int progress_max = READ_ONCE(khugepaged_pages_to_scan); 2622 unsigned int pass_through_head = 0; 2623 bool wait = true; 2624 enum scan_result result = SCAN_SUCCEED; 2625 2626 lru_add_drain_all(); 2627 2628 cc->progress = 0; 2629 while (true) { 2630 cond_resched(); 2631 2632 if (unlikely(kthread_should_stop())) 2633 break; 2634 2635 spin_lock(&khugepaged_mm_lock); 2636 if (!khugepaged_scan.mm_slot) 2637 pass_through_head++; 2638 if (khugepaged_has_work() && 2639 pass_through_head < 2) 2640 collapse_scan_mm_slot(progress_max, &result, cc); 2641 else 2642 cc->progress = progress_max; 2643 spin_unlock(&khugepaged_mm_lock); 2644 2645 if (cc->progress >= progress_max) 2646 break; 2647 2648 if (result == SCAN_ALLOC_HUGE_PAGE_FAIL) { 2649 /* 2650 * If fail to allocate the first time, try to sleep for 2651 * a while. When hit again, cancel the scan. 2652 */ 2653 if (!wait) 2654 break; 2655 wait = false; 2656 khugepaged_alloc_sleep(); 2657 } 2658 } 2659 } 2660 2661 static bool khugepaged_should_wakeup(void) 2662 { 2663 return kthread_should_stop() || 2664 time_after_eq(jiffies, khugepaged_sleep_expire); 2665 } 2666 2667 static void khugepaged_wait_work(void) 2668 { 2669 if (khugepaged_has_work()) { 2670 const unsigned long scan_sleep_jiffies = 2671 msecs_to_jiffies(khugepaged_scan_sleep_millisecs); 2672 2673 if (!scan_sleep_jiffies) 2674 return; 2675 2676 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies; 2677 wait_event_freezable_timeout(khugepaged_wait, 2678 khugepaged_should_wakeup(), 2679 scan_sleep_jiffies); 2680 return; 2681 } 2682 2683 if (hugepage_pmd_enabled()) 2684 wait_event_freezable(khugepaged_wait, khugepaged_wait_event()); 2685 } 2686 2687 static int khugepaged(void *none) 2688 { 2689 struct mm_slot *slot; 2690 2691 set_freezable(); 2692 set_user_nice(current, MAX_NICE); 2693 2694 while (!kthread_should_stop()) { 2695 khugepaged_do_scan(&khugepaged_collapse_control); 2696 khugepaged_wait_work(); 2697 } 2698 2699 spin_lock(&khugepaged_mm_lock); 2700 slot = khugepaged_scan.mm_slot; 2701 khugepaged_scan.mm_slot = NULL; 2702 if (slot) 2703 collect_mm_slot(slot); 2704 spin_unlock(&khugepaged_mm_lock); 2705 return 0; 2706 } 2707 2708 void set_recommended_min_free_kbytes(void) 2709 { 2710 struct zone *zone; 2711 int nr_zones = 0; 2712 unsigned long recommended_min; 2713 2714 if (!hugepage_pmd_enabled()) { 2715 calculate_min_free_kbytes(); 2716 goto update_wmarks; 2717 } 2718 2719 for_each_populated_zone(zone) { 2720 /* 2721 * We don't need to worry about fragmentation of 2722 * ZONE_MOVABLE since it only has movable pages. 2723 */ 2724 if (zone_idx(zone) > gfp_zone(GFP_USER)) 2725 continue; 2726 2727 nr_zones++; 2728 } 2729 2730 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */ 2731 recommended_min = pageblock_nr_pages * nr_zones * 2; 2732 2733 /* 2734 * Make sure that on average at least two pageblocks are almost free 2735 * of another type, one for a migratetype to fall back to and a 2736 * second to avoid subsequent fallbacks of other types There are 3 2737 * MIGRATE_TYPES we care about. 2738 */ 2739 recommended_min += pageblock_nr_pages * nr_zones * 2740 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES; 2741 2742 /* don't ever allow to reserve more than 5% of the lowmem */ 2743 recommended_min = min(recommended_min, 2744 (unsigned long) nr_free_buffer_pages() / 20); 2745 recommended_min <<= (PAGE_SHIFT-10); 2746 2747 if (recommended_min > min_free_kbytes) { 2748 if (user_min_free_kbytes >= 0) 2749 pr_info_ratelimited("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n", 2750 min_free_kbytes, recommended_min); 2751 2752 min_free_kbytes = recommended_min; 2753 } 2754 2755 update_wmarks: 2756 setup_per_zone_wmarks(); 2757 } 2758 2759 int start_stop_khugepaged(void) 2760 { 2761 int err = 0; 2762 2763 mutex_lock(&khugepaged_mutex); 2764 if (hugepage_pmd_enabled()) { 2765 if (!khugepaged_thread) 2766 khugepaged_thread = kthread_run(khugepaged, NULL, 2767 "khugepaged"); 2768 if (IS_ERR(khugepaged_thread)) { 2769 pr_err("khugepaged: kthread_run(khugepaged) failed\n"); 2770 err = PTR_ERR(khugepaged_thread); 2771 khugepaged_thread = NULL; 2772 goto fail; 2773 } 2774 2775 if (!list_empty(&khugepaged_scan.mm_head)) 2776 wake_up_interruptible(&khugepaged_wait); 2777 } else if (khugepaged_thread) { 2778 kthread_stop(khugepaged_thread); 2779 khugepaged_thread = NULL; 2780 } 2781 set_recommended_min_free_kbytes(); 2782 fail: 2783 mutex_unlock(&khugepaged_mutex); 2784 return err; 2785 } 2786 2787 void khugepaged_min_free_kbytes_update(void) 2788 { 2789 mutex_lock(&khugepaged_mutex); 2790 if (hugepage_pmd_enabled() && khugepaged_thread) 2791 set_recommended_min_free_kbytes(); 2792 mutex_unlock(&khugepaged_mutex); 2793 } 2794 2795 bool current_is_khugepaged(void) 2796 { 2797 return kthread_func(current) == khugepaged; 2798 } 2799 2800 static int madvise_collapse_errno(enum scan_result r) 2801 { 2802 /* 2803 * MADV_COLLAPSE breaks from existing madvise(2) conventions to provide 2804 * actionable feedback to caller, so they may take an appropriate 2805 * fallback measure depending on the nature of the failure. 2806 */ 2807 switch (r) { 2808 case SCAN_ALLOC_HUGE_PAGE_FAIL: 2809 return -ENOMEM; 2810 case SCAN_CGROUP_CHARGE_FAIL: 2811 case SCAN_EXCEED_NONE_PTE: 2812 return -EBUSY; 2813 /* Resource temporary unavailable - trying again might succeed */ 2814 case SCAN_PAGE_COUNT: 2815 case SCAN_PAGE_LOCK: 2816 case SCAN_PAGE_LRU: 2817 case SCAN_DEL_PAGE_LRU: 2818 case SCAN_PAGE_FILLED: 2819 case SCAN_PAGE_HAS_PRIVATE: 2820 case SCAN_PAGE_DIRTY_OR_WRITEBACK: 2821 return -EAGAIN; 2822 /* 2823 * Other: Trying again likely not to succeed / error intrinsic to 2824 * specified memory range. khugepaged likely won't be able to collapse 2825 * either. 2826 */ 2827 default: 2828 return -EINVAL; 2829 } 2830 } 2831 2832 int madvise_collapse(struct vm_area_struct *vma, unsigned long start, 2833 unsigned long end, bool *lock_dropped) 2834 { 2835 struct collapse_control *cc; 2836 struct mm_struct *mm = vma->vm_mm; 2837 unsigned long hstart, hend, addr; 2838 enum scan_result last_fail = SCAN_FAIL; 2839 int thps = 0; 2840 bool mmap_unlocked = false; 2841 2842 BUG_ON(vma->vm_start > start); 2843 BUG_ON(vma->vm_end < end); 2844 2845 if (!thp_vma_allowable_order(vma, vma->vm_flags, TVA_FORCED_COLLAPSE, PMD_ORDER)) 2846 return -EINVAL; 2847 2848 cc = kmalloc_obj(*cc); 2849 if (!cc) 2850 return -ENOMEM; 2851 cc->is_khugepaged = false; 2852 cc->progress = 0; 2853 2854 mmgrab(mm); 2855 lru_add_drain_all(); 2856 2857 hstart = ALIGN(start, HPAGE_PMD_SIZE); 2858 hend = ALIGN_DOWN(end, HPAGE_PMD_SIZE); 2859 2860 for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) { 2861 enum scan_result result = SCAN_FAIL; 2862 2863 if (mmap_unlocked) { 2864 cond_resched(); 2865 mmap_read_lock(mm); 2866 mmap_unlocked = false; 2867 *lock_dropped = true; 2868 result = hugepage_vma_revalidate(mm, addr, false, &vma, 2869 cc); 2870 if (result != SCAN_SUCCEED) { 2871 last_fail = result; 2872 goto out_nolock; 2873 } 2874 2875 hend = min(hend, vma->vm_end & HPAGE_PMD_MASK); 2876 } 2877 2878 result = collapse_single_pmd(addr, vma, &mmap_unlocked, cc); 2879 2880 switch (result) { 2881 case SCAN_SUCCEED: 2882 case SCAN_PMD_MAPPED: 2883 ++thps; 2884 break; 2885 /* Whitelisted set of results where continuing OK */ 2886 case SCAN_NO_PTE_TABLE: 2887 case SCAN_PTE_NON_PRESENT: 2888 case SCAN_PTE_UFFD_WP: 2889 case SCAN_LACK_REFERENCED_PAGE: 2890 case SCAN_PAGE_NULL: 2891 case SCAN_PAGE_COUNT: 2892 case SCAN_PAGE_LOCK: 2893 case SCAN_PAGE_COMPOUND: 2894 case SCAN_PAGE_LRU: 2895 case SCAN_DEL_PAGE_LRU: 2896 last_fail = result; 2897 break; 2898 default: 2899 last_fail = result; 2900 /* Other error, exit */ 2901 goto out_maybelock; 2902 } 2903 } 2904 2905 out_maybelock: 2906 /* Caller expects us to hold mmap_lock on return */ 2907 if (mmap_unlocked) { 2908 *lock_dropped = true; 2909 mmap_read_lock(mm); 2910 } 2911 out_nolock: 2912 mmap_assert_locked(mm); 2913 mmdrop(mm); 2914 kfree(cc); 2915 2916 return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0 2917 : madvise_collapse_errno(last_fail); 2918 } 2919