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