1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * Copyright (C) 2009 Red Hat, Inc. 4 */ 5 6 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 7 8 #include <linux/mm.h> 9 #include <linux/sched.h> 10 #include <linux/sched/mm.h> 11 #include <linux/sched/numa_balancing.h> 12 #include <linux/highmem.h> 13 #include <linux/hugetlb.h> 14 #include <linux/mmu_notifier.h> 15 #include <linux/rmap.h> 16 #include <linux/swap.h> 17 #include <linux/list_lru.h> 18 #include <linux/shrinker.h> 19 #include <linux/mm_inline.h> 20 #include <linux/swapops.h> 21 #include <linux/backing-dev.h> 22 #include <linux/dax.h> 23 #include <linux/mm_types.h> 24 #include <linux/khugepaged.h> 25 #include <linux/freezer.h> 26 #include <linux/mman.h> 27 #include <linux/memremap.h> 28 #include <linux/pagemap.h> 29 #include <linux/debugfs.h> 30 #include <linux/migrate.h> 31 #include <linux/hashtable.h> 32 #include <linux/userfaultfd_k.h> 33 #include <linux/page_idle.h> 34 #include <linux/shmem_fs.h> 35 #include <linux/oom.h> 36 #include <linux/numa.h> 37 #include <linux/page_owner.h> 38 #include <linux/sched/sysctl.h> 39 #include <linux/memory-tiers.h> 40 #include <linux/compat.h> 41 #include <linux/pgalloc.h> 42 #include <linux/pgalloc_tag.h> 43 #include <linux/pagewalk.h> 44 #include <linux/cleanup.h> 45 46 #include <asm/tlb.h> 47 #include "internal.h" 48 #include "swap.h" 49 50 #define CREATE_TRACE_POINTS 51 #include <trace/events/thp.h> 52 53 /* 54 * By default, transparent hugepage support is disabled in order to avoid 55 * risking an increased memory footprint for applications that are not 56 * guaranteed to benefit from it. When transparent hugepage support is 57 * enabled, it is for all mappings, and khugepaged scans all mappings. 58 * Defrag is invoked by khugepaged hugepage allocations and by page faults 59 * for all hugepage allocations. 60 */ 61 unsigned long transparent_hugepage_flags __read_mostly = 62 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS 63 (1<<TRANSPARENT_HUGEPAGE_FLAG)| 64 #endif 65 #ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE 66 (1<<TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG)| 67 #endif 68 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG)| 69 (1<<TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG)| 70 (1<<TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG); 71 72 static struct lock_class_key deferred_split_key; 73 static struct list_lru deferred_split_lru; 74 static struct shrinker *deferred_split_shrinker; 75 static unsigned long deferred_split_count(struct shrinker *shrink, 76 struct shrink_control *sc); 77 static unsigned long deferred_split_scan(struct shrinker *shrink, 78 struct shrink_control *sc); 79 static bool split_underused_thp = true; 80 81 #define HUGE_ZERO_UNSET_PFN (~0UL) 82 struct folio *huge_zero_folio __read_mostly; 83 unsigned long huge_zero_pfn __read_mostly = HUGE_ZERO_UNSET_PFN; 84 #ifndef CONFIG_PERSISTENT_HUGE_ZERO_FOLIO 85 static atomic_t huge_zero_refcount; 86 static DEFINE_SPINLOCK(huge_zero_lock); 87 static struct shrinker *huge_zero_folio_shrinker; 88 #endif 89 90 unsigned long huge_anon_orders_always __read_mostly; 91 unsigned long huge_anon_orders_madvise __read_mostly; 92 unsigned long huge_anon_orders_inherit __read_mostly; 93 static bool anon_orders_configured __initdata; 94 95 static inline bool file_thp_enabled(const struct vm_area_struct *vma) 96 { 97 struct inode *inode; 98 99 if (!vma->vm_file) 100 return false; 101 102 inode = file_inode(vma->vm_file); 103 104 if (IS_ANON_FILE(inode)) 105 return false; 106 107 if (!mapping_pmd_folio_support(vma->vm_file->f_mapping)) 108 return false; 109 110 return S_ISREG(inode->i_mode); 111 } 112 113 static bool vma_file_bypass_thp_tuneables(const struct vm_area_struct *vma, 114 enum tva_type type) 115 { 116 const bool has_huge_fault = vma->vm_ops->huge_fault; 117 118 /* MADV_COLLAPSE ignores tuneables. */ 119 if (type == TVA_FORCED_COLLAPSE) 120 return true; 121 /* Huge PFN mappings are uncompactable so the policy doesn't apply. */ 122 if (vma_test(vma, VMA_PFNMAP_BIT) && has_huge_fault) 123 return true; 124 return false; 125 } 126 127 static bool vma_file_allow_thp_tuneables(vm_flags_t vm_flags) 128 { 129 /* THP=always? */ 130 if (hugepage_global_always()) 131 return true; 132 /* THP=madvise and marked MADV_HUGEPAGE? */ 133 if (hugepage_global_enabled() && (vm_flags & VM_HUGEPAGE)) 134 return true; 135 return false; 136 } 137 138 static bool vma_file_check_thp_tuneables(const struct vm_area_struct *vma, 139 vm_flags_t vm_flags, enum tva_type type) 140 { 141 return vma_file_bypass_thp_tuneables(vma, type) || 142 vma_file_allow_thp_tuneables(vm_flags); 143 } 144 145 static bool vma_can_map_huge_file(const struct vm_area_struct *vma, 146 vm_flags_t vm_flags, enum tva_type type) 147 { 148 const bool has_huge_fault = vma->vm_ops->huge_fault; 149 150 /* 151 * Enforce THP collapse requirements as necessary. Anonymous vmas 152 * were already handled in thp_vma_allowable_orders(). 153 */ 154 if (!vma_file_check_thp_tuneables(vma, vm_flags, type)) 155 return false; 156 157 switch (type) { 158 case TVA_PAGEFAULT: 159 /* 160 * Trust that ->huge_fault() handlers know what they are doing 161 * in fault path. 162 */ 163 return has_huge_fault; 164 case TVA_SMAPS: 165 if (has_huge_fault) 166 return true; 167 fallthrough; 168 default: 169 /* Only regular file is valid in collapse path. */ 170 return file_thp_enabled(vma); 171 } 172 } 173 174 unsigned long __thp_vma_allowable_orders(struct vm_area_struct *vma, 175 vm_flags_t vm_flags, 176 enum tva_type type, 177 unsigned long orders) 178 { 179 const bool smaps = type == TVA_SMAPS; 180 const bool in_pf = type == TVA_PAGEFAULT; 181 const bool forced_collapse = type == TVA_FORCED_COLLAPSE; 182 unsigned long supported_orders; 183 184 /* Check the intersection of requested and supported orders. */ 185 if (vma_is_anonymous(vma)) 186 supported_orders = THP_ORDERS_ALL_ANON; 187 else if (vma_is_dax(vma) || !vma_is_mm_managed(vma)) 188 supported_orders = THP_ORDERS_ALL_SPECIAL_DAX; 189 else 190 supported_orders = THP_ORDERS_ALL_FILE_DEFAULT; 191 192 orders &= supported_orders; 193 if (!orders) 194 return 0; 195 196 if (!vma->vm_mm) /* vdso */ 197 return 0; 198 199 if (thp_disabled_by_hw() || vma_thp_disabled(vma, vm_flags, forced_collapse)) 200 return 0; 201 202 /* khugepaged doesn't collapse DAX vma, but page fault is fine. */ 203 if (vma_is_dax(vma)) 204 return in_pf ? orders : 0; 205 206 /* 207 * khugepaged moves data from VMAs once collapsed, after they have been 208 * faulted in, relying on refaulting for file-backed memory. 209 * 210 * Only mm-backed mappings can be reliably reconstructed from page 211 * faults, and hugetlb mappings cannot be collapsed. 212 */ 213 if (!in_pf && !smaps && (!vma_is_mm_backed(vma) || vma_is_hugetlb(vma))) 214 return 0; 215 216 /* 217 * Check alignment for file vma and size for both file and anon vma by 218 * filtering out the unsuitable orders. 219 * 220 * Skip the check for page fault. Huge fault does the check in fault 221 * handlers. 222 */ 223 if (!in_pf) { 224 int order = highest_order(orders); 225 unsigned long addr; 226 227 while (orders) { 228 addr = vma->vm_end - (PAGE_SIZE << order); 229 if (thp_vma_suitable_order(vma, addr, order)) 230 break; 231 order = next_order(&orders, order); 232 } 233 234 if (!orders) 235 return 0; 236 } 237 238 /* 239 * Enabled via shmem mount options or sysfs settings. 240 * Must be done before hugepage flags check since shmem has its 241 * own flags. 242 */ 243 if (!in_pf && shmem_file(vma->vm_file)) 244 return orders & shmem_allowable_huge_orders(file_inode(vma->vm_file), 245 vma, vma_start_pgoff(vma), 0, 246 forced_collapse); 247 248 if (!vma_is_anonymous(vma)) 249 return vma_can_map_huge_file(vma, vm_flags, type) ? orders : 0; 250 251 if (vma_is_temporary_stack(vma)) 252 return 0; 253 254 /* 255 * THPeligible bit of smaps should show 1 for proper VMAs even 256 * though they don't have an anon rmap yet. 257 * 258 * Allow page fault since the VMA may not have an anon rmap until the 259 * first page fault. 260 */ 261 if (!vma_has_anon_rmap(vma)) 262 return (smaps || in_pf) ? orders : 0; 263 264 return orders; 265 } 266 267 static struct folio *alloc_huge_zero_folio(void) 268 { 269 struct folio *zero_folio; 270 271 zero_folio = folio_alloc((GFP_TRANSHUGE | __GFP_ZERO | __GFP_ZEROTAGS) & 272 ~__GFP_MOVABLE, 273 HPAGE_PMD_ORDER); 274 if (!zero_folio) { 275 count_vm_event(THP_ZERO_PAGE_ALLOC_FAILED); 276 return NULL; 277 } 278 folio_clear_large_rmappable(zero_folio); /* Explicitly not rmappable. */ 279 return zero_folio; 280 } 281 282 #ifdef CONFIG_PERSISTENT_HUGE_ZERO_FOLIO 283 static int __init huge_zero_init(void) 284 { 285 huge_zero_folio = alloc_huge_zero_folio(); 286 if (!huge_zero_folio) { 287 pr_warn("Allocating persistent huge zero folio failed\n"); 288 } else { 289 huge_zero_pfn = folio_pfn(huge_zero_folio); 290 count_vm_event(THP_ZERO_PAGE_ALLOC); 291 } 292 return 0; 293 } 294 295 static void __init huge_zero_shrinker_exit(void) 296 { 297 } 298 299 struct folio *mm_get_huge_zero_folio(struct mm_struct *mm) 300 { 301 return huge_zero_folio; 302 } 303 304 void mm_put_huge_zero_folio(struct mm_struct *mm) 305 { 306 } 307 #else 308 static bool get_huge_zero_folio(void) 309 { 310 struct folio *zero_folio; 311 312 /* Paired with atomic_set_release(). */ 313 if (likely(atomic_inc_not_zero(&huge_zero_refcount))) 314 return true; 315 316 zero_folio = alloc_huge_zero_folio(); 317 if (unlikely(!zero_folio)) 318 return false; 319 320 /* Paired with critical section in shrink_huge_zero_folio_scan(). */ 321 spin_lock(&huge_zero_lock); 322 if (huge_zero_folio) { 323 /* Somebody else already installed it. */ 324 atomic_inc(&huge_zero_refcount); 325 spin_unlock(&huge_zero_lock); 326 folio_put(zero_folio); 327 return true; 328 } 329 WRITE_ONCE(huge_zero_folio, zero_folio); 330 WRITE_ONCE(huge_zero_pfn, folio_pfn(zero_folio)); 331 /* Paired with atomic_inc_not_zero(). +1 for shrinker pin. */ 332 atomic_set_release(&huge_zero_refcount, 2); 333 spin_unlock(&huge_zero_lock); 334 335 count_vm_event(THP_ZERO_PAGE_ALLOC); 336 return true; 337 } 338 339 static void put_huge_zero_folio(void) 340 { 341 /* 342 * Counter should never go to zero here. Only shrinker can put 343 * last reference. 344 */ 345 WARN_ON_ONCE(atomic_dec_and_test(&huge_zero_refcount)); 346 } 347 348 static unsigned long shrink_huge_zero_folio_count(struct shrinker *shrink, 349 struct shrink_control *sc) 350 { 351 /* we can free zero page only if last reference remains */ 352 return atomic_read(&huge_zero_refcount) == 1 ? HPAGE_PMD_NR : 0; 353 } 354 355 static unsigned long shrink_huge_zero_folio_scan(struct shrinker *shrink, 356 struct shrink_control *sc) 357 { 358 struct folio *zero_folio; 359 360 /* Paired with critical section in get_huge_zero_folio(). */ 361 scoped_guard(spinlock, &huge_zero_lock) { 362 /* Paired with atomic_inc_not_zero() in get_huge_zero_folio(). */ 363 if (atomic_cmpxchg(&huge_zero_refcount, 1, 0) != 1) 364 return 0; 365 366 zero_folio = huge_zero_folio; 367 VM_WARN_ON_ONCE(!zero_folio); 368 WRITE_ONCE(huge_zero_folio, NULL); 369 WRITE_ONCE(huge_zero_pfn, HUGE_ZERO_UNSET_PFN); 370 } 371 372 folio_put(zero_folio); 373 return HPAGE_PMD_NR; 374 } 375 376 static int __init huge_zero_init(void) 377 { 378 huge_zero_folio_shrinker = shrinker_alloc(0, "thp-zero"); 379 if (!huge_zero_folio_shrinker) { 380 shrinker_free(deferred_split_shrinker); 381 list_lru_destroy(&deferred_split_lru); 382 return -ENOMEM; 383 } 384 385 huge_zero_folio_shrinker->count_objects = shrink_huge_zero_folio_count; 386 huge_zero_folio_shrinker->scan_objects = shrink_huge_zero_folio_scan; 387 shrinker_register(huge_zero_folio_shrinker); 388 return 0; 389 } 390 391 static void __init huge_zero_shrinker_exit(void) 392 { 393 shrinker_free(huge_zero_folio_shrinker); 394 } 395 396 struct folio *mm_get_huge_zero_folio(struct mm_struct *mm) 397 { 398 if (mm_flags_test(MMF_HUGE_ZERO_FOLIO, mm)) 399 return READ_ONCE(huge_zero_folio); 400 401 if (!get_huge_zero_folio()) 402 return NULL; 403 404 if (mm_flags_test_and_set(MMF_HUGE_ZERO_FOLIO, mm)) 405 put_huge_zero_folio(); 406 407 return READ_ONCE(huge_zero_folio); 408 } 409 410 void mm_put_huge_zero_folio(struct mm_struct *mm) 411 { 412 if (mm_flags_test(MMF_HUGE_ZERO_FOLIO, mm)) 413 put_huge_zero_folio(); 414 } 415 #endif /* CONFIG_PERSISTENT_HUGE_ZERO_FOLIO */ 416 417 #ifdef CONFIG_SYSFS 418 static ssize_t enabled_show(struct kobject *kobj, 419 struct kobj_attribute *attr, char *buf) 420 { 421 const char *output; 422 423 if (test_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags)) 424 output = "[always] madvise never"; 425 else if (test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, 426 &transparent_hugepage_flags)) 427 output = "always [madvise] never"; 428 else 429 output = "always madvise [never]"; 430 431 return sysfs_emit(buf, "%s\n", output); 432 } 433 434 enum anon_enabled_mode { 435 ANON_ENABLED_ALWAYS = 0, 436 ANON_ENABLED_INHERIT = 1, 437 ANON_ENABLED_MADVISE = 2, 438 ANON_ENABLED_NEVER = 3, 439 }; 440 441 static const char * const anon_enabled_mode_strings[] = { 442 [ANON_ENABLED_ALWAYS] = "always", 443 [ANON_ENABLED_INHERIT] = "inherit", 444 [ANON_ENABLED_MADVISE] = "madvise", 445 [ANON_ENABLED_NEVER] = "never", 446 }; 447 448 enum global_enabled_mode { 449 GLOBAL_ENABLED_ALWAYS = 0, 450 GLOBAL_ENABLED_MADVISE = 1, 451 GLOBAL_ENABLED_NEVER = 2, 452 }; 453 454 static const char * const global_enabled_mode_strings[] = { 455 [GLOBAL_ENABLED_ALWAYS] = "always", 456 [GLOBAL_ENABLED_MADVISE] = "madvise", 457 [GLOBAL_ENABLED_NEVER] = "never", 458 }; 459 460 static bool set_global_enabled_mode(enum global_enabled_mode mode) 461 { 462 static const unsigned long thp_flags[] = { 463 TRANSPARENT_HUGEPAGE_FLAG, 464 TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, 465 }; 466 enum global_enabled_mode m; 467 bool changed = false; 468 469 for (m = 0; m < ARRAY_SIZE(thp_flags); m++) { 470 if (m == mode) 471 changed |= !test_and_set_bit(thp_flags[m], 472 &transparent_hugepage_flags); 473 else 474 changed |= test_and_clear_bit(thp_flags[m], 475 &transparent_hugepage_flags); 476 } 477 478 return changed; 479 } 480 481 static ssize_t enabled_store(struct kobject *kobj, 482 struct kobj_attribute *attr, 483 const char *buf, size_t count) 484 { 485 int mode; 486 487 mode = sysfs_match_string(global_enabled_mode_strings, buf); 488 if (mode < 0) 489 return -EINVAL; 490 491 if (set_global_enabled_mode(mode)) { 492 int err = start_stop_khugepaged(); 493 494 if (err) 495 return err; 496 } else { 497 /* 498 * Recalculate watermarks even when the mode didn't 499 * change, as the previous code always called 500 * start_stop_khugepaged() which does this internally. 501 */ 502 set_recommended_min_free_kbytes(); 503 } 504 return count; 505 } 506 507 static struct kobj_attribute enabled_attr = __ATTR_RW(enabled); 508 509 ssize_t single_hugepage_flag_show(struct kobject *kobj, 510 struct kobj_attribute *attr, char *buf, 511 enum transparent_hugepage_flag flag) 512 { 513 return sysfs_emit(buf, "%d\n", 514 !!test_bit(flag, &transparent_hugepage_flags)); 515 } 516 517 ssize_t single_hugepage_flag_store(struct kobject *kobj, 518 struct kobj_attribute *attr, 519 const char *buf, size_t count, 520 enum transparent_hugepage_flag flag) 521 { 522 unsigned long value; 523 int ret; 524 525 ret = kstrtoul(buf, 10, &value); 526 if (ret < 0) 527 return ret; 528 if (value > 1) 529 return -EINVAL; 530 531 if (value) 532 set_bit(flag, &transparent_hugepage_flags); 533 else 534 clear_bit(flag, &transparent_hugepage_flags); 535 536 return count; 537 } 538 539 enum defrag_mode { 540 DEFRAG_ALWAYS = 0, 541 DEFRAG_DEFER, 542 DEFRAG_DEFER_MADVISE, 543 DEFRAG_MADVISE, 544 DEFRAG_NEVER, 545 }; 546 547 static const char * const defrag_mode_strings[] = { 548 [DEFRAG_ALWAYS] = "always", 549 [DEFRAG_DEFER] = "defer", 550 [DEFRAG_DEFER_MADVISE] = "defer+madvise", 551 [DEFRAG_MADVISE] = "madvise", 552 [DEFRAG_NEVER] = "never", 553 }; 554 555 static const enum transparent_hugepage_flag defrag_flags[] = { 556 [DEFRAG_ALWAYS] = TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, 557 [DEFRAG_DEFER] = TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, 558 [DEFRAG_DEFER_MADVISE] = TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, 559 [DEFRAG_MADVISE] = TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, 560 }; 561 562 static ssize_t defrag_show(struct kobject *kobj, 563 struct kobj_attribute *attr, char *buf) 564 { 565 int active = DEFRAG_NEVER; 566 int len = 0; 567 int i; 568 569 for (i = 0; i < ARRAY_SIZE(defrag_flags); i++) { 570 if (test_bit(defrag_flags[i], &transparent_hugepage_flags)) { 571 active = i; 572 break; 573 } 574 } 575 576 for (i = 0; i < ARRAY_SIZE(defrag_mode_strings); i++) { 577 if (i == active) 578 len += sysfs_emit_at(buf, len, "[%s] ", 579 defrag_mode_strings[i]); 580 else 581 len += sysfs_emit_at(buf, len, "%s ", 582 defrag_mode_strings[i]); 583 } 584 585 /* Replace trailing space with newline */ 586 buf[len - 1] = '\n'; 587 588 return len; 589 } 590 591 static ssize_t defrag_store(struct kobject *kobj, 592 struct kobj_attribute *attr, 593 const char *buf, size_t count) 594 { 595 int mode, m; 596 597 mode = sysfs_match_string(defrag_mode_strings, buf); 598 if (mode < 0) 599 return -EINVAL; 600 601 for (m = 0; m < ARRAY_SIZE(defrag_flags); m++) { 602 if (m == mode) 603 set_bit(defrag_flags[m], &transparent_hugepage_flags); 604 else 605 clear_bit(defrag_flags[m], &transparent_hugepage_flags); 606 } 607 608 return count; 609 } 610 static struct kobj_attribute defrag_attr = __ATTR_RW(defrag); 611 612 static ssize_t use_zero_page_show(struct kobject *kobj, 613 struct kobj_attribute *attr, char *buf) 614 { 615 return single_hugepage_flag_show(kobj, attr, buf, 616 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG); 617 } 618 static ssize_t use_zero_page_store(struct kobject *kobj, 619 struct kobj_attribute *attr, const char *buf, size_t count) 620 { 621 return single_hugepage_flag_store(kobj, attr, buf, count, 622 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG); 623 } 624 static struct kobj_attribute use_zero_page_attr = __ATTR_RW(use_zero_page); 625 626 static ssize_t hpage_pmd_size_show(struct kobject *kobj, 627 struct kobj_attribute *attr, char *buf) 628 { 629 return sysfs_emit(buf, "%lu\n", HPAGE_PMD_SIZE); 630 } 631 static struct kobj_attribute hpage_pmd_size_attr = 632 __ATTR_RO(hpage_pmd_size); 633 634 static ssize_t split_underused_thp_show(struct kobject *kobj, 635 struct kobj_attribute *attr, char *buf) 636 { 637 return sysfs_emit(buf, "%d\n", split_underused_thp); 638 } 639 640 static ssize_t split_underused_thp_store(struct kobject *kobj, 641 struct kobj_attribute *attr, 642 const char *buf, size_t count) 643 { 644 int err = kstrtobool(buf, &split_underused_thp); 645 646 if (err < 0) 647 return err; 648 649 return count; 650 } 651 652 static struct kobj_attribute split_underused_thp_attr = __ATTR( 653 shrink_underused, 0644, split_underused_thp_show, split_underused_thp_store); 654 655 static struct attribute *hugepage_attr[] = { 656 &enabled_attr.attr, 657 &defrag_attr.attr, 658 &use_zero_page_attr.attr, 659 &hpage_pmd_size_attr.attr, 660 #ifdef CONFIG_SHMEM 661 &shmem_enabled_attr.attr, 662 #endif 663 &split_underused_thp_attr.attr, 664 NULL, 665 }; 666 667 static const struct attribute_group hugepage_attr_group = { 668 .attrs = hugepage_attr, 669 }; 670 671 static void hugepage_exit_sysfs(struct kobject *hugepage_kobj); 672 static void thpsize_release(struct kobject *kobj); 673 static DEFINE_SPINLOCK(huge_anon_orders_lock); 674 static LIST_HEAD(thpsize_list); 675 676 static ssize_t anon_enabled_show(struct kobject *kobj, 677 struct kobj_attribute *attr, char *buf) 678 { 679 int order = to_thpsize(kobj)->order; 680 const char *output; 681 682 if (test_bit(order, &huge_anon_orders_always)) 683 output = "[always] inherit madvise never"; 684 else if (test_bit(order, &huge_anon_orders_inherit)) 685 output = "always [inherit] madvise never"; 686 else if (test_bit(order, &huge_anon_orders_madvise)) 687 output = "always inherit [madvise] never"; 688 else 689 output = "always inherit madvise [never]"; 690 691 return sysfs_emit(buf, "%s\n", output); 692 } 693 694 static bool set_anon_enabled_mode(int order, enum anon_enabled_mode mode) 695 { 696 static unsigned long *enabled_orders[] = { 697 &huge_anon_orders_always, 698 &huge_anon_orders_inherit, 699 &huge_anon_orders_madvise, 700 }; 701 enum anon_enabled_mode m; 702 bool changed = false; 703 704 spin_lock(&huge_anon_orders_lock); 705 for (m = 0; m < ARRAY_SIZE(enabled_orders); m++) { 706 if (m == mode) 707 changed |= !__test_and_set_bit(order, enabled_orders[m]); 708 else 709 changed |= __test_and_clear_bit(order, enabled_orders[m]); 710 } 711 spin_unlock(&huge_anon_orders_lock); 712 713 return changed; 714 } 715 716 static ssize_t anon_enabled_store(struct kobject *kobj, 717 struct kobj_attribute *attr, 718 const char *buf, size_t count) 719 { 720 int order = to_thpsize(kobj)->order; 721 int mode; 722 723 mode = sysfs_match_string(anon_enabled_mode_strings, buf); 724 if (mode < 0) 725 return -EINVAL; 726 727 if (set_anon_enabled_mode(order, mode)) { 728 int err = start_stop_khugepaged(); 729 730 if (err) 731 return err; 732 } else { 733 /* 734 * Recalculate watermarks even when the mode didn't 735 * change, as the previous code always called 736 * start_stop_khugepaged() which does this internally. 737 */ 738 set_recommended_min_free_kbytes(); 739 } 740 741 return count; 742 } 743 744 static struct kobj_attribute anon_enabled_attr = 745 __ATTR(enabled, 0644, anon_enabled_show, anon_enabled_store); 746 747 static struct attribute *anon_ctrl_attrs[] = { 748 &anon_enabled_attr.attr, 749 NULL, 750 }; 751 752 static const struct attribute_group anon_ctrl_attr_grp = { 753 .attrs = anon_ctrl_attrs, 754 }; 755 756 static struct attribute *file_ctrl_attrs[] = { 757 #ifdef CONFIG_SHMEM 758 &thpsize_shmem_enabled_attr.attr, 759 #endif 760 NULL, 761 }; 762 763 static const struct attribute_group file_ctrl_attr_grp = { 764 .attrs = file_ctrl_attrs, 765 }; 766 767 static struct attribute *any_ctrl_attrs[] = { 768 NULL, 769 }; 770 771 static const struct attribute_group any_ctrl_attr_grp = { 772 .attrs = any_ctrl_attrs, 773 }; 774 775 static const struct kobj_type thpsize_ktype = { 776 .release = &thpsize_release, 777 .sysfs_ops = &kobj_sysfs_ops, 778 }; 779 780 DEFINE_PER_CPU(struct mthp_stat, mthp_stats) = {{{0}}}; 781 782 static unsigned long sum_mthp_stat(int order, enum mthp_stat_item item) 783 { 784 unsigned long sum = 0; 785 int cpu; 786 787 for_each_possible_cpu(cpu) { 788 struct mthp_stat *this = &per_cpu(mthp_stats, cpu); 789 790 sum += this->stats[order][item]; 791 } 792 793 return sum; 794 } 795 796 #define DEFINE_MTHP_STAT_ATTR(_name, _index) \ 797 static ssize_t _name##_show(struct kobject *kobj, \ 798 struct kobj_attribute *attr, char *buf) \ 799 { \ 800 int order = to_thpsize(kobj)->order; \ 801 \ 802 return sysfs_emit(buf, "%lu\n", sum_mthp_stat(order, _index)); \ 803 } \ 804 static struct kobj_attribute _name##_attr = __ATTR_RO(_name) 805 806 DEFINE_MTHP_STAT_ATTR(anon_fault_alloc, MTHP_STAT_ANON_FAULT_ALLOC); 807 DEFINE_MTHP_STAT_ATTR(anon_fault_fallback, MTHP_STAT_ANON_FAULT_FALLBACK); 808 DEFINE_MTHP_STAT_ATTR(anon_fault_fallback_charge, MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE); 809 DEFINE_MTHP_STAT_ATTR(collapse_alloc, MTHP_STAT_COLLAPSE_ALLOC); 810 DEFINE_MTHP_STAT_ATTR(collapse_alloc_failed, MTHP_STAT_COLLAPSE_ALLOC_FAILED); 811 DEFINE_MTHP_STAT_ATTR(zswpout, MTHP_STAT_ZSWPOUT); 812 DEFINE_MTHP_STAT_ATTR(swpin, MTHP_STAT_SWPIN); 813 DEFINE_MTHP_STAT_ATTR(swpin_fallback, MTHP_STAT_SWPIN_FALLBACK); 814 DEFINE_MTHP_STAT_ATTR(swpin_fallback_charge, MTHP_STAT_SWPIN_FALLBACK_CHARGE); 815 DEFINE_MTHP_STAT_ATTR(swpout, MTHP_STAT_SWPOUT); 816 DEFINE_MTHP_STAT_ATTR(swpout_fallback, MTHP_STAT_SWPOUT_FALLBACK); 817 #ifdef CONFIG_SHMEM 818 DEFINE_MTHP_STAT_ATTR(shmem_alloc, MTHP_STAT_SHMEM_ALLOC); 819 DEFINE_MTHP_STAT_ATTR(shmem_fallback, MTHP_STAT_SHMEM_FALLBACK); 820 DEFINE_MTHP_STAT_ATTR(shmem_fallback_charge, MTHP_STAT_SHMEM_FALLBACK_CHARGE); 821 #endif 822 DEFINE_MTHP_STAT_ATTR(split, MTHP_STAT_SPLIT); 823 DEFINE_MTHP_STAT_ATTR(split_failed, MTHP_STAT_SPLIT_FAILED); 824 DEFINE_MTHP_STAT_ATTR(split_deferred, MTHP_STAT_SPLIT_DEFERRED); 825 DEFINE_MTHP_STAT_ATTR(nr_anon, MTHP_STAT_NR_ANON); 826 DEFINE_MTHP_STAT_ATTR(nr_anon_partially_mapped, MTHP_STAT_NR_ANON_PARTIALLY_MAPPED); 827 DEFINE_MTHP_STAT_ATTR(collapse_exceed_swap_pte, MTHP_STAT_COLLAPSE_EXCEED_SWAP); 828 DEFINE_MTHP_STAT_ATTR(collapse_exceed_none_pte, MTHP_STAT_COLLAPSE_EXCEED_NONE); 829 DEFINE_MTHP_STAT_ATTR(collapse_exceed_shared_pte, MTHP_STAT_COLLAPSE_EXCEED_SHARED); 830 831 832 static struct attribute *anon_stats_attrs[] = { 833 &anon_fault_alloc_attr.attr, 834 &anon_fault_fallback_attr.attr, 835 &anon_fault_fallback_charge_attr.attr, 836 #ifndef CONFIG_SHMEM 837 &zswpout_attr.attr, 838 &swpin_attr.attr, 839 &swpin_fallback_attr.attr, 840 &swpin_fallback_charge_attr.attr, 841 &swpout_attr.attr, 842 &swpout_fallback_attr.attr, 843 #endif 844 &split_deferred_attr.attr, 845 &nr_anon_attr.attr, 846 &nr_anon_partially_mapped_attr.attr, 847 &collapse_exceed_swap_pte_attr.attr, 848 &collapse_exceed_none_pte_attr.attr, 849 &collapse_exceed_shared_pte_attr.attr, 850 NULL, 851 }; 852 853 static struct attribute_group anon_stats_attr_grp = { 854 .name = "stats", 855 .attrs = anon_stats_attrs, 856 }; 857 858 static struct attribute *file_stats_attrs[] = { 859 #ifdef CONFIG_SHMEM 860 &shmem_alloc_attr.attr, 861 &shmem_fallback_attr.attr, 862 &shmem_fallback_charge_attr.attr, 863 #endif 864 NULL, 865 }; 866 867 static struct attribute_group file_stats_attr_grp = { 868 .name = "stats", 869 .attrs = file_stats_attrs, 870 }; 871 872 static struct attribute *any_stats_attrs[] = { 873 #ifdef CONFIG_SHMEM 874 &zswpout_attr.attr, 875 &swpin_attr.attr, 876 &swpin_fallback_attr.attr, 877 &swpin_fallback_charge_attr.attr, 878 &swpout_attr.attr, 879 &swpout_fallback_attr.attr, 880 #endif 881 &split_attr.attr, 882 &split_failed_attr.attr, 883 &collapse_alloc_attr.attr, 884 &collapse_alloc_failed_attr.attr, 885 NULL, 886 }; 887 888 static struct attribute_group any_stats_attr_grp = { 889 .name = "stats", 890 .attrs = any_stats_attrs, 891 }; 892 893 static int sysfs_add_group(struct kobject *kobj, 894 const struct attribute_group *grp) 895 { 896 int ret = -ENOENT; 897 898 /* 899 * If the group is named, try to merge first, assuming the subdirectory 900 * was already created. This avoids the warning emitted by 901 * sysfs_create_group() if the directory already exists. 902 */ 903 if (grp->name) 904 ret = sysfs_merge_group(kobj, grp); 905 if (ret) 906 ret = sysfs_create_group(kobj, grp); 907 908 return ret; 909 } 910 911 static struct thpsize *thpsize_create(int order, struct kobject *parent) 912 { 913 unsigned long size = (PAGE_SIZE << order) / SZ_1K; 914 struct thpsize *thpsize; 915 int ret = -ENOMEM; 916 917 thpsize = kzalloc_obj(*thpsize); 918 if (!thpsize) 919 goto err; 920 921 thpsize->order = order; 922 923 ret = kobject_init_and_add(&thpsize->kobj, &thpsize_ktype, parent, 924 "hugepages-%lukB", size); 925 if (ret) 926 goto err_put; 927 928 929 ret = sysfs_add_group(&thpsize->kobj, &any_ctrl_attr_grp); 930 if (ret) 931 goto err_put; 932 933 ret = sysfs_add_group(&thpsize->kobj, &any_stats_attr_grp); 934 if (ret) 935 goto err_put; 936 937 if (BIT(order) & THP_ORDERS_ALL_ANON) { 938 ret = sysfs_add_group(&thpsize->kobj, &anon_ctrl_attr_grp); 939 if (ret) 940 goto err_put; 941 942 ret = sysfs_add_group(&thpsize->kobj, &anon_stats_attr_grp); 943 if (ret) 944 goto err_put; 945 } 946 947 if (BIT(order) & THP_ORDERS_ALL_FILE_DEFAULT) { 948 ret = sysfs_add_group(&thpsize->kobj, &file_ctrl_attr_grp); 949 if (ret) 950 goto err_put; 951 952 ret = sysfs_add_group(&thpsize->kobj, &file_stats_attr_grp); 953 if (ret) 954 goto err_put; 955 } 956 957 return thpsize; 958 err_put: 959 kobject_put(&thpsize->kobj); 960 err: 961 return ERR_PTR(ret); 962 } 963 964 static void thpsize_release(struct kobject *kobj) 965 { 966 kfree(to_thpsize(kobj)); 967 } 968 969 static int __init hugepage_init_sysfs(struct kobject **hugepage_kobj) 970 { 971 int err; 972 struct thpsize *thpsize; 973 unsigned long orders; 974 int order; 975 976 /* 977 * Default to setting PMD-sized THP to inherit the global setting and 978 * disable all other sizes. powerpc's PMD_ORDER isn't a compile-time 979 * constant so we have to do this here. 980 */ 981 if (!anon_orders_configured) 982 huge_anon_orders_inherit = BIT(PMD_ORDER); 983 984 *hugepage_kobj = kobject_create_and_add("transparent_hugepage", mm_kobj); 985 if (unlikely(!*hugepage_kobj)) { 986 pr_err("failed to create transparent hugepage kobject\n"); 987 return -ENOMEM; 988 } 989 990 err = sysfs_create_group(*hugepage_kobj, &hugepage_attr_group); 991 if (err) { 992 pr_err("failed to register transparent hugepage group\n"); 993 goto delete_obj; 994 } 995 996 err = sysfs_create_group(*hugepage_kobj, &khugepaged_attr_group); 997 if (err) { 998 pr_err("failed to register transparent hugepage group\n"); 999 goto remove_hp_group; 1000 } 1001 1002 orders = THP_ORDERS_ALL_ANON | THP_ORDERS_ALL_FILE_DEFAULT; 1003 order = highest_order(orders); 1004 while (orders) { 1005 thpsize = thpsize_create(order, *hugepage_kobj); 1006 if (IS_ERR(thpsize)) { 1007 pr_err("failed to create thpsize for order %d\n", order); 1008 err = PTR_ERR(thpsize); 1009 goto remove_all; 1010 } 1011 list_add(&thpsize->node, &thpsize_list); 1012 order = next_order(&orders, order); 1013 } 1014 1015 return 0; 1016 1017 remove_all: 1018 hugepage_exit_sysfs(*hugepage_kobj); 1019 return err; 1020 remove_hp_group: 1021 sysfs_remove_group(*hugepage_kobj, &hugepage_attr_group); 1022 delete_obj: 1023 kobject_put(*hugepage_kobj); 1024 return err; 1025 } 1026 1027 static void __init hugepage_exit_sysfs(struct kobject *hugepage_kobj) 1028 { 1029 struct thpsize *thpsize, *tmp; 1030 1031 list_for_each_entry_safe(thpsize, tmp, &thpsize_list, node) { 1032 list_del(&thpsize->node); 1033 kobject_put(&thpsize->kobj); 1034 } 1035 1036 sysfs_remove_group(hugepage_kobj, &khugepaged_attr_group); 1037 sysfs_remove_group(hugepage_kobj, &hugepage_attr_group); 1038 kobject_put(hugepage_kobj); 1039 } 1040 #else 1041 static inline int hugepage_init_sysfs(struct kobject **hugepage_kobj) 1042 { 1043 return 0; 1044 } 1045 1046 static inline void hugepage_exit_sysfs(struct kobject *hugepage_kobj) 1047 { 1048 } 1049 #endif /* CONFIG_SYSFS */ 1050 1051 int folio_memcg_alloc_deferred(struct folio *folio) 1052 { 1053 if (mem_cgroup_disabled()) 1054 return 0; 1055 return folio_memcg_list_lru_alloc(folio, &deferred_split_lru, GFP_KERNEL); 1056 } 1057 1058 static int __init thp_shrinker_init(void) 1059 { 1060 deferred_split_shrinker = shrinker_alloc(SHRINKER_NUMA_AWARE | 1061 SHRINKER_MEMCG_AWARE, 1062 "thp-deferred_split"); 1063 if (!deferred_split_shrinker) 1064 return -ENOMEM; 1065 1066 if (list_lru_init_memcg_key(&deferred_split_lru, 1067 deferred_split_shrinker, 1068 &deferred_split_key)) { 1069 shrinker_free(deferred_split_shrinker); 1070 return -ENOMEM; 1071 } 1072 1073 deferred_split_shrinker->count_objects = deferred_split_count; 1074 deferred_split_shrinker->scan_objects = deferred_split_scan; 1075 shrinker_register(deferred_split_shrinker); 1076 1077 return huge_zero_init(); 1078 } 1079 1080 static void __init thp_shrinker_exit(void) 1081 { 1082 shrinker_free(deferred_split_shrinker); 1083 list_lru_destroy(&deferred_split_lru); 1084 huge_zero_shrinker_exit(); 1085 } 1086 1087 static int __init hugepage_init(void) 1088 { 1089 int err; 1090 struct kobject *hugepage_kobj; 1091 1092 if (!has_transparent_hugepage()) { 1093 transparent_hugepage_flags = 1 << TRANSPARENT_HUGEPAGE_UNSUPPORTED; 1094 return -EINVAL; 1095 } 1096 1097 /* 1098 * hugepages can't be allocated by the buddy allocator 1099 */ 1100 MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER > MAX_PAGE_ORDER); 1101 1102 err = hugepage_init_sysfs(&hugepage_kobj); 1103 if (err) 1104 goto err_sysfs; 1105 1106 err = khugepaged_init(); 1107 if (err) 1108 goto err_slab; 1109 1110 err = thp_shrinker_init(); 1111 if (err) 1112 goto err_shrinker; 1113 1114 /* 1115 * By default disable transparent hugepages on smaller systems, 1116 * where the extra memory used could hurt more than TLB overhead 1117 * is likely to save. The admin can still enable it through /sys. 1118 */ 1119 if (totalram_pages() < MB_TO_PAGES(512)) { 1120 transparent_hugepage_flags = 0; 1121 return 0; 1122 } 1123 1124 err = start_stop_khugepaged(); 1125 if (err) 1126 goto err_khugepaged; 1127 1128 return 0; 1129 err_khugepaged: 1130 thp_shrinker_exit(); 1131 err_shrinker: 1132 khugepaged_destroy(); 1133 err_slab: 1134 hugepage_exit_sysfs(hugepage_kobj); 1135 err_sysfs: 1136 return err; 1137 } 1138 subsys_initcall(hugepage_init); 1139 1140 static int __init setup_transparent_hugepage(char *str) 1141 { 1142 int ret = 0; 1143 1144 if (!str) 1145 goto out; 1146 if (!strcmp(str, "always")) { 1147 set_bit(TRANSPARENT_HUGEPAGE_FLAG, 1148 &transparent_hugepage_flags); 1149 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, 1150 &transparent_hugepage_flags); 1151 ret = 1; 1152 } else if (!strcmp(str, "madvise")) { 1153 clear_bit(TRANSPARENT_HUGEPAGE_FLAG, 1154 &transparent_hugepage_flags); 1155 set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, 1156 &transparent_hugepage_flags); 1157 ret = 1; 1158 } else if (!strcmp(str, "never")) { 1159 clear_bit(TRANSPARENT_HUGEPAGE_FLAG, 1160 &transparent_hugepage_flags); 1161 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, 1162 &transparent_hugepage_flags); 1163 ret = 1; 1164 } 1165 out: 1166 if (!ret) 1167 pr_warn("transparent_hugepage= cannot parse, ignored\n"); 1168 return ret; 1169 } 1170 __setup("transparent_hugepage=", setup_transparent_hugepage); 1171 1172 static char str_dup[PAGE_SIZE] __initdata; 1173 static int __init setup_thp_anon(char *str) 1174 { 1175 char *token, *range, *policy, *subtoken; 1176 unsigned long always, inherit, madvise; 1177 char *start_size, *end_size; 1178 int start, end, nr; 1179 char *p; 1180 1181 if (!str || strlen(str) + 1 > PAGE_SIZE) 1182 goto err; 1183 strscpy(str_dup, str); 1184 1185 always = huge_anon_orders_always; 1186 madvise = huge_anon_orders_madvise; 1187 inherit = huge_anon_orders_inherit; 1188 p = str_dup; 1189 while ((token = strsep(&p, ";")) != NULL) { 1190 range = strsep(&token, ":"); 1191 policy = token; 1192 1193 if (!policy) 1194 goto err; 1195 1196 while ((subtoken = strsep(&range, ",")) != NULL) { 1197 if (strchr(subtoken, '-')) { 1198 start_size = strsep(&subtoken, "-"); 1199 end_size = subtoken; 1200 1201 start = get_order_from_str(start_size, THP_ORDERS_ALL_ANON); 1202 end = get_order_from_str(end_size, THP_ORDERS_ALL_ANON); 1203 } else { 1204 start_size = end_size = subtoken; 1205 start = end = get_order_from_str(subtoken, 1206 THP_ORDERS_ALL_ANON); 1207 } 1208 1209 if (start == -EINVAL) { 1210 pr_err("invalid size %s in thp_anon boot parameter\n", start_size); 1211 goto err; 1212 } 1213 1214 if (end == -EINVAL) { 1215 pr_err("invalid size %s in thp_anon boot parameter\n", end_size); 1216 goto err; 1217 } 1218 1219 if (start < 0 || end < 0 || start > end) 1220 goto err; 1221 1222 nr = end - start + 1; 1223 if (!strcmp(policy, "always")) { 1224 bitmap_set(&always, start, nr); 1225 bitmap_clear(&inherit, start, nr); 1226 bitmap_clear(&madvise, start, nr); 1227 } else if (!strcmp(policy, "madvise")) { 1228 bitmap_set(&madvise, start, nr); 1229 bitmap_clear(&inherit, start, nr); 1230 bitmap_clear(&always, start, nr); 1231 } else if (!strcmp(policy, "inherit")) { 1232 bitmap_set(&inherit, start, nr); 1233 bitmap_clear(&madvise, start, nr); 1234 bitmap_clear(&always, start, nr); 1235 } else if (!strcmp(policy, "never")) { 1236 bitmap_clear(&inherit, start, nr); 1237 bitmap_clear(&madvise, start, nr); 1238 bitmap_clear(&always, start, nr); 1239 } else { 1240 pr_err("invalid policy %s in thp_anon boot parameter\n", policy); 1241 goto err; 1242 } 1243 } 1244 } 1245 1246 huge_anon_orders_always = always; 1247 huge_anon_orders_madvise = madvise; 1248 huge_anon_orders_inherit = inherit; 1249 anon_orders_configured = true; 1250 return 1; 1251 1252 err: 1253 pr_warn("thp_anon=%s: error parsing string, ignoring setting\n", str); 1254 return 0; 1255 } 1256 __setup("thp_anon=", setup_thp_anon); 1257 1258 pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma) 1259 { 1260 if (likely(vma->vm_flags & VM_WRITE)) 1261 pmd = pmd_mkwrite(pmd, vma); 1262 return pmd; 1263 } 1264 1265 static inline bool is_transparent_hugepage(const struct folio *folio) 1266 { 1267 if (!folio_test_large(folio)) 1268 return false; 1269 1270 return is_huge_zero_folio(folio) || 1271 folio_test_large_rmappable(folio); 1272 } 1273 1274 static unsigned long __thp_get_unmapped_area(struct file *filp, 1275 unsigned long addr, unsigned long len, 1276 loff_t off, unsigned long flags, unsigned long size, 1277 vma_flags_t vma_flags) 1278 { 1279 loff_t off_end = off + len; 1280 loff_t off_align = round_up(off, size); 1281 unsigned long len_pad, ret, off_sub; 1282 1283 if (!IS_ENABLED(CONFIG_64BIT) || in_compat_syscall()) 1284 return 0; 1285 1286 if (off_end <= off_align || (off_end - off_align) < size) 1287 return 0; 1288 1289 len_pad = len + size; 1290 if (len_pad < len || (off + len_pad) < off) 1291 return 0; 1292 1293 ret = mm_get_unmapped_area_vmaflags(filp, addr, len_pad, 1294 off >> PAGE_SHIFT, flags, 1295 vma_flags); 1296 1297 /* 1298 * The failure might be due to length padding. The caller will retry 1299 * without the padding. 1300 */ 1301 if (IS_ERR_VALUE(ret)) 1302 return 0; 1303 1304 /* 1305 * Do not try to align to THP boundary if allocation at the address 1306 * hint succeeds. 1307 */ 1308 if (ret == addr) 1309 return addr; 1310 1311 off_sub = (off - ret) & (size - 1); 1312 1313 if (mm_flags_test(MMF_TOPDOWN, current->mm) && !off_sub) 1314 return ret + size; 1315 1316 ret += off_sub; 1317 return ret; 1318 } 1319 1320 unsigned long thp_get_unmapped_area_vmaflags(struct file *filp, unsigned long addr, 1321 unsigned long len, unsigned long pgoff, unsigned long flags, 1322 vma_flags_t vma_flags) 1323 { 1324 unsigned long ret; 1325 loff_t off = (loff_t)pgoff << PAGE_SHIFT; 1326 1327 ret = __thp_get_unmapped_area(filp, addr, len, off, flags, PMD_SIZE, 1328 vma_flags); 1329 if (ret) 1330 return ret; 1331 1332 return mm_get_unmapped_area_vmaflags(filp, addr, len, pgoff, flags, 1333 vma_flags); 1334 } 1335 1336 unsigned long thp_get_unmapped_area(struct file *filp, unsigned long addr, 1337 unsigned long len, unsigned long pgoff, unsigned long flags) 1338 { 1339 return thp_get_unmapped_area_vmaflags(filp, addr, len, pgoff, flags, 1340 EMPTY_VMA_FLAGS); 1341 } 1342 EXPORT_SYMBOL_GPL(thp_get_unmapped_area); 1343 1344 static struct folio *vma_alloc_anon_folio_pmd(struct vm_area_struct *vma, 1345 unsigned long addr) 1346 { 1347 gfp_t gfp = vma_thp_gfp_mask(vma); 1348 const int order = HPAGE_PMD_ORDER; 1349 struct folio *folio; 1350 1351 folio = vma_alloc_folio(gfp, order, vma, addr & HPAGE_PMD_MASK); 1352 1353 if (unlikely(!folio)) { 1354 count_vm_event(THP_FAULT_FALLBACK); 1355 count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK); 1356 return NULL; 1357 } 1358 1359 VM_BUG_ON_FOLIO(!folio_test_large(folio), folio); 1360 if (mem_cgroup_charge(folio, vma->vm_mm, gfp)) { 1361 folio_put(folio); 1362 count_vm_event(THP_FAULT_FALLBACK); 1363 count_vm_event(THP_FAULT_FALLBACK_CHARGE); 1364 count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK); 1365 count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE); 1366 return NULL; 1367 } 1368 1369 if (folio_memcg_alloc_deferred(folio)) { 1370 folio_put(folio); 1371 count_vm_event(THP_FAULT_FALLBACK); 1372 count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK); 1373 return NULL; 1374 } 1375 1376 folio_throttle_swaprate(folio, gfp); 1377 1378 /* 1379 * When a folio is not zeroed during allocation (__GFP_ZERO not used) 1380 * or user folios require special handling, folio_zero_user() is used to 1381 * make sure that the page corresponding to the faulting address will be 1382 * hot in the cache after zeroing. 1383 */ 1384 if (user_alloc_needs_zeroing()) 1385 folio_zero_user(folio, addr); 1386 /* 1387 * The memory barrier inside __folio_mark_uptodate makes sure that 1388 * folio_zero_user writes become visible before the set_pmd_at() 1389 * write. 1390 */ 1391 __folio_mark_uptodate(folio); 1392 return folio; 1393 } 1394 1395 void map_anon_folio_pmd_nopf(struct folio *folio, pmd_t *pmd, 1396 struct vm_area_struct *vma, unsigned long haddr) 1397 { 1398 pmd_t entry; 1399 1400 entry = folio_mk_pmd(folio, vma->vm_page_prot); 1401 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); 1402 folio_add_new_anon_rmap(folio, vma, haddr, RMAP_EXCLUSIVE); 1403 folio_add_lru_vma(folio, vma); 1404 set_pmd_at(vma->vm_mm, haddr, pmd, entry); 1405 update_mmu_cache_pmd(vma, haddr, pmd); 1406 deferred_split_folio(folio, false); 1407 } 1408 1409 static void map_anon_folio_pmd_pf(struct folio *folio, pmd_t *pmd, 1410 struct vm_area_struct *vma, unsigned long haddr) 1411 { 1412 map_anon_folio_pmd_nopf(folio, pmd, vma, haddr); 1413 add_mm_counter(vma->vm_mm, MM_ANONPAGES, HPAGE_PMD_NR); 1414 count_vm_event(THP_FAULT_ALLOC); 1415 count_mthp_stat(HPAGE_PMD_ORDER, MTHP_STAT_ANON_FAULT_ALLOC); 1416 count_memcg_event_mm(vma->vm_mm, THP_FAULT_ALLOC); 1417 } 1418 1419 static vm_fault_t __do_huge_pmd_anonymous_page(struct vm_fault *vmf) 1420 { 1421 unsigned long haddr = vmf->address & HPAGE_PMD_MASK; 1422 struct vm_area_struct *vma = vmf->vma; 1423 struct folio *folio; 1424 pgtable_t pgtable; 1425 vm_fault_t ret = 0; 1426 1427 folio = vma_alloc_anon_folio_pmd(vma, vmf->address); 1428 if (unlikely(!folio)) 1429 return VM_FAULT_FALLBACK; 1430 1431 pgtable = pte_alloc_one(vma->vm_mm); 1432 if (unlikely(!pgtable)) { 1433 ret = VM_FAULT_OOM; 1434 goto release; 1435 } 1436 1437 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd); 1438 if (unlikely(!pmd_none(*vmf->pmd))) { 1439 goto unlock_release; 1440 } else { 1441 ret = check_stable_address_space(vma->vm_mm); 1442 if (ret) 1443 goto unlock_release; 1444 1445 /* Deliver the page fault to userland */ 1446 if (userfaultfd_missing(vma)) { 1447 spin_unlock(vmf->ptl); 1448 folio_put(folio); 1449 pte_free(vma->vm_mm, pgtable); 1450 ret = handle_userfault(vmf, VM_UFFD_MISSING); 1451 VM_BUG_ON(ret & VM_FAULT_FALLBACK); 1452 return ret; 1453 } 1454 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, pgtable); 1455 map_anon_folio_pmd_pf(folio, vmf->pmd, vma, haddr); 1456 mm_inc_nr_ptes(vma->vm_mm); 1457 spin_unlock(vmf->ptl); 1458 } 1459 1460 return 0; 1461 unlock_release: 1462 spin_unlock(vmf->ptl); 1463 release: 1464 if (pgtable) 1465 pte_free(vma->vm_mm, pgtable); 1466 folio_put(folio); 1467 return ret; 1468 1469 } 1470 1471 vm_fault_t do_huge_pmd_device_private(struct vm_fault *vmf) 1472 { 1473 struct vm_area_struct *vma = vmf->vma; 1474 vm_fault_t ret = 0; 1475 spinlock_t *ptl; 1476 softleaf_t entry; 1477 struct page *page; 1478 struct folio *folio; 1479 1480 if (vmf->flags & FAULT_FLAG_VMA_LOCK) { 1481 vma_end_read(vma); 1482 return VM_FAULT_RETRY; 1483 } 1484 1485 ptl = pmd_lock(vma->vm_mm, vmf->pmd); 1486 if (unlikely(!pmd_same(*vmf->pmd, vmf->orig_pmd))) { 1487 spin_unlock(ptl); 1488 return 0; 1489 } 1490 1491 entry = softleaf_from_pmd(vmf->orig_pmd); 1492 page = softleaf_to_page(entry); 1493 folio = page_folio(page); 1494 vmf->page = page; 1495 vmf->pte = NULL; 1496 if (folio_trylock(folio)) { 1497 folio_get(folio); 1498 spin_unlock(ptl); 1499 ret = page_pgmap(page)->ops->migrate_to_ram(vmf); 1500 folio_unlock(folio); 1501 folio_put(folio); 1502 } else { 1503 spin_unlock(ptl); 1504 } 1505 1506 return ret; 1507 } 1508 1509 /* 1510 * always: directly stall for all thp allocations 1511 * defer: wake kswapd and fail if not immediately available 1512 * defer+madvise: wake kswapd and directly stall for MADV_HUGEPAGE, otherwise 1513 * fail if not immediately available 1514 * madvise: directly stall for MADV_HUGEPAGE, otherwise fail if not immediately 1515 * available 1516 * never: never stall for any thp allocation 1517 */ 1518 gfp_t vma_thp_gfp_mask(struct vm_area_struct *vma) 1519 { 1520 const bool vma_madvised = vma && (vma->vm_flags & VM_HUGEPAGE); 1521 1522 /* Always do synchronous compaction */ 1523 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags)) 1524 return GFP_TRANSHUGE | (vma_madvised ? 0 : __GFP_NORETRY); 1525 1526 /* Kick kcompactd and fail quickly */ 1527 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags)) 1528 return GFP_TRANSHUGE_LIGHT | __GFP_KSWAPD_RECLAIM; 1529 1530 /* Synchronous compaction if madvised, otherwise kick kcompactd */ 1531 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags)) 1532 return GFP_TRANSHUGE_LIGHT | 1533 (vma_madvised ? __GFP_DIRECT_RECLAIM : 1534 __GFP_KSWAPD_RECLAIM); 1535 1536 /* Only do synchronous compaction if madvised */ 1537 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags)) 1538 return GFP_TRANSHUGE_LIGHT | 1539 (vma_madvised ? __GFP_DIRECT_RECLAIM : 0); 1540 1541 return GFP_TRANSHUGE_LIGHT; 1542 } 1543 1544 /* Caller must hold page table lock. */ 1545 static void set_huge_zero_folio(pgtable_t pgtable, struct mm_struct *mm, 1546 struct vm_area_struct *vma, unsigned long haddr, pmd_t *pmd, 1547 struct folio *zero_folio) 1548 { 1549 pmd_t entry; 1550 1551 entry = folio_mk_pmd(zero_folio, vma->vm_page_prot); 1552 entry = pmd_mkspecial(entry); 1553 pgtable_trans_huge_deposit(mm, pmd, pgtable); 1554 set_pmd_at(mm, haddr, pmd, entry); 1555 mm_inc_nr_ptes(mm); 1556 } 1557 1558 vm_fault_t do_huge_pmd_anonymous_page(struct vm_fault *vmf) 1559 { 1560 struct vm_area_struct *vma = vmf->vma; 1561 unsigned long haddr = vmf->address & HPAGE_PMD_MASK; 1562 vm_fault_t ret; 1563 1564 if (!thp_vma_suitable_order(vma, haddr, PMD_ORDER)) 1565 return VM_FAULT_FALLBACK; 1566 ret = vmf_anon_prepare(vmf); 1567 if (ret) 1568 return ret; 1569 khugepaged_enter_vma(vma, vma->vm_flags); 1570 1571 if (!(vmf->flags & FAULT_FLAG_WRITE) && 1572 !mm_forbids_zeropage(vma->vm_mm) && 1573 transparent_hugepage_use_zero_page()) { 1574 pgtable_t pgtable; 1575 struct folio *zero_folio; 1576 vm_fault_t ret; 1577 1578 pgtable = pte_alloc_one(vma->vm_mm); 1579 if (unlikely(!pgtable)) 1580 return VM_FAULT_OOM; 1581 zero_folio = mm_get_huge_zero_folio(vma->vm_mm); 1582 if (unlikely(!zero_folio)) { 1583 pte_free(vma->vm_mm, pgtable); 1584 count_vm_event(THP_FAULT_FALLBACK); 1585 return VM_FAULT_FALLBACK; 1586 } 1587 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd); 1588 ret = 0; 1589 if (pmd_none(*vmf->pmd)) { 1590 ret = check_stable_address_space(vma->vm_mm); 1591 if (ret) { 1592 spin_unlock(vmf->ptl); 1593 pte_free(vma->vm_mm, pgtable); 1594 } else if (userfaultfd_missing(vma)) { 1595 spin_unlock(vmf->ptl); 1596 pte_free(vma->vm_mm, pgtable); 1597 ret = handle_userfault(vmf, VM_UFFD_MISSING); 1598 VM_BUG_ON(ret & VM_FAULT_FALLBACK); 1599 } else { 1600 set_huge_zero_folio(pgtable, vma->vm_mm, vma, 1601 haddr, vmf->pmd, zero_folio); 1602 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd); 1603 spin_unlock(vmf->ptl); 1604 } 1605 } else { 1606 spin_unlock(vmf->ptl); 1607 pte_free(vma->vm_mm, pgtable); 1608 } 1609 return ret; 1610 } 1611 1612 return __do_huge_pmd_anonymous_page(vmf); 1613 } 1614 1615 struct folio_or_pfn { 1616 union { 1617 struct folio *folio; 1618 unsigned long pfn; 1619 }; 1620 bool is_folio; 1621 }; 1622 1623 static vm_fault_t insert_pmd(struct vm_area_struct *vma, unsigned long addr, 1624 pmd_t *pmd, struct folio_or_pfn fop, pgprot_t prot, 1625 bool write) 1626 { 1627 struct mm_struct *mm = vma->vm_mm; 1628 pgtable_t pgtable = NULL; 1629 spinlock_t *ptl; 1630 pmd_t entry; 1631 1632 if (addr < vma->vm_start || addr >= vma->vm_end) 1633 return VM_FAULT_SIGBUS; 1634 1635 if (arch_needs_pgtable_deposit()) { 1636 pgtable = pte_alloc_one(vma->vm_mm); 1637 if (!pgtable) 1638 return VM_FAULT_OOM; 1639 } 1640 1641 ptl = pmd_lock(mm, pmd); 1642 if (!pmd_none(*pmd)) { 1643 const unsigned long pfn = fop.is_folio ? folio_pfn(fop.folio) : 1644 fop.pfn; 1645 1646 if (write) { 1647 if (pmd_pfn(*pmd) != pfn) { 1648 WARN_ON_ONCE(!is_huge_zero_pmd(*pmd)); 1649 goto out_unlock; 1650 } 1651 entry = pmd_mkyoung(*pmd); 1652 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); 1653 if (pmdp_set_access_flags(vma, addr, pmd, entry, 1)) 1654 update_mmu_cache_pmd(vma, addr, pmd); 1655 } 1656 goto out_unlock; 1657 } 1658 1659 if (fop.is_folio) { 1660 entry = folio_mk_pmd(fop.folio, vma->vm_page_prot); 1661 1662 if (is_huge_zero_folio(fop.folio)) { 1663 entry = pmd_mkspecial(entry); 1664 } else { 1665 folio_get(fop.folio); 1666 folio_add_file_rmap_pmd(fop.folio, &fop.folio->page, vma); 1667 add_mm_counter(mm, mm_counter_file(fop.folio), HPAGE_PMD_NR); 1668 } 1669 } else { 1670 entry = pmd_mkhuge(pfn_pmd(fop.pfn, prot)); 1671 entry = pmd_mkspecial(entry); 1672 } 1673 if (write) { 1674 entry = pmd_mkyoung(pmd_mkdirty(entry)); 1675 entry = maybe_pmd_mkwrite(entry, vma); 1676 } 1677 1678 if (pgtable) { 1679 pgtable_trans_huge_deposit(mm, pmd, pgtable); 1680 mm_inc_nr_ptes(mm); 1681 pgtable = NULL; 1682 } 1683 1684 set_pmd_at(mm, addr, pmd, entry); 1685 update_mmu_cache_pmd(vma, addr, pmd); 1686 1687 out_unlock: 1688 spin_unlock(ptl); 1689 if (pgtable) 1690 pte_free(mm, pgtable); 1691 return VM_FAULT_NOPAGE; 1692 } 1693 1694 /** 1695 * vmf_insert_pfn_pmd - insert a pmd size pfn 1696 * @vmf: Structure describing the fault 1697 * @pfn: pfn to insert 1698 * @write: whether it's a write fault 1699 * 1700 * Insert a pmd size pfn. See vmf_insert_pfn() for additional info. 1701 * 1702 * Return: vm_fault_t value. 1703 */ 1704 vm_fault_t vmf_insert_pfn_pmd(struct vm_fault *vmf, unsigned long pfn, 1705 bool write) 1706 { 1707 unsigned long addr = vmf->address & PMD_MASK; 1708 struct vm_area_struct *vma = vmf->vma; 1709 pgprot_t pgprot = vma->vm_page_prot; 1710 struct folio_or_pfn fop = { 1711 .pfn = pfn, 1712 }; 1713 1714 /* 1715 * If we had pmd_special, we could avoid all these restrictions, 1716 * but we need to be consistent with PTEs and architectures that 1717 * can't support a 'special' bit. 1718 */ 1719 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))); 1720 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) == 1721 (VM_PFNMAP|VM_MIXEDMAP)); 1722 BUG_ON((vma->vm_flags & VM_PFNMAP) && vma_is_cow_mapping(vma)); 1723 1724 if (unlikely(is_huge_zero_pfn(pfn))) 1725 return VM_FAULT_SIGBUS; 1726 1727 pfnmap_setup_cachemode_pfn(pfn, &pgprot); 1728 1729 return insert_pmd(vma, addr, vmf->pmd, fop, pgprot, write); 1730 } 1731 EXPORT_SYMBOL_GPL(vmf_insert_pfn_pmd); 1732 1733 vm_fault_t vmf_insert_folio_pmd(struct vm_fault *vmf, struct folio *folio, 1734 bool write) 1735 { 1736 struct vm_area_struct *vma = vmf->vma; 1737 unsigned long addr = vmf->address & PMD_MASK; 1738 struct folio_or_pfn fop = { 1739 .folio = folio, 1740 .is_folio = true, 1741 }; 1742 1743 if (WARN_ON_ONCE(folio_order(folio) != PMD_ORDER)) 1744 return VM_FAULT_SIGBUS; 1745 1746 return insert_pmd(vma, addr, vmf->pmd, fop, vma->vm_page_prot, write); 1747 } 1748 EXPORT_SYMBOL_GPL(vmf_insert_folio_pmd); 1749 1750 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD 1751 static pud_t maybe_pud_mkwrite(pud_t pud, struct vm_area_struct *vma) 1752 { 1753 if (likely(vma->vm_flags & VM_WRITE)) 1754 pud = pud_mkwrite(pud); 1755 return pud; 1756 } 1757 1758 static vm_fault_t insert_pud(struct vm_area_struct *vma, unsigned long addr, 1759 pud_t *pud, struct folio_or_pfn fop, pgprot_t prot, bool write) 1760 { 1761 struct mm_struct *mm = vma->vm_mm; 1762 spinlock_t *ptl; 1763 pud_t entry; 1764 1765 if (addr < vma->vm_start || addr >= vma->vm_end) 1766 return VM_FAULT_SIGBUS; 1767 1768 ptl = pud_lock(mm, pud); 1769 if (!pud_none(*pud)) { 1770 const unsigned long pfn = fop.is_folio ? folio_pfn(fop.folio) : 1771 fop.pfn; 1772 1773 if (write) { 1774 if (WARN_ON_ONCE(pud_pfn(*pud) != pfn)) 1775 goto out_unlock; 1776 entry = pud_mkyoung(*pud); 1777 entry = maybe_pud_mkwrite(pud_mkdirty(entry), vma); 1778 if (pudp_set_access_flags(vma, addr, pud, entry, 1)) 1779 update_mmu_cache_pud(vma, addr, pud); 1780 } 1781 goto out_unlock; 1782 } 1783 1784 if (fop.is_folio) { 1785 entry = folio_mk_pud(fop.folio, vma->vm_page_prot); 1786 1787 folio_get(fop.folio); 1788 folio_add_file_rmap_pud(fop.folio, &fop.folio->page, vma); 1789 add_mm_counter(mm, mm_counter_file(fop.folio), HPAGE_PUD_NR); 1790 } else { 1791 entry = pud_mkhuge(pfn_pud(fop.pfn, prot)); 1792 entry = pud_mkspecial(entry); 1793 } 1794 if (write) { 1795 entry = pud_mkyoung(pud_mkdirty(entry)); 1796 entry = maybe_pud_mkwrite(entry, vma); 1797 } 1798 set_pud_at(mm, addr, pud, entry); 1799 update_mmu_cache_pud(vma, addr, pud); 1800 out_unlock: 1801 spin_unlock(ptl); 1802 return VM_FAULT_NOPAGE; 1803 } 1804 1805 /** 1806 * vmf_insert_pfn_pud - insert a pud size pfn 1807 * @vmf: Structure describing the fault 1808 * @pfn: pfn to insert 1809 * @write: whether it's a write fault 1810 * 1811 * Insert a pud size pfn. See vmf_insert_pfn() for additional info. 1812 * 1813 * Return: vm_fault_t value. 1814 */ 1815 vm_fault_t vmf_insert_pfn_pud(struct vm_fault *vmf, unsigned long pfn, 1816 bool write) 1817 { 1818 unsigned long addr = vmf->address & PUD_MASK; 1819 struct vm_area_struct *vma = vmf->vma; 1820 pgprot_t pgprot = vma->vm_page_prot; 1821 struct folio_or_pfn fop = { 1822 .pfn = pfn, 1823 }; 1824 1825 /* 1826 * If we had pud_special, we could avoid all these restrictions, 1827 * but we need to be consistent with PTEs and architectures that 1828 * can't support a 'special' bit. 1829 */ 1830 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))); 1831 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) == 1832 (VM_PFNMAP|VM_MIXEDMAP)); 1833 BUG_ON((vma->vm_flags & VM_PFNMAP) && vma_is_cow_mapping(vma)); 1834 1835 pfnmap_setup_cachemode_pfn(pfn, &pgprot); 1836 1837 return insert_pud(vma, addr, vmf->pud, fop, pgprot, write); 1838 } 1839 EXPORT_SYMBOL_GPL(vmf_insert_pfn_pud); 1840 1841 /** 1842 * vmf_insert_folio_pud - insert a pud size folio mapped by a pud entry 1843 * @vmf: Structure describing the fault 1844 * @folio: folio to insert 1845 * @write: whether it's a write fault 1846 * 1847 * Return: vm_fault_t value. 1848 */ 1849 vm_fault_t vmf_insert_folio_pud(struct vm_fault *vmf, struct folio *folio, 1850 bool write) 1851 { 1852 struct vm_area_struct *vma = vmf->vma; 1853 unsigned long addr = vmf->address & PUD_MASK; 1854 struct folio_or_pfn fop = { 1855 .folio = folio, 1856 .is_folio = true, 1857 }; 1858 1859 if (WARN_ON_ONCE(folio_order(folio) != PUD_ORDER)) 1860 return VM_FAULT_SIGBUS; 1861 1862 return insert_pud(vma, addr, vmf->pud, fop, vma->vm_page_prot, write); 1863 } 1864 EXPORT_SYMBOL_GPL(vmf_insert_folio_pud); 1865 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */ 1866 1867 /** 1868 * touch_pmd - Mark page table pmd entry as accessed and dirty (for write) 1869 * @vma: The VMA covering @addr 1870 * @addr: The virtual address 1871 * @pmd: pmd pointer into the page table mapping @addr 1872 * @write: Whether it's a write access 1873 * 1874 * Return: whether the pmd entry is changed 1875 */ 1876 bool touch_pmd(struct vm_area_struct *vma, unsigned long addr, 1877 pmd_t *pmd, bool write) 1878 { 1879 pmd_t entry; 1880 1881 entry = pmd_mkyoung(*pmd); 1882 if (write) 1883 entry = pmd_mkdirty(entry); 1884 if (pmdp_set_access_flags(vma, addr & HPAGE_PMD_MASK, 1885 pmd, entry, write)) { 1886 update_mmu_cache_pmd(vma, addr, pmd); 1887 return true; 1888 } 1889 1890 return false; 1891 } 1892 1893 static void copy_huge_non_present_pmd( 1894 struct mm_struct *dst_mm, struct mm_struct *src_mm, 1895 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr, 1896 struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 1897 pmd_t pmd, pgtable_t pgtable) 1898 { 1899 softleaf_t entry = softleaf_from_pmd(pmd); 1900 struct folio *src_folio; 1901 1902 VM_WARN_ON_ONCE(!pmd_is_valid_softleaf(pmd)); 1903 1904 if (softleaf_is_migration_write(entry) || 1905 softleaf_is_migration_read_exclusive(entry)) { 1906 entry = make_readable_migration_entry(swp_offset(entry)); 1907 pmd = softleaf_to_pmd(entry); 1908 if (pmd_swp_soft_dirty(*src_pmd)) 1909 pmd = pmd_swp_mksoft_dirty(pmd); 1910 if (pmd_swp_uffd(*src_pmd)) 1911 pmd = pmd_swp_mkuffd(pmd); 1912 set_pmd_at(src_mm, addr, src_pmd, pmd); 1913 } else if (softleaf_is_device_private(entry)) { 1914 /* 1915 * For device private entries, since there are no 1916 * read exclusive entries, writable = !readable 1917 */ 1918 if (softleaf_is_device_private_write(entry)) { 1919 entry = make_readable_device_private_entry(swp_offset(entry)); 1920 pmd = softleaf_to_pmd(entry); 1921 1922 if (pmd_swp_soft_dirty(*src_pmd)) 1923 pmd = pmd_swp_mksoft_dirty(pmd); 1924 if (pmd_swp_uffd(*src_pmd)) 1925 pmd = pmd_swp_mkuffd(pmd); 1926 set_pmd_at(src_mm, addr, src_pmd, pmd); 1927 } 1928 1929 src_folio = softleaf_to_folio(entry); 1930 VM_WARN_ON(!folio_test_large(src_folio)); 1931 1932 folio_get(src_folio); 1933 /* 1934 * folio_try_dup_anon_rmap_pmd does not fail for 1935 * device private entries. 1936 */ 1937 folio_try_dup_anon_rmap_pmd(src_folio, &src_folio->page, 1938 dst_vma, src_vma); 1939 } 1940 1941 add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR); 1942 mm_inc_nr_ptes(dst_mm); 1943 pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable); 1944 if (!userfaultfd_protected(dst_vma)) 1945 pmd = pmd_swp_clear_uffd(pmd); 1946 set_pmd_at(dst_mm, addr, dst_pmd, pmd); 1947 } 1948 1949 int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm, 1950 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr, 1951 struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma) 1952 { 1953 spinlock_t *dst_ptl, *src_ptl; 1954 struct page *src_page; 1955 struct folio *src_folio; 1956 pmd_t pmd; 1957 pgtable_t pgtable = NULL; 1958 int ret = -ENOMEM; 1959 1960 pmd = pmdp_get_lockless(src_pmd); 1961 if (unlikely(pmd_present(pmd) && pmd_special(pmd) && 1962 !is_huge_zero_pmd(pmd))) { 1963 dst_ptl = pmd_lock(dst_mm, dst_pmd); 1964 src_ptl = pmd_lockptr(src_mm, src_pmd); 1965 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING); 1966 /* 1967 * No need to recheck the pmd, it can't change with write 1968 * mmap lock held here. 1969 * 1970 * Meanwhile, making sure it's not a CoW VMA with writable 1971 * mapping, otherwise it means either the anon page wrongly 1972 * applied special bit, or we made the PRIVATE mapping be 1973 * able to wrongly write to the backend MMIO. 1974 */ 1975 VM_WARN_ON_ONCE(vma_is_cow_mapping(src_vma) && pmd_write(pmd)); 1976 goto set_pmd; 1977 } 1978 1979 /* Skip if can be re-fill on fault */ 1980 if (!vma_is_anonymous(dst_vma)) 1981 return 0; 1982 1983 pgtable = pte_alloc_one(dst_mm); 1984 if (unlikely(!pgtable)) 1985 goto out; 1986 1987 dst_ptl = pmd_lock(dst_mm, dst_pmd); 1988 src_ptl = pmd_lockptr(src_mm, src_pmd); 1989 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING); 1990 1991 ret = -EAGAIN; 1992 pmd = *src_pmd; 1993 1994 if (unlikely(thp_migration_supported() && 1995 pmd_is_valid_softleaf(pmd))) { 1996 copy_huge_non_present_pmd(dst_mm, src_mm, dst_pmd, src_pmd, addr, 1997 dst_vma, src_vma, pmd, pgtable); 1998 ret = 0; 1999 goto out_unlock; 2000 } 2001 2002 if (unlikely(!pmd_trans_huge(pmd))) { 2003 pte_free(dst_mm, pgtable); 2004 goto out_unlock; 2005 } 2006 /* 2007 * When page table lock is held, the huge zero pmd should not be 2008 * under splitting since we don't split the page itself, only pmd to 2009 * a page table. 2010 */ 2011 if (is_huge_zero_pmd(pmd)) { 2012 /* 2013 * mm_get_huge_zero_folio() will never allocate a new 2014 * folio here, since we already have a zero page to 2015 * copy. It just takes a reference. 2016 */ 2017 mm_get_huge_zero_folio(dst_mm); 2018 goto out_zero_page; 2019 } 2020 2021 src_page = pmd_page(pmd); 2022 VM_BUG_ON_PAGE(!PageHead(src_page), src_page); 2023 src_folio = page_folio(src_page); 2024 2025 folio_get(src_folio); 2026 if (unlikely(folio_try_dup_anon_rmap_pmd(src_folio, src_page, dst_vma, src_vma))) { 2027 /* Page maybe pinned: split and retry the fault on PTEs. */ 2028 folio_put(src_folio); 2029 pte_free(dst_mm, pgtable); 2030 spin_unlock(src_ptl); 2031 spin_unlock(dst_ptl); 2032 __split_huge_pmd(src_vma, src_pmd, addr, false); 2033 return -EAGAIN; 2034 } 2035 add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR); 2036 out_zero_page: 2037 mm_inc_nr_ptes(dst_mm); 2038 pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable); 2039 2040 /* See __copy_present_ptes(): restore accessible protection. */ 2041 if (!userfaultfd_protected(dst_vma)) { 2042 if (userfaultfd_rwp(src_vma) && pmd_uffd(pmd)) 2043 pmd = pmd_modify(pmd, dst_vma->vm_page_prot); 2044 pmd = pmd_clear_uffd(pmd); 2045 } 2046 2047 pmdp_set_wrprotect(src_mm, addr, src_pmd); 2048 pmd = pmd_wrprotect(pmd); 2049 set_pmd: 2050 pmd = pmd_mkold(pmd); 2051 set_pmd_at(dst_mm, addr, dst_pmd, pmd); 2052 2053 ret = 0; 2054 out_unlock: 2055 spin_unlock(src_ptl); 2056 spin_unlock(dst_ptl); 2057 out: 2058 return ret; 2059 } 2060 2061 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD 2062 void touch_pud(struct vm_area_struct *vma, unsigned long addr, 2063 pud_t *pud, bool write) 2064 { 2065 pud_t _pud; 2066 2067 _pud = pud_mkyoung(*pud); 2068 if (write) 2069 _pud = pud_mkdirty(_pud); 2070 if (pudp_set_access_flags(vma, addr & HPAGE_PUD_MASK, 2071 pud, _pud, write)) 2072 update_mmu_cache_pud(vma, addr, pud); 2073 } 2074 2075 int copy_huge_pud(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 2076 pud_t *dst_pud, pud_t *src_pud, unsigned long addr) 2077 { 2078 struct mm_struct *dst_mm = dst_vma->vm_mm; 2079 struct mm_struct *src_mm = src_vma->vm_mm; 2080 spinlock_t *dst_ptl, *src_ptl; 2081 struct page *page; 2082 pud_t pud; 2083 int ret; 2084 2085 dst_ptl = pud_lock(dst_mm, dst_pud); 2086 src_ptl = pud_lockptr(src_mm, src_pud); 2087 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING); 2088 2089 ret = -EAGAIN; 2090 pud = *src_pud; 2091 if (unlikely(!pud_trans_huge(pud))) 2092 goto out_unlock; 2093 2094 page = vm_normal_page_pud(src_vma, addr, pud); 2095 if (page) { 2096 struct folio *folio = page_folio(page); 2097 2098 folio_get(folio); 2099 /* 2100 * TODO: once we support anonymous pages, use 2101 * folio_try_dup_anon_rmap_*() and split if duplicating fails. 2102 */ 2103 folio_add_file_rmap_pud(folio, page, dst_vma); 2104 add_mm_counter(dst_mm, mm_counter_file(folio), HPAGE_PUD_NR); 2105 } 2106 2107 if (vma_is_cow_mapping(src_vma) && pud_write(pud)) { 2108 pudp_set_wrprotect(src_mm, addr, src_pud); 2109 pud = pud_wrprotect(pud); 2110 } 2111 pud = pud_mkold(pud); 2112 set_pud_at(dst_mm, addr, dst_pud, pud); 2113 2114 ret = 0; 2115 out_unlock: 2116 spin_unlock(src_ptl); 2117 spin_unlock(dst_ptl); 2118 return ret; 2119 } 2120 2121 void huge_pud_set_accessed(struct vm_fault *vmf, pud_t orig_pud) 2122 { 2123 bool write = vmf->flags & FAULT_FLAG_WRITE; 2124 2125 vmf->ptl = pud_lock(vmf->vma->vm_mm, vmf->pud); 2126 if (unlikely(!pud_same(*vmf->pud, orig_pud))) 2127 goto unlock; 2128 2129 touch_pud(vmf->vma, vmf->address, vmf->pud, write); 2130 unlock: 2131 spin_unlock(vmf->ptl); 2132 } 2133 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */ 2134 2135 bool huge_pmd_set_accessed(struct vm_fault *vmf) 2136 { 2137 bool write = vmf->flags & FAULT_FLAG_WRITE; 2138 2139 if (unlikely(!pmd_same(*vmf->pmd, vmf->orig_pmd))) 2140 return false; 2141 2142 return touch_pmd(vmf->vma, vmf->address, vmf->pmd, write); 2143 } 2144 2145 static vm_fault_t do_huge_zero_wp_pmd(struct vm_fault *vmf) 2146 { 2147 unsigned long haddr = vmf->address & HPAGE_PMD_MASK; 2148 struct vm_area_struct *vma = vmf->vma; 2149 struct mmu_notifier_range range; 2150 struct folio *folio; 2151 vm_fault_t ret = 0; 2152 2153 folio = vma_alloc_anon_folio_pmd(vma, vmf->address); 2154 if (unlikely(!folio)) 2155 return VM_FAULT_FALLBACK; 2156 2157 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm, haddr, 2158 haddr + HPAGE_PMD_SIZE); 2159 mmu_notifier_invalidate_range_start(&range); 2160 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd); 2161 if (unlikely(!pmd_same(pmdp_get(vmf->pmd), vmf->orig_pmd))) 2162 goto release; 2163 ret = check_stable_address_space(vma->vm_mm); 2164 if (ret) 2165 goto release; 2166 (void)pmdp_huge_clear_flush(vma, haddr, vmf->pmd); 2167 map_anon_folio_pmd_pf(folio, vmf->pmd, vma, haddr); 2168 goto unlock; 2169 release: 2170 folio_put(folio); 2171 unlock: 2172 spin_unlock(vmf->ptl); 2173 mmu_notifier_invalidate_range_end(&range); 2174 return ret; 2175 } 2176 2177 vm_fault_t do_huge_pmd_wp_page(struct vm_fault *vmf) 2178 { 2179 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE; 2180 struct vm_area_struct *vma = vmf->vma; 2181 struct folio *folio; 2182 struct page *page; 2183 unsigned long haddr = vmf->address & HPAGE_PMD_MASK; 2184 pmd_t orig_pmd = vmf->orig_pmd; 2185 2186 vmf->ptl = pmd_lockptr(vma->vm_mm, vmf->pmd); 2187 VM_BUG_ON_VMA(!vma_has_anon_rmap(vma), vma); 2188 2189 if (is_huge_zero_pmd(orig_pmd)) { 2190 vm_fault_t ret = do_huge_zero_wp_pmd(vmf); 2191 2192 if (!(ret & VM_FAULT_FALLBACK)) 2193 return ret; 2194 2195 /* Fallback to splitting PMD if THP cannot be allocated */ 2196 goto fallback; 2197 } 2198 2199 spin_lock(vmf->ptl); 2200 2201 if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) { 2202 spin_unlock(vmf->ptl); 2203 return 0; 2204 } 2205 2206 page = pmd_page(orig_pmd); 2207 folio = page_folio(page); 2208 VM_BUG_ON_PAGE(!PageHead(page), page); 2209 2210 /* Early check when only holding the PT lock. */ 2211 if (PageAnonExclusive(page)) 2212 goto reuse; 2213 2214 if (!folio_trylock(folio)) { 2215 folio_get(folio); 2216 spin_unlock(vmf->ptl); 2217 folio_lock(folio); 2218 spin_lock(vmf->ptl); 2219 if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) { 2220 spin_unlock(vmf->ptl); 2221 folio_unlock(folio); 2222 folio_put(folio); 2223 return 0; 2224 } 2225 folio_put(folio); 2226 } 2227 2228 /* Recheck after temporarily dropping the PT lock. */ 2229 if (PageAnonExclusive(page)) { 2230 folio_unlock(folio); 2231 goto reuse; 2232 } 2233 2234 /* 2235 * See do_wp_page(): we can only reuse the folio exclusively if 2236 * there are no additional references. Note that we always drain 2237 * the LRU cache immediately after adding a THP. 2238 */ 2239 if (folio_ref_count(folio) > 2240 1 + folio_test_swapcache(folio) * folio_nr_pages(folio)) 2241 goto unlock_fallback; 2242 if (folio_test_swapcache(folio)) 2243 folio_free_swap(folio); 2244 if (folio_ref_count(folio) == 1) { 2245 pmd_t entry; 2246 2247 folio_move_anon_rmap(folio, vma); 2248 SetPageAnonExclusive(page); 2249 folio_unlock(folio); 2250 reuse: 2251 if (unlikely(unshare)) { 2252 spin_unlock(vmf->ptl); 2253 return 0; 2254 } 2255 entry = pmd_mkyoung(orig_pmd); 2256 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); 2257 if (pmdp_set_access_flags(vma, haddr, vmf->pmd, entry, 1)) 2258 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd); 2259 spin_unlock(vmf->ptl); 2260 return 0; 2261 } 2262 2263 unlock_fallback: 2264 folio_unlock(folio); 2265 spin_unlock(vmf->ptl); 2266 fallback: 2267 __split_huge_pmd(vma, vmf->pmd, vmf->address, false); 2268 return VM_FAULT_FALLBACK; 2269 } 2270 2271 static inline bool can_change_pmd_writable(struct vm_area_struct *vma, 2272 unsigned long addr, pmd_t pmd) 2273 { 2274 struct page *page; 2275 2276 if (WARN_ON_ONCE(!(vma->vm_flags & VM_WRITE))) 2277 return false; 2278 2279 /* Don't touch entries that are not even readable (NUMA hinting). */ 2280 if (pmd_protnone(pmd)) 2281 return false; 2282 2283 /* Do we need write faults for softdirty tracking? */ 2284 if (pmd_needs_soft_dirty_wp(vma, pmd)) 2285 return false; 2286 2287 /* Do we need write faults for uffd-wp tracking? */ 2288 if (userfaultfd_huge_pmd_wp(vma, pmd)) 2289 return false; 2290 2291 if (!(vma->vm_flags & VM_SHARED)) { 2292 /* See can_change_pte_writable(). */ 2293 page = vm_normal_page_pmd(vma, addr, pmd); 2294 return page && PageAnon(page) && PageAnonExclusive(page); 2295 } 2296 2297 /* See can_change_pte_writable(). */ 2298 return pmd_dirty(pmd); 2299 } 2300 2301 vm_fault_t do_huge_pmd_uffd_rwp(struct vm_fault *vmf) 2302 { 2303 struct vm_area_struct *vma = vmf->vma; 2304 pmd_t pmd; 2305 2306 if (!userfaultfd_rwp_async(vma)) 2307 return handle_userfault(vmf, VM_UFFD_RWP); 2308 2309 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd); 2310 if (unlikely(!pmd_same(pmdp_get(vmf->pmd), vmf->orig_pmd))) { 2311 spin_unlock(vmf->ptl); 2312 return 0; 2313 } 2314 pmd = pmd_modify(vmf->orig_pmd, vma->vm_page_prot); 2315 /* pmd_modify() preserves _PAGE_UFFD; drop it on resolution */ 2316 pmd = pmd_clear_uffd(pmd); 2317 pmd = pmd_mkyoung(pmd); 2318 if (!pmd_write(pmd) && 2319 vma_wants_manual_pte_write_upgrade(vma) && 2320 can_change_pmd_writable(vma, vmf->address, pmd)) 2321 pmd = pmd_mkwrite(pmd, vma); 2322 set_pmd_at(vma->vm_mm, vmf->address & HPAGE_PMD_MASK, 2323 vmf->pmd, pmd); 2324 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd); 2325 spin_unlock(vmf->ptl); 2326 return 0; 2327 } 2328 2329 /* NUMA hinting page fault entry point for trans huge pmds */ 2330 vm_fault_t do_huge_pmd_numa_page(struct vm_fault *vmf) 2331 { 2332 struct vm_area_struct *vma = vmf->vma; 2333 struct folio *folio; 2334 unsigned long haddr = vmf->address & HPAGE_PMD_MASK; 2335 int nid = NUMA_NO_NODE; 2336 int target_nid, last_cpupid; 2337 pmd_t pmd, old_pmd; 2338 bool writable = false; 2339 int flags = 0; 2340 2341 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd); 2342 old_pmd = pmdp_get(vmf->pmd); 2343 2344 if (unlikely(!pmd_same(old_pmd, vmf->orig_pmd))) { 2345 spin_unlock(vmf->ptl); 2346 return 0; 2347 } 2348 2349 pmd = pmd_modify(old_pmd, vma->vm_page_prot); 2350 2351 /* 2352 * Detect now whether the PMD could be writable; this information 2353 * is only valid while holding the PT lock. 2354 */ 2355 writable = pmd_write(pmd); 2356 if (!writable && vma_wants_manual_pte_write_upgrade(vma) && 2357 can_change_pmd_writable(vma, vmf->address, pmd)) 2358 writable = true; 2359 2360 folio = vm_normal_folio_pmd(vma, haddr, pmd); 2361 if (!folio) 2362 goto out_map; 2363 2364 nid = folio_nid(folio); 2365 2366 target_nid = numa_migrate_check(folio, vmf, haddr, &flags, writable, 2367 &last_cpupid); 2368 if (target_nid == NUMA_NO_NODE) 2369 goto out_map; 2370 if (migrate_misplaced_folio_prepare(folio, vma, target_nid)) { 2371 flags |= TNF_MIGRATE_FAIL; 2372 goto out_map; 2373 } 2374 /* The folio is isolated and isolation code holds a folio reference. */ 2375 spin_unlock(vmf->ptl); 2376 writable = false; 2377 2378 if (!migrate_misplaced_folio(folio, target_nid)) { 2379 flags |= TNF_MIGRATED; 2380 nid = target_nid; 2381 task_numa_fault(last_cpupid, nid, HPAGE_PMD_NR, flags); 2382 return 0; 2383 } 2384 2385 flags |= TNF_MIGRATE_FAIL; 2386 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd); 2387 if (unlikely(!pmd_same(pmdp_get(vmf->pmd), vmf->orig_pmd))) { 2388 spin_unlock(vmf->ptl); 2389 return 0; 2390 } 2391 out_map: 2392 /* Restore the PMD */ 2393 pmd = pmd_modify(pmdp_get(vmf->pmd), vma->vm_page_prot); 2394 pmd = pmd_mkyoung(pmd); 2395 if (writable) 2396 pmd = pmd_mkwrite(pmd, vma); 2397 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, pmd); 2398 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd); 2399 spin_unlock(vmf->ptl); 2400 2401 if (nid != NUMA_NO_NODE) 2402 task_numa_fault(last_cpupid, nid, HPAGE_PMD_NR, flags); 2403 return 0; 2404 } 2405 2406 /* 2407 * Return true if we do MADV_FREE successfully on entire pmd page. 2408 * Otherwise, return false. 2409 */ 2410 bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, 2411 pmd_t *pmd, unsigned long addr, unsigned long next) 2412 { 2413 spinlock_t *ptl; 2414 pmd_t orig_pmd; 2415 struct folio *folio; 2416 struct mm_struct *mm = tlb->mm; 2417 bool ret = false; 2418 2419 tlb_change_page_size(tlb, HPAGE_PMD_SIZE); 2420 2421 ptl = pmd_trans_huge_lock(pmd, vma); 2422 if (!ptl) 2423 goto out_unlocked; 2424 2425 orig_pmd = *pmd; 2426 if (is_huge_zero_pmd(orig_pmd)) 2427 goto out; 2428 2429 if (unlikely(!pmd_present(orig_pmd))) { 2430 VM_WARN_ON_ONCE(!pmd_is_migration_entry(orig_pmd) && 2431 !pmd_is_device_private_entry(orig_pmd)); 2432 goto out; 2433 } 2434 2435 folio = pmd_folio(orig_pmd); 2436 2437 if (folio_is_zone_device(folio)) 2438 goto out; 2439 2440 /* 2441 * If other processes are mapping this folio, we couldn't discard 2442 * the folio unless they all do MADV_FREE so let's skip the folio. 2443 */ 2444 if (folio_maybe_mapped_shared(folio)) 2445 goto out; 2446 2447 if (!folio_trylock(folio)) 2448 goto out; 2449 2450 /* 2451 * If user want to discard part-pages of THP, split it so MADV_FREE 2452 * will deactivate only them. 2453 */ 2454 if (next - addr != HPAGE_PMD_SIZE) { 2455 folio_get(folio); 2456 spin_unlock(ptl); 2457 split_folio(folio); 2458 folio_unlock(folio); 2459 folio_put(folio); 2460 goto out_unlocked; 2461 } 2462 2463 if (folio_test_dirty(folio)) 2464 folio_clear_dirty(folio); 2465 folio_unlock(folio); 2466 2467 if (pmd_young(orig_pmd) || pmd_dirty(orig_pmd)) { 2468 pmdp_invalidate(vma, addr, pmd); 2469 orig_pmd = pmd_mkold(orig_pmd); 2470 orig_pmd = pmd_mkclean(orig_pmd); 2471 2472 set_pmd_at(mm, addr, pmd, orig_pmd); 2473 tlb_remove_pmd_tlb_entry(tlb, pmd, addr); 2474 } 2475 2476 folio_mark_lazyfree(folio); 2477 ret = true; 2478 out: 2479 spin_unlock(ptl); 2480 out_unlocked: 2481 return ret; 2482 } 2483 2484 static inline void zap_deposited_table(struct mm_struct *mm, pmd_t *pmd) 2485 { 2486 pgtable_t pgtable; 2487 2488 pgtable = pgtable_trans_huge_withdraw(mm, pmd); 2489 pte_free(mm, pgtable); 2490 mm_dec_nr_ptes(mm); 2491 } 2492 2493 static void zap_huge_pmd_folio(struct mm_struct *mm, struct vm_area_struct *vma, 2494 pmd_t pmdval, struct folio *folio, bool is_present) 2495 { 2496 const bool is_device_private = pmd_is_device_private_entry(pmdval); 2497 2498 if (folio_test_anon(folio)) { 2499 add_mm_counter(mm, MM_ANONPAGES, -HPAGE_PMD_NR); 2500 } else { 2501 add_mm_counter(mm, mm_counter_file(folio), 2502 -HPAGE_PMD_NR); 2503 2504 if (is_present && pmd_dirty(pmdval)) 2505 folio_mark_dirty(folio); 2506 if (is_present && pmd_young(pmdval) && 2507 likely(vma_has_recency(vma))) 2508 folio_mark_accessed(folio); 2509 } 2510 2511 /* 2512 * Present and device private folios are rmappable. Remove the 2513 * rmap after transferring young+dirty to the folio. 2514 */ 2515 if (is_present || is_device_private) 2516 folio_remove_rmap_pmd(folio, &folio->page, vma); 2517 2518 /* Device private folios are pinned. */ 2519 if (is_device_private) 2520 folio_put(folio); 2521 } 2522 2523 static struct folio *normal_or_softleaf_folio_pmd(struct vm_area_struct *vma, 2524 unsigned long addr, pmd_t pmdval, bool is_present) 2525 { 2526 if (is_present) 2527 return vm_normal_folio_pmd(vma, addr, pmdval); 2528 2529 if (!thp_migration_supported()) 2530 WARN_ONCE(1, "Non present huge pmd without pmd migration enabled!"); 2531 return pmd_to_softleaf_folio(pmdval); 2532 } 2533 2534 static bool vma_has_deposited_pgtable(struct vm_area_struct *vma) 2535 { 2536 /* 2537 * PMDs in anonymous VMAs always have a deposited page table. PMDs in 2538 * other VMAs only have one when required by the architecture. 2539 */ 2540 return arch_needs_pgtable_deposit() || vma_is_anonymous(vma); 2541 } 2542 2543 /** 2544 * zap_huge_pmd - Zap a huge THP which is of PMD size. 2545 * @tlb: The MMU gather TLB state associated with the operation. 2546 * @vma: The VMA containing the range to zap. 2547 * @pmd: A pointer to the leaf PMD entry. 2548 * @addr: The virtual address for the range to zap. 2549 * 2550 * Returns: %true on success, %false otherwise. 2551 */ 2552 bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, 2553 pmd_t *pmd, unsigned long addr) 2554 { 2555 struct mm_struct *mm = tlb->mm; 2556 struct folio *folio = NULL; 2557 bool is_present = false; 2558 bool has_deposit; 2559 spinlock_t *ptl; 2560 pmd_t orig_pmd; 2561 2562 tlb_change_page_size(tlb, HPAGE_PMD_SIZE); 2563 2564 ptl = __pmd_trans_huge_lock(pmd, vma); 2565 if (!ptl) 2566 return false; 2567 /* 2568 * For architectures like ppc64 we look at deposited pgtable 2569 * when calling pmdp_huge_get_and_clear. So do the 2570 * pgtable_trans_huge_withdraw after finishing pmdp related 2571 * operations. 2572 */ 2573 orig_pmd = pmdp_huge_get_and_clear_full(vma, addr, pmd, 2574 tlb->fullmm); 2575 arch_check_zapped_pmd(vma, orig_pmd); 2576 tlb_remove_pmd_tlb_entry(tlb, pmd, addr); 2577 2578 is_present = pmd_present(orig_pmd); 2579 folio = normal_or_softleaf_folio_pmd(vma, addr, orig_pmd, is_present); 2580 has_deposit = vma_has_deposited_pgtable(vma); 2581 if (folio) 2582 zap_huge_pmd_folio(mm, vma, orig_pmd, folio, is_present); 2583 if (has_deposit) 2584 zap_deposited_table(mm, pmd); 2585 2586 spin_unlock(ptl); 2587 if (is_present && folio) 2588 tlb_remove_page_size(tlb, &folio->page, HPAGE_PMD_SIZE); 2589 return true; 2590 } 2591 2592 #ifndef pmd_move_must_withdraw 2593 static inline int pmd_move_must_withdraw(spinlock_t *new_pmd_ptl, 2594 spinlock_t *old_pmd_ptl, 2595 struct vm_area_struct *vma) 2596 { 2597 /* 2598 * With split pmd lock we also need to move preallocated 2599 * PTE page table if new_pmd is on different PMD page table. 2600 * 2601 * We also don't deposit and withdraw tables for file pages. 2602 */ 2603 return (new_pmd_ptl != old_pmd_ptl) && vma_is_anonymous(vma); 2604 } 2605 #endif 2606 2607 static pmd_t move_soft_dirty_pmd(pmd_t pmd) 2608 { 2609 if (pgtable_supports_soft_dirty()) { 2610 if (unlikely(pmd_is_migration_entry(pmd))) 2611 pmd = pmd_swp_mksoft_dirty(pmd); 2612 else if (pmd_present(pmd)) 2613 pmd = pmd_mksoft_dirty(pmd); 2614 } 2615 2616 return pmd; 2617 } 2618 2619 static pmd_t clear_uffd_wp_pmd(pmd_t pmd) 2620 { 2621 if (pmd_none(pmd)) 2622 return pmd; 2623 if (pmd_present(pmd)) 2624 pmd = pmd_clear_uffd(pmd); 2625 else 2626 pmd = pmd_swp_clear_uffd(pmd); 2627 2628 return pmd; 2629 } 2630 2631 bool move_huge_pmd(struct vm_area_struct *vma, unsigned long old_addr, 2632 unsigned long new_addr, pmd_t *old_pmd, pmd_t *new_pmd) 2633 { 2634 spinlock_t *old_ptl, *new_ptl; 2635 pmd_t pmd; 2636 struct mm_struct *mm = vma->vm_mm; 2637 bool force_flush = false; 2638 2639 /* 2640 * The destination pmd shouldn't be established, free_pgtables() 2641 * should have released it; but move_page_tables() might have already 2642 * inserted a page table, if racing against shmem/file collapse. 2643 */ 2644 if (!pmd_none(*new_pmd)) { 2645 VM_BUG_ON(pmd_trans_huge(*new_pmd)); 2646 return false; 2647 } 2648 2649 old_ptl = pmd_lockptr(mm, old_pmd); 2650 new_ptl = pmd_lockptr(mm, new_pmd); 2651 2652 double_pt_lock(old_ptl, new_ptl); 2653 if (likely(pmd_is_huge(*old_pmd))) { 2654 pmd = pmdp_huge_get_and_clear(mm, old_addr, old_pmd); 2655 if (pmd_present(pmd)) 2656 force_flush = true; 2657 VM_BUG_ON(!pmd_none(*new_pmd)); 2658 2659 if (pmd_move_must_withdraw(new_ptl, old_ptl, vma)) { 2660 pgtable_t pgtable; 2661 2662 pgtable = pgtable_trans_huge_withdraw(mm, old_pmd); 2663 pgtable_trans_huge_deposit(mm, new_pmd, pgtable); 2664 } 2665 pmd = move_soft_dirty_pmd(pmd); 2666 if (vma_has_uffd_without_event_remap(vma)) { 2667 /* 2668 * See __copy_present_ptes(): normalise the RWP marker 2669 * so the destination starts accessible instead of 2670 * taking a numa-hinting fault on first access. Only the 2671 * marker (protnone + uffd) needs it; leave other present 2672 * PMDs in the VMA untouched. 2673 */ 2674 if (pmd_present(pmd) && userfaultfd_rwp(vma) && 2675 pmd_uffd(pmd)) 2676 pmd = pmd_modify(pmd, vma->vm_page_prot); 2677 pmd = clear_uffd_wp_pmd(pmd); 2678 } 2679 set_pmd_at(mm, new_addr, new_pmd, pmd); 2680 if (force_flush) 2681 flush_pmd_tlb_range(vma, old_addr, old_addr + PMD_SIZE); 2682 double_pt_unlock(old_ptl, new_ptl); 2683 return true; 2684 } 2685 double_pt_unlock(old_ptl, new_ptl); 2686 return false; 2687 } 2688 2689 static void change_non_present_huge_pmd(struct mm_struct *mm, 2690 unsigned long addr, pmd_t *pmd, bool uffd_prot, 2691 bool uffd_prot_resolve) 2692 { 2693 softleaf_t entry = softleaf_from_pmd(*pmd); 2694 pmd_t newpmd; 2695 2696 VM_WARN_ON(!pmd_is_valid_softleaf(*pmd)); 2697 if (softleaf_is_migration_write(entry)) { 2698 const struct folio *folio = softleaf_to_folio(entry); 2699 2700 /* 2701 * A protection check is difficult so 2702 * just be safe and disable write 2703 */ 2704 if (folio_test_anon(folio)) 2705 entry = make_readable_exclusive_migration_entry(swp_offset(entry)); 2706 else 2707 entry = make_readable_migration_entry(swp_offset(entry)); 2708 newpmd = softleaf_to_pmd(entry); 2709 if (pmd_swp_soft_dirty(*pmd)) 2710 newpmd = pmd_swp_mksoft_dirty(newpmd); 2711 } else if (softleaf_is_device_private_write(entry)) { 2712 entry = make_readable_device_private_entry(swp_offset(entry)); 2713 newpmd = softleaf_to_pmd(entry); 2714 if (pmd_swp_uffd(*pmd)) 2715 newpmd = pmd_swp_mkuffd(newpmd); 2716 } else { 2717 newpmd = *pmd; 2718 } 2719 2720 if (uffd_prot) 2721 newpmd = pmd_swp_mkuffd(newpmd); 2722 else if (uffd_prot_resolve) 2723 newpmd = pmd_swp_clear_uffd(newpmd); 2724 if (!pmd_same(*pmd, newpmd)) 2725 set_pmd_at(mm, addr, pmd, newpmd); 2726 } 2727 2728 /* 2729 * Returns 2730 * - 0 if PMD could not be locked 2731 * - 1 if PMD was locked but protections unchanged and TLB flush unnecessary 2732 * or if prot_numa but THP migration is not supported 2733 * - HPAGE_PMD_NR if protections changed and TLB flush necessary 2734 */ 2735 int change_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, 2736 pmd_t *pmd, unsigned long addr, pgprot_t newprot, 2737 unsigned long cp_flags) 2738 { 2739 struct mm_struct *mm = vma->vm_mm; 2740 spinlock_t *ptl; 2741 pmd_t oldpmd, entry; 2742 bool prot_numa = cp_flags & MM_CP_PROT_NUMA; 2743 bool uffd_prot = cp_flags & (MM_CP_UFFD_WP | MM_CP_UFFD_RWP); 2744 bool uffd_prot_resolve = cp_flags & 2745 (MM_CP_UFFD_WP_RESOLVE | MM_CP_UFFD_RWP_RESOLVE); 2746 int ret = 1; 2747 2748 tlb_change_page_size(tlb, HPAGE_PMD_SIZE); 2749 2750 if (prot_numa && !thp_migration_supported()) 2751 return 1; 2752 2753 ptl = __pmd_trans_huge_lock(pmd, vma); 2754 if (!ptl) 2755 return 0; 2756 2757 if (thp_migration_supported() && pmd_is_valid_softleaf(*pmd)) { 2758 change_non_present_huge_pmd(mm, addr, pmd, uffd_prot, 2759 uffd_prot_resolve); 2760 goto unlock; 2761 } 2762 2763 /* Already in the desired state */ 2764 if (prot_numa && pmd_protnone(*pmd)) 2765 goto unlock; 2766 if ((cp_flags & MM_CP_UFFD_RWP) && pmd_protnone(*pmd) && pmd_uffd(*pmd)) 2767 goto unlock; 2768 2769 if (prot_numa) { 2770 2771 /* 2772 * Avoid trapping faults against the zero page. The read-only 2773 * data is likely to be read-cached on the local CPU and 2774 * local/remote hits to the zero page are not interesting. 2775 */ 2776 if (is_huge_zero_pmd(*pmd)) 2777 goto unlock; 2778 2779 if (!folio_can_map_prot_numa(pmd_folio(*pmd), vma, 2780 vma_is_single_threaded_private(vma))) 2781 goto unlock; 2782 } 2783 /* 2784 * In case prot_numa, we are under mmap_read_lock(mm). It's critical 2785 * to not clear pmd intermittently to avoid race with MADV_DONTNEED 2786 * which is also under mmap_read_lock(mm): 2787 * 2788 * CPU0: CPU1: 2789 * change_huge_pmd(prot_numa=1) 2790 * pmdp_huge_get_and_clear_notify() 2791 * madvise_dontneed() 2792 * zap_pmd_range() 2793 * pmd_trans_huge(*pmd) == 0 (without ptl) 2794 * // skip the pmd 2795 * set_pmd_at(); 2796 * // pmd is re-established 2797 * 2798 * The race makes MADV_DONTNEED miss the huge pmd and don't clear it 2799 * which may break userspace. 2800 * 2801 * pmdp_invalidate_ad() is required to make sure we don't miss 2802 * dirty/young flags set by hardware. 2803 */ 2804 oldpmd = pmdp_invalidate_ad(vma, addr, pmd); 2805 2806 entry = pmd_modify(oldpmd, newprot); 2807 if (uffd_prot) 2808 entry = pmd_mkuffd(entry); 2809 else if (uffd_prot_resolve) 2810 /* 2811 * Leave the write bit to be handled by PF interrupt 2812 * handler, then things like COW could be properly 2813 * handled. 2814 */ 2815 entry = pmd_clear_uffd(entry); 2816 2817 /* See change_pte_range(): preserve RWP protection across mprotect() */ 2818 if (userfaultfd_rwp(vma) && pmd_uffd(entry)) 2819 entry = pmd_modify(entry, PAGE_NONE); 2820 2821 /* See change_pte_range(). */ 2822 if ((cp_flags & MM_CP_TRY_CHANGE_WRITABLE) && !pmd_write(entry) && 2823 can_change_pmd_writable(vma, addr, entry)) 2824 entry = pmd_mkwrite(entry, vma); 2825 2826 ret = HPAGE_PMD_NR; 2827 set_pmd_at(mm, addr, pmd, entry); 2828 2829 if (huge_pmd_needs_flush(oldpmd, entry)) 2830 tlb_flush_pmd_range(tlb, addr, HPAGE_PMD_SIZE); 2831 unlock: 2832 spin_unlock(ptl); 2833 return ret; 2834 } 2835 2836 /* 2837 * Returns: 2838 * 2839 * - 0: if pud leaf changed from under us 2840 * - 1: if pud can be skipped 2841 * - HPAGE_PUD_NR: if pud was successfully processed 2842 */ 2843 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD 2844 int change_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma, 2845 pud_t *pudp, unsigned long addr, pgprot_t newprot, 2846 unsigned long cp_flags) 2847 { 2848 struct mm_struct *mm = vma->vm_mm; 2849 pud_t oldpud, entry; 2850 spinlock_t *ptl; 2851 2852 tlb_change_page_size(tlb, HPAGE_PUD_SIZE); 2853 2854 /* NUMA balancing doesn't apply to dax */ 2855 if (cp_flags & MM_CP_PROT_NUMA) 2856 return 1; 2857 2858 /* 2859 * Huge entries on userfault-wp or userfault-rwp only work with 2860 * anonymous, while we don't have anonymous PUDs yet. 2861 */ 2862 if (WARN_ON_ONCE(cp_flags & (MM_CP_UFFD_WP_ALL | MM_CP_UFFD_RWP_ALL))) 2863 return 1; 2864 2865 ptl = __pud_trans_huge_lock(pudp, vma); 2866 if (!ptl) 2867 return 0; 2868 2869 /* 2870 * Can't clear PUD or it can race with concurrent zapping. See 2871 * change_huge_pmd(). 2872 */ 2873 oldpud = pudp_invalidate(vma, addr, pudp); 2874 entry = pud_modify(oldpud, newprot); 2875 set_pud_at(mm, addr, pudp, entry); 2876 tlb_flush_pud_range(tlb, addr, HPAGE_PUD_SIZE); 2877 2878 spin_unlock(ptl); 2879 return HPAGE_PUD_NR; 2880 } 2881 #endif 2882 2883 #ifdef CONFIG_USERFAULTFD 2884 /* 2885 * The PT lock for src_pmd and dst_vma/src_vma (for reading) are locked by 2886 * the caller, but it must return after releasing the page_table_lock. 2887 * Just move the page from src_pmd to dst_pmd if possible. 2888 * Return zero if succeeded in moving the page, -EAGAIN if it needs to be 2889 * repeated by the caller, or other errors in case of failure. 2890 */ 2891 int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pmd_t dst_pmdval, 2892 struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 2893 unsigned long dst_addr, unsigned long src_addr) 2894 { 2895 pmd_t _dst_pmd, src_pmdval; 2896 struct page *src_page; 2897 struct folio *src_folio; 2898 spinlock_t *src_ptl, *dst_ptl; 2899 pgtable_t src_pgtable; 2900 struct mmu_notifier_range range; 2901 int err = 0; 2902 2903 src_pmdval = *src_pmd; 2904 src_ptl = pmd_lockptr(mm, src_pmd); 2905 2906 lockdep_assert_held(src_ptl); 2907 vma_assert_locked(src_vma); 2908 vma_assert_locked(dst_vma); 2909 2910 /* Sanity checks before the operation */ 2911 if (WARN_ON_ONCE(!pmd_none(dst_pmdval)) || WARN_ON_ONCE(src_addr & ~HPAGE_PMD_MASK) || 2912 WARN_ON_ONCE(dst_addr & ~HPAGE_PMD_MASK)) { 2913 spin_unlock(src_ptl); 2914 return -EINVAL; 2915 } 2916 2917 if (!pmd_trans_huge(src_pmdval)) { 2918 spin_unlock(src_ptl); 2919 if (pmd_is_migration_entry(src_pmdval)) { 2920 pmd_migration_entry_wait(mm, src_pmd); 2921 return -EAGAIN; 2922 } 2923 return -ENOENT; 2924 } 2925 2926 src_page = pmd_page(src_pmdval); 2927 2928 if (!is_huge_zero_pmd(src_pmdval)) { 2929 if (unlikely(!PageAnonExclusive(src_page))) { 2930 spin_unlock(src_ptl); 2931 return -EBUSY; 2932 } 2933 2934 src_folio = page_folio(src_page); 2935 folio_get(src_folio); 2936 } else 2937 src_folio = NULL; 2938 2939 spin_unlock(src_ptl); 2940 2941 flush_cache_range(src_vma, src_addr, src_addr + HPAGE_PMD_SIZE); 2942 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, src_addr, 2943 src_addr + HPAGE_PMD_SIZE); 2944 mmu_notifier_invalidate_range_start(&range); 2945 2946 if (src_folio) 2947 folio_lock(src_folio); 2948 2949 dst_ptl = pmd_lockptr(mm, dst_pmd); 2950 double_pt_lock(src_ptl, dst_ptl); 2951 if (unlikely(!pmd_same(*src_pmd, src_pmdval) || 2952 !pmd_same(*dst_pmd, dst_pmdval))) { 2953 err = -EAGAIN; 2954 goto unlock_ptls; 2955 } 2956 if (src_folio) { 2957 if (folio_maybe_dma_pinned(src_folio) || 2958 !PageAnonExclusive(&src_folio->page)) { 2959 err = -EBUSY; 2960 goto unlock_ptls; 2961 } 2962 2963 if (WARN_ON_ONCE(!folio_test_head(src_folio)) || 2964 WARN_ON_ONCE(!folio_test_anon(src_folio))) { 2965 err = -EBUSY; 2966 goto unlock_ptls; 2967 } 2968 2969 src_pmdval = pmdp_huge_clear_flush(src_vma, src_addr, src_pmd); 2970 /* Folio got pinned from under us. Put it back and fail the move. */ 2971 if (folio_maybe_dma_pinned(src_folio)) { 2972 set_pmd_at(mm, src_addr, src_pmd, src_pmdval); 2973 err = -EBUSY; 2974 goto unlock_ptls; 2975 } 2976 2977 folio_move_anon_rmap(src_folio, dst_vma); 2978 src_folio->index = linear_anon_page_index(dst_vma, dst_addr); 2979 2980 _dst_pmd = folio_mk_pmd(src_folio, dst_vma->vm_page_prot); 2981 /* Follow mremap() behavior and treat the entry dirty after the move */ 2982 _dst_pmd = pmd_mkwrite(pmd_mkdirty(_dst_pmd), dst_vma); 2983 } else { 2984 src_pmdval = pmdp_huge_clear_flush(src_vma, src_addr, src_pmd); 2985 _dst_pmd = move_soft_dirty_pmd(src_pmdval); 2986 _dst_pmd = clear_uffd_wp_pmd(_dst_pmd); 2987 } 2988 2989 /* Re-arm RWP on the moved PMD if dst_vma is RWP-registered. */ 2990 if (userfaultfd_rwp(dst_vma)) { 2991 _dst_pmd = pmd_modify(_dst_pmd, PAGE_NONE); 2992 _dst_pmd = pmd_mkuffd(_dst_pmd); 2993 } 2994 2995 set_pmd_at(mm, dst_addr, dst_pmd, _dst_pmd); 2996 2997 src_pgtable = pgtable_trans_huge_withdraw(mm, src_pmd); 2998 pgtable_trans_huge_deposit(mm, dst_pmd, src_pgtable); 2999 unlock_ptls: 3000 double_pt_unlock(src_ptl, dst_ptl); 3001 /* unblock rmap walks */ 3002 if (src_folio) 3003 folio_unlock(src_folio); 3004 mmu_notifier_invalidate_range_end(&range); 3005 if (src_folio) 3006 folio_put(src_folio); 3007 return err; 3008 } 3009 #endif /* CONFIG_USERFAULTFD */ 3010 3011 /* 3012 * Returns page table lock pointer if a given pmd maps a thp, NULL otherwise. 3013 * 3014 * Note that if it returns page table lock pointer, this routine returns without 3015 * unlocking page table lock. So callers must unlock it. 3016 */ 3017 spinlock_t *__pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma) 3018 { 3019 spinlock_t *ptl; 3020 3021 ptl = pmd_lock(vma->vm_mm, pmd); 3022 if (likely(pmd_is_huge(*pmd))) 3023 return ptl; 3024 spin_unlock(ptl); 3025 return NULL; 3026 } 3027 3028 /* 3029 * Returns page table lock pointer if a given pud maps a thp, NULL otherwise. 3030 * 3031 * Note that if it returns page table lock pointer, this routine returns without 3032 * unlocking page table lock. So callers must unlock it. 3033 */ 3034 spinlock_t *__pud_trans_huge_lock(pud_t *pud, struct vm_area_struct *vma) 3035 { 3036 spinlock_t *ptl; 3037 3038 ptl = pud_lock(vma->vm_mm, pud); 3039 if (likely(pud_trans_huge(*pud))) 3040 return ptl; 3041 spin_unlock(ptl); 3042 return NULL; 3043 } 3044 3045 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD 3046 int zap_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma, 3047 pud_t *pud, unsigned long addr) 3048 { 3049 spinlock_t *ptl; 3050 pud_t orig_pud; 3051 3052 tlb_change_page_size(tlb, HPAGE_PUD_SIZE); 3053 3054 ptl = __pud_trans_huge_lock(pud, vma); 3055 if (!ptl) 3056 return 0; 3057 3058 orig_pud = pudp_huge_get_and_clear_full(vma, addr, pud, tlb->fullmm); 3059 arch_check_zapped_pud(vma, orig_pud); 3060 tlb_remove_pud_tlb_entry(tlb, pud, addr); 3061 if (!vma_is_mm_managed(vma)) { 3062 spin_unlock(ptl); 3063 /* No zero page support yet */ 3064 } else { 3065 struct page *page = NULL; 3066 struct folio *folio; 3067 3068 /* No support for anonymous PUD pages or migration yet */ 3069 VM_WARN_ON_ONCE(vma_is_anonymous(vma) || 3070 !pud_present(orig_pud)); 3071 3072 page = pud_page(orig_pud); 3073 folio = page_folio(page); 3074 folio_remove_rmap_pud(folio, page, vma); 3075 add_mm_counter(tlb->mm, mm_counter_file(folio), -HPAGE_PUD_NR); 3076 3077 spin_unlock(ptl); 3078 tlb_remove_page_size(tlb, page, HPAGE_PUD_SIZE); 3079 } 3080 return 1; 3081 } 3082 3083 static void __split_huge_pud_locked(struct vm_area_struct *vma, pud_t *pud, 3084 unsigned long haddr) 3085 { 3086 struct folio *folio; 3087 struct page *page; 3088 pud_t old_pud; 3089 3090 VM_BUG_ON(haddr & ~HPAGE_PUD_MASK); 3091 VM_BUG_ON_VMA(vma->vm_start > haddr, vma); 3092 VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PUD_SIZE, vma); 3093 VM_BUG_ON(!pud_trans_huge(*pud)); 3094 3095 count_vm_event(THP_SPLIT_PUD); 3096 3097 old_pud = pudp_huge_clear_flush(vma, haddr, pud); 3098 3099 if (!vma_is_dax(vma)) 3100 return; 3101 3102 page = pud_page(old_pud); 3103 folio = page_folio(page); 3104 3105 if (!folio_test_dirty(folio) && pud_dirty(old_pud)) 3106 folio_mark_dirty(folio); 3107 if (!folio_test_referenced(folio) && pud_young(old_pud)) 3108 folio_set_referenced(folio); 3109 folio_remove_rmap_pud(folio, page, vma); 3110 add_mm_counter(vma->vm_mm, mm_counter_file(folio), 3111 -HPAGE_PUD_NR); 3112 folio_put(folio); 3113 } 3114 3115 void __split_huge_pud(struct vm_area_struct *vma, pud_t *pud, 3116 unsigned long address) 3117 { 3118 spinlock_t *ptl; 3119 struct mmu_notifier_range range; 3120 3121 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm, 3122 address & HPAGE_PUD_MASK, 3123 (address & HPAGE_PUD_MASK) + HPAGE_PUD_SIZE); 3124 mmu_notifier_invalidate_range_start(&range); 3125 ptl = pud_lock(vma->vm_mm, pud); 3126 if (unlikely(!pud_trans_huge(*pud))) 3127 goto out; 3128 __split_huge_pud_locked(vma, pud, range.start); 3129 3130 out: 3131 spin_unlock(ptl); 3132 mmu_notifier_invalidate_range_end(&range); 3133 } 3134 #else 3135 void __split_huge_pud(struct vm_area_struct *vma, pud_t *pud, 3136 unsigned long address) 3137 { 3138 } 3139 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */ 3140 3141 static void __split_huge_zero_page_pmd(struct vm_area_struct *vma, 3142 unsigned long haddr, pmd_t *pmd) 3143 { 3144 struct mm_struct *mm = vma->vm_mm; 3145 pgtable_t pgtable; 3146 pmd_t _pmd, old_pmd; 3147 unsigned long addr; 3148 pte_t *pte; 3149 int i; 3150 3151 /* 3152 * Leave pmd empty until pte is filled note that it is fine to delay 3153 * notification until mmu_notifier_invalidate_range_end() as we are 3154 * replacing a zero pmd write protected page with a zero pte write 3155 * protected page. 3156 * 3157 * See Documentation/mm/mmu_notifier.rst 3158 */ 3159 old_pmd = pmdp_huge_clear_flush(vma, haddr, pmd); 3160 3161 pgtable = pgtable_trans_huge_withdraw(mm, pmd); 3162 pmd_populate(mm, &_pmd, pgtable); 3163 3164 pte = pte_offset_map(&_pmd, haddr); 3165 VM_BUG_ON(!pte); 3166 for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) { 3167 pte_t entry; 3168 3169 entry = pfn_pte(zero_pfn(addr), vma->vm_page_prot); 3170 entry = pte_mkspecial(entry); 3171 if (pmd_uffd(old_pmd)) 3172 entry = pte_mkuffd(entry); 3173 3174 /* Restore PAGE_NONE so an RWP marker keeps trapping */ 3175 if (userfaultfd_rwp(vma) && pmd_uffd(old_pmd)) 3176 entry = pte_modify(entry, PAGE_NONE); 3177 3178 VM_BUG_ON(!pte_none(ptep_get(pte))); 3179 set_pte_at(mm, addr, pte, entry); 3180 pte++; 3181 } 3182 pte_unmap(pte - 1); 3183 smp_wmb(); /* make pte visible before pmd */ 3184 pmd_populate(mm, pmd, pgtable); 3185 } 3186 3187 static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd, 3188 unsigned long haddr, bool freeze) 3189 { 3190 struct mm_struct *mm = vma->vm_mm; 3191 struct folio *folio; 3192 struct page *page; 3193 pgtable_t pgtable; 3194 pmd_t old_pmd, _pmd; 3195 bool soft_dirty, uffd_wp = false, young = false, write = false; 3196 bool anon_exclusive = false, dirty = false; 3197 unsigned long addr; 3198 pte_t *pte; 3199 int i; 3200 3201 VM_BUG_ON(haddr & ~HPAGE_PMD_MASK); 3202 VM_BUG_ON_VMA(vma->vm_start > haddr, vma); 3203 VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PMD_SIZE, vma); 3204 3205 VM_WARN_ON_ONCE(!pmd_is_valid_softleaf(*pmd) && !pmd_trans_huge(*pmd)); 3206 3207 count_vm_event(THP_SPLIT_PMD); 3208 3209 if (!vma_is_anonymous(vma)) { 3210 old_pmd = pmdp_huge_clear_flush(vma, haddr, pmd); 3211 /* 3212 * We are going to unmap this huge page. So 3213 * just go ahead and zap it 3214 */ 3215 if (arch_needs_pgtable_deposit()) 3216 zap_deposited_table(mm, pmd); 3217 if (!vma_is_mm_managed(vma)) 3218 return; 3219 if (unlikely(pmd_is_migration_entry(old_pmd))) { 3220 const softleaf_t old_entry = softleaf_from_pmd(old_pmd); 3221 3222 folio = softleaf_to_folio(old_entry); 3223 } else if (is_huge_zero_pmd(old_pmd)) { 3224 return; 3225 } else { 3226 page = pmd_page(old_pmd); 3227 folio = page_folio(page); 3228 if (!folio_test_dirty(folio) && pmd_dirty(old_pmd)) 3229 folio_mark_dirty(folio); 3230 if (!folio_test_referenced(folio) && pmd_young(old_pmd)) 3231 folio_set_referenced(folio); 3232 folio_remove_rmap_pmd(folio, page, vma); 3233 add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR); 3234 folio_put(folio); 3235 return; 3236 } 3237 add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR); 3238 return; 3239 } 3240 3241 if (is_huge_zero_pmd(*pmd)) { 3242 /* 3243 * FIXME: Do we want to invalidate secondary mmu by calling 3244 * mmu_notifier_arch_invalidate_secondary_tlbs() see comments below 3245 * inside __split_huge_pmd() ? 3246 * 3247 * We are going from a zero huge page write protected to zero 3248 * small page also write protected so it does not seems useful 3249 * to invalidate secondary mmu at this time. 3250 */ 3251 return __split_huge_zero_page_pmd(vma, haddr, pmd); 3252 } 3253 3254 if (pmd_is_migration_entry(*pmd)) { 3255 softleaf_t entry; 3256 3257 old_pmd = *pmd; 3258 entry = softleaf_from_pmd(old_pmd); 3259 page = softleaf_to_page(entry); 3260 folio = page_folio(page); 3261 3262 soft_dirty = pmd_swp_soft_dirty(old_pmd); 3263 uffd_wp = pmd_swp_uffd(old_pmd); 3264 3265 write = softleaf_is_migration_write(entry); 3266 if (PageAnon(page)) 3267 anon_exclusive = softleaf_is_migration_read_exclusive(entry); 3268 young = softleaf_is_migration_young(entry); 3269 dirty = softleaf_is_migration_dirty(entry); 3270 } else if (pmd_is_device_private_entry(*pmd)) { 3271 softleaf_t entry; 3272 3273 old_pmd = *pmd; 3274 entry = softleaf_from_pmd(old_pmd); 3275 page = softleaf_to_page(entry); 3276 folio = page_folio(page); 3277 3278 soft_dirty = pmd_swp_soft_dirty(old_pmd); 3279 uffd_wp = pmd_swp_uffd(old_pmd); 3280 3281 write = softleaf_is_device_private_write(entry); 3282 anon_exclusive = PageAnonExclusive(page); 3283 3284 /* 3285 * Device private THP should be treated the same as regular 3286 * folios w.r.t anon exclusive handling. See the comments for 3287 * folio handling and anon_exclusive below. 3288 */ 3289 if (freeze && anon_exclusive && 3290 folio_try_share_anon_rmap_pmd(folio, page)) 3291 freeze = false; 3292 if (!freeze) { 3293 rmap_t rmap_flags = RMAP_NONE; 3294 3295 folio_ref_add(folio, HPAGE_PMD_NR - 1); 3296 if (anon_exclusive) 3297 rmap_flags |= RMAP_EXCLUSIVE; 3298 3299 folio_add_anon_rmap_ptes(folio, page, HPAGE_PMD_NR, 3300 vma, haddr, rmap_flags); 3301 } 3302 } else { 3303 /* 3304 * Up to this point the pmd is present and huge and userland has 3305 * the whole access to the hugepage during the split (which 3306 * happens in place). If we overwrite the pmd with the not-huge 3307 * version pointing to the pte here (which of course we could if 3308 * all CPUs were bug free), userland could trigger a small page 3309 * size TLB miss on the small sized TLB while the hugepage TLB 3310 * entry is still established in the huge TLB. Some CPU doesn't 3311 * like that. See 3312 * http://support.amd.com/TechDocs/41322_10h_Rev_Gd.pdf, Erratum 3313 * 383 on page 105. Intel should be safe but is also warns that 3314 * it's only safe if the permission and cache attributes of the 3315 * two entries loaded in the two TLB is identical (which should 3316 * be the case here). But it is generally safer to never allow 3317 * small and huge TLB entries for the same virtual address to be 3318 * loaded simultaneously. So instead of doing "pmd_populate(); 3319 * flush_pmd_tlb_range();" we first mark the current pmd 3320 * notpresent (atomically because here the pmd_trans_huge must 3321 * remain set at all times on the pmd until the split is 3322 * complete for this pmd), then we flush the SMP TLB and finally 3323 * we write the non-huge version of the pmd entry with 3324 * pmd_populate. 3325 */ 3326 old_pmd = pmdp_invalidate(vma, haddr, pmd); 3327 page = pmd_page(old_pmd); 3328 folio = page_folio(page); 3329 if (pmd_dirty(old_pmd)) { 3330 dirty = true; 3331 folio_set_dirty(folio); 3332 } 3333 write = pmd_write(old_pmd); 3334 young = pmd_young(old_pmd); 3335 soft_dirty = pmd_soft_dirty(old_pmd); 3336 uffd_wp = pmd_uffd(old_pmd); 3337 3338 VM_WARN_ON_FOLIO(!folio_ref_count(folio), folio); 3339 VM_WARN_ON_FOLIO(!folio_test_anon(folio), folio); 3340 3341 /* 3342 * Without "freeze", we'll simply split the PMD, propagating the 3343 * PageAnonExclusive() flag for each PTE by setting it for 3344 * each subpage -- no need to (temporarily) clear. 3345 * 3346 * With "freeze" we want to replace mapped pages by 3347 * migration entries right away. This is only possible if we 3348 * managed to clear PageAnonExclusive() -- see 3349 * set_pmd_migration_entry(). 3350 * 3351 * In case we cannot clear PageAnonExclusive(), split the PMD 3352 * only and let try_to_migrate_one() fail later. 3353 * 3354 * See folio_try_share_anon_rmap_pmd(): invalidate PMD first. 3355 */ 3356 anon_exclusive = PageAnonExclusive(page); 3357 if (freeze && anon_exclusive && 3358 folio_try_share_anon_rmap_pmd(folio, page)) 3359 freeze = false; 3360 if (!freeze) { 3361 rmap_t rmap_flags = RMAP_NONE; 3362 3363 folio_ref_add(folio, HPAGE_PMD_NR - 1); 3364 if (anon_exclusive) 3365 rmap_flags |= RMAP_EXCLUSIVE; 3366 folio_add_anon_rmap_ptes(folio, page, HPAGE_PMD_NR, 3367 vma, haddr, rmap_flags); 3368 } 3369 } 3370 3371 /* 3372 * Withdraw the table only after we mark the pmd entry invalid. 3373 * This's critical for some architectures (Power). 3374 */ 3375 pgtable = pgtable_trans_huge_withdraw(mm, pmd); 3376 pmd_populate(mm, &_pmd, pgtable); 3377 3378 pte = pte_offset_map(&_pmd, haddr); 3379 VM_BUG_ON(!pte); 3380 3381 /* 3382 * Note that NUMA hinting access restrictions are not transferred to 3383 * avoid any possibility of altering permissions across VMAs. 3384 */ 3385 if (freeze || pmd_is_migration_entry(old_pmd)) { 3386 pte_t entry; 3387 swp_entry_t swp_entry; 3388 3389 for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) { 3390 if (write) 3391 swp_entry = make_writable_migration_entry( 3392 page_to_pfn(page + i)); 3393 else if (anon_exclusive) 3394 swp_entry = make_readable_exclusive_migration_entry( 3395 page_to_pfn(page + i)); 3396 else 3397 swp_entry = make_readable_migration_entry( 3398 page_to_pfn(page + i)); 3399 if (young) 3400 swp_entry = make_migration_entry_young(swp_entry); 3401 if (dirty) 3402 swp_entry = make_migration_entry_dirty(swp_entry); 3403 entry = swp_entry_to_pte(swp_entry); 3404 if (soft_dirty) 3405 entry = pte_swp_mksoft_dirty(entry); 3406 if (uffd_wp) 3407 entry = pte_swp_mkuffd(entry); 3408 VM_WARN_ON(!pte_none(ptep_get(pte + i))); 3409 set_pte_at(mm, addr, pte + i, entry); 3410 } 3411 } else if (pmd_is_device_private_entry(old_pmd)) { 3412 pte_t entry; 3413 swp_entry_t swp_entry; 3414 3415 for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) { 3416 /* 3417 * anon_exclusive was already propagated to the relevant 3418 * pages corresponding to the pte entries when freeze 3419 * is false. 3420 */ 3421 if (write) 3422 swp_entry = make_writable_device_private_entry( 3423 page_to_pfn(page + i)); 3424 else 3425 swp_entry = make_readable_device_private_entry( 3426 page_to_pfn(page + i)); 3427 /* 3428 * Young and dirty bits are not propagated via swp_entry 3429 */ 3430 entry = swp_entry_to_pte(swp_entry); 3431 if (soft_dirty) 3432 entry = pte_swp_mksoft_dirty(entry); 3433 if (uffd_wp) 3434 entry = pte_swp_mkuffd(entry); 3435 VM_WARN_ON(!pte_none(ptep_get(pte + i))); 3436 set_pte_at(mm, addr, pte + i, entry); 3437 } 3438 } else { 3439 pte_t entry; 3440 3441 entry = mk_pte(page, READ_ONCE(vma->vm_page_prot)); 3442 if (write) 3443 entry = pte_mkwrite(entry, vma); 3444 if (!young) 3445 entry = pte_mkold(entry); 3446 /* NOTE: this may set soft-dirty too on some archs */ 3447 if (dirty) 3448 entry = pte_mkdirty(entry); 3449 if (soft_dirty) 3450 entry = pte_mksoft_dirty(entry); 3451 if (uffd_wp) 3452 entry = pte_mkuffd(entry); 3453 3454 /* Restore PAGE_NONE so an RWP marker keeps trapping */ 3455 if (userfaultfd_rwp(vma) && uffd_wp) 3456 entry = pte_modify(entry, PAGE_NONE); 3457 3458 for (i = 0; i < HPAGE_PMD_NR; i++) 3459 VM_WARN_ON(!pte_none(ptep_get(pte + i))); 3460 3461 set_ptes(mm, haddr, pte, entry, HPAGE_PMD_NR); 3462 } 3463 pte_unmap(pte); 3464 3465 if (!pmd_is_migration_entry(*pmd)) 3466 folio_remove_rmap_pmd(folio, page, vma); 3467 if (freeze) 3468 put_page(page); 3469 3470 smp_wmb(); /* make pte visible before pmd */ 3471 pmd_populate(mm, pmd, pgtable); 3472 } 3473 3474 void split_huge_pmd_locked(struct vm_area_struct *vma, unsigned long address, 3475 pmd_t *pmd, bool freeze) 3476 { 3477 VM_WARN_ON_ONCE(!IS_ALIGNED(address, HPAGE_PMD_SIZE)); 3478 if (pmd_trans_huge(*pmd) || pmd_is_valid_softleaf(*pmd)) 3479 __split_huge_pmd_locked(vma, pmd, address, freeze); 3480 } 3481 3482 void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd, 3483 unsigned long address, bool freeze) 3484 { 3485 spinlock_t *ptl; 3486 struct mmu_notifier_range range; 3487 3488 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm, 3489 address & HPAGE_PMD_MASK, 3490 (address & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE); 3491 mmu_notifier_invalidate_range_start(&range); 3492 ptl = pmd_lock(vma->vm_mm, pmd); 3493 split_huge_pmd_locked(vma, range.start, pmd, freeze); 3494 spin_unlock(ptl); 3495 mmu_notifier_invalidate_range_end(&range); 3496 } 3497 3498 void split_huge_pmd_address(struct vm_area_struct *vma, unsigned long address, 3499 bool freeze) 3500 { 3501 pmd_t *pmd = mm_find_pmd(vma->vm_mm, address); 3502 3503 if (!pmd) 3504 return; 3505 3506 __split_huge_pmd(vma, pmd, address, freeze); 3507 } 3508 3509 static bool pud_split_required(const struct vm_area_struct *vma, 3510 unsigned long address) 3511 { 3512 if (!IS_ENABLED(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)) 3513 return false; 3514 if (IS_ALIGNED(address, HPAGE_PUD_SIZE)) 3515 return false; 3516 /* 3517 * Only selected VMAs support mapping PUDs for now. Lift the 3518 * restriction once this changes. 3519 */ 3520 if (!vma_is_dax(vma) && !vma_test_any(vma, VMA_PFNMAP_BIT, VMA_MIXEDMAP_BIT)) 3521 return false; 3522 return range_in_vma(vma, ALIGN_DOWN(address, HPAGE_PUD_SIZE), 3523 ALIGN(address, HPAGE_PUD_SIZE)); 3524 } 3525 3526 static bool pmd_split_required(const struct vm_area_struct *vma, 3527 unsigned long address) 3528 { 3529 if (IS_ALIGNED(address, HPAGE_PMD_SIZE)) 3530 return false; 3531 3532 return range_in_vma(vma, ALIGN_DOWN(address, HPAGE_PMD_SIZE), 3533 ALIGN(address, HPAGE_PMD_SIZE)); 3534 } 3535 3536 static void split_huge_leaf(struct vm_area_struct *vma, 3537 unsigned long address) 3538 { 3539 const bool split_pud = pud_split_required(vma, address); 3540 const bool split_pmd = pmd_split_required(vma, address); 3541 pgd_t *pgd; 3542 p4d_t *p4d; 3543 pud_t *pud; 3544 pmd_t *pmd; 3545 3546 /* 3547 * mmap, VMA and rmap write locks protect the walk; the split helpers 3548 * take the page table locks. 3549 */ 3550 if (!split_pud && !split_pmd) 3551 return; 3552 3553 pgd = pgd_offset(vma->vm_mm, address); 3554 if (!pgd_present(*pgd)) 3555 return; 3556 3557 p4d = p4d_offset(pgd, address); 3558 if (!p4d_present(*p4d)) 3559 return; 3560 3561 pud = pud_offset(p4d, address); 3562 if (pud_leaf(*pud)) 3563 __split_huge_pud(vma, pud, address); 3564 if (!split_pmd || !pud_present(*pud)) 3565 return; 3566 3567 pmd = pmd_offset(pud, address); 3568 __split_huge_pmd(vma, pmd, address, false); 3569 } 3570 3571 void vma_adjust_trans_huge(struct vm_area_struct *vma, 3572 unsigned long start, 3573 unsigned long end, 3574 struct vm_area_struct *next) 3575 { 3576 /* Check if we need to split start first. */ 3577 split_huge_leaf(vma, start); 3578 3579 /* Check if we need to split end next. */ 3580 split_huge_leaf(vma, end); 3581 3582 /* If we're incrementing next->vm_start, we might need to split it. */ 3583 if (next) 3584 split_huge_leaf(next, end); 3585 } 3586 3587 /* 3588 * A return value of 0 does not mean that unmapping succeeded. It might 3589 * still have failed, but remap_anon_folio() must be called afterwards, 3590 * for anon folios. 3591 */ 3592 static int unmap_folio(struct folio *folio) 3593 { 3594 enum ttu_flags ttu_flags = TTU_RMAP_LOCKED | TTU_SYNC | 3595 TTU_BATCH_FLUSH; 3596 3597 VM_BUG_ON_FOLIO(!folio_test_large(folio), folio); 3598 3599 /* Racy check if we can split the page, before we split PMDs */ 3600 if (folio_expected_ref_count(folio) != folio_ref_count(folio) - 1) 3601 return -EAGAIN; 3602 3603 if (folio_test_pmd_mappable(folio)) 3604 ttu_flags |= TTU_SPLIT_HUGE_PMD; 3605 3606 /* 3607 * Anon pages need migration entries to preserve them, but file 3608 * pages can simply be left unmapped, then faulted back on demand. 3609 */ 3610 if (folio_test_anon(folio)) 3611 try_to_migrate(folio, ttu_flags); 3612 else 3613 try_to_unmap(folio, ttu_flags | TTU_IGNORE_MLOCK); 3614 3615 try_to_unmap_flush(); 3616 3617 return 0; 3618 } 3619 3620 static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma, 3621 unsigned long addr, pmd_t *pmdp, 3622 struct folio *folio) 3623 { 3624 struct mm_struct *mm = vma->vm_mm; 3625 int ref_count, map_count; 3626 pmd_t orig_pmd = *pmdp; 3627 3628 if (pmd_dirty(orig_pmd)) 3629 folio_set_dirty(folio); 3630 if (folio_test_dirty(folio) && !(vma->vm_flags & VM_DROPPABLE)) { 3631 folio_set_swapbacked(folio); 3632 return false; 3633 } 3634 3635 orig_pmd = pmdp_huge_clear_flush(vma, addr, pmdp); 3636 3637 /* 3638 * Syncing against concurrent GUP-fast: 3639 * - clear PMD; barrier; read refcount 3640 * - inc refcount; barrier; read PMD 3641 */ 3642 smp_mb(); 3643 3644 ref_count = folio_ref_count(folio); 3645 map_count = folio_mapcount(folio); 3646 3647 /* 3648 * Order reads for folio refcount and dirty flag 3649 * (see comments in __remove_mapping()). 3650 */ 3651 smp_rmb(); 3652 3653 /* 3654 * If the folio or its PMD is redirtied at this point, or if there 3655 * are unexpected references, we will give up to discard this folio 3656 * and remap it. 3657 * 3658 * The only folio refs must be one from isolation plus the rmap(s). 3659 */ 3660 if (pmd_dirty(orig_pmd)) 3661 folio_set_dirty(folio); 3662 if (folio_test_dirty(folio) && !(vma->vm_flags & VM_DROPPABLE)) { 3663 folio_set_swapbacked(folio); 3664 set_pmd_at(mm, addr, pmdp, orig_pmd); 3665 return false; 3666 } 3667 3668 if (ref_count != map_count + 1) { 3669 set_pmd_at(mm, addr, pmdp, orig_pmd); 3670 return false; 3671 } 3672 3673 folio_remove_rmap_pmd(folio, pmd_page(orig_pmd), vma); 3674 zap_deposited_table(mm, pmdp); 3675 add_mm_counter(mm, MM_ANONPAGES, -HPAGE_PMD_NR); 3676 if (vma->vm_flags & VM_LOCKED) 3677 mlock_drain_local(); 3678 folio_put(folio); 3679 3680 return true; 3681 } 3682 3683 bool unmap_huge_pmd_locked(struct vm_area_struct *vma, unsigned long addr, 3684 pmd_t *pmdp, struct folio *folio) 3685 { 3686 VM_WARN_ON_FOLIO(!folio_test_pmd_mappable(folio), folio); 3687 VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio); 3688 VM_WARN_ON_FOLIO(!folio_test_anon(folio), folio); 3689 VM_WARN_ON_FOLIO(folio_test_swapbacked(folio), folio); 3690 VM_WARN_ON_ONCE(!IS_ALIGNED(addr, HPAGE_PMD_SIZE)); 3691 3692 return __discard_anon_folio_pmd_locked(vma, addr, pmdp, folio); 3693 } 3694 3695 static void remap_anon_folio(struct folio *folio, unsigned long nr, int flags) 3696 { 3697 int i = 0; 3698 3699 /* 3700 * unmap_folio() installs migration entries only for anon folios, 3701 * so currently only anon folios need to be remapped. File folios 3702 * stay unmapped after the split and are faulted back on demand. 3703 */ 3704 VM_WARN_ON_FOLIO(!folio_test_anon(folio), folio); 3705 3706 for (;;) { 3707 remove_migration_ptes(folio, folio, TTU_RMAP_LOCKED | flags); 3708 i += folio_nr_pages(folio); 3709 if (i >= nr) 3710 break; 3711 folio = folio_next(folio); 3712 } 3713 } 3714 3715 static void lru_add_split_folio(struct folio *folio, struct folio *new_folio, 3716 struct lruvec *lruvec, struct list_head *list) 3717 { 3718 VM_BUG_ON_FOLIO(folio_test_lru(new_folio), folio); 3719 lockdep_assert_held(&lruvec->lru_lock); 3720 3721 if (folio_is_device_private(folio)) 3722 return; 3723 3724 if (list) { 3725 /* page reclaim is reclaiming a huge page */ 3726 VM_WARN_ON(folio_test_lru(folio)); 3727 folio_get(new_folio); 3728 list_add_tail(&new_folio->lru, list); 3729 } else { 3730 /* head is still on lru (and we have it frozen) */ 3731 VM_WARN_ON(!folio_test_lru(folio)); 3732 if (folio_test_unevictable(folio)) 3733 new_folio->mlock_count = 0; 3734 else 3735 list_add_tail(&new_folio->lru, &folio->lru); 3736 folio_set_lru(new_folio); 3737 } 3738 } 3739 3740 static bool page_range_has_hwpoisoned(struct page *page, long nr_pages) 3741 { 3742 for (; nr_pages; page++, nr_pages--) 3743 if (PageHWPoison(page)) 3744 return true; 3745 return false; 3746 } 3747 3748 /* 3749 * It splits @folio into @new_order folios and copies the @folio metadata to 3750 * all the resulting folios. 3751 */ 3752 static void __split_folio_to_order(struct folio *folio, int old_order, 3753 int new_order) 3754 { 3755 /* Scan poisoned pages when split a poisoned folio to large folios */ 3756 const bool handle_hwpoison = folio_test_has_hwpoisoned(folio) && new_order; 3757 long new_nr_pages = 1 << new_order; 3758 long nr_pages = 1 << old_order; 3759 long i; 3760 3761 folio_clear_has_hwpoisoned(folio); 3762 3763 /* Check first new_nr_pages since the loop below skips them */ 3764 if (handle_hwpoison && 3765 page_range_has_hwpoisoned(folio_page(folio, 0), new_nr_pages)) 3766 folio_set_has_hwpoisoned(folio); 3767 /* 3768 * Skip the first new_nr_pages, since the new folio from them have all 3769 * the flags from the original folio. 3770 */ 3771 for (i = new_nr_pages; i < nr_pages; i += new_nr_pages) { 3772 struct page *new_head = &folio->page + i; 3773 /* 3774 * Careful: new_folio is not a "real" folio before we cleared PageTail. 3775 * Don't pass it around before clear_compound_head(). 3776 */ 3777 struct folio *new_folio = (struct folio *)new_head; 3778 3779 VM_BUG_ON_PAGE(atomic_read(&new_folio->_mapcount) != -1, new_head); 3780 3781 /* 3782 * Clone page flags before unfreezing refcount. 3783 * 3784 * After successful get_page_unless_zero() might follow flags change, 3785 * for example lock_page() which set PG_waiters. 3786 * 3787 * Note that for mapped sub-pages of an anonymous THP, 3788 * PG_anon_exclusive has been cleared in unmap_folio() and is stored in 3789 * the migration entry instead from where remap_anon_folio() will restore it. 3790 * We can still have PG_anon_exclusive set on effectively unmapped and 3791 * unreferenced sub-pages of an anonymous THP: we can simply drop 3792 * PG_anon_exclusive (-> PG_mappedtodisk) for these here. 3793 */ 3794 new_folio->flags.f &= ~PAGE_FLAGS_CHECK_AT_PREP; 3795 new_folio->flags.f |= (folio->flags.f & 3796 ((1L << PG_referenced) | 3797 (1L << PG_swapbacked) | 3798 (1L << PG_swapcache) | 3799 (1L << PG_mlocked) | 3800 (1L << PG_uptodate) | 3801 (1L << PG_active) | 3802 (1L << PG_workingset) | 3803 (1L << PG_locked) | 3804 (1L << PG_unevictable) | 3805 #ifdef CONFIG_ARCH_USES_PG_ARCH_2 3806 (1L << PG_arch_2) | 3807 #endif 3808 #ifdef CONFIG_ARCH_USES_PG_ARCH_3 3809 (1L << PG_arch_3) | 3810 #endif 3811 (1L << PG_dirty) | 3812 (1L << PG_dropbehind) | 3813 LRU_GEN_MASK | LRU_REFS_MASK)); 3814 3815 new_folio->mapping = folio->mapping; 3816 new_folio->index = folio->index + i; 3817 3818 /* 3819 * page->private should not be set in tail pages. Warn once 3820 * if private is unexpectedly set. Do it before swap.val assignment 3821 * since private overlaps with swap.val. 3822 */ 3823 VM_WARN_ON_ONCE_PAGE(new_folio->private, new_head); 3824 3825 /* 3826 * Not all folio fields are valid during a split, so open-code 3827 * the swap entry rather than using folio_swap_entry(). 3828 */ 3829 if (folio_test_swapcache(folio)) 3830 new_folio->swap.val = folio->swap.val + i; 3831 3832 /* Page flags must be visible before we make the page non-compound. */ 3833 smp_wmb(); 3834 3835 /* 3836 * Clear PageTail before unfreezing page refcount. 3837 * 3838 * After successful get_page_unless_zero() might follow put_page() 3839 * which needs correct compound_head(). 3840 */ 3841 clear_compound_head(new_head); 3842 if (new_order) { 3843 prep_compound_page(new_head, new_order); 3844 folio_set_large_rmappable(new_folio); 3845 } 3846 3847 /* 3848 * PG_has_hwpoisoned is on the 2nd page, so set it after 3849 * the compound head is prepped. 3850 */ 3851 if (handle_hwpoison && 3852 page_range_has_hwpoisoned(new_head, new_nr_pages)) 3853 folio_set_has_hwpoisoned(new_folio); 3854 3855 if (folio_test_young(folio)) 3856 folio_set_young(new_folio); 3857 if (folio_test_idle(folio)) 3858 folio_set_idle(new_folio); 3859 #ifdef CONFIG_MEMCG 3860 new_folio->memcg_data = folio->memcg_data; 3861 #endif 3862 3863 folio_xchg_last_cpupid(new_folio, folio_last_cpupid(folio)); 3864 } 3865 3866 if (new_order) 3867 folio_set_order(folio, new_order); 3868 else 3869 ClearPageCompound(&folio->page); 3870 } 3871 3872 /** 3873 * __split_frozen_folio() - splits a frozen @folio to lower order folios 3874 * in two ways: uniform split or non-uniform split. 3875 * @folio: the to-be-split folio 3876 * @new_order: the smallest order of the after split folios (since buddy 3877 * allocator like split generates folios with orders from @folio's 3878 * order - 1 to new_order). 3879 * @split_at: in buddy allocator like split, the folio containing @split_at 3880 * will be split until its order becomes @new_order. 3881 * @xas: xa_state pointing to folio->mapping->i_pages and locked by caller 3882 * @split_type: if the split is uniform or not (buddy allocator like split) 3883 * 3884 * 3885 * 1. uniform split: the given @folio into multiple @new_order small folios, 3886 * where all small folios have the same order. This is done when 3887 * split_type is SPLIT_TYPE_UNIFORM. 3888 * 2. buddy allocator like (non-uniform) split: the given @folio is split into 3889 * half and one of the half (containing the given page) is split into half 3890 * until the given @folio's order becomes @new_order. This is done when 3891 * split_type is SPLIT_TYPE_NON_UNIFORM. 3892 * 3893 * The high level flow for these two methods are: 3894 * 3895 * 1. uniform split: @xas is split with no expectation of failure and a single 3896 * __split_folio_to_order() is called to split the @folio into @new_order 3897 * along with stats update. 3898 * 2. non-uniform split: folio_order - @new_order calls to 3899 * __split_folio_to_order() are expected to be made in a for loop to split 3900 * the @folio to one lower order at a time. The folio containing @split_at 3901 * is split in each iteration. @xas is split into half in each iteration and 3902 * can fail. A failed @xas split leaves split folios as is without merging 3903 * them back. 3904 * 3905 * After splitting, the caller's folio reference will be transferred to the 3906 * folio containing @split_at. The caller needs to unlock and/or free 3907 * after-split folios if necessary. 3908 * 3909 * Return: 0 - successful, <0 - failed (if -ENOMEM is returned, @folio might be 3910 * split but not to @new_order, the caller needs to check) 3911 */ 3912 static int __split_frozen_folio(struct folio *folio, int new_order, 3913 struct page *split_at, struct xa_state *xas, 3914 enum split_type split_type) 3915 { 3916 const bool is_anon = folio_test_anon(folio); 3917 int old_order = folio_order(folio); 3918 int start_order = split_type == SPLIT_TYPE_UNIFORM ? new_order : old_order - 1; 3919 struct folio *old_folio = folio; 3920 int split_order; 3921 3922 /* Frozen implies unmapped, callers unmap before splitting. */ 3923 VM_WARN_ON_ONCE_FOLIO(folio_mapped(folio), folio); 3924 3925 /* 3926 * split to new_order one order at a time. For uniform split, 3927 * folio is split to new_order directly. 3928 */ 3929 for (split_order = start_order; 3930 split_order >= new_order; 3931 split_order--) { 3932 int nr_new_folios = 1UL << (old_order - split_order); 3933 3934 /* order-1 anonymous folio is not supported */ 3935 if (is_anon && split_order == 1) 3936 continue; 3937 3938 if (xas) { 3939 /* 3940 * uniform split has xas_split_alloc() called before 3941 * irq is disabled to allocate enough memory, whereas 3942 * non-uniform split can handle ENOMEM. 3943 * Use the to-be-split folio, so that a parallel 3944 * folio_try_get() waits on it until xarray is updated 3945 * with after-split folios and the original one is 3946 * unfrozen. 3947 */ 3948 if (split_type == SPLIT_TYPE_UNIFORM) { 3949 xas_split(xas, old_folio, old_order); 3950 } else { 3951 xas_set_order(xas, folio->index, split_order); 3952 xas_try_split(xas, old_folio, old_order); 3953 if (xas_error(xas)) 3954 return xas_error(xas); 3955 } 3956 } 3957 3958 folio_split_memcg_refs(folio, old_order, split_order); 3959 split_page_owner(&folio->page, old_order, split_order); 3960 pgalloc_tag_split(folio, old_order, split_order); 3961 __split_folio_to_order(folio, old_order, split_order); 3962 3963 if (is_anon) { 3964 mod_mthp_stat(old_order, MTHP_STAT_NR_ANON, -1); 3965 mod_mthp_stat(split_order, MTHP_STAT_NR_ANON, nr_new_folios); 3966 } 3967 /* 3968 * If uniform split, the process is complete. 3969 * If non-uniform, continue splitting the folio at @split_at 3970 * as long as the next @split_order is >= @new_order. 3971 */ 3972 folio = page_folio(split_at); 3973 old_order = split_order; 3974 } 3975 3976 return 0; 3977 } 3978 3979 /** 3980 * folio_check_splittable() - check if a folio can be split to a given order 3981 * @folio: folio to be split 3982 * @new_order: the smallest order of the after split folios (since buddy 3983 * allocator like split generates folios with orders from @folio's 3984 * order - 1 to new_order). 3985 * @split_type: uniform or non-uniform split 3986 * 3987 * folio_check_splittable() checks if @folio can be split to @new_order using 3988 * @split_type method. The truncated folio check must come first. 3989 * 3990 * Context: folio must be locked. 3991 * 3992 * Return: 0 - @folio can be split to @new_order, otherwise an error number is 3993 * returned. 3994 */ 3995 int folio_check_splittable(struct folio *folio, unsigned int new_order, 3996 enum split_type split_type) 3997 { 3998 const bool is_anon = folio_test_anon(folio); 3999 const bool is_swapcache = folio_test_swapcache(folio); 4000 4001 VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio); 4002 /* 4003 * Folios that just got truncated cannot get split. Signal to the 4004 * caller that there was a race. 4005 * 4006 * TODO: this will also currently refuse folios without a mapping in the 4007 * swapcache (shmem or to-be-anon folios). 4008 */ 4009 if (!folio->mapping && !is_anon) 4010 return -EBUSY; 4011 4012 /* order-1 is not supported for anonymous THP. */ 4013 if (is_anon && new_order == 1) 4014 return -EINVAL; 4015 4016 /* 4017 * swapcache folio could only be split to order 0 4018 * 4019 * non-uniform split creates after-split folios with orders from 4020 * folio_order(folio) - 1 to new_order, making it not suitable for any 4021 * swapcache folio split. Only uniform split to order-0 can be used 4022 * here. 4023 */ 4024 if ((split_type == SPLIT_TYPE_NON_UNIFORM || new_order) && is_swapcache) 4025 return -EINVAL; 4026 4027 if (is_huge_zero_folio(folio)) 4028 return -EINVAL; 4029 4030 if (folio_test_writeback(folio)) 4031 return -EBUSY; 4032 4033 /* 4034 * A non-anon swapcache folio that still has a mapping can only be a 4035 * shmem folio under SWAP IO, it's removed from either swap cache or 4036 * shmem mapping afterward. There is little benefit in splitting them 4037 * hence reject it here up front before touching anything. 4038 */ 4039 if (!is_anon && is_swapcache && folio->mapping) 4040 return -EBUSY; 4041 4042 return 0; 4043 } 4044 4045 /* Number of folio references from the swapcache. */ 4046 static unsigned int folio_swapcache_ref_count(const struct folio *folio) 4047 { 4048 if (!folio_test_swapcache(folio)) 4049 return 0; 4050 return folio_nr_pages(folio); 4051 } 4052 4053 static void folio_reset_partially_mapped(struct folio *folio) 4054 { 4055 /* Folio must be frozen. */ 4056 VM_WARN_ON_FOLIO(folio_ref_count(folio), folio); 4057 4058 if (!folio_test_partially_mapped(folio)) 4059 return; 4060 4061 /* 4062 * Order-1 folios have no _deferred_list. The flag is only ever set 4063 * on folios that do, so the list can be checked after the flag. 4064 */ 4065 VM_WARN_ON_FOLIO(!list_empty(&folio->_deferred_list), folio); 4066 4067 folio_clear_partially_mapped(folio); 4068 mod_mthp_stat(folio_order(folio), 4069 MTHP_STAT_NR_ANON_PARTIALLY_MAPPED, -1); 4070 } 4071 4072 static int __folio_freeze_split_anon(struct folio *folio, 4073 unsigned int new_order, struct page *split_at, bool do_lru, 4074 struct list_head *list, enum split_type split_type) 4075 { 4076 struct folio *end_folio = folio_next(folio); 4077 struct swap_cluster_info *ci = NULL; 4078 const int old_order = folio_order(folio); 4079 struct folio *new_folio, *next; 4080 struct anon_vma *anon_vma = NULL; 4081 enum ttu_flags ttu_flags = 0; 4082 struct lruvec *lruvec; 4083 int ret = 0; 4084 4085 /* 4086 * Unmap/remap needs the anon_vma, so we first take a reference on 4087 * it to prevent it from disappearing, and lock it for write here, 4088 * letting unmap_folio() walk the rmap with TTU_RMAP_LOCKED. 4089 * 4090 * folio_mapped() is not stable here, but it can only change in 4091 * one direction while the folio is locked. The mapcount can drop 4092 * to zero at any time, zap_pte_range() takes no folio lock. It 4093 * cannot go up: swapin, migration and uffd move all lock the folio 4094 * before mapping it, and fork only copies PTEs that already exist. 4095 * 4096 * So if we see the folio mapped, the worst case is an empty rmap 4097 * walk. If we see it unmapped, it stays unmapped and needs neither 4098 * the reference nor the lock. Anything else needs a reference 4099 * first and folio_ref_freeze() below catches it. 4100 * 4101 * Note that entirely swapped-out THPs are unmapped but can be split. 4102 */ 4103 if (folio_mapped(folio)) { 4104 anon_vma = folio_get_anon_vma(folio); 4105 if (!anon_vma) 4106 return -EBUSY; 4107 anon_vma_lock_write(anon_vma); 4108 ret = unmap_folio(folio); 4109 if (ret) 4110 goto out_unlock; 4111 } 4112 4113 local_irq_disable(); 4114 4115 if (!folio_ref_freeze(folio, folio_swapcache_ref_count(folio) + 1)) { 4116 ret = -EAGAIN; 4117 goto out_no_split; 4118 } 4119 4120 /* Take off the deferred split queue while frozen and memcg set */ 4121 folio_unqueue_deferred_split(folio); 4122 4123 /* 4124 * deferred_split_scan() takes the folio off the queue before it 4125 * splits it, so the unqueue above finds an empty list and 4126 * leaves PG_partially_mapped set. 4127 * Clear it here: the flag does not survive the split. 4128 */ 4129 folio_reset_partially_mapped(folio); 4130 4131 if (folio_test_swapcache(folio)) 4132 ci = swap_cluster_get_and_lock(folio); 4133 4134 if (do_lru) 4135 lruvec = folio_lruvec_lock(folio); 4136 4137 ret = __split_frozen_folio(folio, new_order, split_at, NULL, split_type); 4138 4139 /* 4140 * Unfreeze the after-split folios and put them back to the right 4141 * place. Keep the head @folio frozen until the end: sub entries 4142 * in swap cache must be updated first, so a concurrent 4143 * swap_cache_get_folio() cannot return the head folio for a sub 4144 * entry (folio_try_get() will fail on the head @folio until unfreeze). 4145 */ 4146 for (new_folio = folio_next(folio); new_folio != end_folio; 4147 new_folio = next) { 4148 next = folio_next(new_folio); 4149 zone_device_private_split_cb(folio, new_folio); 4150 folio_ref_unfreeze(new_folio, 4151 folio_swapcache_ref_count(new_folio) + 1); 4152 if (do_lru) 4153 lru_add_split_folio(folio, new_folio, lruvec, list); 4154 if (ci) 4155 __swap_cache_replace_folio(ci, folio, new_folio); 4156 } 4157 4158 zone_device_private_split_cb(folio, NULL); 4159 folio_ref_unfreeze(folio, folio_swapcache_ref_count(folio) + 1); 4160 4161 if (do_lru) 4162 lruvec_unlock(lruvec); 4163 if (ci) 4164 swap_cluster_unlock(ci); 4165 out_no_split: 4166 local_irq_enable(); 4167 if (anon_vma) { 4168 if (!ret && !folio_is_device_private(folio)) 4169 ttu_flags = TTU_USE_SHARED_ZEROPAGE; 4170 remap_anon_folio(folio, 1 << old_order, ttu_flags); 4171 } 4172 out_unlock: 4173 if (anon_vma) { 4174 anon_vma_unlock_write(anon_vma); 4175 put_anon_vma(anon_vma); 4176 } 4177 4178 return ret; 4179 } 4180 4181 static int __folio_freeze_split_file(struct folio *folio, 4182 unsigned int new_order, struct page *split_at, 4183 struct list_head *list, enum split_type split_type) 4184 { 4185 const long old_nr_pages = folio_nr_pages(folio); 4186 struct address_space *mapping = folio->mapping; 4187 XA_STATE(xas, &mapping->i_pages, folio->index); 4188 struct folio *end_folio = folio_next(folio); 4189 struct mem_cgroup *memcg, *old_memcg; 4190 struct folio *new_folio, *next; 4191 int nr_shmem_dropped = 0; 4192 unsigned int min_order; 4193 struct lruvec *lruvec; 4194 pgoff_t end; 4195 gfp_t gfp; 4196 int ret = 0; 4197 4198 min_order = mapping_min_folio_order(mapping); 4199 if (new_order < min_order) 4200 return -EINVAL; 4201 4202 /* 4203 * Switch to folio's memcg as xarray node allocation can happen and 4204 * needs to charge to it. 4205 */ 4206 memcg = get_mem_cgroup_from_folio(folio); 4207 old_memcg = set_active_memcg(memcg); 4208 4209 gfp = current_gfp_context(mapping_gfp_mask(mapping) & GFP_RECLAIM_MASK); 4210 if (!filemap_release_folio(folio, gfp)) { 4211 ret = -EBUSY; 4212 goto fail_free; 4213 } 4214 4215 mapping_set_update(&xas, mapping); 4216 4217 if (split_type == SPLIT_TYPE_UNIFORM) { 4218 const int old_order = folio_order(folio); 4219 4220 xas_set_order(&xas, folio->index, new_order); 4221 xas_split_alloc(&xas, folio, old_order, gfp); 4222 if (xas_error(&xas)) { 4223 ret = xas_error(&xas); 4224 goto fail_free; 4225 } 4226 } 4227 4228 i_mmap_lock_read(mapping); 4229 4230 /* Currently device private folios can only back anonymous memory. */ 4231 VM_WARN_ON_ONCE_FOLIO(folio_is_device_private(folio), folio); 4232 4233 /* 4234 * The loop below may need to trim off pages beyond 4235 * EOF: but on 32-bit, i_size_read() takes an irq-unsafe 4236 * seqlock, which cannot be nested inside the page tree lock. 4237 * So note end now: i_size itself may be changed at any moment, 4238 * but folio lock is good enough to serialize the trimming. 4239 */ 4240 end = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE); 4241 if (shmem_mapping(mapping)) 4242 end = shmem_fallocend(mapping->host, end); 4243 4244 ret = unmap_folio(folio); 4245 if (ret) 4246 goto fail_mmap_unlock; 4247 4248 xas_lock_irq(&xas); 4249 4250 /* 4251 * Check if the folio is present in page cache. 4252 * We assume all tail are present too, if folio is there. 4253 */ 4254 if (xas_load(&xas) != folio) { 4255 ret = -EAGAIN; 4256 goto fail; 4257 } 4258 4259 if (!folio_ref_freeze(folio, old_nr_pages + 1)) { 4260 ret = -EAGAIN; 4261 goto fail; 4262 } 4263 4264 if (folio_test_pmd_mappable(folio) && new_order < HPAGE_PMD_ORDER) { 4265 if (folio_test_swapbacked(folio)) 4266 lruvec_stat_mod_folio(folio, NR_SHMEM_THPS, -old_nr_pages); 4267 else 4268 lruvec_stat_mod_folio(folio, NR_FILE_THPS, -old_nr_pages); 4269 } 4270 4271 /* lock lru list/PageCompound, ref frozen by page_ref_freeze */ 4272 lruvec = folio_lruvec_lock(folio); 4273 ret = __split_frozen_folio(folio, new_order, split_at, &xas, split_type); 4274 4275 /* 4276 * Unfreeze after-split folios and put them back to the right 4277 * list. @folio should be kept frozen until page cache 4278 * entries are updated with all the other after-split folios 4279 * to prevent others seeing stale page cache entries. 4280 * As a result, new_folio starts from the next folio of 4281 * @folio. 4282 */ 4283 for (new_folio = folio_next(folio); new_folio != end_folio; 4284 new_folio = next) { 4285 unsigned long nr_pages = folio_nr_pages(new_folio); 4286 4287 /* compute next before the folio can be freed below */ 4288 next = folio_next(new_folio); 4289 4290 folio_ref_unfreeze(new_folio, 4291 folio_nr_pages(new_folio) + 1); 4292 4293 lru_add_split_folio(folio, new_folio, lruvec, list); 4294 4295 /* Add the new folio to the page cache. */ 4296 if (new_folio->index < end) { 4297 __xa_store(&mapping->i_pages, new_folio->index, 4298 new_folio, 0); 4299 continue; 4300 } 4301 4302 /* Drop folio beyond EOF: ->index >= end */ 4303 if (shmem_mapping(mapping)) 4304 nr_shmem_dropped += nr_pages; 4305 else if (folio_test_clear_dirty(new_folio)) 4306 folio_account_cleaned( 4307 new_folio, inode_to_wb(mapping->host)); 4308 __filemap_remove_folio(new_folio, NULL); 4309 folio_put_refs(new_folio, nr_pages); 4310 } 4311 4312 /* 4313 * Unfreeze @folio only after all page cache entries, which 4314 * used to point to it, have been updated with new folios. 4315 * Otherwise, a parallel folio_try_get() can grab @folio 4316 * and its caller can see stale page cache entries. 4317 */ 4318 folio_ref_unfreeze(folio, folio_nr_pages(folio) + 1); 4319 lruvec_unlock(lruvec); 4320 fail: 4321 xas_unlock_irq(&xas); 4322 fail_mmap_unlock: 4323 if (nr_shmem_dropped) 4324 shmem_uncharge(mapping->host, nr_shmem_dropped); 4325 /* 4326 * Drop the mapping while the inode is still pinned. @folio stays 4327 * locked and present in the page cache, so eviction cannot free 4328 * the inode yet, nothing past this point may touch the inode or 4329 * the mapping. 4330 */ 4331 i_mmap_unlock_read(mapping); 4332 fail_free: 4333 /* Restore the previously active memcg */ 4334 set_active_memcg(old_memcg); 4335 mem_cgroup_put(memcg); 4336 xas_destroy(&xas); 4337 return ret; 4338 } 4339 4340 /** 4341 * __folio_split() - split a folio at @split_at to a @new_order folio 4342 * @folio: folio to split 4343 * @new_order: the order of the new folio 4344 * @split_at: a page within the new folio 4345 * @lock_at: a page within @folio to be left locked to caller 4346 * @list: after-split folios will be put on it if non NULL 4347 * @split_type: perform uniform split or not (non-uniform split) 4348 * 4349 * It calls __split_frozen_folio() to perform uniform and non-uniform split. 4350 * It is in charge of checking whether the split is supported or not and 4351 * preparing @folio for __split_frozen_folio(). 4352 * 4353 * After splitting, the after-split folio containing @lock_at remains locked 4354 * and others are unlocked: 4355 * 1. for uniform split, @lock_at points to one of @folio's subpages; 4356 * 2. for buddy allocator like (non-uniform) split, @lock_at points to @folio. 4357 * 4358 * Return: 0 - successful, <0 - failed (if -ENOMEM is returned, @folio might be 4359 * split but not to @new_order, the caller needs to check) 4360 */ 4361 static int __folio_split(struct folio *folio, unsigned int new_order, 4362 struct page *split_at, struct page *lock_at, 4363 struct list_head *list, enum split_type split_type) 4364 { 4365 struct folio *end_folio = folio_next(folio); 4366 const bool is_anon = folio_test_anon(folio); 4367 const bool is_swapcache = folio_test_swapcache(folio); 4368 int old_order = folio_order(folio); 4369 struct folio *new_folio, *next; 4370 int ret; 4371 4372 VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); 4373 VM_WARN_ON_ONCE_FOLIO(!folio_test_large(folio), folio); 4374 4375 if (folio != page_folio(split_at) || folio != page_folio(lock_at)) { 4376 ret = -EINVAL; 4377 goto out; 4378 } 4379 4380 if (new_order >= old_order) { 4381 ret = -EINVAL; 4382 goto out; 4383 } 4384 4385 ret = folio_check_splittable(folio, new_order, split_type); 4386 if (ret) { 4387 VM_WARN_ONCE(ret == -EINVAL, "Tried to split an unsplittable folio"); 4388 goto out; 4389 } 4390 4391 if (is_anon) 4392 ret = __folio_freeze_split_anon(folio, new_order, split_at, 4393 true, list, split_type); 4394 else 4395 ret = __folio_freeze_split_file(folio, new_order, split_at, 4396 list, split_type); 4397 4398 /* 4399 * Unlock all after-split folios except the one containing 4400 * @lock_at page. If @folio is not split, it will be kept locked. 4401 */ 4402 for (new_folio = folio; new_folio != end_folio; new_folio = next) { 4403 next = folio_next(new_folio); 4404 if (new_folio == page_folio(lock_at)) 4405 continue; 4406 4407 /* 4408 * Subpages whose mapping has been zapped may be freed 4409 * earlier, but freeing them requires taking the 4410 * lru_lock, so we defer folio_put() on tail pages until 4411 * after the split completes. 4412 */ 4413 if (is_swapcache && !folio_mapped(new_folio)) 4414 folio_free_swap(new_folio); 4415 folio_unlock(new_folio); 4416 folio_put(new_folio); 4417 } 4418 4419 out: 4420 if (is_pmd_order(old_order)) 4421 count_vm_event(!ret ? THP_SPLIT_PAGE : THP_SPLIT_PAGE_FAILED); 4422 count_mthp_stat(old_order, !ret ? MTHP_STAT_SPLIT : MTHP_STAT_SPLIT_FAILED); 4423 return ret; 4424 } 4425 4426 /** 4427 * folio_split_unmapped() - split a large anon folio that is already unmapped 4428 * @folio: folio to split 4429 * @new_order: the order of folios after split 4430 * 4431 * This function is a helper for splitting folios that have already been 4432 * unmapped. The use case is that the device or the CPU can refuse to migrate 4433 * THP pages in the middle of migration, due to allocation issues on either 4434 * side. 4435 * 4436 * The anon rmap lock is not required to be held, mmap_read_lock() or 4437 * mmap_write_lock() should be held. @folio is expected to be locked by the 4438 * caller. device-private and non device-private folios are supported along 4439 * with folios that are in the swapcache. @folio should also be unmapped and 4440 * isolated from LRU (if applicable) 4441 * 4442 * Upon return, the folio is not remapped, split folios are not added to LRU, 4443 * folio_free_swap() is not called, and new folios remain locked. 4444 * 4445 * Return: 0 on success, -EAGAIN if the folio cannot be split (e.g., due to 4446 * insufficient reference count or extra pins). 4447 */ 4448 int folio_split_unmapped(struct folio *folio, unsigned int new_order) 4449 { 4450 VM_WARN_ON_ONCE_FOLIO(folio_mapped(folio), folio); 4451 VM_WARN_ON_ONCE_FOLIO(!folio_test_locked(folio), folio); 4452 VM_WARN_ON_ONCE_FOLIO(!folio_test_large(folio), folio); 4453 VM_WARN_ON_ONCE_FOLIO(!folio_test_anon(folio), folio); 4454 4455 return __folio_freeze_split_anon(folio, new_order, &folio->page, 4456 false, NULL, SPLIT_TYPE_UNIFORM); 4457 } 4458 4459 /* 4460 * This function splits a large folio into smaller folios of order @new_order. 4461 * @page can point to any page of the large folio to split. The split operation 4462 * does not change the position of @page. 4463 * 4464 * Prerequisites: 4465 * 4466 * 1) The caller must hold a reference on the @page's owning folio, also known 4467 * as the large folio. 4468 * 4469 * 2) The large folio must be locked. 4470 * 4471 * 3) The folio must not be pinned. Any unexpected folio references, including 4472 * GUP pins, will result in the folio not getting split; instead, the caller 4473 * will receive an -EAGAIN. 4474 * 4475 * 4) @new_order > 1, usually. Splitting to order-1 anonymous folios is not 4476 * supported for non-file-backed folios, because folio->_deferred_list, which 4477 * is used by partially mapped folios, is stored in subpage 2, but an order-1 4478 * folio only has subpages 0 and 1. File-backed order-1 folios are supported, 4479 * since they do not use _deferred_list. 4480 * 4481 * After splitting, the caller's folio reference will be transferred to @page, 4482 * resulting in a raised refcount of @page after this call. The other pages may 4483 * be freed if they are not mapped. 4484 * 4485 * If @list is null, tail pages will be added to LRU list, otherwise, to @list. 4486 * 4487 * Pages in @new_order will inherit the mapping, flags, and so on from the 4488 * huge page. 4489 * 4490 * Returns 0 if the huge page was split successfully. 4491 * 4492 * Returns -EAGAIN if the folio has unexpected reference (e.g., GUP) or if 4493 * the folio was concurrently removed from the page cache. 4494 * 4495 * Returns -EBUSY when trying to split the huge zeropage, if the folio is 4496 * under writeback, if fs-specific folio metadata cannot currently be 4497 * released, or if some unexpected race happened (e.g., anon VMA disappeared, 4498 * truncation). 4499 * 4500 * Callers should ensure that the order respects the address space mapping 4501 * min-order if one is set for non-anonymous folios. 4502 * 4503 * Returns -EINVAL when trying to split to an order that is incompatible 4504 * with the folio. Splitting to order 0 is compatible with all folios. 4505 */ 4506 int __split_huge_page_to_list_to_order(struct page *page, struct list_head *list, 4507 unsigned int new_order) 4508 { 4509 struct folio *folio = page_folio(page); 4510 4511 return __folio_split(folio, new_order, &folio->page, page, list, 4512 SPLIT_TYPE_UNIFORM); 4513 } 4514 4515 /** 4516 * folio_split() - split a folio at @split_at to a @new_order folio 4517 * @folio: folio to split 4518 * @new_order: the order of the new folio 4519 * @split_at: a page within the new folio 4520 * @list: after-split folios are added to @list if not null, otherwise to LRU 4521 * list 4522 * 4523 * It has the same prerequisites and returns as 4524 * split_huge_page_to_list_to_order(). 4525 * 4526 * Split a folio at @split_at to a new_order folio, leave the 4527 * remaining subpages of the original folio as large as possible. For example, 4528 * in the case of splitting an order-9 folio at its third order-3 subpages to 4529 * an order-3 folio, there are 2^(9-3)=64 order-3 subpages in the order-9 folio. 4530 * After the split, there will be a group of folios with different orders and 4531 * the new folio containing @split_at is marked in bracket: 4532 * [order-4, {order-3}, order-3, order-5, order-6, order-7, order-8]. 4533 * 4534 * After split, folio is left locked for caller. 4535 * 4536 * Return: 0 - successful, <0 - failed (if -ENOMEM is returned, @folio might be 4537 * split but not to @new_order, the caller needs to check) 4538 */ 4539 int folio_split(struct folio *folio, unsigned int new_order, 4540 struct page *split_at, struct list_head *list) 4541 { 4542 return __folio_split(folio, new_order, split_at, &folio->page, list, 4543 SPLIT_TYPE_NON_UNIFORM); 4544 } 4545 4546 /** 4547 * min_order_for_split() - get the minimum order @folio can be split to 4548 * @folio: folio to split 4549 * 4550 * min_order_for_split() tells the minimum order @folio can be split to. 4551 * If a file-backed folio is truncated, 0 will be returned. Any subsequent 4552 * split attempt should get -EBUSY from split checking code. 4553 * 4554 * Return: @folio's minimum order for split 4555 */ 4556 unsigned int min_order_for_split(struct folio *folio) 4557 { 4558 if (folio_test_anon(folio)) 4559 return 0; 4560 4561 /* 4562 * If the folio got truncated, we don't know the previous mapping and 4563 * consequently the old min order. But it doesn't matter, as any split 4564 * attempt will immediately fail with -EBUSY as the folio cannot get 4565 * split until freed. 4566 */ 4567 if (!folio->mapping) 4568 return 0; 4569 4570 return mapping_min_folio_order(folio->mapping); 4571 } 4572 4573 int split_folio_to_list(struct folio *folio, struct list_head *list) 4574 { 4575 return split_huge_page_to_list_to_order(&folio->page, list, 0); 4576 } 4577 4578 /* 4579 * __folio_unqueue_deferred_split() is not to be called directly: 4580 * the folio_unqueue_deferred_split() inline wrapper in mm/internal.h 4581 * limits its calls to those folios which may have a _deferred_list for 4582 * queueing THP splits, and that list is (racily observed to be) non-empty. 4583 * 4584 * It is unsafe to call folio_unqueue_deferred_split() until folio refcount is 4585 * zero: because even when the list_lru lock is held, a non-empty 4586 * _deferred_list might be in use on deferred_split_scan()'s on-stack list. 4587 * 4588 * The list_lru sublist is determined by folio's memcg: it is therefore 4589 * important to unqueue deferred split before changing folio memcg. 4590 */ 4591 bool __folio_unqueue_deferred_split(struct folio *folio) 4592 { 4593 struct mem_cgroup *memcg; 4594 struct list_lru_one *lru; 4595 int nid = folio_nid(folio); 4596 unsigned long flags; 4597 bool unqueued = false; 4598 4599 WARN_ON_ONCE(folio_ref_count(folio)); 4600 WARN_ON_ONCE(!mem_cgroup_disabled() && !folio_memcg_charged(folio)); 4601 4602 rcu_read_lock(); 4603 memcg = folio_memcg(folio); 4604 lru = list_lru_lock_irqsave(&deferred_split_lru, nid, &memcg, &flags); 4605 if (__list_lru_del(&deferred_split_lru, lru, &folio->_deferred_list, nid)) { 4606 folio_reset_partially_mapped(folio); 4607 unqueued = true; 4608 } 4609 list_lru_unlock_irqrestore(lru, &flags); 4610 rcu_read_unlock(); 4611 4612 return unqueued; /* useful for debug warnings */ 4613 } 4614 4615 /* partially_mapped=false won't clear PG_partially_mapped folio flag */ 4616 void deferred_split_folio(struct folio *folio, bool partially_mapped) 4617 { 4618 struct list_lru_one *lru; 4619 int nid; 4620 struct mem_cgroup *memcg; 4621 unsigned long flags; 4622 4623 /* 4624 * Order 1 folios have no space for a deferred list, but we also 4625 * won't waste much memory by not adding them to the deferred list. 4626 */ 4627 if (folio_order(folio) <= 1) 4628 return; 4629 4630 if (!partially_mapped && !split_underused_thp) 4631 return; 4632 4633 /* 4634 * Exclude swapcache: originally to avoid a corrupt deferred split 4635 * queue. Nowadays that is fully prevented by __memcg1_swapout(); 4636 * but if page reclaim is already handling the same folio, it is 4637 * unnecessary to handle it again in the shrinker, so excluding 4638 * swapcache here may still be a useful optimization. 4639 */ 4640 if (folio_test_swapcache(folio)) 4641 return; 4642 4643 nid = folio_nid(folio); 4644 4645 rcu_read_lock(); 4646 memcg = folio_memcg(folio); 4647 lru = list_lru_lock_irqsave(&deferred_split_lru, nid, &memcg, &flags); 4648 if (partially_mapped) { 4649 if (!folio_test_partially_mapped(folio)) { 4650 folio_set_partially_mapped(folio); 4651 if (folio_test_pmd_mappable(folio)) 4652 count_vm_event(THP_DEFERRED_SPLIT_PAGE); 4653 count_mthp_stat(folio_order(folio), MTHP_STAT_SPLIT_DEFERRED); 4654 mod_mthp_stat(folio_order(folio), MTHP_STAT_NR_ANON_PARTIALLY_MAPPED, 1); 4655 } 4656 } else { 4657 /* partially mapped folios cannot become non-partially mapped */ 4658 VM_WARN_ON_FOLIO(folio_test_partially_mapped(folio), folio); 4659 } 4660 __list_lru_add(&deferred_split_lru, lru, &folio->_deferred_list, nid, memcg); 4661 list_lru_unlock_irqrestore(lru, &flags); 4662 rcu_read_unlock(); 4663 } 4664 4665 static unsigned long deferred_split_count(struct shrinker *shrink, 4666 struct shrink_control *sc) 4667 { 4668 unsigned long count; 4669 4670 count = list_lru_shrink_count(&deferred_split_lru, sc); 4671 return count ?: SHRINK_EMPTY; 4672 } 4673 4674 static bool thp_underused(struct folio *folio) 4675 { 4676 int num_zero_pages = 0, num_filled_pages = 0; 4677 int i; 4678 4679 if (khugepaged_max_ptes_none == HPAGE_PMD_NR - 1) 4680 return false; 4681 4682 if (folio_contain_hwpoisoned_page(folio)) 4683 return false; 4684 4685 for (i = 0; i < folio_nr_pages(folio); i++) { 4686 if (pages_identical(folio_page(folio, i), ZERO_PAGE(0))) { 4687 if (++num_zero_pages > khugepaged_max_ptes_none) 4688 return true; 4689 } else { 4690 /* 4691 * Another path for early exit once the number 4692 * of non-zero filled pages exceeds threshold. 4693 */ 4694 if (++num_filled_pages >= HPAGE_PMD_NR - khugepaged_max_ptes_none) 4695 return false; 4696 } 4697 } 4698 return false; 4699 } 4700 4701 static enum lru_status deferred_split_isolate(struct list_head *item, 4702 struct list_lru_one *lru, 4703 void *cb_arg) 4704 { 4705 struct folio *folio = container_of(item, struct folio, _deferred_list); 4706 struct list_head *freeable = cb_arg; 4707 4708 /* Lost race to folio_put() or the folio is under folio_ref_freeze() */ 4709 if (!folio_try_get(folio)) 4710 return LRU_SKIP; 4711 4712 list_lru_isolate_move(lru, item, freeable); 4713 return LRU_REMOVED; 4714 } 4715 4716 static unsigned long deferred_split_scan(struct shrinker *shrink, 4717 struct shrink_control *sc) 4718 { 4719 LIST_HEAD(dispose); 4720 struct folio *folio, *next; 4721 int split = 0; 4722 unsigned long isolated; 4723 4724 isolated = list_lru_shrink_walk_irq(&deferred_split_lru, sc, 4725 deferred_split_isolate, &dispose); 4726 4727 list_for_each_entry_safe(folio, next, &dispose, _deferred_list) { 4728 struct mem_cgroup *memcg; 4729 struct list_lru_one *lru; 4730 bool did_split = false; 4731 bool underused = false; 4732 4733 /* 4734 * Sync with deferred_split_folio(), which can requeue the 4735 * folio once list_empty() is true, and sets PG_partially_mapped. 4736 */ 4737 rcu_read_lock(); 4738 memcg = folio_memcg(folio); 4739 lru = list_lru_lock_irq(&deferred_split_lru, folio_nid(folio), 4740 &memcg); 4741 list_del_init(&folio->_deferred_list); 4742 list_lru_unlock_irq(lru); 4743 rcu_read_unlock(); 4744 4745 if (!folio_test_partially_mapped(folio)) { 4746 /* 4747 * See try_to_map_unused_to_zeropage(): we cannot 4748 * optimize zero-filled pages after splitting an 4749 * mlocked folio. 4750 */ 4751 if (folio_test_mlocked(folio)) 4752 goto next; 4753 underused = thp_underused(folio); 4754 if (!underused) 4755 goto next; 4756 } 4757 if (!folio_trylock(folio)) 4758 goto requeue; 4759 if (!split_folio(folio)) { 4760 did_split = true; 4761 if (underused) 4762 count_vm_event(THP_UNDERUSED_SPLIT_PAGE); 4763 split++; 4764 } 4765 folio_unlock(folio); 4766 next: 4767 /* 4768 * If thp_underused() returns false, or if split_folio() 4769 * succeeds, or if split_folio() fails in the case it was 4770 * underused, then consider it used and don't add it back to 4771 * split_queue. 4772 */ 4773 if (!did_split && folio_test_partially_mapped(folio)) { 4774 requeue: 4775 rcu_read_lock(); 4776 list_lru_add_irq(&deferred_split_lru, 4777 &folio->_deferred_list, 4778 folio_nid(folio), 4779 folio_memcg(folio)); 4780 rcu_read_unlock(); 4781 } 4782 folio_put(folio); 4783 } 4784 4785 if (!split && !isolated) 4786 return SHRINK_STOP; 4787 return split; 4788 } 4789 4790 #ifdef CONFIG_DEBUG_FS 4791 static void split_huge_pages_all(void) 4792 { 4793 struct zone *zone; 4794 struct page *page; 4795 struct folio *folio; 4796 unsigned long pfn, max_zone_pfn; 4797 unsigned long total = 0, split = 0; 4798 4799 pr_debug("Split all THPs\n"); 4800 for_each_zone(zone) { 4801 if (!managed_zone(zone)) 4802 continue; 4803 max_zone_pfn = zone_end_pfn(zone); 4804 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++) { 4805 int nr_pages; 4806 4807 page = pfn_to_online_page(pfn); 4808 if (!page || PageTail(page)) 4809 continue; 4810 folio = page_folio(page); 4811 if (!folio_try_get(folio)) 4812 continue; 4813 4814 if (unlikely(page_folio(page) != folio)) 4815 goto next; 4816 4817 if (zone != folio_zone(folio)) 4818 goto next; 4819 4820 if (!folio_test_large(folio) 4821 || folio_test_hugetlb(folio) 4822 || !folio_test_lru(folio)) 4823 goto next; 4824 4825 total++; 4826 folio_lock(folio); 4827 nr_pages = folio_nr_pages(folio); 4828 if (!split_folio(folio)) 4829 split++; 4830 pfn += nr_pages - 1; 4831 folio_unlock(folio); 4832 next: 4833 folio_put(folio); 4834 cond_resched(); 4835 } 4836 } 4837 4838 pr_debug("%lu of %lu THP split\n", split, total); 4839 } 4840 4841 static inline bool vma_not_suitable_for_thp_split(struct vm_area_struct *vma) 4842 { 4843 if (vma_is_dax(vma)) 4844 return true; 4845 if (!vma_is_mm_managed(vma)) 4846 return true; 4847 if (vma_is_hugetlb(vma)) 4848 return true; 4849 4850 return false; 4851 } 4852 4853 static int split_huge_pages_pid(int pid, unsigned long vaddr_start, 4854 unsigned long vaddr_end, unsigned int new_order, 4855 long in_folio_offset) 4856 { 4857 int ret = 0; 4858 struct task_struct *task; 4859 struct mm_struct *mm; 4860 unsigned long total = 0, split = 0; 4861 unsigned long addr; 4862 4863 vaddr_start &= PAGE_MASK; 4864 vaddr_end &= PAGE_MASK; 4865 4866 task = find_get_task_by_vpid(pid); 4867 if (!task) { 4868 ret = -ESRCH; 4869 goto out; 4870 } 4871 4872 /* Find the mm_struct */ 4873 mm = get_task_mm(task); 4874 put_task_struct(task); 4875 4876 if (!mm) { 4877 ret = -EINVAL; 4878 goto out; 4879 } 4880 4881 pr_debug("Split huge pages in pid: %d, vaddr: [0x%lx - 0x%lx], new_order: %u, in_folio_offset: %ld\n", 4882 pid, vaddr_start, vaddr_end, new_order, in_folio_offset); 4883 4884 mmap_read_lock(mm); 4885 /* 4886 * always increase addr by PAGE_SIZE, since we could have a PTE page 4887 * table filled with PTE-mapped THPs, each of which is distinct. 4888 */ 4889 for (addr = vaddr_start; addr < vaddr_end; addr += PAGE_SIZE) { 4890 struct vm_area_struct *vma = vma_lookup(mm, addr); 4891 struct folio_walk fw; 4892 struct folio *folio; 4893 struct address_space *mapping; 4894 unsigned int target_order = new_order; 4895 4896 if (!vma) 4897 break; 4898 4899 /* skip special VMA and hugetlb VMA */ 4900 if (vma_not_suitable_for_thp_split(vma)) { 4901 addr = vma->vm_end; 4902 continue; 4903 } 4904 4905 folio = folio_walk_start(&fw, vma, addr, 0); 4906 if (!folio) 4907 continue; 4908 4909 if (!is_transparent_hugepage(folio)) 4910 goto next; 4911 4912 if (!folio_test_anon(folio)) { 4913 mapping = folio->mapping; 4914 target_order = max(new_order, 4915 mapping_min_folio_order(mapping)); 4916 } 4917 4918 if (target_order >= folio_order(folio)) 4919 goto next; 4920 4921 total++; 4922 /* 4923 * For folios with private, split_huge_page_to_list_to_order() 4924 * will try to drop it before split and then check if the folio 4925 * can be split or not. So skip the check here. 4926 */ 4927 if (!folio_has_attached_private(folio) && 4928 folio_expected_ref_count(folio) != folio_ref_count(folio)) 4929 goto next; 4930 4931 if (!folio_trylock(folio)) 4932 goto next; 4933 folio_get(folio); 4934 folio_walk_end(&fw, vma); 4935 4936 if (!folio_test_anon(folio) && folio->mapping != mapping) 4937 goto unlock; 4938 4939 if (in_folio_offset < 0 || 4940 in_folio_offset >= folio_nr_pages(folio)) { 4941 if (!split_folio_to_order(folio, target_order)) 4942 split++; 4943 } else { 4944 struct page *split_at = folio_page(folio, 4945 in_folio_offset); 4946 if (!folio_split(folio, target_order, split_at, NULL)) 4947 split++; 4948 } 4949 4950 unlock: 4951 4952 folio_unlock(folio); 4953 folio_put(folio); 4954 4955 cond_resched(); 4956 continue; 4957 next: 4958 folio_walk_end(&fw, vma); 4959 cond_resched(); 4960 } 4961 mmap_read_unlock(mm); 4962 mmput(mm); 4963 4964 pr_debug("%lu of %lu THP split\n", split, total); 4965 4966 out: 4967 return ret; 4968 } 4969 4970 static int split_huge_pages_in_file(const char *file_path, pgoff_t off_start, 4971 pgoff_t off_end, unsigned int new_order, 4972 long in_folio_offset) 4973 { 4974 struct file *candidate; 4975 struct address_space *mapping; 4976 pgoff_t index; 4977 int nr_pages = 1; 4978 unsigned long total = 0, split = 0; 4979 unsigned int min_order; 4980 unsigned int target_order; 4981 4982 CLASS(filename_kernel, file)(file_path); 4983 candidate = file_open_name(file, O_RDONLY, 0); 4984 if (IS_ERR(candidate)) 4985 return -EINVAL; 4986 4987 pr_debug("split file-backed THPs in file: %s, page offset: [0x%lx - 0x%lx], new_order: %u, in_folio_offset: %ld\n", 4988 file_path, off_start, off_end, new_order, in_folio_offset); 4989 4990 mapping = candidate->f_mapping; 4991 min_order = mapping_min_folio_order(mapping); 4992 target_order = max(new_order, min_order); 4993 4994 for (index = off_start; index < off_end; index += nr_pages) { 4995 struct folio *folio = filemap_get_folio(mapping, index); 4996 4997 nr_pages = 1; 4998 if (IS_ERR(folio)) 4999 continue; 5000 5001 if (!folio_test_large(folio)) 5002 goto next; 5003 5004 total++; 5005 nr_pages = folio_nr_pages(folio); 5006 5007 if (target_order >= folio_order(folio)) 5008 goto next; 5009 5010 if (!folio_trylock(folio)) 5011 goto next; 5012 5013 if (folio->mapping != mapping) 5014 goto unlock; 5015 5016 if (in_folio_offset < 0 || in_folio_offset >= nr_pages) { 5017 if (!split_folio_to_order(folio, target_order)) 5018 split++; 5019 } else { 5020 struct page *split_at = folio_page(folio, 5021 in_folio_offset); 5022 if (!folio_split(folio, target_order, split_at, NULL)) 5023 split++; 5024 } 5025 5026 unlock: 5027 folio_unlock(folio); 5028 next: 5029 folio_put(folio); 5030 cond_resched(); 5031 } 5032 5033 filp_close(candidate, NULL); 5034 pr_debug("%lu of %lu file-backed THP split\n", split, total); 5035 return 0; 5036 } 5037 5038 #define MAX_INPUT_BUF_SZ 255 5039 5040 static ssize_t split_huge_pages_write(struct file *file, const char __user *buf, 5041 size_t count, loff_t *ppops) 5042 { 5043 static DEFINE_MUTEX(split_debug_mutex); 5044 ssize_t ret; 5045 /* 5046 * hold pid, start_vaddr, end_vaddr, new_order or 5047 * file_path, off_start, off_end, new_order 5048 */ 5049 char input_buf[MAX_INPUT_BUF_SZ]; 5050 int pid; 5051 unsigned long vaddr_start, vaddr_end; 5052 unsigned int new_order = 0; 5053 long in_folio_offset = -1; 5054 5055 ret = mutex_lock_interruptible(&split_debug_mutex); 5056 if (ret) 5057 return ret; 5058 5059 ret = -EFAULT; 5060 5061 memset(input_buf, 0, MAX_INPUT_BUF_SZ); 5062 if (copy_from_user(input_buf, buf, min_t(size_t, count, MAX_INPUT_BUF_SZ))) 5063 goto out; 5064 5065 input_buf[MAX_INPUT_BUF_SZ - 1] = '\0'; 5066 5067 if (input_buf[0] == '/') { 5068 char *tok; 5069 char *tok_buf = input_buf; 5070 char file_path[MAX_INPUT_BUF_SZ]; 5071 pgoff_t off_start = 0, off_end = 0; 5072 size_t input_len = strlen(input_buf); 5073 5074 tok = strsep(&tok_buf, ","); 5075 if (tok && tok_buf) { 5076 strscpy(file_path, tok); 5077 } else { 5078 ret = -EINVAL; 5079 goto out; 5080 } 5081 5082 ret = sscanf(tok_buf, "0x%lx,0x%lx,%d,%ld", &off_start, &off_end, 5083 &new_order, &in_folio_offset); 5084 if (ret != 2 && ret != 3 && ret != 4) { 5085 ret = -EINVAL; 5086 goto out; 5087 } 5088 ret = split_huge_pages_in_file(file_path, off_start, off_end, 5089 new_order, in_folio_offset); 5090 if (!ret) 5091 ret = input_len; 5092 5093 goto out; 5094 } 5095 5096 ret = sscanf(input_buf, "%d,0x%lx,0x%lx,%d,%ld", &pid, &vaddr_start, 5097 &vaddr_end, &new_order, &in_folio_offset); 5098 if (ret == 1 && pid == 1) { 5099 split_huge_pages_all(); 5100 ret = strlen(input_buf); 5101 goto out; 5102 } else if (ret != 3 && ret != 4 && ret != 5) { 5103 ret = -EINVAL; 5104 goto out; 5105 } 5106 5107 ret = split_huge_pages_pid(pid, vaddr_start, vaddr_end, new_order, 5108 in_folio_offset); 5109 if (!ret) 5110 ret = strlen(input_buf); 5111 out: 5112 mutex_unlock(&split_debug_mutex); 5113 return ret; 5114 5115 } 5116 5117 static const struct file_operations split_huge_pages_fops = { 5118 .owner = THIS_MODULE, 5119 .write = split_huge_pages_write, 5120 }; 5121 5122 static int __init split_huge_pages_debugfs(void) 5123 { 5124 debugfs_create_file("split_huge_pages", 0200, NULL, NULL, 5125 &split_huge_pages_fops); 5126 return 0; 5127 } 5128 late_initcall(split_huge_pages_debugfs); 5129 #endif 5130 5131 #ifdef CONFIG_ARCH_HAS_PMD_SOFTLEAVES 5132 int set_pmd_migration_entry(struct page_vma_mapped_walk *pvmw, 5133 struct page *page) 5134 { 5135 struct folio *folio = page_folio(page); 5136 struct vm_area_struct *vma = pvmw->vma; 5137 struct mm_struct *mm = vma->vm_mm; 5138 unsigned long address = pvmw->address; 5139 bool anon_exclusive, present, writable, softdirty, uffd_wp; 5140 pmd_t pmdval; 5141 swp_entry_t entry; 5142 pmd_t pmdswp; 5143 5144 if (!(pvmw->pmd && !pvmw->pte)) 5145 return 0; 5146 5147 present = pmd_present(*pvmw->pmd); 5148 if (likely(present)) { 5149 flush_cache_range(vma, address, address + HPAGE_PMD_SIZE); 5150 5151 pmdval = pmdp_invalidate(vma, address, pvmw->pmd); 5152 5153 writable = pmd_write(pmdval); 5154 softdirty = pmd_soft_dirty(pmdval); 5155 uffd_wp = pmd_uffd(pmdval); 5156 } else { 5157 softleaf_t old_entry; 5158 5159 pmdval = pmdp_huge_get_and_clear(vma->vm_mm, address, pvmw->pmd); 5160 old_entry = softleaf_from_pmd(pmdval); 5161 5162 writable = softleaf_is_device_private_write(old_entry); 5163 softdirty = pmd_swp_soft_dirty(pmdval); 5164 uffd_wp = pmd_swp_uffd(pmdval); 5165 } 5166 5167 /* See folio_try_share_anon_rmap_pmd(): invalidate PMD first. */ 5168 anon_exclusive = folio_test_anon(folio) && PageAnonExclusive(page); 5169 if (anon_exclusive && folio_try_share_anon_rmap_pmd(folio, page)) { 5170 set_pmd_at(mm, address, pvmw->pmd, pmdval); 5171 return -EBUSY; 5172 } 5173 5174 /* Determine type of migration entry. */ 5175 if (writable) 5176 entry = make_writable_migration_entry(page_to_pfn(page)); 5177 else if (anon_exclusive) 5178 entry = make_readable_exclusive_migration_entry(page_to_pfn(page)); 5179 else 5180 entry = make_readable_migration_entry(page_to_pfn(page)); 5181 5182 /* Set A/D bits as necessary. */ 5183 if (present && pmd_young(pmdval)) 5184 entry = make_migration_entry_young(entry); 5185 if (present && pmd_dirty(pmdval)) { 5186 folio_mark_dirty(folio); 5187 entry = make_migration_entry_dirty(entry); 5188 } 5189 5190 /* Set PMD. */ 5191 pmdswp = softleaf_to_pmd(entry); 5192 if (softdirty) 5193 pmdswp = pmd_swp_mksoft_dirty(pmdswp); 5194 if (uffd_wp) 5195 pmdswp = pmd_swp_mkuffd(pmdswp); 5196 set_pmd_at(mm, address, pvmw->pmd, pmdswp); 5197 5198 /* Migration entry installed: cleanup rmap, folio. */ 5199 folio_remove_rmap_pmd(folio, page, vma); 5200 folio_put(folio); 5201 trace_set_migration_pmd(address, pmd_val(pmdswp)); 5202 5203 return 0; 5204 } 5205 5206 void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct folio *folio) 5207 { 5208 struct vm_area_struct *vma = pvmw->vma; 5209 struct mm_struct *mm = vma->vm_mm; 5210 unsigned long address = pvmw->address; 5211 unsigned long haddr = address & HPAGE_PMD_MASK; 5212 pmd_t pmde; 5213 softleaf_t entry; 5214 5215 if (!(pvmw->pmd && !pvmw->pte)) 5216 return; 5217 5218 entry = softleaf_from_pmd(*pvmw->pmd); 5219 folio_get(folio); 5220 pmde = folio_mk_pmd(folio, READ_ONCE(vma->vm_page_prot)); 5221 5222 if (pmd_swp_soft_dirty(*pvmw->pmd)) 5223 pmde = pmd_mksoft_dirty(pmde); 5224 if (softleaf_is_migration_write(entry)) 5225 pmde = pmd_mkwrite(pmde, vma); 5226 if (pmd_swp_uffd(*pvmw->pmd)) 5227 pmde = pmd_mkuffd(pmde); 5228 5229 /* See do_swap_page(): restore PAGE_NONE for RWP */ 5230 if (pmd_swp_uffd(*pvmw->pmd) && userfaultfd_rwp(vma)) 5231 pmde = pmd_modify(pmde, PAGE_NONE); 5232 5233 if (!softleaf_is_migration_young(entry)) 5234 pmde = pmd_mkold(pmde); 5235 /* NOTE: this may contain setting soft-dirty on some archs */ 5236 if (folio_test_dirty(folio) && softleaf_is_migration_dirty(entry)) 5237 pmde = pmd_mkdirty(pmde); 5238 5239 if (folio_is_device_private(folio)) { 5240 swp_entry_t entry; 5241 5242 if (pmd_write(pmde)) 5243 entry = make_writable_device_private_entry(folio_pfn(folio)); 5244 else 5245 entry = make_readable_device_private_entry(folio_pfn(folio)); 5246 pmde = softleaf_to_pmd(entry); 5247 5248 if (pmd_swp_soft_dirty(*pvmw->pmd)) 5249 pmde = pmd_swp_mksoft_dirty(pmde); 5250 if (pmd_swp_uffd(*pvmw->pmd)) 5251 pmde = pmd_swp_mkuffd(pmde); 5252 } 5253 5254 if (folio_test_anon(folio)) { 5255 rmap_t rmap_flags = RMAP_NONE; 5256 5257 if (!softleaf_is_migration_read(entry)) 5258 rmap_flags |= RMAP_EXCLUSIVE; 5259 5260 folio_add_anon_rmap_pmd(folio, &folio->page, vma, haddr, rmap_flags); 5261 } else { 5262 folio_add_file_rmap_pmd(folio, &folio->page, vma); 5263 } 5264 VM_WARN_ON_ONCE(pmd_write(pmde) && folio_test_anon(folio) && 5265 !PageAnonExclusive(&folio->page)); 5266 set_pmd_at(mm, haddr, pvmw->pmd, pmde); 5267 5268 /* No need to invalidate - it was non-present before */ 5269 update_mmu_cache_pmd(vma, address, pvmw->pmd); 5270 trace_remove_migration_pmd(address, pmd_val(pmde)); 5271 } 5272 #endif 5273