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 mmap_read_lock(mm); 1127 result = hugepage_vma_revalidate(mm, address, true, &vma, cc); 1128 if (result != SCAN_SUCCEED) { 1129 mmap_read_unlock(mm); 1130 goto out_nolock; 1131 } 1132 1133 result = find_pmd_or_thp_or_none(mm, address, &pmd); 1134 if (result != SCAN_SUCCEED) { 1135 mmap_read_unlock(mm); 1136 goto out_nolock; 1137 } 1138 1139 if (unmapped) { 1140 /* 1141 * __collapse_huge_page_swapin will return with mmap_lock 1142 * released when it fails. So we jump out_nolock directly in 1143 * that case. Continuing to collapse causes inconsistency. 1144 */ 1145 result = __collapse_huge_page_swapin(mm, vma, address, pmd, 1146 referenced); 1147 if (result != SCAN_SUCCEED) 1148 goto out_nolock; 1149 } 1150 1151 mmap_read_unlock(mm); 1152 /* 1153 * Prevent all access to pagetables with the exception of 1154 * gup_fast later handled by the ptep_clear_flush and the VM 1155 * handled by the anon_vma lock + PG_lock. 1156 * 1157 * UFFDIO_MOVE is prevented to race as well thanks to the 1158 * mmap_lock. 1159 */ 1160 mmap_write_lock(mm); 1161 result = hugepage_vma_revalidate(mm, address, true, &vma, cc); 1162 if (result != SCAN_SUCCEED) 1163 goto out_up_write; 1164 /* check if the pmd is still valid */ 1165 vma_start_write(vma); 1166 result = check_pmd_still_valid(mm, address, pmd); 1167 if (result != SCAN_SUCCEED) 1168 goto out_up_write; 1169 1170 anon_vma_lock_write(vma->anon_vma); 1171 1172 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, address, 1173 address + HPAGE_PMD_SIZE); 1174 mmu_notifier_invalidate_range_start(&range); 1175 1176 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */ 1177 /* 1178 * This removes any huge TLB entry from the CPU so we won't allow 1179 * huge and small TLB entries for the same virtual address to 1180 * avoid the risk of CPU bugs in that area. 1181 * 1182 * Parallel GUP-fast is fine since GUP-fast will back off when 1183 * it detects PMD is changed. 1184 */ 1185 _pmd = pmdp_collapse_flush(vma, address, pmd); 1186 spin_unlock(pmd_ptl); 1187 mmu_notifier_invalidate_range_end(&range); 1188 tlb_remove_table_sync_one(); 1189 1190 pte = pte_offset_map_lock(mm, &_pmd, address, &pte_ptl); 1191 if (pte) { 1192 result = __collapse_huge_page_isolate(vma, address, pte, cc, 1193 &compound_pagelist); 1194 spin_unlock(pte_ptl); 1195 } else { 1196 result = SCAN_NO_PTE_TABLE; 1197 } 1198 1199 if (unlikely(result != SCAN_SUCCEED)) { 1200 if (pte) 1201 pte_unmap(pte); 1202 spin_lock(pmd_ptl); 1203 BUG_ON(!pmd_none(*pmd)); 1204 /* 1205 * We can only use set_pmd_at when establishing 1206 * hugepmds and never for establishing regular pmds that 1207 * points to regular pagetables. Use pmd_populate for that 1208 */ 1209 pmd_populate(mm, pmd, pmd_pgtable(_pmd)); 1210 spin_unlock(pmd_ptl); 1211 anon_vma_unlock_write(vma->anon_vma); 1212 goto out_up_write; 1213 } 1214 1215 /* 1216 * All pages are isolated and locked so anon_vma rmap 1217 * can't run anymore. 1218 */ 1219 anon_vma_unlock_write(vma->anon_vma); 1220 1221 result = __collapse_huge_page_copy(pte, folio, pmd, _pmd, 1222 vma, address, pte_ptl, 1223 &compound_pagelist); 1224 pte_unmap(pte); 1225 if (unlikely(result != SCAN_SUCCEED)) 1226 goto out_up_write; 1227 1228 /* 1229 * The smp_wmb() inside __folio_mark_uptodate() ensures the 1230 * copy_huge_page writes become visible before the set_pmd_at() 1231 * write. 1232 */ 1233 __folio_mark_uptodate(folio); 1234 pgtable = pmd_pgtable(_pmd); 1235 1236 spin_lock(pmd_ptl); 1237 BUG_ON(!pmd_none(*pmd)); 1238 pgtable_trans_huge_deposit(mm, pmd, pgtable); 1239 map_anon_folio_pmd_nopf(folio, pmd, vma, address); 1240 spin_unlock(pmd_ptl); 1241 1242 folio = NULL; 1243 1244 result = SCAN_SUCCEED; 1245 out_up_write: 1246 mmap_write_unlock(mm); 1247 out_nolock: 1248 if (folio) 1249 folio_put(folio); 1250 trace_mm_collapse_huge_page(mm, result == SCAN_SUCCEED, result); 1251 return result; 1252 } 1253 1254 static enum scan_result collapse_scan_pmd(struct mm_struct *mm, 1255 struct vm_area_struct *vma, unsigned long start_addr, 1256 bool *lock_dropped, struct collapse_control *cc) 1257 { 1258 pmd_t *pmd; 1259 pte_t *pte, *_pte; 1260 int none_or_zero = 0, shared = 0, referenced = 0; 1261 enum scan_result result = SCAN_FAIL; 1262 struct page *page = NULL; 1263 struct folio *folio = NULL; 1264 unsigned long addr; 1265 spinlock_t *ptl; 1266 int node = NUMA_NO_NODE, unmapped = 0; 1267 1268 VM_BUG_ON(start_addr & ~HPAGE_PMD_MASK); 1269 1270 result = find_pmd_or_thp_or_none(mm, start_addr, &pmd); 1271 if (result != SCAN_SUCCEED) { 1272 cc->progress++; 1273 goto out; 1274 } 1275 1276 memset(cc->node_load, 0, sizeof(cc->node_load)); 1277 nodes_clear(cc->alloc_nmask); 1278 pte = pte_offset_map_lock(mm, pmd, start_addr, &ptl); 1279 if (!pte) { 1280 cc->progress++; 1281 result = SCAN_NO_PTE_TABLE; 1282 goto out; 1283 } 1284 1285 for (addr = start_addr, _pte = pte; _pte < pte + HPAGE_PMD_NR; 1286 _pte++, addr += PAGE_SIZE) { 1287 cc->progress++; 1288 1289 pte_t pteval = ptep_get(_pte); 1290 if (pte_none_or_zero(pteval)) { 1291 ++none_or_zero; 1292 if (!userfaultfd_armed(vma) && 1293 (!cc->is_khugepaged || 1294 none_or_zero <= khugepaged_max_ptes_none)) { 1295 continue; 1296 } else { 1297 result = SCAN_EXCEED_NONE_PTE; 1298 count_vm_event(THP_SCAN_EXCEED_NONE_PTE); 1299 goto out_unmap; 1300 } 1301 } 1302 if (!pte_present(pteval)) { 1303 ++unmapped; 1304 if (!cc->is_khugepaged || 1305 unmapped <= khugepaged_max_ptes_swap) { 1306 /* 1307 * Always be strict with uffd-wp 1308 * enabled swap entries. Please see 1309 * comment below for pte_uffd_wp(). 1310 */ 1311 if (pte_swp_uffd_wp_any(pteval)) { 1312 result = SCAN_PTE_UFFD_WP; 1313 goto out_unmap; 1314 } 1315 continue; 1316 } else { 1317 result = SCAN_EXCEED_SWAP_PTE; 1318 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE); 1319 goto out_unmap; 1320 } 1321 } 1322 if (pte_uffd_wp(pteval)) { 1323 /* 1324 * Don't collapse the page if any of the small 1325 * PTEs are armed with uffd write protection. 1326 * Here we can also mark the new huge pmd as 1327 * write protected if any of the small ones is 1328 * marked but that could bring unknown 1329 * userfault messages that falls outside of 1330 * the registered range. So, just be simple. 1331 */ 1332 result = SCAN_PTE_UFFD_WP; 1333 goto out_unmap; 1334 } 1335 1336 page = vm_normal_page(vma, addr, pteval); 1337 if (unlikely(!page) || unlikely(is_zone_device_page(page))) { 1338 result = SCAN_PAGE_NULL; 1339 goto out_unmap; 1340 } 1341 folio = page_folio(page); 1342 1343 /* 1344 * If the vma has the VM_DROPPABLE flag, the collapse will 1345 * preserve the lazyfree property without needing to skip. 1346 */ 1347 if (cc->is_khugepaged && !(vma->vm_flags & VM_DROPPABLE) && 1348 folio_test_lazyfree(folio) && !pte_dirty(pteval)) { 1349 result = SCAN_PAGE_LAZYFREE; 1350 goto out_unmap; 1351 } 1352 1353 if (!folio_test_anon(folio)) { 1354 result = SCAN_PAGE_ANON; 1355 goto out_unmap; 1356 } 1357 1358 /* 1359 * We treat a single page as shared if any part of the THP 1360 * is shared. 1361 */ 1362 if (folio_maybe_mapped_shared(folio)) { 1363 ++shared; 1364 if (cc->is_khugepaged && 1365 shared > khugepaged_max_ptes_shared) { 1366 result = SCAN_EXCEED_SHARED_PTE; 1367 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE); 1368 goto out_unmap; 1369 } 1370 } 1371 1372 /* 1373 * Record which node the original page is from and save this 1374 * information to cc->node_load[]. 1375 * Khugepaged will allocate hugepage from the node has the max 1376 * hit record. 1377 */ 1378 node = folio_nid(folio); 1379 if (collapse_scan_abort(node, cc)) { 1380 result = SCAN_SCAN_ABORT; 1381 goto out_unmap; 1382 } 1383 cc->node_load[node]++; 1384 if (!folio_test_lru(folio)) { 1385 result = SCAN_PAGE_LRU; 1386 goto out_unmap; 1387 } 1388 if (folio_test_locked(folio)) { 1389 result = SCAN_PAGE_LOCK; 1390 goto out_unmap; 1391 } 1392 1393 /* 1394 * Check if the page has any GUP (or other external) pins. 1395 * 1396 * Here the check may be racy: 1397 * it may see folio_mapcount() > folio_ref_count(). 1398 * But such case is ephemeral we could always retry collapse 1399 * later. However it may report false positive if the page 1400 * has excessive GUP pins (i.e. 512). Anyway the same check 1401 * will be done again later the risk seems low. 1402 */ 1403 if (folio_expected_ref_count(folio) != folio_ref_count(folio)) { 1404 result = SCAN_PAGE_COUNT; 1405 goto out_unmap; 1406 } 1407 1408 /* 1409 * If collapse was initiated by khugepaged, check that there is 1410 * enough young pte to justify collapsing the page 1411 */ 1412 if (cc->is_khugepaged && 1413 (pte_young(pteval) || folio_test_young(folio) || 1414 folio_test_referenced(folio) || 1415 mmu_notifier_test_young(vma->vm_mm, addr))) 1416 referenced++; 1417 } 1418 if (cc->is_khugepaged && 1419 (!referenced || 1420 (unmapped && referenced < HPAGE_PMD_NR / 2))) { 1421 result = SCAN_LACK_REFERENCED_PAGE; 1422 } else { 1423 result = SCAN_SUCCEED; 1424 } 1425 out_unmap: 1426 pte_unmap_unlock(pte, ptl); 1427 if (result == SCAN_SUCCEED) { 1428 result = collapse_huge_page(mm, start_addr, referenced, 1429 unmapped, cc); 1430 /* collapse_huge_page will return with the mmap_lock released */ 1431 *lock_dropped = true; 1432 } 1433 out: 1434 trace_mm_khugepaged_scan_pmd(mm, folio, referenced, 1435 none_or_zero, result, unmapped); 1436 return result; 1437 } 1438 1439 static void collect_mm_slot(struct mm_slot *slot) 1440 { 1441 struct mm_struct *mm = slot->mm; 1442 1443 lockdep_assert_held(&khugepaged_mm_lock); 1444 1445 if (collapse_test_exit(mm)) { 1446 /* free mm_slot */ 1447 hash_del(&slot->hash); 1448 list_del(&slot->mm_node); 1449 1450 /* 1451 * Not strictly needed because the mm exited already. 1452 * 1453 * mm_flags_clear(MMF_VM_HUGEPAGE, mm); 1454 */ 1455 1456 /* khugepaged_mm_lock actually not necessary for the below */ 1457 mm_slot_free(mm_slot_cache, slot); 1458 mmdrop(mm); 1459 } 1460 } 1461 1462 /* folio must be locked, and mmap_lock must be held */ 1463 static enum scan_result set_huge_pmd(struct vm_area_struct *vma, unsigned long addr, 1464 pmd_t *pmdp, struct folio *folio, struct page *page) 1465 { 1466 struct mm_struct *mm = vma->vm_mm; 1467 struct vm_fault vmf = { 1468 .vma = vma, 1469 .address = addr, 1470 .flags = 0, 1471 }; 1472 pgd_t *pgdp; 1473 p4d_t *p4dp; 1474 pud_t *pudp; 1475 1476 mmap_assert_locked(vma->vm_mm); 1477 1478 if (!pmdp) { 1479 pgdp = pgd_offset(mm, addr); 1480 p4dp = p4d_alloc(mm, pgdp, addr); 1481 if (!p4dp) 1482 return SCAN_FAIL; 1483 pudp = pud_alloc(mm, p4dp, addr); 1484 if (!pudp) 1485 return SCAN_FAIL; 1486 pmdp = pmd_alloc(mm, pudp, addr); 1487 if (!pmdp) 1488 return SCAN_FAIL; 1489 } 1490 1491 vmf.pmd = pmdp; 1492 if (do_set_pmd(&vmf, folio, page)) 1493 return SCAN_FAIL; 1494 1495 folio_get(folio); 1496 return SCAN_SUCCEED; 1497 } 1498 1499 static enum scan_result try_collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr, 1500 bool install_pmd) 1501 { 1502 enum scan_result result = SCAN_FAIL; 1503 int nr_mapped_ptes = 0; 1504 unsigned int nr_batch_ptes; 1505 struct mmu_notifier_range range; 1506 bool notified = false; 1507 unsigned long haddr = addr & HPAGE_PMD_MASK; 1508 unsigned long end = haddr + HPAGE_PMD_SIZE; 1509 struct vm_area_struct *vma = vma_lookup(mm, haddr); 1510 struct folio *folio; 1511 pte_t *start_pte, *pte; 1512 pmd_t *pmd, pgt_pmd; 1513 spinlock_t *pml = NULL, *ptl; 1514 int i; 1515 1516 mmap_assert_locked(mm); 1517 1518 /* First check VMA found, in case page tables are being torn down */ 1519 if (!vma || !vma->vm_file || 1520 !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE)) 1521 return SCAN_VMA_CHECK; 1522 1523 /* Fast check before locking page if already PMD-mapped */ 1524 result = find_pmd_or_thp_or_none(mm, haddr, &pmd); 1525 if (result == SCAN_PMD_MAPPED) 1526 return result; 1527 1528 /* 1529 * If we are here, we've succeeded in replacing all the native pages 1530 * in the page cache with a single hugepage. If a mm were to fault-in 1531 * this memory (mapped by a suitably aligned VMA), we'd get the hugepage 1532 * and map it by a PMD, regardless of sysfs THP settings. As such, let's 1533 * analogously elide sysfs THP settings here and force collapse. 1534 */ 1535 if (!thp_vma_allowable_order(vma, vma->vm_flags, TVA_FORCED_COLLAPSE, PMD_ORDER)) 1536 return SCAN_VMA_CHECK; 1537 1538 /* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */ 1539 if (userfaultfd_wp(vma)) 1540 return SCAN_PTE_UFFD_WP; 1541 1542 folio = filemap_lock_folio(vma->vm_file->f_mapping, 1543 linear_page_index(vma, haddr)); 1544 if (IS_ERR(folio)) 1545 return SCAN_PAGE_NULL; 1546 1547 if (!is_pmd_order(folio_order(folio))) { 1548 result = SCAN_PAGE_COMPOUND; 1549 goto drop_folio; 1550 } 1551 1552 result = find_pmd_or_thp_or_none(mm, haddr, &pmd); 1553 switch (result) { 1554 case SCAN_SUCCEED: 1555 break; 1556 case SCAN_NO_PTE_TABLE: 1557 /* 1558 * All pte entries have been removed and pmd cleared. 1559 * Skip all the pte checks and just update the pmd mapping. 1560 */ 1561 goto maybe_install_pmd; 1562 default: 1563 goto drop_folio; 1564 } 1565 1566 result = SCAN_FAIL; 1567 start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl); 1568 if (!start_pte) /* mmap_lock + page lock should prevent this */ 1569 goto drop_folio; 1570 1571 /* step 1: check all mapped PTEs are to the right huge page */ 1572 for (i = 0, addr = haddr, pte = start_pte; 1573 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) { 1574 struct page *page; 1575 pte_t ptent = ptep_get(pte); 1576 1577 /* empty pte, skip */ 1578 if (pte_none(ptent)) 1579 continue; 1580 1581 /* page swapped out, abort */ 1582 if (!pte_present(ptent)) { 1583 result = SCAN_PTE_NON_PRESENT; 1584 goto abort; 1585 } 1586 1587 page = vm_normal_page(vma, addr, ptent); 1588 if (WARN_ON_ONCE(page && is_zone_device_page(page))) 1589 page = NULL; 1590 /* 1591 * Note that uprobe, debugger, or MAP_PRIVATE may change the 1592 * page table, but the new page will not be a subpage of hpage. 1593 */ 1594 if (folio_page(folio, i) != page) 1595 goto abort; 1596 } 1597 1598 pte_unmap_unlock(start_pte, ptl); 1599 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, 1600 haddr, haddr + HPAGE_PMD_SIZE); 1601 mmu_notifier_invalidate_range_start(&range); 1602 notified = true; 1603 1604 /* 1605 * pmd_lock covers a wider range than ptl, and (if split from mm's 1606 * page_table_lock) ptl nests inside pml. The less time we hold pml, 1607 * the better; but userfaultfd's mfill_atomic_pte() on a private VMA 1608 * inserts a valid as-if-COWed PTE without even looking up page cache. 1609 * So page lock of folio does not protect from it, so we must not drop 1610 * ptl before pgt_pmd is removed, so uffd private needs pml taken now. 1611 */ 1612 if (userfaultfd_armed(vma) && !(vma->vm_flags & VM_SHARED)) 1613 pml = pmd_lock(mm, pmd); 1614 1615 start_pte = pte_offset_map_rw_nolock(mm, pmd, haddr, &pgt_pmd, &ptl); 1616 if (!start_pte) /* mmap_lock + page lock should prevent this */ 1617 goto abort; 1618 if (!pml) 1619 spin_lock(ptl); 1620 else if (ptl != pml) 1621 spin_lock_nested(ptl, SINGLE_DEPTH_NESTING); 1622 1623 if (unlikely(!pmd_same(pgt_pmd, pmdp_get_lockless(pmd)))) 1624 goto abort; 1625 1626 /* step 2: clear page table and adjust rmap */ 1627 for (i = 0, addr = haddr, pte = start_pte; i < HPAGE_PMD_NR; 1628 i += nr_batch_ptes, addr += nr_batch_ptes * PAGE_SIZE, 1629 pte += nr_batch_ptes) { 1630 unsigned int max_nr_batch_ptes = (end - addr) >> PAGE_SHIFT; 1631 struct page *page; 1632 pte_t ptent = ptep_get(pte); 1633 1634 nr_batch_ptes = 1; 1635 1636 if (pte_none(ptent)) 1637 continue; 1638 /* 1639 * We dropped ptl after the first scan, to do the mmu_notifier: 1640 * page lock stops more PTEs of the folio being faulted in, but 1641 * does not stop write faults COWing anon copies from existing 1642 * PTEs; and does not stop those being swapped out or migrated. 1643 */ 1644 if (!pte_present(ptent)) { 1645 result = SCAN_PTE_NON_PRESENT; 1646 goto abort; 1647 } 1648 page = vm_normal_page(vma, addr, ptent); 1649 1650 if (folio_page(folio, i) != page) 1651 goto abort; 1652 1653 nr_batch_ptes = folio_pte_batch(folio, pte, ptent, max_nr_batch_ptes); 1654 1655 /* 1656 * Must clear entry, or a racing truncate may re-remove it. 1657 * TLB flush can be left until pmdp_collapse_flush() does it. 1658 * PTE dirty? Shmem page is already dirty; file is read-only. 1659 */ 1660 clear_ptes(mm, addr, pte, nr_batch_ptes); 1661 folio_remove_rmap_ptes(folio, page, nr_batch_ptes, vma); 1662 nr_mapped_ptes += nr_batch_ptes; 1663 } 1664 1665 if (!pml) 1666 spin_unlock(ptl); 1667 1668 /* step 3: set proper refcount and mm_counters. */ 1669 if (nr_mapped_ptes) { 1670 folio_ref_sub(folio, nr_mapped_ptes); 1671 add_mm_counter(mm, mm_counter_file(folio), -nr_mapped_ptes); 1672 } 1673 1674 /* step 4: remove empty page table */ 1675 if (!pml) { 1676 pml = pmd_lock(mm, pmd); 1677 if (ptl != pml) { 1678 spin_lock_nested(ptl, SINGLE_DEPTH_NESTING); 1679 if (unlikely(!pmd_same(pgt_pmd, pmdp_get_lockless(pmd)))) { 1680 flush_tlb_mm(mm); 1681 goto unlock; 1682 } 1683 } 1684 } 1685 pgt_pmd = pmdp_collapse_flush(vma, haddr, pmd); 1686 pmdp_get_lockless_sync(); 1687 pte_unmap_unlock(start_pte, ptl); 1688 if (ptl != pml) 1689 spin_unlock(pml); 1690 1691 mmu_notifier_invalidate_range_end(&range); 1692 1693 mm_dec_nr_ptes(mm); 1694 page_table_check_pte_clear_range(mm, haddr, pgt_pmd); 1695 pte_free_defer(mm, pmd_pgtable(pgt_pmd)); 1696 1697 maybe_install_pmd: 1698 /* step 5: install pmd entry */ 1699 result = install_pmd 1700 ? set_huge_pmd(vma, haddr, pmd, folio, &folio->page) 1701 : SCAN_SUCCEED; 1702 goto drop_folio; 1703 abort: 1704 if (nr_mapped_ptes) { 1705 flush_tlb_mm(mm); 1706 folio_ref_sub(folio, nr_mapped_ptes); 1707 add_mm_counter(mm, mm_counter_file(folio), -nr_mapped_ptes); 1708 } 1709 unlock: 1710 if (start_pte) 1711 pte_unmap_unlock(start_pte, ptl); 1712 if (pml && pml != ptl) 1713 spin_unlock(pml); 1714 if (notified) 1715 mmu_notifier_invalidate_range_end(&range); 1716 drop_folio: 1717 folio_unlock(folio); 1718 folio_put(folio); 1719 return result; 1720 } 1721 1722 /** 1723 * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at 1724 * address haddr. 1725 * 1726 * @mm: process address space where collapse happens 1727 * @addr: THP collapse address 1728 * @install_pmd: If a huge PMD should be installed 1729 * 1730 * This function checks whether all the PTEs in the PMD are pointing to the 1731 * right THP. If so, retract the page table so the THP can refault in with 1732 * as pmd-mapped. Possibly install a huge PMD mapping the THP. 1733 */ 1734 void collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr, 1735 bool install_pmd) 1736 { 1737 try_collapse_pte_mapped_thp(mm, addr, install_pmd); 1738 } 1739 1740 /* Can we retract page tables for this file-backed VMA? */ 1741 static bool file_backed_vma_is_retractable(struct vm_area_struct *vma) 1742 { 1743 /* 1744 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that 1745 * got written to. These VMAs are likely not worth removing 1746 * page tables from, as PMD-mapping is likely to be split later. 1747 */ 1748 if (READ_ONCE(vma->anon_vma)) 1749 return false; 1750 1751 /* 1752 * When a vma is registered with uffd-wp, we cannot recycle 1753 * the page table because there may be pte markers installed. 1754 * Other vmas can still have the same file mapped hugely, but 1755 * skip this one: it will always be mapped in small page size 1756 * for uffd-wp registered ranges. 1757 */ 1758 if (userfaultfd_wp(vma)) 1759 return false; 1760 1761 /* 1762 * If the VMA contains guard regions then we can't collapse it. 1763 * 1764 * This is set atomically on guard marker installation under mmap/VMA 1765 * read lock, and here we may not hold any VMA or mmap lock at all. 1766 * 1767 * This is therefore serialised on the PTE page table lock, which is 1768 * obtained on guard region installation after the flag is set, so this 1769 * check being performed under this lock excludes races. 1770 */ 1771 if (vma_test_atomic_flag(vma, VMA_MAYBE_GUARD_BIT)) 1772 return false; 1773 1774 return true; 1775 } 1776 1777 static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff) 1778 { 1779 struct vm_area_struct *vma; 1780 1781 i_mmap_lock_read(mapping); 1782 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) { 1783 struct mmu_notifier_range range; 1784 struct mm_struct *mm; 1785 unsigned long addr; 1786 pmd_t *pmd, pgt_pmd; 1787 spinlock_t *pml; 1788 spinlock_t *ptl; 1789 bool success = false; 1790 1791 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT); 1792 if (addr & ~HPAGE_PMD_MASK || 1793 vma->vm_end < addr + HPAGE_PMD_SIZE) 1794 continue; 1795 1796 mm = vma->vm_mm; 1797 if (find_pmd_or_thp_or_none(mm, addr, &pmd) != SCAN_SUCCEED) 1798 continue; 1799 1800 if (collapse_test_exit(mm)) 1801 continue; 1802 1803 if (!file_backed_vma_is_retractable(vma)) 1804 continue; 1805 1806 /* PTEs were notified when unmapped; but now for the PMD? */ 1807 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, 1808 addr, addr + HPAGE_PMD_SIZE); 1809 mmu_notifier_invalidate_range_start(&range); 1810 1811 pml = pmd_lock(mm, pmd); 1812 /* 1813 * The lock of new_folio is still held, we will be blocked in 1814 * the page fault path, which prevents the pte entries from 1815 * being set again. So even though the old empty PTE page may be 1816 * concurrently freed and a new PTE page is filled into the pmd 1817 * entry, it is still empty and can be removed. 1818 * 1819 * So here we only need to recheck if the state of pmd entry 1820 * still meets our requirements, rather than checking pmd_same() 1821 * like elsewhere. 1822 */ 1823 if (check_pmd_state(pmd) != SCAN_SUCCEED) 1824 goto drop_pml; 1825 ptl = pte_lockptr(mm, pmd); 1826 if (ptl != pml) 1827 spin_lock_nested(ptl, SINGLE_DEPTH_NESTING); 1828 1829 /* 1830 * Huge page lock is still held, so normally the page table must 1831 * remain empty; and we have already skipped anon_vma and 1832 * userfaultfd_wp() vmas. But since the mmap_lock is not held, 1833 * it is still possible for a racing userfaultfd_ioctl() or 1834 * madvise() to have inserted ptes or markers. Now that we hold 1835 * ptlock, repeating the retractable checks protects us from 1836 * races against the prior checks. 1837 */ 1838 if (likely(file_backed_vma_is_retractable(vma))) { 1839 pgt_pmd = pmdp_collapse_flush(vma, addr, pmd); 1840 pmdp_get_lockless_sync(); 1841 success = true; 1842 } 1843 1844 if (ptl != pml) 1845 spin_unlock(ptl); 1846 drop_pml: 1847 spin_unlock(pml); 1848 1849 mmu_notifier_invalidate_range_end(&range); 1850 1851 if (success) { 1852 mm_dec_nr_ptes(mm); 1853 page_table_check_pte_clear_range(mm, addr, pgt_pmd); 1854 pte_free_defer(mm, pmd_pgtable(pgt_pmd)); 1855 } 1856 } 1857 i_mmap_unlock_read(mapping); 1858 } 1859 1860 /** 1861 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one. 1862 * 1863 * @mm: process address space where collapse happens 1864 * @addr: virtual collapse start address 1865 * @file: file that collapse on 1866 * @start: collapse start address 1867 * @cc: collapse context and scratchpad 1868 * 1869 * Basic scheme is simple, details are more complex: 1870 * - allocate and lock a new huge page; 1871 * - scan page cache, locking old pages 1872 * + swap/gup in pages if necessary; 1873 * - copy data to new page 1874 * - handle shmem holes 1875 * + re-validate that holes weren't filled by someone else 1876 * + check for userfaultfd 1877 * - finalize updates to the page cache; 1878 * - if replacing succeeds: 1879 * + unlock huge page; 1880 * + free old pages; 1881 * - if replacing failed; 1882 * + unlock old pages 1883 * + unlock and free huge page; 1884 */ 1885 static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr, 1886 struct file *file, pgoff_t start, struct collapse_control *cc) 1887 { 1888 struct address_space *mapping = file->f_mapping; 1889 struct page *dst; 1890 struct folio *folio, *tmp, *new_folio; 1891 pgoff_t index = 0, end = start + HPAGE_PMD_NR; 1892 LIST_HEAD(pagelist); 1893 XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER); 1894 enum scan_result result = SCAN_SUCCEED; 1895 int nr_none = 0; 1896 bool is_shmem = shmem_file(file); 1897 1898 VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem); 1899 VM_BUG_ON(start & (HPAGE_PMD_NR - 1)); 1900 1901 result = alloc_charge_folio(&new_folio, mm, cc); 1902 if (result != SCAN_SUCCEED) 1903 goto out; 1904 1905 mapping_set_update(&xas, mapping); 1906 1907 __folio_set_locked(new_folio); 1908 if (is_shmem) 1909 __folio_set_swapbacked(new_folio); 1910 new_folio->index = start; 1911 new_folio->mapping = mapping; 1912 1913 /* 1914 * Ensure we have slots for all the pages in the range. This is 1915 * almost certainly a no-op because most of the pages must be present 1916 */ 1917 do { 1918 xas_lock_irq(&xas); 1919 xas_create_range(&xas); 1920 if (!xas_error(&xas)) 1921 break; 1922 xas_unlock_irq(&xas); 1923 if (!xas_nomem(&xas, GFP_KERNEL)) { 1924 result = SCAN_FAIL; 1925 goto rollback; 1926 } 1927 } while (1); 1928 1929 for (index = start; index < end;) { 1930 xas_set(&xas, index); 1931 folio = xas_load(&xas); 1932 1933 VM_BUG_ON(index != xas.xa_index); 1934 if (is_shmem) { 1935 if (!folio) { 1936 /* 1937 * Stop if extent has been truncated or 1938 * hole-punched, and is now completely 1939 * empty. 1940 */ 1941 if (index == start) { 1942 if (!xas_next_entry(&xas, end - 1)) { 1943 result = SCAN_TRUNCATED; 1944 goto xa_locked; 1945 } 1946 } 1947 nr_none++; 1948 index++; 1949 continue; 1950 } 1951 1952 if (xa_is_value(folio) || !folio_test_uptodate(folio)) { 1953 xas_unlock_irq(&xas); 1954 /* swap in or instantiate fallocated page */ 1955 if (shmem_get_folio(mapping->host, index, 0, 1956 &folio, SGP_NOALLOC)) { 1957 result = SCAN_FAIL; 1958 goto xa_unlocked; 1959 } 1960 /* drain lru cache to help folio_isolate_lru() */ 1961 lru_add_drain(); 1962 } else if (folio_trylock(folio)) { 1963 folio_get(folio); 1964 xas_unlock_irq(&xas); 1965 } else { 1966 result = SCAN_PAGE_LOCK; 1967 goto xa_locked; 1968 } 1969 } else { /* !is_shmem */ 1970 if (!folio || xa_is_value(folio)) { 1971 xas_unlock_irq(&xas); 1972 page_cache_sync_readahead(mapping, &file->f_ra, 1973 file, index, 1974 end - index); 1975 /* drain lru cache to help folio_isolate_lru() */ 1976 lru_add_drain(); 1977 folio = filemap_lock_folio(mapping, index); 1978 if (IS_ERR(folio)) { 1979 result = SCAN_FAIL; 1980 goto xa_unlocked; 1981 } 1982 } else if (folio_test_dirty(folio)) { 1983 /* 1984 * khugepaged only works on read-only fd, 1985 * so this page is dirty because it hasn't 1986 * been flushed since first write. There 1987 * won't be new dirty pages. 1988 * 1989 * Trigger async flush here and hope the 1990 * writeback is done when khugepaged 1991 * revisits this page. 1992 * 1993 * This is a one-off situation. We are not 1994 * forcing writeback in loop. 1995 */ 1996 xas_unlock_irq(&xas); 1997 filemap_flush(mapping); 1998 result = SCAN_PAGE_DIRTY_OR_WRITEBACK; 1999 goto xa_unlocked; 2000 } else if (folio_test_writeback(folio)) { 2001 xas_unlock_irq(&xas); 2002 result = SCAN_PAGE_DIRTY_OR_WRITEBACK; 2003 goto xa_unlocked; 2004 } else if (folio_trylock(folio)) { 2005 folio_get(folio); 2006 xas_unlock_irq(&xas); 2007 } else { 2008 result = SCAN_PAGE_LOCK; 2009 goto xa_locked; 2010 } 2011 } 2012 2013 /* 2014 * The folio must be locked, so we can drop the i_pages lock 2015 * without racing with truncate. 2016 */ 2017 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 2018 2019 /* make sure the folio is up to date */ 2020 if (unlikely(!folio_test_uptodate(folio))) { 2021 result = SCAN_FAIL; 2022 goto out_unlock; 2023 } 2024 2025 /* 2026 * If file was truncated then extended, or hole-punched, before 2027 * we locked the first folio, then a THP might be there already. 2028 * This will be discovered on the first iteration. 2029 */ 2030 if (is_pmd_order(folio_order(folio))) { 2031 result = SCAN_PTE_MAPPED_HUGEPAGE; 2032 goto out_unlock; 2033 } 2034 2035 if (folio_mapping(folio) != mapping) { 2036 result = SCAN_TRUNCATED; 2037 goto out_unlock; 2038 } 2039 2040 if (!is_shmem && (folio_test_dirty(folio) || 2041 folio_test_writeback(folio))) { 2042 /* 2043 * khugepaged only works on read-only fd, so this 2044 * folio is dirty because it hasn't been flushed 2045 * since first write. 2046 */ 2047 result = SCAN_PAGE_DIRTY_OR_WRITEBACK; 2048 goto out_unlock; 2049 } 2050 2051 if (!folio_isolate_lru(folio)) { 2052 result = SCAN_DEL_PAGE_LRU; 2053 goto out_unlock; 2054 } 2055 2056 if (!filemap_release_folio(folio, GFP_KERNEL)) { 2057 result = SCAN_PAGE_HAS_PRIVATE; 2058 folio_putback_lru(folio); 2059 goto out_unlock; 2060 } 2061 2062 if (folio_mapped(folio)) 2063 try_to_unmap(folio, 2064 TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH); 2065 2066 xas_lock_irq(&xas); 2067 2068 VM_BUG_ON_FOLIO(folio != xa_load(xas.xa, index), folio); 2069 2070 /* 2071 * We control 2 + nr_pages references to the folio: 2072 * - we hold a pin on it; 2073 * - nr_pages reference from page cache; 2074 * - one from lru_isolate_folio; 2075 * If those are the only references, then any new usage 2076 * of the folio will have to fetch it from the page 2077 * cache. That requires locking the folio to handle 2078 * truncate, so any new usage will be blocked until we 2079 * unlock folio after collapse/during rollback. 2080 */ 2081 if (folio_ref_count(folio) != 2 + folio_nr_pages(folio)) { 2082 result = SCAN_PAGE_COUNT; 2083 xas_unlock_irq(&xas); 2084 folio_putback_lru(folio); 2085 goto out_unlock; 2086 } 2087 2088 /* 2089 * Accumulate the folios that are being collapsed. 2090 */ 2091 list_add_tail(&folio->lru, &pagelist); 2092 index += folio_nr_pages(folio); 2093 continue; 2094 out_unlock: 2095 folio_unlock(folio); 2096 folio_put(folio); 2097 goto xa_unlocked; 2098 } 2099 2100 if (!is_shmem) { 2101 filemap_nr_thps_inc(mapping); 2102 /* 2103 * Paired with the fence in do_dentry_open() -> get_write_access() 2104 * to ensure i_writecount is up to date and the update to nr_thps 2105 * is visible. Ensures the page cache will be truncated if the 2106 * file is opened writable. 2107 */ 2108 smp_mb(); 2109 if (inode_is_open_for_write(mapping->host)) { 2110 result = SCAN_FAIL; 2111 filemap_nr_thps_dec(mapping); 2112 } 2113 } 2114 2115 xa_locked: 2116 xas_unlock_irq(&xas); 2117 xa_unlocked: 2118 2119 /* 2120 * If collapse is successful, flush must be done now before copying. 2121 * If collapse is unsuccessful, does flush actually need to be done? 2122 * Do it anyway, to clear the state. 2123 */ 2124 try_to_unmap_flush(); 2125 2126 if (result == SCAN_SUCCEED && nr_none && 2127 !shmem_charge(mapping->host, nr_none)) 2128 result = SCAN_FAIL; 2129 if (result != SCAN_SUCCEED) { 2130 nr_none = 0; 2131 goto rollback; 2132 } 2133 2134 /* 2135 * The old folios are locked, so they won't change anymore. 2136 */ 2137 index = start; 2138 dst = folio_page(new_folio, 0); 2139 list_for_each_entry(folio, &pagelist, lru) { 2140 int i, nr_pages = folio_nr_pages(folio); 2141 2142 while (index < folio->index) { 2143 clear_highpage(dst); 2144 index++; 2145 dst++; 2146 } 2147 2148 for (i = 0; i < nr_pages; i++) { 2149 if (copy_mc_highpage(dst, folio_page(folio, i)) > 0) { 2150 result = SCAN_COPY_MC; 2151 goto rollback; 2152 } 2153 index++; 2154 dst++; 2155 } 2156 } 2157 while (index < end) { 2158 clear_highpage(dst); 2159 index++; 2160 dst++; 2161 } 2162 2163 if (nr_none) { 2164 struct vm_area_struct *vma; 2165 int nr_none_check = 0; 2166 2167 i_mmap_lock_read(mapping); 2168 xas_lock_irq(&xas); 2169 2170 xas_set(&xas, start); 2171 for (index = start; index < end; index++) { 2172 if (!xas_next(&xas)) { 2173 xas_store(&xas, XA_RETRY_ENTRY); 2174 if (xas_error(&xas)) { 2175 result = SCAN_STORE_FAILED; 2176 goto immap_locked; 2177 } 2178 nr_none_check++; 2179 } 2180 } 2181 2182 if (nr_none != nr_none_check) { 2183 result = SCAN_PAGE_FILLED; 2184 goto immap_locked; 2185 } 2186 2187 /* 2188 * If userspace observed a missing page in a VMA with 2189 * a MODE_MISSING userfaultfd, then it might expect a 2190 * UFFD_EVENT_PAGEFAULT for that page. If so, we need to 2191 * roll back to avoid suppressing such an event. Since 2192 * wp/minor userfaultfds don't give userspace any 2193 * guarantees that the kernel doesn't fill a missing 2194 * page with a zero page, so they don't matter here. 2195 * 2196 * Any userfaultfds registered after this point will 2197 * not be able to observe any missing pages due to the 2198 * previously inserted retry entries. 2199 */ 2200 vma_interval_tree_foreach(vma, &mapping->i_mmap, start, end) { 2201 if (userfaultfd_missing(vma)) { 2202 result = SCAN_EXCEED_NONE_PTE; 2203 goto immap_locked; 2204 } 2205 } 2206 2207 immap_locked: 2208 i_mmap_unlock_read(mapping); 2209 if (result != SCAN_SUCCEED) { 2210 xas_set(&xas, start); 2211 for (index = start; index < end; index++) { 2212 if (xas_next(&xas) == XA_RETRY_ENTRY) 2213 xas_store(&xas, NULL); 2214 } 2215 2216 xas_unlock_irq(&xas); 2217 goto rollback; 2218 } 2219 } else { 2220 xas_lock_irq(&xas); 2221 } 2222 2223 if (is_shmem) { 2224 lruvec_stat_mod_folio(new_folio, NR_SHMEM, HPAGE_PMD_NR); 2225 lruvec_stat_mod_folio(new_folio, NR_SHMEM_THPS, HPAGE_PMD_NR); 2226 } else { 2227 lruvec_stat_mod_folio(new_folio, NR_FILE_THPS, HPAGE_PMD_NR); 2228 } 2229 lruvec_stat_mod_folio(new_folio, NR_FILE_PAGES, HPAGE_PMD_NR); 2230 2231 /* 2232 * Mark new_folio as uptodate before inserting it into the 2233 * page cache so that it isn't mistaken for an fallocated but 2234 * unwritten page. 2235 */ 2236 folio_mark_uptodate(new_folio); 2237 folio_ref_add(new_folio, HPAGE_PMD_NR - 1); 2238 2239 if (is_shmem) 2240 folio_mark_dirty(new_folio); 2241 folio_add_lru(new_folio); 2242 2243 /* Join all the small entries into a single multi-index entry. */ 2244 xas_set_order(&xas, start, HPAGE_PMD_ORDER); 2245 xas_store(&xas, new_folio); 2246 WARN_ON_ONCE(xas_error(&xas)); 2247 xas_unlock_irq(&xas); 2248 2249 /* 2250 * Remove pte page tables, so we can re-fault the page as huge. 2251 * If MADV_COLLAPSE, adjust result to call try_collapse_pte_mapped_thp(). 2252 */ 2253 retract_page_tables(mapping, start); 2254 if (cc && !cc->is_khugepaged) 2255 result = SCAN_PTE_MAPPED_HUGEPAGE; 2256 folio_unlock(new_folio); 2257 2258 /* 2259 * The collapse has succeeded, so free the old folios. 2260 */ 2261 list_for_each_entry_safe(folio, tmp, &pagelist, lru) { 2262 list_del(&folio->lru); 2263 lruvec_stat_mod_folio(folio, NR_FILE_PAGES, 2264 -folio_nr_pages(folio)); 2265 if (is_shmem) 2266 lruvec_stat_mod_folio(folio, NR_SHMEM, 2267 -folio_nr_pages(folio)); 2268 folio->mapping = NULL; 2269 folio_clear_active(folio); 2270 folio_clear_unevictable(folio); 2271 folio_unlock(folio); 2272 folio_put_refs(folio, 2 + folio_nr_pages(folio)); 2273 } 2274 2275 goto out; 2276 2277 rollback: 2278 /* Something went wrong: roll back page cache changes */ 2279 if (nr_none) { 2280 xas_lock_irq(&xas); 2281 mapping->nrpages -= nr_none; 2282 xas_unlock_irq(&xas); 2283 shmem_uncharge(mapping->host, nr_none); 2284 } 2285 2286 list_for_each_entry_safe(folio, tmp, &pagelist, lru) { 2287 list_del(&folio->lru); 2288 folio_unlock(folio); 2289 folio_putback_lru(folio); 2290 folio_put(folio); 2291 } 2292 /* 2293 * Undo the updates of filemap_nr_thps_inc for non-SHMEM 2294 * file only. This undo is not needed unless failure is 2295 * due to SCAN_COPY_MC. 2296 */ 2297 if (!is_shmem && result == SCAN_COPY_MC) { 2298 filemap_nr_thps_dec(mapping); 2299 /* 2300 * Paired with the fence in do_dentry_open() -> get_write_access() 2301 * to ensure the update to nr_thps is visible. 2302 */ 2303 smp_mb(); 2304 } 2305 2306 new_folio->mapping = NULL; 2307 2308 folio_unlock(new_folio); 2309 folio_put(new_folio); 2310 out: 2311 VM_BUG_ON(!list_empty(&pagelist)); 2312 trace_mm_khugepaged_collapse_file(mm, new_folio, index, addr, is_shmem, file, HPAGE_PMD_NR, result); 2313 return result; 2314 } 2315 2316 static enum scan_result collapse_scan_file(struct mm_struct *mm, 2317 unsigned long addr, struct file *file, pgoff_t start, 2318 struct collapse_control *cc) 2319 { 2320 struct folio *folio = NULL; 2321 struct address_space *mapping = file->f_mapping; 2322 XA_STATE(xas, &mapping->i_pages, start); 2323 int present, swap; 2324 int node = NUMA_NO_NODE; 2325 enum scan_result result = SCAN_SUCCEED; 2326 2327 present = 0; 2328 swap = 0; 2329 memset(cc->node_load, 0, sizeof(cc->node_load)); 2330 nodes_clear(cc->alloc_nmask); 2331 rcu_read_lock(); 2332 xas_for_each(&xas, folio, start + HPAGE_PMD_NR - 1) { 2333 if (xas_retry(&xas, folio)) 2334 continue; 2335 2336 if (xa_is_value(folio)) { 2337 swap += 1 << xas_get_order(&xas); 2338 if (cc->is_khugepaged && 2339 swap > khugepaged_max_ptes_swap) { 2340 result = SCAN_EXCEED_SWAP_PTE; 2341 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE); 2342 break; 2343 } 2344 continue; 2345 } 2346 2347 if (!folio_try_get(folio)) { 2348 xas_reset(&xas); 2349 continue; 2350 } 2351 2352 if (unlikely(folio != xas_reload(&xas))) { 2353 folio_put(folio); 2354 xas_reset(&xas); 2355 continue; 2356 } 2357 2358 if (is_pmd_order(folio_order(folio))) { 2359 result = SCAN_PTE_MAPPED_HUGEPAGE; 2360 /* 2361 * PMD-sized THP implies that we can only try 2362 * retracting the PTE table. 2363 */ 2364 folio_put(folio); 2365 break; 2366 } 2367 2368 node = folio_nid(folio); 2369 if (collapse_scan_abort(node, cc)) { 2370 result = SCAN_SCAN_ABORT; 2371 folio_put(folio); 2372 break; 2373 } 2374 cc->node_load[node]++; 2375 2376 if (!folio_test_lru(folio)) { 2377 result = SCAN_PAGE_LRU; 2378 folio_put(folio); 2379 break; 2380 } 2381 2382 if (folio_expected_ref_count(folio) + 1 != folio_ref_count(folio)) { 2383 result = SCAN_PAGE_COUNT; 2384 folio_put(folio); 2385 break; 2386 } 2387 2388 /* 2389 * We probably should check if the folio is referenced 2390 * here, but nobody would transfer pte_young() to 2391 * folio_test_referenced() for us. And rmap walk here 2392 * is just too costly... 2393 */ 2394 2395 present += folio_nr_pages(folio); 2396 folio_put(folio); 2397 2398 if (need_resched()) { 2399 xas_pause(&xas); 2400 cond_resched_rcu(); 2401 } 2402 } 2403 rcu_read_unlock(); 2404 if (result == SCAN_PTE_MAPPED_HUGEPAGE) 2405 cc->progress++; 2406 else 2407 cc->progress += HPAGE_PMD_NR; 2408 2409 if (result == SCAN_SUCCEED) { 2410 if (cc->is_khugepaged && 2411 present < HPAGE_PMD_NR - khugepaged_max_ptes_none) { 2412 result = SCAN_EXCEED_NONE_PTE; 2413 count_vm_event(THP_SCAN_EXCEED_NONE_PTE); 2414 } else { 2415 result = collapse_file(mm, addr, file, start, cc); 2416 } 2417 } 2418 2419 trace_mm_khugepaged_scan_file(mm, folio, file, present, swap, result); 2420 return result; 2421 } 2422 2423 /* 2424 * Try to collapse a single PMD starting at a PMD aligned addr, and return 2425 * the results. 2426 */ 2427 static enum scan_result collapse_single_pmd(unsigned long addr, 2428 struct vm_area_struct *vma, bool *lock_dropped, 2429 struct collapse_control *cc) 2430 { 2431 struct mm_struct *mm = vma->vm_mm; 2432 bool triggered_wb = false; 2433 enum scan_result result; 2434 struct file *file; 2435 pgoff_t pgoff; 2436 2437 mmap_assert_locked(mm); 2438 2439 if (vma_is_anonymous(vma)) { 2440 result = collapse_scan_pmd(mm, vma, addr, lock_dropped, cc); 2441 goto end; 2442 } 2443 2444 file = get_file(vma->vm_file); 2445 pgoff = linear_page_index(vma, addr); 2446 2447 mmap_read_unlock(mm); 2448 *lock_dropped = true; 2449 retry: 2450 result = collapse_scan_file(mm, addr, file, pgoff, cc); 2451 2452 /* 2453 * For MADV_COLLAPSE, when encountering dirty pages, try to writeback, 2454 * then retry the collapse one time. 2455 */ 2456 if (!cc->is_khugepaged && result == SCAN_PAGE_DIRTY_OR_WRITEBACK && 2457 !triggered_wb && mapping_can_writeback(file->f_mapping)) { 2458 const loff_t lstart = (loff_t)pgoff << PAGE_SHIFT; 2459 const loff_t lend = lstart + HPAGE_PMD_SIZE - 1; 2460 2461 filemap_write_and_wait_range(file->f_mapping, lstart, lend); 2462 triggered_wb = true; 2463 goto retry; 2464 } 2465 fput(file); 2466 2467 if (result == SCAN_PTE_MAPPED_HUGEPAGE) { 2468 mmap_read_lock(mm); 2469 if (collapse_test_exit_or_disable(mm)) 2470 result = SCAN_ANY_PROCESS; 2471 else 2472 result = try_collapse_pte_mapped_thp(mm, addr, 2473 !cc->is_khugepaged); 2474 if (result == SCAN_PMD_MAPPED) 2475 result = SCAN_SUCCEED; 2476 mmap_read_unlock(mm); 2477 } 2478 end: 2479 if (cc->is_khugepaged && result == SCAN_SUCCEED) 2480 ++khugepaged_pages_collapsed; 2481 return result; 2482 } 2483 2484 static void collapse_scan_mm_slot(unsigned int progress_max, 2485 enum scan_result *result, struct collapse_control *cc) 2486 __releases(&khugepaged_mm_lock) 2487 __acquires(&khugepaged_mm_lock) 2488 { 2489 struct vma_iterator vmi; 2490 struct mm_slot *slot; 2491 struct mm_struct *mm; 2492 struct vm_area_struct *vma; 2493 unsigned int progress_prev = cc->progress; 2494 2495 lockdep_assert_held(&khugepaged_mm_lock); 2496 *result = SCAN_FAIL; 2497 2498 if (khugepaged_scan.mm_slot) { 2499 slot = khugepaged_scan.mm_slot; 2500 } else { 2501 slot = list_first_entry(&khugepaged_scan.mm_head, 2502 struct mm_slot, mm_node); 2503 khugepaged_scan.address = 0; 2504 khugepaged_scan.mm_slot = slot; 2505 } 2506 spin_unlock(&khugepaged_mm_lock); 2507 2508 mm = slot->mm; 2509 /* 2510 * Don't wait for semaphore (to avoid long wait times). Just move to 2511 * the next mm on the list. 2512 */ 2513 vma = NULL; 2514 if (unlikely(!mmap_read_trylock(mm))) 2515 goto breakouterloop_mmap_lock; 2516 2517 cc->progress++; 2518 if (unlikely(collapse_test_exit_or_disable(mm))) 2519 goto breakouterloop; 2520 2521 vma_iter_init(&vmi, mm, khugepaged_scan.address); 2522 for_each_vma(vmi, vma) { 2523 unsigned long hstart, hend; 2524 2525 cond_resched(); 2526 if (unlikely(collapse_test_exit_or_disable(mm))) { 2527 cc->progress++; 2528 break; 2529 } 2530 if (!thp_vma_allowable_order(vma, vma->vm_flags, TVA_KHUGEPAGED, PMD_ORDER)) { 2531 cc->progress++; 2532 continue; 2533 } 2534 hstart = ALIGN(vma->vm_start, HPAGE_PMD_SIZE); 2535 hend = ALIGN_DOWN(vma->vm_end, HPAGE_PMD_SIZE); 2536 if (khugepaged_scan.address > hend) { 2537 cc->progress++; 2538 continue; 2539 } 2540 if (khugepaged_scan.address < hstart) 2541 khugepaged_scan.address = hstart; 2542 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK); 2543 2544 while (khugepaged_scan.address < hend) { 2545 bool lock_dropped = false; 2546 2547 cond_resched(); 2548 if (unlikely(collapse_test_exit_or_disable(mm))) 2549 goto breakouterloop; 2550 2551 VM_WARN_ON_ONCE(khugepaged_scan.address < hstart || 2552 khugepaged_scan.address + HPAGE_PMD_SIZE > 2553 hend); 2554 2555 *result = collapse_single_pmd(khugepaged_scan.address, 2556 vma, &lock_dropped, cc); 2557 /* move to next address */ 2558 khugepaged_scan.address += HPAGE_PMD_SIZE; 2559 if (lock_dropped) 2560 /* 2561 * We released mmap_lock so break loop. Note 2562 * that we drop mmap_lock before all hugepage 2563 * allocations, so if allocation fails, we are 2564 * guaranteed to break here and report the 2565 * correct result back to caller. 2566 */ 2567 goto breakouterloop_mmap_lock; 2568 if (cc->progress >= progress_max) 2569 goto breakouterloop; 2570 } 2571 } 2572 breakouterloop: 2573 mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */ 2574 breakouterloop_mmap_lock: 2575 2576 spin_lock(&khugepaged_mm_lock); 2577 VM_BUG_ON(khugepaged_scan.mm_slot != slot); 2578 /* 2579 * Release the current mm_slot if this mm is about to die, or 2580 * if we scanned all vmas of this mm, or THP got disabled. 2581 */ 2582 if (collapse_test_exit_or_disable(mm) || !vma) { 2583 /* 2584 * Make sure that if mm_users is reaching zero while 2585 * khugepaged runs here, khugepaged_exit will find 2586 * mm_slot not pointing to the exiting mm. 2587 */ 2588 if (!list_is_last(&slot->mm_node, &khugepaged_scan.mm_head)) { 2589 khugepaged_scan.mm_slot = list_next_entry(slot, mm_node); 2590 khugepaged_scan.address = 0; 2591 } else { 2592 khugepaged_scan.mm_slot = NULL; 2593 khugepaged_full_scans++; 2594 } 2595 2596 collect_mm_slot(slot); 2597 } 2598 2599 trace_mm_khugepaged_scan(mm, cc->progress - progress_prev, 2600 khugepaged_scan.mm_slot == NULL); 2601 } 2602 2603 static int khugepaged_has_work(void) 2604 { 2605 return !list_empty(&khugepaged_scan.mm_head) && hugepage_pmd_enabled(); 2606 } 2607 2608 static int khugepaged_wait_event(void) 2609 { 2610 return !list_empty(&khugepaged_scan.mm_head) || 2611 kthread_should_stop(); 2612 } 2613 2614 static void khugepaged_do_scan(struct collapse_control *cc) 2615 { 2616 const unsigned int progress_max = READ_ONCE(khugepaged_pages_to_scan); 2617 unsigned int pass_through_head = 0; 2618 bool wait = true; 2619 enum scan_result result = SCAN_SUCCEED; 2620 2621 lru_add_drain_all(); 2622 2623 cc->progress = 0; 2624 while (true) { 2625 cond_resched(); 2626 2627 if (unlikely(kthread_should_stop())) 2628 break; 2629 2630 spin_lock(&khugepaged_mm_lock); 2631 if (!khugepaged_scan.mm_slot) 2632 pass_through_head++; 2633 if (khugepaged_has_work() && 2634 pass_through_head < 2) 2635 collapse_scan_mm_slot(progress_max, &result, cc); 2636 else 2637 cc->progress = progress_max; 2638 spin_unlock(&khugepaged_mm_lock); 2639 2640 if (cc->progress >= progress_max) 2641 break; 2642 2643 if (result == SCAN_ALLOC_HUGE_PAGE_FAIL) { 2644 /* 2645 * If fail to allocate the first time, try to sleep for 2646 * a while. When hit again, cancel the scan. 2647 */ 2648 if (!wait) 2649 break; 2650 wait = false; 2651 khugepaged_alloc_sleep(); 2652 } 2653 } 2654 } 2655 2656 static bool khugepaged_should_wakeup(void) 2657 { 2658 return kthread_should_stop() || 2659 time_after_eq(jiffies, khugepaged_sleep_expire); 2660 } 2661 2662 static void khugepaged_wait_work(void) 2663 { 2664 if (khugepaged_has_work()) { 2665 const unsigned long scan_sleep_jiffies = 2666 msecs_to_jiffies(khugepaged_scan_sleep_millisecs); 2667 2668 if (!scan_sleep_jiffies) 2669 return; 2670 2671 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies; 2672 wait_event_freezable_timeout(khugepaged_wait, 2673 khugepaged_should_wakeup(), 2674 scan_sleep_jiffies); 2675 return; 2676 } 2677 2678 if (hugepage_pmd_enabled()) 2679 wait_event_freezable(khugepaged_wait, khugepaged_wait_event()); 2680 } 2681 2682 static int khugepaged(void *none) 2683 { 2684 struct mm_slot *slot; 2685 2686 set_freezable(); 2687 set_user_nice(current, MAX_NICE); 2688 2689 while (!kthread_should_stop()) { 2690 khugepaged_do_scan(&khugepaged_collapse_control); 2691 khugepaged_wait_work(); 2692 } 2693 2694 spin_lock(&khugepaged_mm_lock); 2695 slot = khugepaged_scan.mm_slot; 2696 khugepaged_scan.mm_slot = NULL; 2697 if (slot) 2698 collect_mm_slot(slot); 2699 spin_unlock(&khugepaged_mm_lock); 2700 return 0; 2701 } 2702 2703 void set_recommended_min_free_kbytes(void) 2704 { 2705 struct zone *zone; 2706 int nr_zones = 0; 2707 unsigned long recommended_min; 2708 2709 if (!hugepage_pmd_enabled()) { 2710 calculate_min_free_kbytes(); 2711 goto update_wmarks; 2712 } 2713 2714 for_each_populated_zone(zone) { 2715 /* 2716 * We don't need to worry about fragmentation of 2717 * ZONE_MOVABLE since it only has movable pages. 2718 */ 2719 if (zone_idx(zone) > gfp_zone(GFP_USER)) 2720 continue; 2721 2722 nr_zones++; 2723 } 2724 2725 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */ 2726 recommended_min = pageblock_nr_pages * nr_zones * 2; 2727 2728 /* 2729 * Make sure that on average at least two pageblocks are almost free 2730 * of another type, one for a migratetype to fall back to and a 2731 * second to avoid subsequent fallbacks of other types There are 3 2732 * MIGRATE_TYPES we care about. 2733 */ 2734 recommended_min += pageblock_nr_pages * nr_zones * 2735 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES; 2736 2737 /* don't ever allow to reserve more than 5% of the lowmem */ 2738 recommended_min = min(recommended_min, 2739 (unsigned long) nr_free_buffer_pages() / 20); 2740 recommended_min <<= (PAGE_SHIFT-10); 2741 2742 if (recommended_min > min_free_kbytes) { 2743 if (user_min_free_kbytes >= 0) 2744 pr_info_ratelimited("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n", 2745 min_free_kbytes, recommended_min); 2746 2747 min_free_kbytes = recommended_min; 2748 } 2749 2750 update_wmarks: 2751 setup_per_zone_wmarks(); 2752 } 2753 2754 int start_stop_khugepaged(void) 2755 { 2756 int err = 0; 2757 2758 mutex_lock(&khugepaged_mutex); 2759 if (hugepage_pmd_enabled()) { 2760 if (!khugepaged_thread) 2761 khugepaged_thread = kthread_run(khugepaged, NULL, 2762 "khugepaged"); 2763 if (IS_ERR(khugepaged_thread)) { 2764 pr_err("khugepaged: kthread_run(khugepaged) failed\n"); 2765 err = PTR_ERR(khugepaged_thread); 2766 khugepaged_thread = NULL; 2767 goto fail; 2768 } 2769 2770 if (!list_empty(&khugepaged_scan.mm_head)) 2771 wake_up_interruptible(&khugepaged_wait); 2772 } else if (khugepaged_thread) { 2773 kthread_stop(khugepaged_thread); 2774 khugepaged_thread = NULL; 2775 } 2776 set_recommended_min_free_kbytes(); 2777 fail: 2778 mutex_unlock(&khugepaged_mutex); 2779 return err; 2780 } 2781 2782 void khugepaged_min_free_kbytes_update(void) 2783 { 2784 mutex_lock(&khugepaged_mutex); 2785 if (hugepage_pmd_enabled() && khugepaged_thread) 2786 set_recommended_min_free_kbytes(); 2787 mutex_unlock(&khugepaged_mutex); 2788 } 2789 2790 bool current_is_khugepaged(void) 2791 { 2792 return kthread_func(current) == khugepaged; 2793 } 2794 2795 static int madvise_collapse_errno(enum scan_result r) 2796 { 2797 /* 2798 * MADV_COLLAPSE breaks from existing madvise(2) conventions to provide 2799 * actionable feedback to caller, so they may take an appropriate 2800 * fallback measure depending on the nature of the failure. 2801 */ 2802 switch (r) { 2803 case SCAN_ALLOC_HUGE_PAGE_FAIL: 2804 return -ENOMEM; 2805 case SCAN_CGROUP_CHARGE_FAIL: 2806 case SCAN_EXCEED_NONE_PTE: 2807 return -EBUSY; 2808 /* Resource temporary unavailable - trying again might succeed */ 2809 case SCAN_PAGE_COUNT: 2810 case SCAN_PAGE_LOCK: 2811 case SCAN_PAGE_LRU: 2812 case SCAN_DEL_PAGE_LRU: 2813 case SCAN_PAGE_FILLED: 2814 case SCAN_PAGE_HAS_PRIVATE: 2815 case SCAN_PAGE_DIRTY_OR_WRITEBACK: 2816 return -EAGAIN; 2817 /* 2818 * Other: Trying again likely not to succeed / error intrinsic to 2819 * specified memory range. khugepaged likely won't be able to collapse 2820 * either. 2821 */ 2822 default: 2823 return -EINVAL; 2824 } 2825 } 2826 2827 int madvise_collapse(struct vm_area_struct *vma, unsigned long start, 2828 unsigned long end, bool *lock_dropped) 2829 { 2830 struct collapse_control *cc; 2831 struct mm_struct *mm = vma->vm_mm; 2832 unsigned long hstart, hend, addr; 2833 enum scan_result last_fail = SCAN_FAIL; 2834 int thps = 0; 2835 bool mmap_unlocked = false; 2836 2837 BUG_ON(vma->vm_start > start); 2838 BUG_ON(vma->vm_end < end); 2839 2840 if (!thp_vma_allowable_order(vma, vma->vm_flags, TVA_FORCED_COLLAPSE, PMD_ORDER)) 2841 return -EINVAL; 2842 2843 cc = kmalloc_obj(*cc); 2844 if (!cc) 2845 return -ENOMEM; 2846 cc->is_khugepaged = false; 2847 cc->progress = 0; 2848 2849 mmgrab(mm); 2850 lru_add_drain_all(); 2851 2852 hstart = ALIGN(start, HPAGE_PMD_SIZE); 2853 hend = ALIGN_DOWN(end, HPAGE_PMD_SIZE); 2854 2855 for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) { 2856 enum scan_result result = SCAN_FAIL; 2857 2858 if (mmap_unlocked) { 2859 cond_resched(); 2860 mmap_read_lock(mm); 2861 mmap_unlocked = false; 2862 *lock_dropped = true; 2863 result = hugepage_vma_revalidate(mm, addr, false, &vma, 2864 cc); 2865 if (result != SCAN_SUCCEED) { 2866 last_fail = result; 2867 goto out_nolock; 2868 } 2869 2870 hend = min(hend, vma->vm_end & HPAGE_PMD_MASK); 2871 } 2872 2873 result = collapse_single_pmd(addr, vma, &mmap_unlocked, cc); 2874 2875 switch (result) { 2876 case SCAN_SUCCEED: 2877 case SCAN_PMD_MAPPED: 2878 ++thps; 2879 break; 2880 /* Whitelisted set of results where continuing OK */ 2881 case SCAN_NO_PTE_TABLE: 2882 case SCAN_PTE_NON_PRESENT: 2883 case SCAN_PTE_UFFD_WP: 2884 case SCAN_LACK_REFERENCED_PAGE: 2885 case SCAN_PAGE_NULL: 2886 case SCAN_PAGE_COUNT: 2887 case SCAN_PAGE_LOCK: 2888 case SCAN_PAGE_COMPOUND: 2889 case SCAN_PAGE_LRU: 2890 case SCAN_DEL_PAGE_LRU: 2891 last_fail = result; 2892 break; 2893 default: 2894 last_fail = result; 2895 /* Other error, exit */ 2896 goto out_maybelock; 2897 } 2898 } 2899 2900 out_maybelock: 2901 /* Caller expects us to hold mmap_lock on return */ 2902 if (mmap_unlocked) { 2903 *lock_dropped = true; 2904 mmap_read_lock(mm); 2905 } 2906 out_nolock: 2907 mmap_assert_locked(mm); 2908 mmdrop(mm); 2909 kfree(cc); 2910 2911 return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0 2912 : madvise_collapse_errno(last_fail); 2913 } 2914