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 23 #include <asm/tlb.h> 24 #include <asm/pgalloc.h> 25 #include "internal.h" 26 27 enum scan_result { 28 SCAN_FAIL, 29 SCAN_SUCCEED, 30 SCAN_PMD_NULL, 31 SCAN_EXCEED_NONE_PTE, 32 SCAN_EXCEED_SWAP_PTE, 33 SCAN_EXCEED_SHARED_PTE, 34 SCAN_PTE_NON_PRESENT, 35 SCAN_PTE_UFFD_WP, 36 SCAN_PAGE_RO, 37 SCAN_LACK_REFERENCED_PAGE, 38 SCAN_PAGE_NULL, 39 SCAN_SCAN_ABORT, 40 SCAN_PAGE_COUNT, 41 SCAN_PAGE_LRU, 42 SCAN_PAGE_LOCK, 43 SCAN_PAGE_ANON, 44 SCAN_PAGE_COMPOUND, 45 SCAN_ANY_PROCESS, 46 SCAN_VMA_NULL, 47 SCAN_VMA_CHECK, 48 SCAN_ADDRESS_RANGE, 49 SCAN_DEL_PAGE_LRU, 50 SCAN_ALLOC_HUGE_PAGE_FAIL, 51 SCAN_CGROUP_CHARGE_FAIL, 52 SCAN_TRUNCATED, 53 SCAN_PAGE_HAS_PRIVATE, 54 }; 55 56 #define CREATE_TRACE_POINTS 57 #include <trace/events/huge_memory.h> 58 59 static struct task_struct *khugepaged_thread __read_mostly; 60 static DEFINE_MUTEX(khugepaged_mutex); 61 62 /* default scan 8*512 pte (or vmas) every 30 second */ 63 static unsigned int khugepaged_pages_to_scan __read_mostly; 64 static unsigned int khugepaged_pages_collapsed; 65 static unsigned int khugepaged_full_scans; 66 static unsigned int khugepaged_scan_sleep_millisecs __read_mostly = 10000; 67 /* during fragmentation poll the hugepage allocator once every minute */ 68 static unsigned int khugepaged_alloc_sleep_millisecs __read_mostly = 60000; 69 static unsigned long khugepaged_sleep_expire; 70 static DEFINE_SPINLOCK(khugepaged_mm_lock); 71 static DECLARE_WAIT_QUEUE_HEAD(khugepaged_wait); 72 /* 73 * default collapse hugepages if there is at least one pte mapped like 74 * it would have happened if the vma was large enough during page 75 * fault. 76 */ 77 static unsigned int khugepaged_max_ptes_none __read_mostly; 78 static unsigned int khugepaged_max_ptes_swap __read_mostly; 79 static unsigned int khugepaged_max_ptes_shared __read_mostly; 80 81 #define MM_SLOTS_HASH_BITS 10 82 static __read_mostly DEFINE_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS); 83 84 static struct kmem_cache *mm_slot_cache __read_mostly; 85 86 #define MAX_PTE_MAPPED_THP 8 87 88 /** 89 * struct mm_slot - hash lookup from mm to mm_slot 90 * @hash: hash collision list 91 * @mm_node: khugepaged scan list headed in khugepaged_scan.mm_head 92 * @mm: the mm that this information is valid for 93 * @nr_pte_mapped_thp: number of pte mapped THP 94 * @pte_mapped_thp: address array corresponding pte mapped THP 95 */ 96 struct mm_slot { 97 struct hlist_node hash; 98 struct list_head mm_node; 99 struct mm_struct *mm; 100 101 /* pte-mapped THP in this mm */ 102 int nr_pte_mapped_thp; 103 unsigned long pte_mapped_thp[MAX_PTE_MAPPED_THP]; 104 }; 105 106 /** 107 * struct khugepaged_scan - cursor for scanning 108 * @mm_head: the head of the mm list to scan 109 * @mm_slot: the current mm_slot we are scanning 110 * @address: the next address inside that to be scanned 111 * 112 * There is only the one khugepaged_scan instance of this cursor structure. 113 */ 114 struct khugepaged_scan { 115 struct list_head mm_head; 116 struct mm_slot *mm_slot; 117 unsigned long address; 118 }; 119 120 static struct khugepaged_scan khugepaged_scan = { 121 .mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head), 122 }; 123 124 #ifdef CONFIG_SYSFS 125 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj, 126 struct kobj_attribute *attr, 127 char *buf) 128 { 129 return sysfs_emit(buf, "%u\n", khugepaged_scan_sleep_millisecs); 130 } 131 132 static ssize_t scan_sleep_millisecs_store(struct kobject *kobj, 133 struct kobj_attribute *attr, 134 const char *buf, size_t count) 135 { 136 unsigned int msecs; 137 int err; 138 139 err = kstrtouint(buf, 10, &msecs); 140 if (err) 141 return -EINVAL; 142 143 khugepaged_scan_sleep_millisecs = msecs; 144 khugepaged_sleep_expire = 0; 145 wake_up_interruptible(&khugepaged_wait); 146 147 return count; 148 } 149 static struct kobj_attribute scan_sleep_millisecs_attr = 150 __ATTR_RW(scan_sleep_millisecs); 151 152 static ssize_t alloc_sleep_millisecs_show(struct kobject *kobj, 153 struct kobj_attribute *attr, 154 char *buf) 155 { 156 return sysfs_emit(buf, "%u\n", khugepaged_alloc_sleep_millisecs); 157 } 158 159 static ssize_t alloc_sleep_millisecs_store(struct kobject *kobj, 160 struct kobj_attribute *attr, 161 const char *buf, size_t count) 162 { 163 unsigned int msecs; 164 int err; 165 166 err = kstrtouint(buf, 10, &msecs); 167 if (err) 168 return -EINVAL; 169 170 khugepaged_alloc_sleep_millisecs = msecs; 171 khugepaged_sleep_expire = 0; 172 wake_up_interruptible(&khugepaged_wait); 173 174 return count; 175 } 176 static struct kobj_attribute alloc_sleep_millisecs_attr = 177 __ATTR_RW(alloc_sleep_millisecs); 178 179 static ssize_t pages_to_scan_show(struct kobject *kobj, 180 struct kobj_attribute *attr, 181 char *buf) 182 { 183 return sysfs_emit(buf, "%u\n", khugepaged_pages_to_scan); 184 } 185 static ssize_t pages_to_scan_store(struct kobject *kobj, 186 struct kobj_attribute *attr, 187 const char *buf, size_t count) 188 { 189 unsigned int pages; 190 int err; 191 192 err = kstrtouint(buf, 10, &pages); 193 if (err || !pages) 194 return -EINVAL; 195 196 khugepaged_pages_to_scan = pages; 197 198 return count; 199 } 200 static struct kobj_attribute pages_to_scan_attr = 201 __ATTR_RW(pages_to_scan); 202 203 static ssize_t pages_collapsed_show(struct kobject *kobj, 204 struct kobj_attribute *attr, 205 char *buf) 206 { 207 return sysfs_emit(buf, "%u\n", khugepaged_pages_collapsed); 208 } 209 static struct kobj_attribute pages_collapsed_attr = 210 __ATTR_RO(pages_collapsed); 211 212 static ssize_t full_scans_show(struct kobject *kobj, 213 struct kobj_attribute *attr, 214 char *buf) 215 { 216 return sysfs_emit(buf, "%u\n", khugepaged_full_scans); 217 } 218 static struct kobj_attribute full_scans_attr = 219 __ATTR_RO(full_scans); 220 221 static ssize_t defrag_show(struct kobject *kobj, 222 struct kobj_attribute *attr, char *buf) 223 { 224 return single_hugepage_flag_show(kobj, attr, buf, 225 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG); 226 } 227 static ssize_t defrag_store(struct kobject *kobj, 228 struct kobj_attribute *attr, 229 const char *buf, size_t count) 230 { 231 return single_hugepage_flag_store(kobj, attr, buf, count, 232 TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG); 233 } 234 static struct kobj_attribute khugepaged_defrag_attr = 235 __ATTR_RW(defrag); 236 237 /* 238 * max_ptes_none controls if khugepaged should collapse hugepages over 239 * any unmapped ptes in turn potentially increasing the memory 240 * footprint of the vmas. When max_ptes_none is 0 khugepaged will not 241 * reduce the available free memory in the system as it 242 * runs. Increasing max_ptes_none will instead potentially reduce the 243 * free memory in the system during the khugepaged scan. 244 */ 245 static ssize_t max_ptes_none_show(struct kobject *kobj, 246 struct kobj_attribute *attr, 247 char *buf) 248 { 249 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_none); 250 } 251 static ssize_t max_ptes_none_store(struct kobject *kobj, 252 struct kobj_attribute *attr, 253 const char *buf, size_t count) 254 { 255 int err; 256 unsigned long max_ptes_none; 257 258 err = kstrtoul(buf, 10, &max_ptes_none); 259 if (err || max_ptes_none > HPAGE_PMD_NR - 1) 260 return -EINVAL; 261 262 khugepaged_max_ptes_none = max_ptes_none; 263 264 return count; 265 } 266 static struct kobj_attribute khugepaged_max_ptes_none_attr = 267 __ATTR_RW(max_ptes_none); 268 269 static ssize_t max_ptes_swap_show(struct kobject *kobj, 270 struct kobj_attribute *attr, 271 char *buf) 272 { 273 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_swap); 274 } 275 276 static ssize_t max_ptes_swap_store(struct kobject *kobj, 277 struct kobj_attribute *attr, 278 const char *buf, size_t count) 279 { 280 int err; 281 unsigned long max_ptes_swap; 282 283 err = kstrtoul(buf, 10, &max_ptes_swap); 284 if (err || max_ptes_swap > HPAGE_PMD_NR - 1) 285 return -EINVAL; 286 287 khugepaged_max_ptes_swap = max_ptes_swap; 288 289 return count; 290 } 291 292 static struct kobj_attribute khugepaged_max_ptes_swap_attr = 293 __ATTR_RW(max_ptes_swap); 294 295 static ssize_t max_ptes_shared_show(struct kobject *kobj, 296 struct kobj_attribute *attr, 297 char *buf) 298 { 299 return sysfs_emit(buf, "%u\n", khugepaged_max_ptes_shared); 300 } 301 302 static ssize_t max_ptes_shared_store(struct kobject *kobj, 303 struct kobj_attribute *attr, 304 const char *buf, size_t count) 305 { 306 int err; 307 unsigned long max_ptes_shared; 308 309 err = kstrtoul(buf, 10, &max_ptes_shared); 310 if (err || max_ptes_shared > HPAGE_PMD_NR - 1) 311 return -EINVAL; 312 313 khugepaged_max_ptes_shared = max_ptes_shared; 314 315 return count; 316 } 317 318 static struct kobj_attribute khugepaged_max_ptes_shared_attr = 319 __ATTR_RW(max_ptes_shared); 320 321 static struct attribute *khugepaged_attr[] = { 322 &khugepaged_defrag_attr.attr, 323 &khugepaged_max_ptes_none_attr.attr, 324 &khugepaged_max_ptes_swap_attr.attr, 325 &khugepaged_max_ptes_shared_attr.attr, 326 &pages_to_scan_attr.attr, 327 &pages_collapsed_attr.attr, 328 &full_scans_attr.attr, 329 &scan_sleep_millisecs_attr.attr, 330 &alloc_sleep_millisecs_attr.attr, 331 NULL, 332 }; 333 334 struct attribute_group khugepaged_attr_group = { 335 .attrs = khugepaged_attr, 336 .name = "khugepaged", 337 }; 338 #endif /* CONFIG_SYSFS */ 339 340 int hugepage_madvise(struct vm_area_struct *vma, 341 unsigned long *vm_flags, int advice) 342 { 343 switch (advice) { 344 case MADV_HUGEPAGE: 345 #ifdef CONFIG_S390 346 /* 347 * qemu blindly sets MADV_HUGEPAGE on all allocations, but s390 348 * can't handle this properly after s390_enable_sie, so we simply 349 * ignore the madvise to prevent qemu from causing a SIGSEGV. 350 */ 351 if (mm_has_pgste(vma->vm_mm)) 352 return 0; 353 #endif 354 *vm_flags &= ~VM_NOHUGEPAGE; 355 *vm_flags |= VM_HUGEPAGE; 356 /* 357 * If the vma become good for khugepaged to scan, 358 * register it here without waiting a page fault that 359 * may not happen any time soon. 360 */ 361 khugepaged_enter_vma(vma, *vm_flags); 362 break; 363 case MADV_NOHUGEPAGE: 364 *vm_flags &= ~VM_HUGEPAGE; 365 *vm_flags |= VM_NOHUGEPAGE; 366 /* 367 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning 368 * this vma even if we leave the mm registered in khugepaged if 369 * it got registered before VM_NOHUGEPAGE was set. 370 */ 371 break; 372 } 373 374 return 0; 375 } 376 377 int __init khugepaged_init(void) 378 { 379 mm_slot_cache = kmem_cache_create("khugepaged_mm_slot", 380 sizeof(struct mm_slot), 381 __alignof__(struct mm_slot), 0, NULL); 382 if (!mm_slot_cache) 383 return -ENOMEM; 384 385 khugepaged_pages_to_scan = HPAGE_PMD_NR * 8; 386 khugepaged_max_ptes_none = HPAGE_PMD_NR - 1; 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 struct mm_slot *alloc_mm_slot(void) 399 { 400 if (!mm_slot_cache) /* initialization failed */ 401 return NULL; 402 return kmem_cache_zalloc(mm_slot_cache, GFP_KERNEL); 403 } 404 405 static inline void free_mm_slot(struct mm_slot *mm_slot) 406 { 407 kmem_cache_free(mm_slot_cache, mm_slot); 408 } 409 410 static struct mm_slot *get_mm_slot(struct mm_struct *mm) 411 { 412 struct mm_slot *mm_slot; 413 414 hash_for_each_possible(mm_slots_hash, mm_slot, hash, (unsigned long)mm) 415 if (mm == mm_slot->mm) 416 return mm_slot; 417 418 return NULL; 419 } 420 421 static void insert_to_mm_slots_hash(struct mm_struct *mm, 422 struct mm_slot *mm_slot) 423 { 424 mm_slot->mm = mm; 425 hash_add(mm_slots_hash, &mm_slot->hash, (long)mm); 426 } 427 428 static inline int khugepaged_test_exit(struct mm_struct *mm) 429 { 430 return atomic_read(&mm->mm_users) == 0; 431 } 432 433 bool hugepage_vma_check(struct vm_area_struct *vma, 434 unsigned long vm_flags) 435 { 436 if (!transhuge_vma_enabled(vma, vm_flags)) 437 return false; 438 439 if (vm_flags & VM_NO_KHUGEPAGED) 440 return false; 441 442 /* Don't run khugepaged against DAX vma */ 443 if (vma_is_dax(vma)) 444 return false; 445 446 if (vma->vm_file && !IS_ALIGNED((vma->vm_start >> PAGE_SHIFT) - 447 vma->vm_pgoff, HPAGE_PMD_NR)) 448 return false; 449 450 /* Enabled via shmem mount options or sysfs settings. */ 451 if (shmem_file(vma->vm_file)) 452 return shmem_huge_enabled(vma); 453 454 if (!khugepaged_enabled()) 455 return false; 456 457 /* THP settings require madvise. */ 458 if (!(vm_flags & VM_HUGEPAGE) && !khugepaged_always()) 459 return false; 460 461 /* Only regular file is valid */ 462 if (file_thp_enabled(vma)) 463 return true; 464 465 if (!vma->anon_vma || !vma_is_anonymous(vma)) 466 return false; 467 if (vma_is_temporary_stack(vma)) 468 return false; 469 470 return true; 471 } 472 473 void __khugepaged_enter(struct mm_struct *mm) 474 { 475 struct mm_slot *mm_slot; 476 int wakeup; 477 478 mm_slot = alloc_mm_slot(); 479 if (!mm_slot) 480 return; 481 482 /* __khugepaged_exit() must not run from under us */ 483 VM_BUG_ON_MM(khugepaged_test_exit(mm), mm); 484 if (unlikely(test_and_set_bit(MMF_VM_HUGEPAGE, &mm->flags))) { 485 free_mm_slot(mm_slot); 486 return; 487 } 488 489 spin_lock(&khugepaged_mm_lock); 490 insert_to_mm_slots_hash(mm, mm_slot); 491 /* 492 * Insert just behind the scanning cursor, to let the area settle 493 * down a little. 494 */ 495 wakeup = list_empty(&khugepaged_scan.mm_head); 496 list_add_tail(&mm_slot->mm_node, &khugepaged_scan.mm_head); 497 spin_unlock(&khugepaged_mm_lock); 498 499 mmgrab(mm); 500 if (wakeup) 501 wake_up_interruptible(&khugepaged_wait); 502 } 503 504 void khugepaged_enter_vma(struct vm_area_struct *vma, 505 unsigned long vm_flags) 506 { 507 if (!test_bit(MMF_VM_HUGEPAGE, &vma->vm_mm->flags) && 508 khugepaged_enabled() && 509 (((vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK) < 510 (vma->vm_end & HPAGE_PMD_MASK))) { 511 if (hugepage_vma_check(vma, vm_flags)) 512 __khugepaged_enter(vma->vm_mm); 513 } 514 } 515 516 void __khugepaged_exit(struct mm_struct *mm) 517 { 518 struct mm_slot *mm_slot; 519 int free = 0; 520 521 spin_lock(&khugepaged_mm_lock); 522 mm_slot = get_mm_slot(mm); 523 if (mm_slot && khugepaged_scan.mm_slot != mm_slot) { 524 hash_del(&mm_slot->hash); 525 list_del(&mm_slot->mm_node); 526 free = 1; 527 } 528 spin_unlock(&khugepaged_mm_lock); 529 530 if (free) { 531 clear_bit(MMF_VM_HUGEPAGE, &mm->flags); 532 free_mm_slot(mm_slot); 533 mmdrop(mm); 534 } else if (mm_slot) { 535 /* 536 * This is required to serialize against 537 * khugepaged_test_exit() (which is guaranteed to run 538 * under mmap sem read mode). Stop here (after we 539 * return all pagetables will be destroyed) until 540 * khugepaged has finished working on the pagetables 541 * under the mmap_lock. 542 */ 543 mmap_write_lock(mm); 544 mmap_write_unlock(mm); 545 } 546 } 547 548 static void release_pte_page(struct page *page) 549 { 550 mod_node_page_state(page_pgdat(page), 551 NR_ISOLATED_ANON + page_is_file_lru(page), 552 -compound_nr(page)); 553 unlock_page(page); 554 putback_lru_page(page); 555 } 556 557 static void release_pte_pages(pte_t *pte, pte_t *_pte, 558 struct list_head *compound_pagelist) 559 { 560 struct page *page, *tmp; 561 562 while (--_pte >= pte) { 563 pte_t pteval = *_pte; 564 565 page = pte_page(pteval); 566 if (!pte_none(pteval) && !is_zero_pfn(pte_pfn(pteval)) && 567 !PageCompound(page)) 568 release_pte_page(page); 569 } 570 571 list_for_each_entry_safe(page, tmp, compound_pagelist, lru) { 572 list_del(&page->lru); 573 release_pte_page(page); 574 } 575 } 576 577 static bool is_refcount_suitable(struct page *page) 578 { 579 int expected_refcount; 580 581 expected_refcount = total_mapcount(page); 582 if (PageSwapCache(page)) 583 expected_refcount += compound_nr(page); 584 585 return page_count(page) == expected_refcount; 586 } 587 588 static int __collapse_huge_page_isolate(struct vm_area_struct *vma, 589 unsigned long address, 590 pte_t *pte, 591 struct list_head *compound_pagelist) 592 { 593 struct page *page = NULL; 594 pte_t *_pte; 595 int none_or_zero = 0, shared = 0, result = 0, referenced = 0; 596 bool writable = false; 597 598 for (_pte = pte; _pte < pte + HPAGE_PMD_NR; 599 _pte++, address += PAGE_SIZE) { 600 pte_t pteval = *_pte; 601 if (pte_none(pteval) || (pte_present(pteval) && 602 is_zero_pfn(pte_pfn(pteval)))) { 603 if (!userfaultfd_armed(vma) && 604 ++none_or_zero <= khugepaged_max_ptes_none) { 605 continue; 606 } else { 607 result = SCAN_EXCEED_NONE_PTE; 608 count_vm_event(THP_SCAN_EXCEED_NONE_PTE); 609 goto out; 610 } 611 } 612 if (!pte_present(pteval)) { 613 result = SCAN_PTE_NON_PRESENT; 614 goto out; 615 } 616 page = vm_normal_page(vma, address, pteval); 617 if (unlikely(!page) || unlikely(is_zone_device_page(page))) { 618 result = SCAN_PAGE_NULL; 619 goto out; 620 } 621 622 VM_BUG_ON_PAGE(!PageAnon(page), page); 623 624 if (page_mapcount(page) > 1 && 625 ++shared > khugepaged_max_ptes_shared) { 626 result = SCAN_EXCEED_SHARED_PTE; 627 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE); 628 goto out; 629 } 630 631 if (PageCompound(page)) { 632 struct page *p; 633 page = compound_head(page); 634 635 /* 636 * Check if we have dealt with the compound page 637 * already 638 */ 639 list_for_each_entry(p, compound_pagelist, lru) { 640 if (page == p) 641 goto next; 642 } 643 } 644 645 /* 646 * We can do it before isolate_lru_page because the 647 * page can't be freed from under us. NOTE: PG_lock 648 * is needed to serialize against split_huge_page 649 * when invoked from the VM. 650 */ 651 if (!trylock_page(page)) { 652 result = SCAN_PAGE_LOCK; 653 goto out; 654 } 655 656 /* 657 * Check if the page has any GUP (or other external) pins. 658 * 659 * The page table that maps the page has been already unlinked 660 * from the page table tree and this process cannot get 661 * an additional pin on the page. 662 * 663 * New pins can come later if the page is shared across fork, 664 * but not from this process. The other process cannot write to 665 * the page, only trigger CoW. 666 */ 667 if (!is_refcount_suitable(page)) { 668 unlock_page(page); 669 result = SCAN_PAGE_COUNT; 670 goto out; 671 } 672 673 /* 674 * Isolate the page to avoid collapsing an hugepage 675 * currently in use by the VM. 676 */ 677 if (isolate_lru_page(page)) { 678 unlock_page(page); 679 result = SCAN_DEL_PAGE_LRU; 680 goto out; 681 } 682 mod_node_page_state(page_pgdat(page), 683 NR_ISOLATED_ANON + page_is_file_lru(page), 684 compound_nr(page)); 685 VM_BUG_ON_PAGE(!PageLocked(page), page); 686 VM_BUG_ON_PAGE(PageLRU(page), page); 687 688 if (PageCompound(page)) 689 list_add_tail(&page->lru, compound_pagelist); 690 next: 691 /* There should be enough young pte to collapse the page */ 692 if (pte_young(pteval) || 693 page_is_young(page) || PageReferenced(page) || 694 mmu_notifier_test_young(vma->vm_mm, address)) 695 referenced++; 696 697 if (pte_write(pteval)) 698 writable = true; 699 } 700 701 if (unlikely(!writable)) { 702 result = SCAN_PAGE_RO; 703 } else if (unlikely(!referenced)) { 704 result = SCAN_LACK_REFERENCED_PAGE; 705 } else { 706 result = SCAN_SUCCEED; 707 trace_mm_collapse_huge_page_isolate(page, none_or_zero, 708 referenced, writable, result); 709 return 1; 710 } 711 out: 712 release_pte_pages(pte, _pte, compound_pagelist); 713 trace_mm_collapse_huge_page_isolate(page, none_or_zero, 714 referenced, writable, result); 715 return 0; 716 } 717 718 static void __collapse_huge_page_copy(pte_t *pte, struct page *page, 719 struct vm_area_struct *vma, 720 unsigned long address, 721 spinlock_t *ptl, 722 struct list_head *compound_pagelist) 723 { 724 struct page *src_page, *tmp; 725 pte_t *_pte; 726 for (_pte = pte; _pte < pte + HPAGE_PMD_NR; 727 _pte++, page++, address += PAGE_SIZE) { 728 pte_t pteval = *_pte; 729 730 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) { 731 clear_user_highpage(page, address); 732 add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1); 733 if (is_zero_pfn(pte_pfn(pteval))) { 734 /* 735 * ptl mostly unnecessary. 736 */ 737 spin_lock(ptl); 738 ptep_clear(vma->vm_mm, address, _pte); 739 spin_unlock(ptl); 740 } 741 } else { 742 src_page = pte_page(pteval); 743 copy_user_highpage(page, src_page, address, vma); 744 if (!PageCompound(src_page)) 745 release_pte_page(src_page); 746 /* 747 * ptl mostly unnecessary, but preempt has to 748 * be disabled to update the per-cpu stats 749 * inside page_remove_rmap(). 750 */ 751 spin_lock(ptl); 752 ptep_clear(vma->vm_mm, address, _pte); 753 page_remove_rmap(src_page, vma, false); 754 spin_unlock(ptl); 755 free_page_and_swap_cache(src_page); 756 } 757 } 758 759 list_for_each_entry_safe(src_page, tmp, compound_pagelist, lru) { 760 list_del(&src_page->lru); 761 mod_node_page_state(page_pgdat(src_page), 762 NR_ISOLATED_ANON + page_is_file_lru(src_page), 763 -compound_nr(src_page)); 764 unlock_page(src_page); 765 free_swap_cache(src_page); 766 putback_lru_page(src_page); 767 } 768 } 769 770 static void khugepaged_alloc_sleep(void) 771 { 772 DEFINE_WAIT(wait); 773 774 add_wait_queue(&khugepaged_wait, &wait); 775 freezable_schedule_timeout_interruptible( 776 msecs_to_jiffies(khugepaged_alloc_sleep_millisecs)); 777 remove_wait_queue(&khugepaged_wait, &wait); 778 } 779 780 static int khugepaged_node_load[MAX_NUMNODES]; 781 782 static bool khugepaged_scan_abort(int nid) 783 { 784 int i; 785 786 /* 787 * If node_reclaim_mode is disabled, then no extra effort is made to 788 * allocate memory locally. 789 */ 790 if (!node_reclaim_enabled()) 791 return false; 792 793 /* If there is a count for this node already, it must be acceptable */ 794 if (khugepaged_node_load[nid]) 795 return false; 796 797 for (i = 0; i < MAX_NUMNODES; i++) { 798 if (!khugepaged_node_load[i]) 799 continue; 800 if (node_distance(nid, i) > node_reclaim_distance) 801 return true; 802 } 803 return false; 804 } 805 806 /* Defrag for khugepaged will enter direct reclaim/compaction if necessary */ 807 static inline gfp_t alloc_hugepage_khugepaged_gfpmask(void) 808 { 809 return khugepaged_defrag() ? GFP_TRANSHUGE : GFP_TRANSHUGE_LIGHT; 810 } 811 812 #ifdef CONFIG_NUMA 813 static int khugepaged_find_target_node(void) 814 { 815 static int last_khugepaged_target_node = NUMA_NO_NODE; 816 int nid, target_node = 0, max_value = 0; 817 818 /* find first node with max normal pages hit */ 819 for (nid = 0; nid < MAX_NUMNODES; nid++) 820 if (khugepaged_node_load[nid] > max_value) { 821 max_value = khugepaged_node_load[nid]; 822 target_node = nid; 823 } 824 825 /* do some balance if several nodes have the same hit record */ 826 if (target_node <= last_khugepaged_target_node) 827 for (nid = last_khugepaged_target_node + 1; nid < MAX_NUMNODES; 828 nid++) 829 if (max_value == khugepaged_node_load[nid]) { 830 target_node = nid; 831 break; 832 } 833 834 last_khugepaged_target_node = target_node; 835 return target_node; 836 } 837 838 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait) 839 { 840 if (IS_ERR(*hpage)) { 841 if (!*wait) 842 return false; 843 844 *wait = false; 845 *hpage = NULL; 846 khugepaged_alloc_sleep(); 847 } else if (*hpage) { 848 put_page(*hpage); 849 *hpage = NULL; 850 } 851 852 return true; 853 } 854 855 static struct page * 856 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node) 857 { 858 VM_BUG_ON_PAGE(*hpage, *hpage); 859 860 *hpage = __alloc_pages_node(node, gfp, HPAGE_PMD_ORDER); 861 if (unlikely(!*hpage)) { 862 count_vm_event(THP_COLLAPSE_ALLOC_FAILED); 863 *hpage = ERR_PTR(-ENOMEM); 864 return NULL; 865 } 866 867 prep_transhuge_page(*hpage); 868 count_vm_event(THP_COLLAPSE_ALLOC); 869 return *hpage; 870 } 871 #else 872 static int khugepaged_find_target_node(void) 873 { 874 return 0; 875 } 876 877 static inline struct page *alloc_khugepaged_hugepage(void) 878 { 879 struct page *page; 880 881 page = alloc_pages(alloc_hugepage_khugepaged_gfpmask(), 882 HPAGE_PMD_ORDER); 883 if (page) 884 prep_transhuge_page(page); 885 return page; 886 } 887 888 static struct page *khugepaged_alloc_hugepage(bool *wait) 889 { 890 struct page *hpage; 891 892 do { 893 hpage = alloc_khugepaged_hugepage(); 894 if (!hpage) { 895 count_vm_event(THP_COLLAPSE_ALLOC_FAILED); 896 if (!*wait) 897 return NULL; 898 899 *wait = false; 900 khugepaged_alloc_sleep(); 901 } else 902 count_vm_event(THP_COLLAPSE_ALLOC); 903 } while (unlikely(!hpage) && likely(khugepaged_enabled())); 904 905 return hpage; 906 } 907 908 static bool khugepaged_prealloc_page(struct page **hpage, bool *wait) 909 { 910 /* 911 * If the hpage allocated earlier was briefly exposed in page cache 912 * before collapse_file() failed, it is possible that racing lookups 913 * have not yet completed, and would then be unpleasantly surprised by 914 * finding the hpage reused for the same mapping at a different offset. 915 * Just release the previous allocation if there is any danger of that. 916 */ 917 if (*hpage && page_count(*hpage) > 1) { 918 put_page(*hpage); 919 *hpage = NULL; 920 } 921 922 if (!*hpage) 923 *hpage = khugepaged_alloc_hugepage(wait); 924 925 if (unlikely(!*hpage)) 926 return false; 927 928 return true; 929 } 930 931 static struct page * 932 khugepaged_alloc_page(struct page **hpage, gfp_t gfp, int node) 933 { 934 VM_BUG_ON(!*hpage); 935 936 return *hpage; 937 } 938 #endif 939 940 /* 941 * If mmap_lock temporarily dropped, revalidate vma 942 * before taking mmap_lock. 943 * Return 0 if succeeds, otherwise return none-zero 944 * value (scan code). 945 */ 946 947 static int hugepage_vma_revalidate(struct mm_struct *mm, unsigned long address, 948 struct vm_area_struct **vmap) 949 { 950 struct vm_area_struct *vma; 951 unsigned long hstart, hend; 952 953 if (unlikely(khugepaged_test_exit(mm))) 954 return SCAN_ANY_PROCESS; 955 956 *vmap = vma = find_vma(mm, address); 957 if (!vma) 958 return SCAN_VMA_NULL; 959 960 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK; 961 hend = vma->vm_end & HPAGE_PMD_MASK; 962 if (address < hstart || address + HPAGE_PMD_SIZE > hend) 963 return SCAN_ADDRESS_RANGE; 964 if (!hugepage_vma_check(vma, vma->vm_flags)) 965 return SCAN_VMA_CHECK; 966 /* Anon VMA expected */ 967 if (!vma->anon_vma || !vma_is_anonymous(vma)) 968 return SCAN_VMA_CHECK; 969 return 0; 970 } 971 972 /* 973 * Bring missing pages in from swap, to complete THP collapse. 974 * Only done if khugepaged_scan_pmd believes it is worthwhile. 975 * 976 * Called and returns without pte mapped or spinlocks held. 977 * Note that if false is returned, mmap_lock will be released. 978 */ 979 980 static bool __collapse_huge_page_swapin(struct mm_struct *mm, 981 struct vm_area_struct *vma, 982 unsigned long haddr, pmd_t *pmd, 983 int referenced) 984 { 985 int swapped_in = 0; 986 vm_fault_t ret = 0; 987 unsigned long address, end = haddr + (HPAGE_PMD_NR * PAGE_SIZE); 988 989 for (address = haddr; address < end; address += PAGE_SIZE) { 990 struct vm_fault vmf = { 991 .vma = vma, 992 .address = address, 993 .pgoff = linear_page_index(vma, haddr), 994 .flags = FAULT_FLAG_ALLOW_RETRY, 995 .pmd = pmd, 996 }; 997 998 vmf.pte = pte_offset_map(pmd, address); 999 vmf.orig_pte = *vmf.pte; 1000 if (!is_swap_pte(vmf.orig_pte)) { 1001 pte_unmap(vmf.pte); 1002 continue; 1003 } 1004 ret = do_swap_page(&vmf); 1005 1006 /* 1007 * do_swap_page returns VM_FAULT_RETRY with released mmap_lock. 1008 * Note we treat VM_FAULT_RETRY as VM_FAULT_ERROR here because 1009 * we do not retry here and swap entry will remain in pagetable 1010 * resulting in later failure. 1011 */ 1012 if (ret & VM_FAULT_RETRY) { 1013 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0); 1014 return false; 1015 } 1016 if (ret & VM_FAULT_ERROR) { 1017 mmap_read_unlock(mm); 1018 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 0); 1019 return false; 1020 } 1021 swapped_in++; 1022 } 1023 1024 /* Drain LRU add pagevec to remove extra pin on the swapped in pages */ 1025 if (swapped_in) 1026 lru_add_drain(); 1027 1028 trace_mm_collapse_huge_page_swapin(mm, swapped_in, referenced, 1); 1029 return true; 1030 } 1031 1032 static void collapse_huge_page(struct mm_struct *mm, 1033 unsigned long address, 1034 struct page **hpage, 1035 int node, int referenced, int unmapped) 1036 { 1037 LIST_HEAD(compound_pagelist); 1038 pmd_t *pmd, _pmd; 1039 pte_t *pte; 1040 pgtable_t pgtable; 1041 struct page *new_page; 1042 spinlock_t *pmd_ptl, *pte_ptl; 1043 int isolated = 0, result = 0; 1044 struct vm_area_struct *vma; 1045 struct mmu_notifier_range range; 1046 gfp_t gfp; 1047 1048 VM_BUG_ON(address & ~HPAGE_PMD_MASK); 1049 1050 /* Only allocate from the target node */ 1051 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE; 1052 1053 /* 1054 * Before allocating the hugepage, release the mmap_lock read lock. 1055 * The allocation can take potentially a long time if it involves 1056 * sync compaction, and we do not need to hold the mmap_lock during 1057 * that. We will recheck the vma after taking it again in write mode. 1058 */ 1059 mmap_read_unlock(mm); 1060 new_page = khugepaged_alloc_page(hpage, gfp, node); 1061 if (!new_page) { 1062 result = SCAN_ALLOC_HUGE_PAGE_FAIL; 1063 goto out_nolock; 1064 } 1065 1066 if (unlikely(mem_cgroup_charge(page_folio(new_page), mm, gfp))) { 1067 result = SCAN_CGROUP_CHARGE_FAIL; 1068 goto out_nolock; 1069 } 1070 count_memcg_page_event(new_page, THP_COLLAPSE_ALLOC); 1071 1072 mmap_read_lock(mm); 1073 result = hugepage_vma_revalidate(mm, address, &vma); 1074 if (result) { 1075 mmap_read_unlock(mm); 1076 goto out_nolock; 1077 } 1078 1079 pmd = mm_find_pmd(mm, address); 1080 if (!pmd) { 1081 result = SCAN_PMD_NULL; 1082 mmap_read_unlock(mm); 1083 goto out_nolock; 1084 } 1085 1086 /* 1087 * __collapse_huge_page_swapin will return with mmap_lock released 1088 * when it fails. So we jump out_nolock directly in that case. 1089 * Continuing to collapse causes inconsistency. 1090 */ 1091 if (unmapped && !__collapse_huge_page_swapin(mm, vma, address, 1092 pmd, referenced)) { 1093 goto out_nolock; 1094 } 1095 1096 mmap_read_unlock(mm); 1097 /* 1098 * Prevent all access to pagetables with the exception of 1099 * gup_fast later handled by the ptep_clear_flush and the VM 1100 * handled by the anon_vma lock + PG_lock. 1101 */ 1102 mmap_write_lock(mm); 1103 result = hugepage_vma_revalidate(mm, address, &vma); 1104 if (result) 1105 goto out_up_write; 1106 /* check if the pmd is still valid */ 1107 if (mm_find_pmd(mm, address) != pmd) 1108 goto out_up_write; 1109 1110 anon_vma_lock_write(vma->anon_vma); 1111 1112 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, NULL, mm, 1113 address, address + HPAGE_PMD_SIZE); 1114 mmu_notifier_invalidate_range_start(&range); 1115 1116 pte = pte_offset_map(pmd, address); 1117 pte_ptl = pte_lockptr(mm, pmd); 1118 1119 pmd_ptl = pmd_lock(mm, pmd); /* probably unnecessary */ 1120 /* 1121 * After this gup_fast can't run anymore. This also removes 1122 * any huge TLB entry from the CPU so we won't allow 1123 * huge and small TLB entries for the same virtual address 1124 * to avoid the risk of CPU bugs in that area. 1125 */ 1126 _pmd = pmdp_collapse_flush(vma, address, pmd); 1127 spin_unlock(pmd_ptl); 1128 mmu_notifier_invalidate_range_end(&range); 1129 1130 spin_lock(pte_ptl); 1131 isolated = __collapse_huge_page_isolate(vma, address, pte, 1132 &compound_pagelist); 1133 spin_unlock(pte_ptl); 1134 1135 if (unlikely(!isolated)) { 1136 pte_unmap(pte); 1137 spin_lock(pmd_ptl); 1138 BUG_ON(!pmd_none(*pmd)); 1139 /* 1140 * We can only use set_pmd_at when establishing 1141 * hugepmds and never for establishing regular pmds that 1142 * points to regular pagetables. Use pmd_populate for that 1143 */ 1144 pmd_populate(mm, pmd, pmd_pgtable(_pmd)); 1145 spin_unlock(pmd_ptl); 1146 anon_vma_unlock_write(vma->anon_vma); 1147 result = SCAN_FAIL; 1148 goto out_up_write; 1149 } 1150 1151 /* 1152 * All pages are isolated and locked so anon_vma rmap 1153 * can't run anymore. 1154 */ 1155 anon_vma_unlock_write(vma->anon_vma); 1156 1157 __collapse_huge_page_copy(pte, new_page, vma, address, pte_ptl, 1158 &compound_pagelist); 1159 pte_unmap(pte); 1160 /* 1161 * spin_lock() below is not the equivalent of smp_wmb(), but 1162 * the smp_wmb() inside __SetPageUptodate() can be reused to 1163 * avoid the copy_huge_page writes to become visible after 1164 * the set_pmd_at() write. 1165 */ 1166 __SetPageUptodate(new_page); 1167 pgtable = pmd_pgtable(_pmd); 1168 1169 _pmd = mk_huge_pmd(new_page, vma->vm_page_prot); 1170 _pmd = maybe_pmd_mkwrite(pmd_mkdirty(_pmd), vma); 1171 1172 spin_lock(pmd_ptl); 1173 BUG_ON(!pmd_none(*pmd)); 1174 page_add_new_anon_rmap(new_page, vma, address); 1175 lru_cache_add_inactive_or_unevictable(new_page, vma); 1176 pgtable_trans_huge_deposit(mm, pmd, pgtable); 1177 set_pmd_at(mm, address, pmd, _pmd); 1178 update_mmu_cache_pmd(vma, address, pmd); 1179 spin_unlock(pmd_ptl); 1180 1181 *hpage = NULL; 1182 1183 khugepaged_pages_collapsed++; 1184 result = SCAN_SUCCEED; 1185 out_up_write: 1186 mmap_write_unlock(mm); 1187 out_nolock: 1188 if (!IS_ERR_OR_NULL(*hpage)) 1189 mem_cgroup_uncharge(page_folio(*hpage)); 1190 trace_mm_collapse_huge_page(mm, isolated, result); 1191 return; 1192 } 1193 1194 static int khugepaged_scan_pmd(struct mm_struct *mm, 1195 struct vm_area_struct *vma, 1196 unsigned long address, 1197 struct page **hpage) 1198 { 1199 pmd_t *pmd; 1200 pte_t *pte, *_pte; 1201 int ret = 0, result = 0, referenced = 0; 1202 int none_or_zero = 0, shared = 0; 1203 struct page *page = NULL; 1204 unsigned long _address; 1205 spinlock_t *ptl; 1206 int node = NUMA_NO_NODE, unmapped = 0; 1207 bool writable = false; 1208 1209 VM_BUG_ON(address & ~HPAGE_PMD_MASK); 1210 1211 pmd = mm_find_pmd(mm, address); 1212 if (!pmd) { 1213 result = SCAN_PMD_NULL; 1214 goto out; 1215 } 1216 1217 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load)); 1218 pte = pte_offset_map_lock(mm, pmd, address, &ptl); 1219 for (_address = address, _pte = pte; _pte < pte + HPAGE_PMD_NR; 1220 _pte++, _address += PAGE_SIZE) { 1221 pte_t pteval = *_pte; 1222 if (is_swap_pte(pteval)) { 1223 if (++unmapped <= khugepaged_max_ptes_swap) { 1224 /* 1225 * Always be strict with uffd-wp 1226 * enabled swap entries. Please see 1227 * comment below for pte_uffd_wp(). 1228 */ 1229 if (pte_swp_uffd_wp(pteval)) { 1230 result = SCAN_PTE_UFFD_WP; 1231 goto out_unmap; 1232 } 1233 continue; 1234 } else { 1235 result = SCAN_EXCEED_SWAP_PTE; 1236 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE); 1237 goto out_unmap; 1238 } 1239 } 1240 if (pte_none(pteval) || is_zero_pfn(pte_pfn(pteval))) { 1241 if (!userfaultfd_armed(vma) && 1242 ++none_or_zero <= khugepaged_max_ptes_none) { 1243 continue; 1244 } else { 1245 result = SCAN_EXCEED_NONE_PTE; 1246 count_vm_event(THP_SCAN_EXCEED_NONE_PTE); 1247 goto out_unmap; 1248 } 1249 } 1250 if (pte_uffd_wp(pteval)) { 1251 /* 1252 * Don't collapse the page if any of the small 1253 * PTEs are armed with uffd write protection. 1254 * Here we can also mark the new huge pmd as 1255 * write protected if any of the small ones is 1256 * marked but that could bring unknown 1257 * userfault messages that falls outside of 1258 * the registered range. So, just be simple. 1259 */ 1260 result = SCAN_PTE_UFFD_WP; 1261 goto out_unmap; 1262 } 1263 if (pte_write(pteval)) 1264 writable = true; 1265 1266 page = vm_normal_page(vma, _address, pteval); 1267 if (unlikely(!page) || unlikely(is_zone_device_page(page))) { 1268 result = SCAN_PAGE_NULL; 1269 goto out_unmap; 1270 } 1271 1272 if (page_mapcount(page) > 1 && 1273 ++shared > khugepaged_max_ptes_shared) { 1274 result = SCAN_EXCEED_SHARED_PTE; 1275 count_vm_event(THP_SCAN_EXCEED_SHARED_PTE); 1276 goto out_unmap; 1277 } 1278 1279 page = compound_head(page); 1280 1281 /* 1282 * Record which node the original page is from and save this 1283 * information to khugepaged_node_load[]. 1284 * Khugepaged will allocate hugepage from the node has the max 1285 * hit record. 1286 */ 1287 node = page_to_nid(page); 1288 if (khugepaged_scan_abort(node)) { 1289 result = SCAN_SCAN_ABORT; 1290 goto out_unmap; 1291 } 1292 khugepaged_node_load[node]++; 1293 if (!PageLRU(page)) { 1294 result = SCAN_PAGE_LRU; 1295 goto out_unmap; 1296 } 1297 if (PageLocked(page)) { 1298 result = SCAN_PAGE_LOCK; 1299 goto out_unmap; 1300 } 1301 if (!PageAnon(page)) { 1302 result = SCAN_PAGE_ANON; 1303 goto out_unmap; 1304 } 1305 1306 /* 1307 * Check if the page has any GUP (or other external) pins. 1308 * 1309 * Here the check is racy it may see total_mapcount > refcount 1310 * in some cases. 1311 * For example, one process with one forked child process. 1312 * The parent has the PMD split due to MADV_DONTNEED, then 1313 * the child is trying unmap the whole PMD, but khugepaged 1314 * may be scanning the parent between the child has 1315 * PageDoubleMap flag cleared and dec the mapcount. So 1316 * khugepaged may see total_mapcount > refcount. 1317 * 1318 * But such case is ephemeral we could always retry collapse 1319 * later. However it may report false positive if the page 1320 * has excessive GUP pins (i.e. 512). Anyway the same check 1321 * will be done again later the risk seems low. 1322 */ 1323 if (!is_refcount_suitable(page)) { 1324 result = SCAN_PAGE_COUNT; 1325 goto out_unmap; 1326 } 1327 if (pte_young(pteval) || 1328 page_is_young(page) || PageReferenced(page) || 1329 mmu_notifier_test_young(vma->vm_mm, address)) 1330 referenced++; 1331 } 1332 if (!writable) { 1333 result = SCAN_PAGE_RO; 1334 } else if (!referenced || (unmapped && referenced < HPAGE_PMD_NR/2)) { 1335 result = SCAN_LACK_REFERENCED_PAGE; 1336 } else { 1337 result = SCAN_SUCCEED; 1338 ret = 1; 1339 } 1340 out_unmap: 1341 pte_unmap_unlock(pte, ptl); 1342 if (ret) { 1343 node = khugepaged_find_target_node(); 1344 /* collapse_huge_page will return with the mmap_lock released */ 1345 collapse_huge_page(mm, address, hpage, node, 1346 referenced, unmapped); 1347 } 1348 out: 1349 trace_mm_khugepaged_scan_pmd(mm, page, writable, referenced, 1350 none_or_zero, result, unmapped); 1351 return ret; 1352 } 1353 1354 static void collect_mm_slot(struct mm_slot *mm_slot) 1355 { 1356 struct mm_struct *mm = mm_slot->mm; 1357 1358 lockdep_assert_held(&khugepaged_mm_lock); 1359 1360 if (khugepaged_test_exit(mm)) { 1361 /* free mm_slot */ 1362 hash_del(&mm_slot->hash); 1363 list_del(&mm_slot->mm_node); 1364 1365 /* 1366 * Not strictly needed because the mm exited already. 1367 * 1368 * clear_bit(MMF_VM_HUGEPAGE, &mm->flags); 1369 */ 1370 1371 /* khugepaged_mm_lock actually not necessary for the below */ 1372 free_mm_slot(mm_slot); 1373 mmdrop(mm); 1374 } 1375 } 1376 1377 #ifdef CONFIG_SHMEM 1378 /* 1379 * Notify khugepaged that given addr of the mm is pte-mapped THP. Then 1380 * khugepaged should try to collapse the page table. 1381 */ 1382 static void khugepaged_add_pte_mapped_thp(struct mm_struct *mm, 1383 unsigned long addr) 1384 { 1385 struct mm_slot *mm_slot; 1386 1387 VM_BUG_ON(addr & ~HPAGE_PMD_MASK); 1388 1389 spin_lock(&khugepaged_mm_lock); 1390 mm_slot = get_mm_slot(mm); 1391 if (likely(mm_slot && mm_slot->nr_pte_mapped_thp < MAX_PTE_MAPPED_THP)) 1392 mm_slot->pte_mapped_thp[mm_slot->nr_pte_mapped_thp++] = addr; 1393 spin_unlock(&khugepaged_mm_lock); 1394 } 1395 1396 static void collapse_and_free_pmd(struct mm_struct *mm, struct vm_area_struct *vma, 1397 unsigned long addr, pmd_t *pmdp) 1398 { 1399 spinlock_t *ptl; 1400 pmd_t pmd; 1401 1402 mmap_assert_write_locked(mm); 1403 ptl = pmd_lock(vma->vm_mm, pmdp); 1404 pmd = pmdp_collapse_flush(vma, addr, pmdp); 1405 spin_unlock(ptl); 1406 mm_dec_nr_ptes(mm); 1407 page_table_check_pte_clear_range(mm, addr, pmd); 1408 pte_free(mm, pmd_pgtable(pmd)); 1409 } 1410 1411 /** 1412 * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at 1413 * address haddr. 1414 * 1415 * @mm: process address space where collapse happens 1416 * @addr: THP collapse address 1417 * 1418 * This function checks whether all the PTEs in the PMD are pointing to the 1419 * right THP. If so, retract the page table so the THP can refault in with 1420 * as pmd-mapped. 1421 */ 1422 void collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr) 1423 { 1424 unsigned long haddr = addr & HPAGE_PMD_MASK; 1425 struct vm_area_struct *vma = find_vma(mm, haddr); 1426 struct page *hpage; 1427 pte_t *start_pte, *pte; 1428 pmd_t *pmd; 1429 spinlock_t *ptl; 1430 int count = 0; 1431 int i; 1432 1433 if (!vma || !vma->vm_file || 1434 !range_in_vma(vma, haddr, haddr + HPAGE_PMD_SIZE)) 1435 return; 1436 1437 /* 1438 * This vm_flags may not have VM_HUGEPAGE if the page was not 1439 * collapsed by this mm. But we can still collapse if the page is 1440 * the valid THP. Add extra VM_HUGEPAGE so hugepage_vma_check() 1441 * will not fail the vma for missing VM_HUGEPAGE 1442 */ 1443 if (!hugepage_vma_check(vma, vma->vm_flags | VM_HUGEPAGE)) 1444 return; 1445 1446 /* Keep pmd pgtable for uffd-wp; see comment in retract_page_tables() */ 1447 if (userfaultfd_wp(vma)) 1448 return; 1449 1450 hpage = find_lock_page(vma->vm_file->f_mapping, 1451 linear_page_index(vma, haddr)); 1452 if (!hpage) 1453 return; 1454 1455 if (!PageHead(hpage)) 1456 goto drop_hpage; 1457 1458 pmd = mm_find_pmd(mm, haddr); 1459 if (!pmd) 1460 goto drop_hpage; 1461 1462 start_pte = pte_offset_map_lock(mm, pmd, haddr, &ptl); 1463 1464 /* step 1: check all mapped PTEs are to the right huge page */ 1465 for (i = 0, addr = haddr, pte = start_pte; 1466 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) { 1467 struct page *page; 1468 1469 /* empty pte, skip */ 1470 if (pte_none(*pte)) 1471 continue; 1472 1473 /* page swapped out, abort */ 1474 if (!pte_present(*pte)) 1475 goto abort; 1476 1477 page = vm_normal_page(vma, addr, *pte); 1478 if (WARN_ON_ONCE(page && is_zone_device_page(page))) 1479 page = NULL; 1480 /* 1481 * Note that uprobe, debugger, or MAP_PRIVATE may change the 1482 * page table, but the new page will not be a subpage of hpage. 1483 */ 1484 if (hpage + i != page) 1485 goto abort; 1486 count++; 1487 } 1488 1489 /* step 2: adjust rmap */ 1490 for (i = 0, addr = haddr, pte = start_pte; 1491 i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE, pte++) { 1492 struct page *page; 1493 1494 if (pte_none(*pte)) 1495 continue; 1496 page = vm_normal_page(vma, addr, *pte); 1497 if (WARN_ON_ONCE(page && is_zone_device_page(page))) 1498 goto abort; 1499 page_remove_rmap(page, vma, false); 1500 } 1501 1502 pte_unmap_unlock(start_pte, ptl); 1503 1504 /* step 3: set proper refcount and mm_counters. */ 1505 if (count) { 1506 page_ref_sub(hpage, count); 1507 add_mm_counter(vma->vm_mm, mm_counter_file(hpage), -count); 1508 } 1509 1510 /* step 4: collapse pmd */ 1511 collapse_and_free_pmd(mm, vma, haddr, pmd); 1512 drop_hpage: 1513 unlock_page(hpage); 1514 put_page(hpage); 1515 return; 1516 1517 abort: 1518 pte_unmap_unlock(start_pte, ptl); 1519 goto drop_hpage; 1520 } 1521 1522 static void khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot) 1523 { 1524 struct mm_struct *mm = mm_slot->mm; 1525 int i; 1526 1527 if (likely(mm_slot->nr_pte_mapped_thp == 0)) 1528 return; 1529 1530 if (!mmap_write_trylock(mm)) 1531 return; 1532 1533 if (unlikely(khugepaged_test_exit(mm))) 1534 goto out; 1535 1536 for (i = 0; i < mm_slot->nr_pte_mapped_thp; i++) 1537 collapse_pte_mapped_thp(mm, mm_slot->pte_mapped_thp[i]); 1538 1539 out: 1540 mm_slot->nr_pte_mapped_thp = 0; 1541 mmap_write_unlock(mm); 1542 } 1543 1544 static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff) 1545 { 1546 struct vm_area_struct *vma; 1547 struct mm_struct *mm; 1548 unsigned long addr; 1549 pmd_t *pmd; 1550 1551 i_mmap_lock_write(mapping); 1552 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff, pgoff) { 1553 /* 1554 * Check vma->anon_vma to exclude MAP_PRIVATE mappings that 1555 * got written to. These VMAs are likely not worth investing 1556 * mmap_write_lock(mm) as PMD-mapping is likely to be split 1557 * later. 1558 * 1559 * Note that vma->anon_vma check is racy: it can be set up after 1560 * the check but before we took mmap_lock by the fault path. 1561 * But page lock would prevent establishing any new ptes of the 1562 * page, so we are safe. 1563 * 1564 * An alternative would be drop the check, but check that page 1565 * table is clear before calling pmdp_collapse_flush() under 1566 * ptl. It has higher chance to recover THP for the VMA, but 1567 * has higher cost too. 1568 */ 1569 if (vma->anon_vma) 1570 continue; 1571 addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT); 1572 if (addr & ~HPAGE_PMD_MASK) 1573 continue; 1574 if (vma->vm_end < addr + HPAGE_PMD_SIZE) 1575 continue; 1576 mm = vma->vm_mm; 1577 pmd = mm_find_pmd(mm, addr); 1578 if (!pmd) 1579 continue; 1580 /* 1581 * We need exclusive mmap_lock to retract page table. 1582 * 1583 * We use trylock due to lock inversion: we need to acquire 1584 * mmap_lock while holding page lock. Fault path does it in 1585 * reverse order. Trylock is a way to avoid deadlock. 1586 */ 1587 if (mmap_write_trylock(mm)) { 1588 /* 1589 * When a vma is registered with uffd-wp, we can't 1590 * recycle the pmd pgtable because there can be pte 1591 * markers installed. Skip it only, so the rest mm/vma 1592 * can still have the same file mapped hugely, however 1593 * it'll always mapped in small page size for uffd-wp 1594 * registered ranges. 1595 */ 1596 if (!khugepaged_test_exit(mm) && !userfaultfd_wp(vma)) 1597 collapse_and_free_pmd(mm, vma, addr, pmd); 1598 mmap_write_unlock(mm); 1599 } else { 1600 /* Try again later */ 1601 khugepaged_add_pte_mapped_thp(mm, addr); 1602 } 1603 } 1604 i_mmap_unlock_write(mapping); 1605 } 1606 1607 /** 1608 * collapse_file - collapse filemap/tmpfs/shmem pages into huge one. 1609 * 1610 * @mm: process address space where collapse happens 1611 * @file: file that collapse on 1612 * @start: collapse start address 1613 * @hpage: new allocated huge page for collapse 1614 * @node: appointed node the new huge page allocate from 1615 * 1616 * Basic scheme is simple, details are more complex: 1617 * - allocate and lock a new huge page; 1618 * - scan page cache replacing old pages with the new one 1619 * + swap/gup in pages if necessary; 1620 * + fill in gaps; 1621 * + keep old pages around in case rollback is required; 1622 * - if replacing succeeds: 1623 * + copy data over; 1624 * + free old pages; 1625 * + unlock huge page; 1626 * - if replacing failed; 1627 * + put all pages back and unfreeze them; 1628 * + restore gaps in the page cache; 1629 * + unlock and free huge page; 1630 */ 1631 static void collapse_file(struct mm_struct *mm, 1632 struct file *file, pgoff_t start, 1633 struct page **hpage, int node) 1634 { 1635 struct address_space *mapping = file->f_mapping; 1636 gfp_t gfp; 1637 struct page *new_page; 1638 pgoff_t index, end = start + HPAGE_PMD_NR; 1639 LIST_HEAD(pagelist); 1640 XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER); 1641 int nr_none = 0, result = SCAN_SUCCEED; 1642 bool is_shmem = shmem_file(file); 1643 int nr; 1644 1645 VM_BUG_ON(!IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && !is_shmem); 1646 VM_BUG_ON(start & (HPAGE_PMD_NR - 1)); 1647 1648 /* Only allocate from the target node */ 1649 gfp = alloc_hugepage_khugepaged_gfpmask() | __GFP_THISNODE; 1650 1651 new_page = khugepaged_alloc_page(hpage, gfp, node); 1652 if (!new_page) { 1653 result = SCAN_ALLOC_HUGE_PAGE_FAIL; 1654 goto out; 1655 } 1656 1657 if (unlikely(mem_cgroup_charge(page_folio(new_page), mm, gfp))) { 1658 result = SCAN_CGROUP_CHARGE_FAIL; 1659 goto out; 1660 } 1661 count_memcg_page_event(new_page, THP_COLLAPSE_ALLOC); 1662 1663 /* 1664 * Ensure we have slots for all the pages in the range. This is 1665 * almost certainly a no-op because most of the pages must be present 1666 */ 1667 do { 1668 xas_lock_irq(&xas); 1669 xas_create_range(&xas); 1670 if (!xas_error(&xas)) 1671 break; 1672 xas_unlock_irq(&xas); 1673 if (!xas_nomem(&xas, GFP_KERNEL)) { 1674 result = SCAN_FAIL; 1675 goto out; 1676 } 1677 } while (1); 1678 1679 __SetPageLocked(new_page); 1680 if (is_shmem) 1681 __SetPageSwapBacked(new_page); 1682 new_page->index = start; 1683 new_page->mapping = mapping; 1684 1685 /* 1686 * At this point the new_page is locked and not up-to-date. 1687 * It's safe to insert it into the page cache, because nobody would 1688 * be able to map it or use it in another way until we unlock it. 1689 */ 1690 1691 xas_set(&xas, start); 1692 for (index = start; index < end; index++) { 1693 struct page *page = xas_next(&xas); 1694 1695 VM_BUG_ON(index != xas.xa_index); 1696 if (is_shmem) { 1697 if (!page) { 1698 /* 1699 * Stop if extent has been truncated or 1700 * hole-punched, and is now completely 1701 * empty. 1702 */ 1703 if (index == start) { 1704 if (!xas_next_entry(&xas, end - 1)) { 1705 result = SCAN_TRUNCATED; 1706 goto xa_locked; 1707 } 1708 xas_set(&xas, index); 1709 } 1710 if (!shmem_charge(mapping->host, 1)) { 1711 result = SCAN_FAIL; 1712 goto xa_locked; 1713 } 1714 xas_store(&xas, new_page); 1715 nr_none++; 1716 continue; 1717 } 1718 1719 if (xa_is_value(page) || !PageUptodate(page)) { 1720 xas_unlock_irq(&xas); 1721 /* swap in or instantiate fallocated page */ 1722 if (shmem_getpage(mapping->host, index, &page, 1723 SGP_NOALLOC)) { 1724 result = SCAN_FAIL; 1725 goto xa_unlocked; 1726 } 1727 } else if (trylock_page(page)) { 1728 get_page(page); 1729 xas_unlock_irq(&xas); 1730 } else { 1731 result = SCAN_PAGE_LOCK; 1732 goto xa_locked; 1733 } 1734 } else { /* !is_shmem */ 1735 if (!page || xa_is_value(page)) { 1736 xas_unlock_irq(&xas); 1737 page_cache_sync_readahead(mapping, &file->f_ra, 1738 file, index, 1739 end - index); 1740 /* drain pagevecs to help isolate_lru_page() */ 1741 lru_add_drain(); 1742 page = find_lock_page(mapping, index); 1743 if (unlikely(page == NULL)) { 1744 result = SCAN_FAIL; 1745 goto xa_unlocked; 1746 } 1747 } else if (PageDirty(page)) { 1748 /* 1749 * khugepaged only works on read-only fd, 1750 * so this page is dirty because it hasn't 1751 * been flushed since first write. There 1752 * won't be new dirty pages. 1753 * 1754 * Trigger async flush here and hope the 1755 * writeback is done when khugepaged 1756 * revisits this page. 1757 * 1758 * This is a one-off situation. We are not 1759 * forcing writeback in loop. 1760 */ 1761 xas_unlock_irq(&xas); 1762 filemap_flush(mapping); 1763 result = SCAN_FAIL; 1764 goto xa_unlocked; 1765 } else if (PageWriteback(page)) { 1766 xas_unlock_irq(&xas); 1767 result = SCAN_FAIL; 1768 goto xa_unlocked; 1769 } else if (trylock_page(page)) { 1770 get_page(page); 1771 xas_unlock_irq(&xas); 1772 } else { 1773 result = SCAN_PAGE_LOCK; 1774 goto xa_locked; 1775 } 1776 } 1777 1778 /* 1779 * The page must be locked, so we can drop the i_pages lock 1780 * without racing with truncate. 1781 */ 1782 VM_BUG_ON_PAGE(!PageLocked(page), page); 1783 1784 /* make sure the page is up to date */ 1785 if (unlikely(!PageUptodate(page))) { 1786 result = SCAN_FAIL; 1787 goto out_unlock; 1788 } 1789 1790 /* 1791 * If file was truncated then extended, or hole-punched, before 1792 * we locked the first page, then a THP might be there already. 1793 */ 1794 if (PageTransCompound(page)) { 1795 result = SCAN_PAGE_COMPOUND; 1796 goto out_unlock; 1797 } 1798 1799 if (page_mapping(page) != mapping) { 1800 result = SCAN_TRUNCATED; 1801 goto out_unlock; 1802 } 1803 1804 if (!is_shmem && (PageDirty(page) || 1805 PageWriteback(page))) { 1806 /* 1807 * khugepaged only works on read-only fd, so this 1808 * page is dirty because it hasn't been flushed 1809 * since first write. 1810 */ 1811 result = SCAN_FAIL; 1812 goto out_unlock; 1813 } 1814 1815 if (isolate_lru_page(page)) { 1816 result = SCAN_DEL_PAGE_LRU; 1817 goto out_unlock; 1818 } 1819 1820 if (page_has_private(page) && 1821 !try_to_release_page(page, GFP_KERNEL)) { 1822 result = SCAN_PAGE_HAS_PRIVATE; 1823 putback_lru_page(page); 1824 goto out_unlock; 1825 } 1826 1827 if (page_mapped(page)) 1828 try_to_unmap(page_folio(page), 1829 TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH); 1830 1831 xas_lock_irq(&xas); 1832 xas_set(&xas, index); 1833 1834 VM_BUG_ON_PAGE(page != xas_load(&xas), page); 1835 1836 /* 1837 * The page is expected to have page_count() == 3: 1838 * - we hold a pin on it; 1839 * - one reference from page cache; 1840 * - one from isolate_lru_page; 1841 */ 1842 if (!page_ref_freeze(page, 3)) { 1843 result = SCAN_PAGE_COUNT; 1844 xas_unlock_irq(&xas); 1845 putback_lru_page(page); 1846 goto out_unlock; 1847 } 1848 1849 /* 1850 * Add the page to the list to be able to undo the collapse if 1851 * something go wrong. 1852 */ 1853 list_add_tail(&page->lru, &pagelist); 1854 1855 /* Finally, replace with the new page. */ 1856 xas_store(&xas, new_page); 1857 continue; 1858 out_unlock: 1859 unlock_page(page); 1860 put_page(page); 1861 goto xa_unlocked; 1862 } 1863 nr = thp_nr_pages(new_page); 1864 1865 if (is_shmem) 1866 __mod_lruvec_page_state(new_page, NR_SHMEM_THPS, nr); 1867 else { 1868 __mod_lruvec_page_state(new_page, NR_FILE_THPS, nr); 1869 filemap_nr_thps_inc(mapping); 1870 /* 1871 * Paired with smp_mb() in do_dentry_open() to ensure 1872 * i_writecount is up to date and the update to nr_thps is 1873 * visible. Ensures the page cache will be truncated if the 1874 * file is opened writable. 1875 */ 1876 smp_mb(); 1877 if (inode_is_open_for_write(mapping->host)) { 1878 result = SCAN_FAIL; 1879 __mod_lruvec_page_state(new_page, NR_FILE_THPS, -nr); 1880 filemap_nr_thps_dec(mapping); 1881 goto xa_locked; 1882 } 1883 } 1884 1885 if (nr_none) { 1886 __mod_lruvec_page_state(new_page, NR_FILE_PAGES, nr_none); 1887 /* nr_none is always 0 for non-shmem. */ 1888 __mod_lruvec_page_state(new_page, NR_SHMEM, nr_none); 1889 } 1890 1891 /* Join all the small entries into a single multi-index entry */ 1892 xas_set_order(&xas, start, HPAGE_PMD_ORDER); 1893 xas_store(&xas, new_page); 1894 xa_locked: 1895 xas_unlock_irq(&xas); 1896 xa_unlocked: 1897 1898 /* 1899 * If collapse is successful, flush must be done now before copying. 1900 * If collapse is unsuccessful, does flush actually need to be done? 1901 * Do it anyway, to clear the state. 1902 */ 1903 try_to_unmap_flush(); 1904 1905 if (result == SCAN_SUCCEED) { 1906 struct page *page, *tmp; 1907 1908 /* 1909 * Replacing old pages with new one has succeeded, now we 1910 * need to copy the content and free the old pages. 1911 */ 1912 index = start; 1913 list_for_each_entry_safe(page, tmp, &pagelist, lru) { 1914 while (index < page->index) { 1915 clear_highpage(new_page + (index % HPAGE_PMD_NR)); 1916 index++; 1917 } 1918 copy_highpage(new_page + (page->index % HPAGE_PMD_NR), 1919 page); 1920 list_del(&page->lru); 1921 page->mapping = NULL; 1922 page_ref_unfreeze(page, 1); 1923 ClearPageActive(page); 1924 ClearPageUnevictable(page); 1925 unlock_page(page); 1926 put_page(page); 1927 index++; 1928 } 1929 while (index < end) { 1930 clear_highpage(new_page + (index % HPAGE_PMD_NR)); 1931 index++; 1932 } 1933 1934 SetPageUptodate(new_page); 1935 page_ref_add(new_page, HPAGE_PMD_NR - 1); 1936 if (is_shmem) 1937 set_page_dirty(new_page); 1938 lru_cache_add(new_page); 1939 1940 /* 1941 * Remove pte page tables, so we can re-fault the page as huge. 1942 */ 1943 retract_page_tables(mapping, start); 1944 *hpage = NULL; 1945 1946 khugepaged_pages_collapsed++; 1947 } else { 1948 struct page *page; 1949 1950 /* Something went wrong: roll back page cache changes */ 1951 xas_lock_irq(&xas); 1952 if (nr_none) { 1953 mapping->nrpages -= nr_none; 1954 shmem_uncharge(mapping->host, nr_none); 1955 } 1956 1957 xas_set(&xas, start); 1958 xas_for_each(&xas, page, end - 1) { 1959 page = list_first_entry_or_null(&pagelist, 1960 struct page, lru); 1961 if (!page || xas.xa_index < page->index) { 1962 if (!nr_none) 1963 break; 1964 nr_none--; 1965 /* Put holes back where they were */ 1966 xas_store(&xas, NULL); 1967 continue; 1968 } 1969 1970 VM_BUG_ON_PAGE(page->index != xas.xa_index, page); 1971 1972 /* Unfreeze the page. */ 1973 list_del(&page->lru); 1974 page_ref_unfreeze(page, 2); 1975 xas_store(&xas, page); 1976 xas_pause(&xas); 1977 xas_unlock_irq(&xas); 1978 unlock_page(page); 1979 putback_lru_page(page); 1980 xas_lock_irq(&xas); 1981 } 1982 VM_BUG_ON(nr_none); 1983 xas_unlock_irq(&xas); 1984 1985 new_page->mapping = NULL; 1986 } 1987 1988 unlock_page(new_page); 1989 out: 1990 VM_BUG_ON(!list_empty(&pagelist)); 1991 if (!IS_ERR_OR_NULL(*hpage)) 1992 mem_cgroup_uncharge(page_folio(*hpage)); 1993 /* TODO: tracepoints */ 1994 } 1995 1996 static void khugepaged_scan_file(struct mm_struct *mm, 1997 struct file *file, pgoff_t start, struct page **hpage) 1998 { 1999 struct page *page = NULL; 2000 struct address_space *mapping = file->f_mapping; 2001 XA_STATE(xas, &mapping->i_pages, start); 2002 int present, swap; 2003 int node = NUMA_NO_NODE; 2004 int result = SCAN_SUCCEED; 2005 2006 present = 0; 2007 swap = 0; 2008 memset(khugepaged_node_load, 0, sizeof(khugepaged_node_load)); 2009 rcu_read_lock(); 2010 xas_for_each(&xas, page, start + HPAGE_PMD_NR - 1) { 2011 if (xas_retry(&xas, page)) 2012 continue; 2013 2014 if (xa_is_value(page)) { 2015 if (++swap > khugepaged_max_ptes_swap) { 2016 result = SCAN_EXCEED_SWAP_PTE; 2017 count_vm_event(THP_SCAN_EXCEED_SWAP_PTE); 2018 break; 2019 } 2020 continue; 2021 } 2022 2023 /* 2024 * XXX: khugepaged should compact smaller compound pages 2025 * into a PMD sized page 2026 */ 2027 if (PageTransCompound(page)) { 2028 result = SCAN_PAGE_COMPOUND; 2029 break; 2030 } 2031 2032 node = page_to_nid(page); 2033 if (khugepaged_scan_abort(node)) { 2034 result = SCAN_SCAN_ABORT; 2035 break; 2036 } 2037 khugepaged_node_load[node]++; 2038 2039 if (!PageLRU(page)) { 2040 result = SCAN_PAGE_LRU; 2041 break; 2042 } 2043 2044 if (page_count(page) != 2045 1 + page_mapcount(page) + page_has_private(page)) { 2046 result = SCAN_PAGE_COUNT; 2047 break; 2048 } 2049 2050 /* 2051 * We probably should check if the page is referenced here, but 2052 * nobody would transfer pte_young() to PageReferenced() for us. 2053 * And rmap walk here is just too costly... 2054 */ 2055 2056 present++; 2057 2058 if (need_resched()) { 2059 xas_pause(&xas); 2060 cond_resched_rcu(); 2061 } 2062 } 2063 rcu_read_unlock(); 2064 2065 if (result == SCAN_SUCCEED) { 2066 if (present < HPAGE_PMD_NR - khugepaged_max_ptes_none) { 2067 result = SCAN_EXCEED_NONE_PTE; 2068 count_vm_event(THP_SCAN_EXCEED_NONE_PTE); 2069 } else { 2070 node = khugepaged_find_target_node(); 2071 collapse_file(mm, file, start, hpage, node); 2072 } 2073 } 2074 2075 /* TODO: tracepoints */ 2076 } 2077 #else 2078 static void khugepaged_scan_file(struct mm_struct *mm, 2079 struct file *file, pgoff_t start, struct page **hpage) 2080 { 2081 BUILD_BUG(); 2082 } 2083 2084 static void khugepaged_collapse_pte_mapped_thps(struct mm_slot *mm_slot) 2085 { 2086 } 2087 #endif 2088 2089 static unsigned int khugepaged_scan_mm_slot(unsigned int pages, 2090 struct page **hpage) 2091 __releases(&khugepaged_mm_lock) 2092 __acquires(&khugepaged_mm_lock) 2093 { 2094 struct mm_slot *mm_slot; 2095 struct mm_struct *mm; 2096 struct vm_area_struct *vma; 2097 int progress = 0; 2098 2099 VM_BUG_ON(!pages); 2100 lockdep_assert_held(&khugepaged_mm_lock); 2101 2102 if (khugepaged_scan.mm_slot) 2103 mm_slot = khugepaged_scan.mm_slot; 2104 else { 2105 mm_slot = list_entry(khugepaged_scan.mm_head.next, 2106 struct mm_slot, mm_node); 2107 khugepaged_scan.address = 0; 2108 khugepaged_scan.mm_slot = mm_slot; 2109 } 2110 spin_unlock(&khugepaged_mm_lock); 2111 khugepaged_collapse_pte_mapped_thps(mm_slot); 2112 2113 mm = mm_slot->mm; 2114 /* 2115 * Don't wait for semaphore (to avoid long wait times). Just move to 2116 * the next mm on the list. 2117 */ 2118 vma = NULL; 2119 if (unlikely(!mmap_read_trylock(mm))) 2120 goto breakouterloop_mmap_lock; 2121 if (likely(!khugepaged_test_exit(mm))) 2122 vma = find_vma(mm, khugepaged_scan.address); 2123 2124 progress++; 2125 for (; vma; vma = vma->vm_next) { 2126 unsigned long hstart, hend; 2127 2128 cond_resched(); 2129 if (unlikely(khugepaged_test_exit(mm))) { 2130 progress++; 2131 break; 2132 } 2133 if (!hugepage_vma_check(vma, vma->vm_flags)) { 2134 skip: 2135 progress++; 2136 continue; 2137 } 2138 hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK; 2139 hend = vma->vm_end & HPAGE_PMD_MASK; 2140 if (hstart >= hend) 2141 goto skip; 2142 if (khugepaged_scan.address > hend) 2143 goto skip; 2144 if (khugepaged_scan.address < hstart) 2145 khugepaged_scan.address = hstart; 2146 VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK); 2147 2148 while (khugepaged_scan.address < hend) { 2149 int ret; 2150 cond_resched(); 2151 if (unlikely(khugepaged_test_exit(mm))) 2152 goto breakouterloop; 2153 2154 VM_BUG_ON(khugepaged_scan.address < hstart || 2155 khugepaged_scan.address + HPAGE_PMD_SIZE > 2156 hend); 2157 if (IS_ENABLED(CONFIG_SHMEM) && vma->vm_file) { 2158 struct file *file = get_file(vma->vm_file); 2159 pgoff_t pgoff = linear_page_index(vma, 2160 khugepaged_scan.address); 2161 2162 mmap_read_unlock(mm); 2163 ret = 1; 2164 khugepaged_scan_file(mm, file, pgoff, hpage); 2165 fput(file); 2166 } else { 2167 ret = khugepaged_scan_pmd(mm, vma, 2168 khugepaged_scan.address, 2169 hpage); 2170 } 2171 /* move to next address */ 2172 khugepaged_scan.address += HPAGE_PMD_SIZE; 2173 progress += HPAGE_PMD_NR; 2174 if (ret) 2175 /* we released mmap_lock so break loop */ 2176 goto breakouterloop_mmap_lock; 2177 if (progress >= pages) 2178 goto breakouterloop; 2179 } 2180 } 2181 breakouterloop: 2182 mmap_read_unlock(mm); /* exit_mmap will destroy ptes after this */ 2183 breakouterloop_mmap_lock: 2184 2185 spin_lock(&khugepaged_mm_lock); 2186 VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot); 2187 /* 2188 * Release the current mm_slot if this mm is about to die, or 2189 * if we scanned all vmas of this mm. 2190 */ 2191 if (khugepaged_test_exit(mm) || !vma) { 2192 /* 2193 * Make sure that if mm_users is reaching zero while 2194 * khugepaged runs here, khugepaged_exit will find 2195 * mm_slot not pointing to the exiting mm. 2196 */ 2197 if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) { 2198 khugepaged_scan.mm_slot = list_entry( 2199 mm_slot->mm_node.next, 2200 struct mm_slot, mm_node); 2201 khugepaged_scan.address = 0; 2202 } else { 2203 khugepaged_scan.mm_slot = NULL; 2204 khugepaged_full_scans++; 2205 } 2206 2207 collect_mm_slot(mm_slot); 2208 } 2209 2210 return progress; 2211 } 2212 2213 static int khugepaged_has_work(void) 2214 { 2215 return !list_empty(&khugepaged_scan.mm_head) && 2216 khugepaged_enabled(); 2217 } 2218 2219 static int khugepaged_wait_event(void) 2220 { 2221 return !list_empty(&khugepaged_scan.mm_head) || 2222 kthread_should_stop(); 2223 } 2224 2225 static void khugepaged_do_scan(void) 2226 { 2227 struct page *hpage = NULL; 2228 unsigned int progress = 0, pass_through_head = 0; 2229 unsigned int pages = READ_ONCE(khugepaged_pages_to_scan); 2230 bool wait = true; 2231 2232 lru_add_drain_all(); 2233 2234 while (progress < pages) { 2235 if (!khugepaged_prealloc_page(&hpage, &wait)) 2236 break; 2237 2238 cond_resched(); 2239 2240 if (unlikely(kthread_should_stop() || try_to_freeze())) 2241 break; 2242 2243 spin_lock(&khugepaged_mm_lock); 2244 if (!khugepaged_scan.mm_slot) 2245 pass_through_head++; 2246 if (khugepaged_has_work() && 2247 pass_through_head < 2) 2248 progress += khugepaged_scan_mm_slot(pages - progress, 2249 &hpage); 2250 else 2251 progress = pages; 2252 spin_unlock(&khugepaged_mm_lock); 2253 } 2254 2255 if (!IS_ERR_OR_NULL(hpage)) 2256 put_page(hpage); 2257 } 2258 2259 static bool khugepaged_should_wakeup(void) 2260 { 2261 return kthread_should_stop() || 2262 time_after_eq(jiffies, khugepaged_sleep_expire); 2263 } 2264 2265 static void khugepaged_wait_work(void) 2266 { 2267 if (khugepaged_has_work()) { 2268 const unsigned long scan_sleep_jiffies = 2269 msecs_to_jiffies(khugepaged_scan_sleep_millisecs); 2270 2271 if (!scan_sleep_jiffies) 2272 return; 2273 2274 khugepaged_sleep_expire = jiffies + scan_sleep_jiffies; 2275 wait_event_freezable_timeout(khugepaged_wait, 2276 khugepaged_should_wakeup(), 2277 scan_sleep_jiffies); 2278 return; 2279 } 2280 2281 if (khugepaged_enabled()) 2282 wait_event_freezable(khugepaged_wait, khugepaged_wait_event()); 2283 } 2284 2285 static int khugepaged(void *none) 2286 { 2287 struct mm_slot *mm_slot; 2288 2289 set_freezable(); 2290 set_user_nice(current, MAX_NICE); 2291 2292 while (!kthread_should_stop()) { 2293 khugepaged_do_scan(); 2294 khugepaged_wait_work(); 2295 } 2296 2297 spin_lock(&khugepaged_mm_lock); 2298 mm_slot = khugepaged_scan.mm_slot; 2299 khugepaged_scan.mm_slot = NULL; 2300 if (mm_slot) 2301 collect_mm_slot(mm_slot); 2302 spin_unlock(&khugepaged_mm_lock); 2303 return 0; 2304 } 2305 2306 static void set_recommended_min_free_kbytes(void) 2307 { 2308 struct zone *zone; 2309 int nr_zones = 0; 2310 unsigned long recommended_min; 2311 2312 if (!khugepaged_enabled()) { 2313 calculate_min_free_kbytes(); 2314 goto update_wmarks; 2315 } 2316 2317 for_each_populated_zone(zone) { 2318 /* 2319 * We don't need to worry about fragmentation of 2320 * ZONE_MOVABLE since it only has movable pages. 2321 */ 2322 if (zone_idx(zone) > gfp_zone(GFP_USER)) 2323 continue; 2324 2325 nr_zones++; 2326 } 2327 2328 /* Ensure 2 pageblocks are free to assist fragmentation avoidance */ 2329 recommended_min = pageblock_nr_pages * nr_zones * 2; 2330 2331 /* 2332 * Make sure that on average at least two pageblocks are almost free 2333 * of another type, one for a migratetype to fall back to and a 2334 * second to avoid subsequent fallbacks of other types There are 3 2335 * MIGRATE_TYPES we care about. 2336 */ 2337 recommended_min += pageblock_nr_pages * nr_zones * 2338 MIGRATE_PCPTYPES * MIGRATE_PCPTYPES; 2339 2340 /* don't ever allow to reserve more than 5% of the lowmem */ 2341 recommended_min = min(recommended_min, 2342 (unsigned long) nr_free_buffer_pages() / 20); 2343 recommended_min <<= (PAGE_SHIFT-10); 2344 2345 if (recommended_min > min_free_kbytes) { 2346 if (user_min_free_kbytes >= 0) 2347 pr_info("raising min_free_kbytes from %d to %lu to help transparent hugepage allocations\n", 2348 min_free_kbytes, recommended_min); 2349 2350 min_free_kbytes = recommended_min; 2351 } 2352 2353 update_wmarks: 2354 setup_per_zone_wmarks(); 2355 } 2356 2357 int start_stop_khugepaged(void) 2358 { 2359 int err = 0; 2360 2361 mutex_lock(&khugepaged_mutex); 2362 if (khugepaged_enabled()) { 2363 if (!khugepaged_thread) 2364 khugepaged_thread = kthread_run(khugepaged, NULL, 2365 "khugepaged"); 2366 if (IS_ERR(khugepaged_thread)) { 2367 pr_err("khugepaged: kthread_run(khugepaged) failed\n"); 2368 err = PTR_ERR(khugepaged_thread); 2369 khugepaged_thread = NULL; 2370 goto fail; 2371 } 2372 2373 if (!list_empty(&khugepaged_scan.mm_head)) 2374 wake_up_interruptible(&khugepaged_wait); 2375 } else if (khugepaged_thread) { 2376 kthread_stop(khugepaged_thread); 2377 khugepaged_thread = NULL; 2378 } 2379 set_recommended_min_free_kbytes(); 2380 fail: 2381 mutex_unlock(&khugepaged_mutex); 2382 return err; 2383 } 2384 2385 void khugepaged_min_free_kbytes_update(void) 2386 { 2387 mutex_lock(&khugepaged_mutex); 2388 if (khugepaged_enabled() && khugepaged_thread) 2389 set_recommended_min_free_kbytes(); 2390 mutex_unlock(&khugepaged_mutex); 2391 } 2392