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/coredump.h> 12 #include <linux/sched/numa_balancing.h> 13 #include <linux/highmem.h> 14 #include <linux/hugetlb.h> 15 #include <linux/mmu_notifier.h> 16 #include <linux/rmap.h> 17 #include <linux/swap.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/pfn_t.h> 27 #include <linux/mman.h> 28 #include <linux/memremap.h> 29 #include <linux/pagemap.h> 30 #include <linux/debugfs.h> 31 #include <linux/migrate.h> 32 #include <linux/hashtable.h> 33 #include <linux/userfaultfd_k.h> 34 #include <linux/page_idle.h> 35 #include <linux/shmem_fs.h> 36 #include <linux/oom.h> 37 #include <linux/numa.h> 38 #include <linux/page_owner.h> 39 #include <linux/sched/sysctl.h> 40 #include <linux/memory-tiers.h> 41 #include <linux/compat.h> 42 #include <linux/pgalloc_tag.h> 43 #include <linux/pagewalk.h> 44 45 #include <asm/tlb.h> 46 #include <asm/pgalloc.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 shrinker *deferred_split_shrinker; 73 static unsigned long deferred_split_count(struct shrinker *shrink, 74 struct shrink_control *sc); 75 static unsigned long deferred_split_scan(struct shrinker *shrink, 76 struct shrink_control *sc); 77 static bool split_underused_thp = true; 78 79 static atomic_t huge_zero_refcount; 80 struct folio *huge_zero_folio __read_mostly; 81 unsigned long huge_zero_pfn __read_mostly = ~0UL; 82 unsigned long huge_anon_orders_always __read_mostly; 83 unsigned long huge_anon_orders_madvise __read_mostly; 84 unsigned long huge_anon_orders_inherit __read_mostly; 85 static bool anon_orders_configured __initdata; 86 87 unsigned long __thp_vma_allowable_orders(struct vm_area_struct *vma, 88 unsigned long vm_flags, 89 unsigned long tva_flags, 90 unsigned long orders) 91 { 92 bool smaps = tva_flags & TVA_SMAPS; 93 bool in_pf = tva_flags & TVA_IN_PF; 94 bool enforce_sysfs = tva_flags & TVA_ENFORCE_SYSFS; 95 unsigned long supported_orders; 96 97 /* Check the intersection of requested and supported orders. */ 98 if (vma_is_anonymous(vma)) 99 supported_orders = THP_ORDERS_ALL_ANON; 100 else if (vma_is_special_huge(vma)) 101 supported_orders = THP_ORDERS_ALL_SPECIAL; 102 else 103 supported_orders = THP_ORDERS_ALL_FILE_DEFAULT; 104 105 orders &= supported_orders; 106 if (!orders) 107 return 0; 108 109 if (!vma->vm_mm) /* vdso */ 110 return 0; 111 112 if (thp_disabled_by_hw() || vma_thp_disabled(vma, vm_flags)) 113 return 0; 114 115 /* khugepaged doesn't collapse DAX vma, but page fault is fine. */ 116 if (vma_is_dax(vma)) 117 return in_pf ? orders : 0; 118 119 /* 120 * khugepaged special VMA and hugetlb VMA. 121 * Must be checked after dax since some dax mappings may have 122 * VM_MIXEDMAP set. 123 */ 124 if (!in_pf && !smaps && (vm_flags & VM_NO_KHUGEPAGED)) 125 return 0; 126 127 /* 128 * Check alignment for file vma and size for both file and anon vma by 129 * filtering out the unsuitable orders. 130 * 131 * Skip the check for page fault. Huge fault does the check in fault 132 * handlers. 133 */ 134 if (!in_pf) { 135 int order = highest_order(orders); 136 unsigned long addr; 137 138 while (orders) { 139 addr = vma->vm_end - (PAGE_SIZE << order); 140 if (thp_vma_suitable_order(vma, addr, order)) 141 break; 142 order = next_order(&orders, order); 143 } 144 145 if (!orders) 146 return 0; 147 } 148 149 /* 150 * Enabled via shmem mount options or sysfs settings. 151 * Must be done before hugepage flags check since shmem has its 152 * own flags. 153 */ 154 if (!in_pf && shmem_file(vma->vm_file)) 155 return shmem_allowable_huge_orders(file_inode(vma->vm_file), 156 vma, vma->vm_pgoff, 0, 157 !enforce_sysfs); 158 159 if (!vma_is_anonymous(vma)) { 160 /* 161 * Enforce sysfs THP requirements as necessary. Anonymous vmas 162 * were already handled in thp_vma_allowable_orders(). 163 */ 164 if (enforce_sysfs && 165 (!hugepage_global_enabled() || (!(vm_flags & VM_HUGEPAGE) && 166 !hugepage_global_always()))) 167 return 0; 168 169 /* 170 * Trust that ->huge_fault() handlers know what they are doing 171 * in fault path. 172 */ 173 if (((in_pf || smaps)) && vma->vm_ops->huge_fault) 174 return orders; 175 /* Only regular file is valid in collapse path */ 176 if (((!in_pf || smaps)) && file_thp_enabled(vma)) 177 return orders; 178 return 0; 179 } 180 181 if (vma_is_temporary_stack(vma)) 182 return 0; 183 184 /* 185 * THPeligible bit of smaps should show 1 for proper VMAs even 186 * though anon_vma is not initialized yet. 187 * 188 * Allow page fault since anon_vma may be not initialized until 189 * the first page fault. 190 */ 191 if (!vma->anon_vma) 192 return (smaps || in_pf) ? orders : 0; 193 194 return orders; 195 } 196 197 static bool get_huge_zero_page(void) 198 { 199 struct folio *zero_folio; 200 retry: 201 if (likely(atomic_inc_not_zero(&huge_zero_refcount))) 202 return true; 203 204 zero_folio = folio_alloc((GFP_TRANSHUGE | __GFP_ZERO) & ~__GFP_MOVABLE, 205 HPAGE_PMD_ORDER); 206 if (!zero_folio) { 207 count_vm_event(THP_ZERO_PAGE_ALLOC_FAILED); 208 return false; 209 } 210 /* Ensure zero folio won't have large_rmappable flag set. */ 211 folio_clear_large_rmappable(zero_folio); 212 preempt_disable(); 213 if (cmpxchg(&huge_zero_folio, NULL, zero_folio)) { 214 preempt_enable(); 215 folio_put(zero_folio); 216 goto retry; 217 } 218 WRITE_ONCE(huge_zero_pfn, folio_pfn(zero_folio)); 219 220 /* We take additional reference here. It will be put back by shrinker */ 221 atomic_set(&huge_zero_refcount, 2); 222 preempt_enable(); 223 count_vm_event(THP_ZERO_PAGE_ALLOC); 224 return true; 225 } 226 227 static void put_huge_zero_page(void) 228 { 229 /* 230 * Counter should never go to zero here. Only shrinker can put 231 * last reference. 232 */ 233 BUG_ON(atomic_dec_and_test(&huge_zero_refcount)); 234 } 235 236 struct folio *mm_get_huge_zero_folio(struct mm_struct *mm) 237 { 238 if (test_bit(MMF_HUGE_ZERO_PAGE, &mm->flags)) 239 return READ_ONCE(huge_zero_folio); 240 241 if (!get_huge_zero_page()) 242 return NULL; 243 244 if (test_and_set_bit(MMF_HUGE_ZERO_PAGE, &mm->flags)) 245 put_huge_zero_page(); 246 247 return READ_ONCE(huge_zero_folio); 248 } 249 250 void mm_put_huge_zero_folio(struct mm_struct *mm) 251 { 252 if (test_bit(MMF_HUGE_ZERO_PAGE, &mm->flags)) 253 put_huge_zero_page(); 254 } 255 256 static unsigned long shrink_huge_zero_page_count(struct shrinker *shrink, 257 struct shrink_control *sc) 258 { 259 /* we can free zero page only if last reference remains */ 260 return atomic_read(&huge_zero_refcount) == 1 ? HPAGE_PMD_NR : 0; 261 } 262 263 static unsigned long shrink_huge_zero_page_scan(struct shrinker *shrink, 264 struct shrink_control *sc) 265 { 266 if (atomic_cmpxchg(&huge_zero_refcount, 1, 0) == 1) { 267 struct folio *zero_folio = xchg(&huge_zero_folio, NULL); 268 BUG_ON(zero_folio == NULL); 269 WRITE_ONCE(huge_zero_pfn, ~0UL); 270 folio_put(zero_folio); 271 return HPAGE_PMD_NR; 272 } 273 274 return 0; 275 } 276 277 static struct shrinker *huge_zero_page_shrinker; 278 279 #ifdef CONFIG_SYSFS 280 static ssize_t enabled_show(struct kobject *kobj, 281 struct kobj_attribute *attr, char *buf) 282 { 283 const char *output; 284 285 if (test_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags)) 286 output = "[always] madvise never"; 287 else if (test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, 288 &transparent_hugepage_flags)) 289 output = "always [madvise] never"; 290 else 291 output = "always madvise [never]"; 292 293 return sysfs_emit(buf, "%s\n", output); 294 } 295 296 static ssize_t enabled_store(struct kobject *kobj, 297 struct kobj_attribute *attr, 298 const char *buf, size_t count) 299 { 300 ssize_t ret = count; 301 302 if (sysfs_streq(buf, "always")) { 303 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags); 304 set_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags); 305 } else if (sysfs_streq(buf, "madvise")) { 306 clear_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags); 307 set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags); 308 } else if (sysfs_streq(buf, "never")) { 309 clear_bit(TRANSPARENT_HUGEPAGE_FLAG, &transparent_hugepage_flags); 310 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, &transparent_hugepage_flags); 311 } else 312 ret = -EINVAL; 313 314 if (ret > 0) { 315 int err = start_stop_khugepaged(); 316 if (err) 317 ret = err; 318 } 319 return ret; 320 } 321 322 static struct kobj_attribute enabled_attr = __ATTR_RW(enabled); 323 324 ssize_t single_hugepage_flag_show(struct kobject *kobj, 325 struct kobj_attribute *attr, char *buf, 326 enum transparent_hugepage_flag flag) 327 { 328 return sysfs_emit(buf, "%d\n", 329 !!test_bit(flag, &transparent_hugepage_flags)); 330 } 331 332 ssize_t single_hugepage_flag_store(struct kobject *kobj, 333 struct kobj_attribute *attr, 334 const char *buf, size_t count, 335 enum transparent_hugepage_flag flag) 336 { 337 unsigned long value; 338 int ret; 339 340 ret = kstrtoul(buf, 10, &value); 341 if (ret < 0) 342 return ret; 343 if (value > 1) 344 return -EINVAL; 345 346 if (value) 347 set_bit(flag, &transparent_hugepage_flags); 348 else 349 clear_bit(flag, &transparent_hugepage_flags); 350 351 return count; 352 } 353 354 static ssize_t defrag_show(struct kobject *kobj, 355 struct kobj_attribute *attr, char *buf) 356 { 357 const char *output; 358 359 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, 360 &transparent_hugepage_flags)) 361 output = "[always] defer defer+madvise madvise never"; 362 else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, 363 &transparent_hugepage_flags)) 364 output = "always [defer] defer+madvise madvise never"; 365 else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, 366 &transparent_hugepage_flags)) 367 output = "always defer [defer+madvise] madvise never"; 368 else if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, 369 &transparent_hugepage_flags)) 370 output = "always defer defer+madvise [madvise] never"; 371 else 372 output = "always defer defer+madvise madvise [never]"; 373 374 return sysfs_emit(buf, "%s\n", output); 375 } 376 377 static ssize_t defrag_store(struct kobject *kobj, 378 struct kobj_attribute *attr, 379 const char *buf, size_t count) 380 { 381 if (sysfs_streq(buf, "always")) { 382 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags); 383 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags); 384 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags); 385 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags); 386 } else if (sysfs_streq(buf, "defer+madvise")) { 387 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags); 388 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags); 389 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags); 390 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags); 391 } else if (sysfs_streq(buf, "defer")) { 392 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags); 393 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags); 394 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags); 395 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags); 396 } else if (sysfs_streq(buf, "madvise")) { 397 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags); 398 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags); 399 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags); 400 set_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags); 401 } else if (sysfs_streq(buf, "never")) { 402 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags); 403 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags); 404 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags); 405 clear_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags); 406 } else 407 return -EINVAL; 408 409 return count; 410 } 411 static struct kobj_attribute defrag_attr = __ATTR_RW(defrag); 412 413 static ssize_t use_zero_page_show(struct kobject *kobj, 414 struct kobj_attribute *attr, char *buf) 415 { 416 return single_hugepage_flag_show(kobj, attr, buf, 417 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG); 418 } 419 static ssize_t use_zero_page_store(struct kobject *kobj, 420 struct kobj_attribute *attr, const char *buf, size_t count) 421 { 422 return single_hugepage_flag_store(kobj, attr, buf, count, 423 TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG); 424 } 425 static struct kobj_attribute use_zero_page_attr = __ATTR_RW(use_zero_page); 426 427 static ssize_t hpage_pmd_size_show(struct kobject *kobj, 428 struct kobj_attribute *attr, char *buf) 429 { 430 return sysfs_emit(buf, "%lu\n", HPAGE_PMD_SIZE); 431 } 432 static struct kobj_attribute hpage_pmd_size_attr = 433 __ATTR_RO(hpage_pmd_size); 434 435 static ssize_t split_underused_thp_show(struct kobject *kobj, 436 struct kobj_attribute *attr, char *buf) 437 { 438 return sysfs_emit(buf, "%d\n", split_underused_thp); 439 } 440 441 static ssize_t split_underused_thp_store(struct kobject *kobj, 442 struct kobj_attribute *attr, 443 const char *buf, size_t count) 444 { 445 int err = kstrtobool(buf, &split_underused_thp); 446 447 if (err < 0) 448 return err; 449 450 return count; 451 } 452 453 static struct kobj_attribute split_underused_thp_attr = __ATTR( 454 shrink_underused, 0644, split_underused_thp_show, split_underused_thp_store); 455 456 static struct attribute *hugepage_attr[] = { 457 &enabled_attr.attr, 458 &defrag_attr.attr, 459 &use_zero_page_attr.attr, 460 &hpage_pmd_size_attr.attr, 461 #ifdef CONFIG_SHMEM 462 &shmem_enabled_attr.attr, 463 #endif 464 &split_underused_thp_attr.attr, 465 NULL, 466 }; 467 468 static const struct attribute_group hugepage_attr_group = { 469 .attrs = hugepage_attr, 470 }; 471 472 static void hugepage_exit_sysfs(struct kobject *hugepage_kobj); 473 static void thpsize_release(struct kobject *kobj); 474 static DEFINE_SPINLOCK(huge_anon_orders_lock); 475 static LIST_HEAD(thpsize_list); 476 477 static ssize_t anon_enabled_show(struct kobject *kobj, 478 struct kobj_attribute *attr, char *buf) 479 { 480 int order = to_thpsize(kobj)->order; 481 const char *output; 482 483 if (test_bit(order, &huge_anon_orders_always)) 484 output = "[always] inherit madvise never"; 485 else if (test_bit(order, &huge_anon_orders_inherit)) 486 output = "always [inherit] madvise never"; 487 else if (test_bit(order, &huge_anon_orders_madvise)) 488 output = "always inherit [madvise] never"; 489 else 490 output = "always inherit madvise [never]"; 491 492 return sysfs_emit(buf, "%s\n", output); 493 } 494 495 static ssize_t anon_enabled_store(struct kobject *kobj, 496 struct kobj_attribute *attr, 497 const char *buf, size_t count) 498 { 499 int order = to_thpsize(kobj)->order; 500 ssize_t ret = count; 501 502 if (sysfs_streq(buf, "always")) { 503 spin_lock(&huge_anon_orders_lock); 504 clear_bit(order, &huge_anon_orders_inherit); 505 clear_bit(order, &huge_anon_orders_madvise); 506 set_bit(order, &huge_anon_orders_always); 507 spin_unlock(&huge_anon_orders_lock); 508 } else if (sysfs_streq(buf, "inherit")) { 509 spin_lock(&huge_anon_orders_lock); 510 clear_bit(order, &huge_anon_orders_always); 511 clear_bit(order, &huge_anon_orders_madvise); 512 set_bit(order, &huge_anon_orders_inherit); 513 spin_unlock(&huge_anon_orders_lock); 514 } else if (sysfs_streq(buf, "madvise")) { 515 spin_lock(&huge_anon_orders_lock); 516 clear_bit(order, &huge_anon_orders_always); 517 clear_bit(order, &huge_anon_orders_inherit); 518 set_bit(order, &huge_anon_orders_madvise); 519 spin_unlock(&huge_anon_orders_lock); 520 } else if (sysfs_streq(buf, "never")) { 521 spin_lock(&huge_anon_orders_lock); 522 clear_bit(order, &huge_anon_orders_always); 523 clear_bit(order, &huge_anon_orders_inherit); 524 clear_bit(order, &huge_anon_orders_madvise); 525 spin_unlock(&huge_anon_orders_lock); 526 } else 527 ret = -EINVAL; 528 529 if (ret > 0) { 530 int err; 531 532 err = start_stop_khugepaged(); 533 if (err) 534 ret = err; 535 } 536 return ret; 537 } 538 539 static struct kobj_attribute anon_enabled_attr = 540 __ATTR(enabled, 0644, anon_enabled_show, anon_enabled_store); 541 542 static struct attribute *anon_ctrl_attrs[] = { 543 &anon_enabled_attr.attr, 544 NULL, 545 }; 546 547 static const struct attribute_group anon_ctrl_attr_grp = { 548 .attrs = anon_ctrl_attrs, 549 }; 550 551 static struct attribute *file_ctrl_attrs[] = { 552 #ifdef CONFIG_SHMEM 553 &thpsize_shmem_enabled_attr.attr, 554 #endif 555 NULL, 556 }; 557 558 static const struct attribute_group file_ctrl_attr_grp = { 559 .attrs = file_ctrl_attrs, 560 }; 561 562 static struct attribute *any_ctrl_attrs[] = { 563 NULL, 564 }; 565 566 static const struct attribute_group any_ctrl_attr_grp = { 567 .attrs = any_ctrl_attrs, 568 }; 569 570 static const struct kobj_type thpsize_ktype = { 571 .release = &thpsize_release, 572 .sysfs_ops = &kobj_sysfs_ops, 573 }; 574 575 DEFINE_PER_CPU(struct mthp_stat, mthp_stats) = {{{0}}}; 576 577 static unsigned long sum_mthp_stat(int order, enum mthp_stat_item item) 578 { 579 unsigned long sum = 0; 580 int cpu; 581 582 for_each_possible_cpu(cpu) { 583 struct mthp_stat *this = &per_cpu(mthp_stats, cpu); 584 585 sum += this->stats[order][item]; 586 } 587 588 return sum; 589 } 590 591 #define DEFINE_MTHP_STAT_ATTR(_name, _index) \ 592 static ssize_t _name##_show(struct kobject *kobj, \ 593 struct kobj_attribute *attr, char *buf) \ 594 { \ 595 int order = to_thpsize(kobj)->order; \ 596 \ 597 return sysfs_emit(buf, "%lu\n", sum_mthp_stat(order, _index)); \ 598 } \ 599 static struct kobj_attribute _name##_attr = __ATTR_RO(_name) 600 601 DEFINE_MTHP_STAT_ATTR(anon_fault_alloc, MTHP_STAT_ANON_FAULT_ALLOC); 602 DEFINE_MTHP_STAT_ATTR(anon_fault_fallback, MTHP_STAT_ANON_FAULT_FALLBACK); 603 DEFINE_MTHP_STAT_ATTR(anon_fault_fallback_charge, MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE); 604 DEFINE_MTHP_STAT_ATTR(swpout, MTHP_STAT_SWPOUT); 605 DEFINE_MTHP_STAT_ATTR(swpout_fallback, MTHP_STAT_SWPOUT_FALLBACK); 606 #ifdef CONFIG_SHMEM 607 DEFINE_MTHP_STAT_ATTR(shmem_alloc, MTHP_STAT_SHMEM_ALLOC); 608 DEFINE_MTHP_STAT_ATTR(shmem_fallback, MTHP_STAT_SHMEM_FALLBACK); 609 DEFINE_MTHP_STAT_ATTR(shmem_fallback_charge, MTHP_STAT_SHMEM_FALLBACK_CHARGE); 610 #endif 611 DEFINE_MTHP_STAT_ATTR(split, MTHP_STAT_SPLIT); 612 DEFINE_MTHP_STAT_ATTR(split_failed, MTHP_STAT_SPLIT_FAILED); 613 DEFINE_MTHP_STAT_ATTR(split_deferred, MTHP_STAT_SPLIT_DEFERRED); 614 DEFINE_MTHP_STAT_ATTR(nr_anon, MTHP_STAT_NR_ANON); 615 DEFINE_MTHP_STAT_ATTR(nr_anon_partially_mapped, MTHP_STAT_NR_ANON_PARTIALLY_MAPPED); 616 617 static struct attribute *anon_stats_attrs[] = { 618 &anon_fault_alloc_attr.attr, 619 &anon_fault_fallback_attr.attr, 620 &anon_fault_fallback_charge_attr.attr, 621 #ifndef CONFIG_SHMEM 622 &swpout_attr.attr, 623 &swpout_fallback_attr.attr, 624 #endif 625 &split_deferred_attr.attr, 626 &nr_anon_attr.attr, 627 &nr_anon_partially_mapped_attr.attr, 628 NULL, 629 }; 630 631 static struct attribute_group anon_stats_attr_grp = { 632 .name = "stats", 633 .attrs = anon_stats_attrs, 634 }; 635 636 static struct attribute *file_stats_attrs[] = { 637 #ifdef CONFIG_SHMEM 638 &shmem_alloc_attr.attr, 639 &shmem_fallback_attr.attr, 640 &shmem_fallback_charge_attr.attr, 641 #endif 642 NULL, 643 }; 644 645 static struct attribute_group file_stats_attr_grp = { 646 .name = "stats", 647 .attrs = file_stats_attrs, 648 }; 649 650 static struct attribute *any_stats_attrs[] = { 651 #ifdef CONFIG_SHMEM 652 &swpout_attr.attr, 653 &swpout_fallback_attr.attr, 654 #endif 655 &split_attr.attr, 656 &split_failed_attr.attr, 657 NULL, 658 }; 659 660 static struct attribute_group any_stats_attr_grp = { 661 .name = "stats", 662 .attrs = any_stats_attrs, 663 }; 664 665 static int sysfs_add_group(struct kobject *kobj, 666 const struct attribute_group *grp) 667 { 668 int ret = -ENOENT; 669 670 /* 671 * If the group is named, try to merge first, assuming the subdirectory 672 * was already created. This avoids the warning emitted by 673 * sysfs_create_group() if the directory already exists. 674 */ 675 if (grp->name) 676 ret = sysfs_merge_group(kobj, grp); 677 if (ret) 678 ret = sysfs_create_group(kobj, grp); 679 680 return ret; 681 } 682 683 static struct thpsize *thpsize_create(int order, struct kobject *parent) 684 { 685 unsigned long size = (PAGE_SIZE << order) / SZ_1K; 686 struct thpsize *thpsize; 687 int ret = -ENOMEM; 688 689 thpsize = kzalloc(sizeof(*thpsize), GFP_KERNEL); 690 if (!thpsize) 691 goto err; 692 693 thpsize->order = order; 694 695 ret = kobject_init_and_add(&thpsize->kobj, &thpsize_ktype, parent, 696 "hugepages-%lukB", size); 697 if (ret) { 698 kfree(thpsize); 699 goto err; 700 } 701 702 703 ret = sysfs_add_group(&thpsize->kobj, &any_ctrl_attr_grp); 704 if (ret) 705 goto err_put; 706 707 ret = sysfs_add_group(&thpsize->kobj, &any_stats_attr_grp); 708 if (ret) 709 goto err_put; 710 711 if (BIT(order) & THP_ORDERS_ALL_ANON) { 712 ret = sysfs_add_group(&thpsize->kobj, &anon_ctrl_attr_grp); 713 if (ret) 714 goto err_put; 715 716 ret = sysfs_add_group(&thpsize->kobj, &anon_stats_attr_grp); 717 if (ret) 718 goto err_put; 719 } 720 721 if (BIT(order) & THP_ORDERS_ALL_FILE_DEFAULT) { 722 ret = sysfs_add_group(&thpsize->kobj, &file_ctrl_attr_grp); 723 if (ret) 724 goto err_put; 725 726 ret = sysfs_add_group(&thpsize->kobj, &file_stats_attr_grp); 727 if (ret) 728 goto err_put; 729 } 730 731 return thpsize; 732 err_put: 733 kobject_put(&thpsize->kobj); 734 err: 735 return ERR_PTR(ret); 736 } 737 738 static void thpsize_release(struct kobject *kobj) 739 { 740 kfree(to_thpsize(kobj)); 741 } 742 743 static int __init hugepage_init_sysfs(struct kobject **hugepage_kobj) 744 { 745 int err; 746 struct thpsize *thpsize; 747 unsigned long orders; 748 int order; 749 750 /* 751 * Default to setting PMD-sized THP to inherit the global setting and 752 * disable all other sizes. powerpc's PMD_ORDER isn't a compile-time 753 * constant so we have to do this here. 754 */ 755 if (!anon_orders_configured) 756 huge_anon_orders_inherit = BIT(PMD_ORDER); 757 758 *hugepage_kobj = kobject_create_and_add("transparent_hugepage", mm_kobj); 759 if (unlikely(!*hugepage_kobj)) { 760 pr_err("failed to create transparent hugepage kobject\n"); 761 return -ENOMEM; 762 } 763 764 err = sysfs_create_group(*hugepage_kobj, &hugepage_attr_group); 765 if (err) { 766 pr_err("failed to register transparent hugepage group\n"); 767 goto delete_obj; 768 } 769 770 err = sysfs_create_group(*hugepage_kobj, &khugepaged_attr_group); 771 if (err) { 772 pr_err("failed to register transparent hugepage group\n"); 773 goto remove_hp_group; 774 } 775 776 orders = THP_ORDERS_ALL_ANON | THP_ORDERS_ALL_FILE_DEFAULT; 777 order = highest_order(orders); 778 while (orders) { 779 thpsize = thpsize_create(order, *hugepage_kobj); 780 if (IS_ERR(thpsize)) { 781 pr_err("failed to create thpsize for order %d\n", order); 782 err = PTR_ERR(thpsize); 783 goto remove_all; 784 } 785 list_add(&thpsize->node, &thpsize_list); 786 order = next_order(&orders, order); 787 } 788 789 return 0; 790 791 remove_all: 792 hugepage_exit_sysfs(*hugepage_kobj); 793 return err; 794 remove_hp_group: 795 sysfs_remove_group(*hugepage_kobj, &hugepage_attr_group); 796 delete_obj: 797 kobject_put(*hugepage_kobj); 798 return err; 799 } 800 801 static void __init hugepage_exit_sysfs(struct kobject *hugepage_kobj) 802 { 803 struct thpsize *thpsize, *tmp; 804 805 list_for_each_entry_safe(thpsize, tmp, &thpsize_list, node) { 806 list_del(&thpsize->node); 807 kobject_put(&thpsize->kobj); 808 } 809 810 sysfs_remove_group(hugepage_kobj, &khugepaged_attr_group); 811 sysfs_remove_group(hugepage_kobj, &hugepage_attr_group); 812 kobject_put(hugepage_kobj); 813 } 814 #else 815 static inline int hugepage_init_sysfs(struct kobject **hugepage_kobj) 816 { 817 return 0; 818 } 819 820 static inline void hugepage_exit_sysfs(struct kobject *hugepage_kobj) 821 { 822 } 823 #endif /* CONFIG_SYSFS */ 824 825 static int __init thp_shrinker_init(void) 826 { 827 huge_zero_page_shrinker = shrinker_alloc(0, "thp-zero"); 828 if (!huge_zero_page_shrinker) 829 return -ENOMEM; 830 831 deferred_split_shrinker = shrinker_alloc(SHRINKER_NUMA_AWARE | 832 SHRINKER_MEMCG_AWARE | 833 SHRINKER_NONSLAB, 834 "thp-deferred_split"); 835 if (!deferred_split_shrinker) { 836 shrinker_free(huge_zero_page_shrinker); 837 return -ENOMEM; 838 } 839 840 huge_zero_page_shrinker->count_objects = shrink_huge_zero_page_count; 841 huge_zero_page_shrinker->scan_objects = shrink_huge_zero_page_scan; 842 shrinker_register(huge_zero_page_shrinker); 843 844 deferred_split_shrinker->count_objects = deferred_split_count; 845 deferred_split_shrinker->scan_objects = deferred_split_scan; 846 shrinker_register(deferred_split_shrinker); 847 848 return 0; 849 } 850 851 static void __init thp_shrinker_exit(void) 852 { 853 shrinker_free(huge_zero_page_shrinker); 854 shrinker_free(deferred_split_shrinker); 855 } 856 857 static int __init hugepage_init(void) 858 { 859 int err; 860 struct kobject *hugepage_kobj; 861 862 if (!has_transparent_hugepage()) { 863 transparent_hugepage_flags = 1 << TRANSPARENT_HUGEPAGE_UNSUPPORTED; 864 return -EINVAL; 865 } 866 867 /* 868 * hugepages can't be allocated by the buddy allocator 869 */ 870 MAYBE_BUILD_BUG_ON(HPAGE_PMD_ORDER > MAX_PAGE_ORDER); 871 872 err = hugepage_init_sysfs(&hugepage_kobj); 873 if (err) 874 goto err_sysfs; 875 876 err = khugepaged_init(); 877 if (err) 878 goto err_slab; 879 880 err = thp_shrinker_init(); 881 if (err) 882 goto err_shrinker; 883 884 /* 885 * By default disable transparent hugepages on smaller systems, 886 * where the extra memory used could hurt more than TLB overhead 887 * is likely to save. The admin can still enable it through /sys. 888 */ 889 if (totalram_pages() < (512 << (20 - PAGE_SHIFT))) { 890 transparent_hugepage_flags = 0; 891 return 0; 892 } 893 894 err = start_stop_khugepaged(); 895 if (err) 896 goto err_khugepaged; 897 898 return 0; 899 err_khugepaged: 900 thp_shrinker_exit(); 901 err_shrinker: 902 khugepaged_destroy(); 903 err_slab: 904 hugepage_exit_sysfs(hugepage_kobj); 905 err_sysfs: 906 return err; 907 } 908 subsys_initcall(hugepage_init); 909 910 static int __init setup_transparent_hugepage(char *str) 911 { 912 int ret = 0; 913 if (!str) 914 goto out; 915 if (!strcmp(str, "always")) { 916 set_bit(TRANSPARENT_HUGEPAGE_FLAG, 917 &transparent_hugepage_flags); 918 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, 919 &transparent_hugepage_flags); 920 ret = 1; 921 } else if (!strcmp(str, "madvise")) { 922 clear_bit(TRANSPARENT_HUGEPAGE_FLAG, 923 &transparent_hugepage_flags); 924 set_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, 925 &transparent_hugepage_flags); 926 ret = 1; 927 } else if (!strcmp(str, "never")) { 928 clear_bit(TRANSPARENT_HUGEPAGE_FLAG, 929 &transparent_hugepage_flags); 930 clear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG, 931 &transparent_hugepage_flags); 932 ret = 1; 933 } 934 out: 935 if (!ret) 936 pr_warn("transparent_hugepage= cannot parse, ignored\n"); 937 return ret; 938 } 939 __setup("transparent_hugepage=", setup_transparent_hugepage); 940 941 static inline int get_order_from_str(const char *size_str) 942 { 943 unsigned long size; 944 char *endptr; 945 int order; 946 947 size = memparse(size_str, &endptr); 948 949 if (!is_power_of_2(size)) 950 goto err; 951 order = get_order(size); 952 if (BIT(order) & ~THP_ORDERS_ALL_ANON) 953 goto err; 954 955 return order; 956 err: 957 pr_err("invalid size %s in thp_anon boot parameter\n", size_str); 958 return -EINVAL; 959 } 960 961 static char str_dup[PAGE_SIZE] __initdata; 962 static int __init setup_thp_anon(char *str) 963 { 964 char *token, *range, *policy, *subtoken; 965 unsigned long always, inherit, madvise; 966 char *start_size, *end_size; 967 int start, end, nr; 968 char *p; 969 970 if (!str || strlen(str) + 1 > PAGE_SIZE) 971 goto err; 972 strcpy(str_dup, str); 973 974 always = huge_anon_orders_always; 975 madvise = huge_anon_orders_madvise; 976 inherit = huge_anon_orders_inherit; 977 p = str_dup; 978 while ((token = strsep(&p, ";")) != NULL) { 979 range = strsep(&token, ":"); 980 policy = token; 981 982 if (!policy) 983 goto err; 984 985 while ((subtoken = strsep(&range, ",")) != NULL) { 986 if (strchr(subtoken, '-')) { 987 start_size = strsep(&subtoken, "-"); 988 end_size = subtoken; 989 990 start = get_order_from_str(start_size); 991 end = get_order_from_str(end_size); 992 } else { 993 start = end = get_order_from_str(subtoken); 994 } 995 996 if (start < 0 || end < 0 || start > end) 997 goto err; 998 999 nr = end - start + 1; 1000 if (!strcmp(policy, "always")) { 1001 bitmap_set(&always, start, nr); 1002 bitmap_clear(&inherit, start, nr); 1003 bitmap_clear(&madvise, start, nr); 1004 } else if (!strcmp(policy, "madvise")) { 1005 bitmap_set(&madvise, start, nr); 1006 bitmap_clear(&inherit, start, nr); 1007 bitmap_clear(&always, start, nr); 1008 } else if (!strcmp(policy, "inherit")) { 1009 bitmap_set(&inherit, start, nr); 1010 bitmap_clear(&madvise, start, nr); 1011 bitmap_clear(&always, start, nr); 1012 } else if (!strcmp(policy, "never")) { 1013 bitmap_clear(&inherit, start, nr); 1014 bitmap_clear(&madvise, start, nr); 1015 bitmap_clear(&always, start, nr); 1016 } else { 1017 pr_err("invalid policy %s in thp_anon boot parameter\n", policy); 1018 goto err; 1019 } 1020 } 1021 } 1022 1023 huge_anon_orders_always = always; 1024 huge_anon_orders_madvise = madvise; 1025 huge_anon_orders_inherit = inherit; 1026 anon_orders_configured = true; 1027 return 1; 1028 1029 err: 1030 pr_warn("thp_anon=%s: error parsing string, ignoring setting\n", str); 1031 return 0; 1032 } 1033 __setup("thp_anon=", setup_thp_anon); 1034 1035 pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma) 1036 { 1037 if (likely(vma->vm_flags & VM_WRITE)) 1038 pmd = pmd_mkwrite(pmd, vma); 1039 return pmd; 1040 } 1041 1042 #ifdef CONFIG_MEMCG 1043 static inline 1044 struct deferred_split *get_deferred_split_queue(struct folio *folio) 1045 { 1046 struct mem_cgroup *memcg = folio_memcg(folio); 1047 struct pglist_data *pgdat = NODE_DATA(folio_nid(folio)); 1048 1049 if (memcg) 1050 return &memcg->deferred_split_queue; 1051 else 1052 return &pgdat->deferred_split_queue; 1053 } 1054 #else 1055 static inline 1056 struct deferred_split *get_deferred_split_queue(struct folio *folio) 1057 { 1058 struct pglist_data *pgdat = NODE_DATA(folio_nid(folio)); 1059 1060 return &pgdat->deferred_split_queue; 1061 } 1062 #endif 1063 1064 static inline bool is_transparent_hugepage(const struct folio *folio) 1065 { 1066 if (!folio_test_large(folio)) 1067 return false; 1068 1069 return is_huge_zero_folio(folio) || 1070 folio_test_large_rmappable(folio); 1071 } 1072 1073 static unsigned long __thp_get_unmapped_area(struct file *filp, 1074 unsigned long addr, unsigned long len, 1075 loff_t off, unsigned long flags, unsigned long size, 1076 vm_flags_t vm_flags) 1077 { 1078 loff_t off_end = off + len; 1079 loff_t off_align = round_up(off, size); 1080 unsigned long len_pad, ret, off_sub; 1081 1082 if (!IS_ENABLED(CONFIG_64BIT) || in_compat_syscall()) 1083 return 0; 1084 1085 if (off_end <= off_align || (off_end - off_align) < size) 1086 return 0; 1087 1088 len_pad = len + size; 1089 if (len_pad < len || (off + len_pad) < off) 1090 return 0; 1091 1092 ret = mm_get_unmapped_area_vmflags(current->mm, filp, addr, len_pad, 1093 off >> PAGE_SHIFT, flags, vm_flags); 1094 1095 /* 1096 * The failure might be due to length padding. The caller will retry 1097 * without the padding. 1098 */ 1099 if (IS_ERR_VALUE(ret)) 1100 return 0; 1101 1102 /* 1103 * Do not try to align to THP boundary if allocation at the address 1104 * hint succeeds. 1105 */ 1106 if (ret == addr) 1107 return addr; 1108 1109 off_sub = (off - ret) & (size - 1); 1110 1111 if (test_bit(MMF_TOPDOWN, ¤t->mm->flags) && !off_sub) 1112 return ret + size; 1113 1114 ret += off_sub; 1115 return ret; 1116 } 1117 1118 unsigned long thp_get_unmapped_area_vmflags(struct file *filp, unsigned long addr, 1119 unsigned long len, unsigned long pgoff, unsigned long flags, 1120 vm_flags_t vm_flags) 1121 { 1122 unsigned long ret; 1123 loff_t off = (loff_t)pgoff << PAGE_SHIFT; 1124 1125 ret = __thp_get_unmapped_area(filp, addr, len, off, flags, PMD_SIZE, vm_flags); 1126 if (ret) 1127 return ret; 1128 1129 return mm_get_unmapped_area_vmflags(current->mm, filp, addr, len, pgoff, flags, 1130 vm_flags); 1131 } 1132 1133 unsigned long thp_get_unmapped_area(struct file *filp, unsigned long addr, 1134 unsigned long len, unsigned long pgoff, unsigned long flags) 1135 { 1136 return thp_get_unmapped_area_vmflags(filp, addr, len, pgoff, flags, 0); 1137 } 1138 EXPORT_SYMBOL_GPL(thp_get_unmapped_area); 1139 1140 static vm_fault_t __do_huge_pmd_anonymous_page(struct vm_fault *vmf, 1141 struct page *page, gfp_t gfp) 1142 { 1143 struct vm_area_struct *vma = vmf->vma; 1144 struct folio *folio = page_folio(page); 1145 pgtable_t pgtable; 1146 unsigned long haddr = vmf->address & HPAGE_PMD_MASK; 1147 vm_fault_t ret = 0; 1148 1149 VM_BUG_ON_FOLIO(!folio_test_large(folio), folio); 1150 1151 if (mem_cgroup_charge(folio, vma->vm_mm, gfp)) { 1152 folio_put(folio); 1153 count_vm_event(THP_FAULT_FALLBACK); 1154 count_vm_event(THP_FAULT_FALLBACK_CHARGE); 1155 count_mthp_stat(HPAGE_PMD_ORDER, MTHP_STAT_ANON_FAULT_FALLBACK); 1156 count_mthp_stat(HPAGE_PMD_ORDER, MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE); 1157 return VM_FAULT_FALLBACK; 1158 } 1159 folio_throttle_swaprate(folio, gfp); 1160 1161 pgtable = pte_alloc_one(vma->vm_mm); 1162 if (unlikely(!pgtable)) { 1163 ret = VM_FAULT_OOM; 1164 goto release; 1165 } 1166 1167 folio_zero_user(folio, vmf->address); 1168 /* 1169 * The memory barrier inside __folio_mark_uptodate makes sure that 1170 * folio_zero_user writes become visible before the set_pmd_at() 1171 * write. 1172 */ 1173 __folio_mark_uptodate(folio); 1174 1175 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd); 1176 if (unlikely(!pmd_none(*vmf->pmd))) { 1177 goto unlock_release; 1178 } else { 1179 pmd_t entry; 1180 1181 ret = check_stable_address_space(vma->vm_mm); 1182 if (ret) 1183 goto unlock_release; 1184 1185 /* Deliver the page fault to userland */ 1186 if (userfaultfd_missing(vma)) { 1187 spin_unlock(vmf->ptl); 1188 folio_put(folio); 1189 pte_free(vma->vm_mm, pgtable); 1190 ret = handle_userfault(vmf, VM_UFFD_MISSING); 1191 VM_BUG_ON(ret & VM_FAULT_FALLBACK); 1192 return ret; 1193 } 1194 1195 entry = mk_huge_pmd(page, vma->vm_page_prot); 1196 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); 1197 folio_add_new_anon_rmap(folio, vma, haddr, RMAP_EXCLUSIVE); 1198 folio_add_lru_vma(folio, vma); 1199 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, pgtable); 1200 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry); 1201 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd); 1202 add_mm_counter(vma->vm_mm, MM_ANONPAGES, HPAGE_PMD_NR); 1203 mm_inc_nr_ptes(vma->vm_mm); 1204 deferred_split_folio(folio, false); 1205 spin_unlock(vmf->ptl); 1206 count_vm_event(THP_FAULT_ALLOC); 1207 count_mthp_stat(HPAGE_PMD_ORDER, MTHP_STAT_ANON_FAULT_ALLOC); 1208 count_memcg_event_mm(vma->vm_mm, THP_FAULT_ALLOC); 1209 } 1210 1211 return 0; 1212 unlock_release: 1213 spin_unlock(vmf->ptl); 1214 release: 1215 if (pgtable) 1216 pte_free(vma->vm_mm, pgtable); 1217 folio_put(folio); 1218 return ret; 1219 1220 } 1221 1222 /* 1223 * always: directly stall for all thp allocations 1224 * defer: wake kswapd and fail if not immediately available 1225 * defer+madvise: wake kswapd and directly stall for MADV_HUGEPAGE, otherwise 1226 * fail if not immediately available 1227 * madvise: directly stall for MADV_HUGEPAGE, otherwise fail if not immediately 1228 * available 1229 * never: never stall for any thp allocation 1230 */ 1231 gfp_t vma_thp_gfp_mask(struct vm_area_struct *vma) 1232 { 1233 const bool vma_madvised = vma && (vma->vm_flags & VM_HUGEPAGE); 1234 1235 /* Always do synchronous compaction */ 1236 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, &transparent_hugepage_flags)) 1237 return GFP_TRANSHUGE | (vma_madvised ? 0 : __GFP_NORETRY); 1238 1239 /* Kick kcompactd and fail quickly */ 1240 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, &transparent_hugepage_flags)) 1241 return GFP_TRANSHUGE_LIGHT | __GFP_KSWAPD_RECLAIM; 1242 1243 /* Synchronous compaction if madvised, otherwise kick kcompactd */ 1244 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, &transparent_hugepage_flags)) 1245 return GFP_TRANSHUGE_LIGHT | 1246 (vma_madvised ? __GFP_DIRECT_RECLAIM : 1247 __GFP_KSWAPD_RECLAIM); 1248 1249 /* Only do synchronous compaction if madvised */ 1250 if (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, &transparent_hugepage_flags)) 1251 return GFP_TRANSHUGE_LIGHT | 1252 (vma_madvised ? __GFP_DIRECT_RECLAIM : 0); 1253 1254 return GFP_TRANSHUGE_LIGHT; 1255 } 1256 1257 /* Caller must hold page table lock. */ 1258 static void set_huge_zero_folio(pgtable_t pgtable, struct mm_struct *mm, 1259 struct vm_area_struct *vma, unsigned long haddr, pmd_t *pmd, 1260 struct folio *zero_folio) 1261 { 1262 pmd_t entry; 1263 if (!pmd_none(*pmd)) 1264 return; 1265 entry = mk_pmd(&zero_folio->page, vma->vm_page_prot); 1266 entry = pmd_mkhuge(entry); 1267 pgtable_trans_huge_deposit(mm, pmd, pgtable); 1268 set_pmd_at(mm, haddr, pmd, entry); 1269 mm_inc_nr_ptes(mm); 1270 } 1271 1272 vm_fault_t do_huge_pmd_anonymous_page(struct vm_fault *vmf) 1273 { 1274 struct vm_area_struct *vma = vmf->vma; 1275 gfp_t gfp; 1276 struct folio *folio; 1277 unsigned long haddr = vmf->address & HPAGE_PMD_MASK; 1278 vm_fault_t ret; 1279 1280 if (!thp_vma_suitable_order(vma, haddr, PMD_ORDER)) 1281 return VM_FAULT_FALLBACK; 1282 ret = vmf_anon_prepare(vmf); 1283 if (ret) 1284 return ret; 1285 khugepaged_enter_vma(vma, vma->vm_flags); 1286 1287 if (!(vmf->flags & FAULT_FLAG_WRITE) && 1288 !mm_forbids_zeropage(vma->vm_mm) && 1289 transparent_hugepage_use_zero_page()) { 1290 pgtable_t pgtable; 1291 struct folio *zero_folio; 1292 vm_fault_t ret; 1293 1294 pgtable = pte_alloc_one(vma->vm_mm); 1295 if (unlikely(!pgtable)) 1296 return VM_FAULT_OOM; 1297 zero_folio = mm_get_huge_zero_folio(vma->vm_mm); 1298 if (unlikely(!zero_folio)) { 1299 pte_free(vma->vm_mm, pgtable); 1300 count_vm_event(THP_FAULT_FALLBACK); 1301 return VM_FAULT_FALLBACK; 1302 } 1303 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd); 1304 ret = 0; 1305 if (pmd_none(*vmf->pmd)) { 1306 ret = check_stable_address_space(vma->vm_mm); 1307 if (ret) { 1308 spin_unlock(vmf->ptl); 1309 pte_free(vma->vm_mm, pgtable); 1310 } else if (userfaultfd_missing(vma)) { 1311 spin_unlock(vmf->ptl); 1312 pte_free(vma->vm_mm, pgtable); 1313 ret = handle_userfault(vmf, VM_UFFD_MISSING); 1314 VM_BUG_ON(ret & VM_FAULT_FALLBACK); 1315 } else { 1316 set_huge_zero_folio(pgtable, vma->vm_mm, vma, 1317 haddr, vmf->pmd, zero_folio); 1318 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd); 1319 spin_unlock(vmf->ptl); 1320 } 1321 } else { 1322 spin_unlock(vmf->ptl); 1323 pte_free(vma->vm_mm, pgtable); 1324 } 1325 return ret; 1326 } 1327 gfp = vma_thp_gfp_mask(vma); 1328 folio = vma_alloc_folio(gfp, HPAGE_PMD_ORDER, vma, haddr, true); 1329 if (unlikely(!folio)) { 1330 count_vm_event(THP_FAULT_FALLBACK); 1331 count_mthp_stat(HPAGE_PMD_ORDER, MTHP_STAT_ANON_FAULT_FALLBACK); 1332 return VM_FAULT_FALLBACK; 1333 } 1334 return __do_huge_pmd_anonymous_page(vmf, &folio->page, gfp); 1335 } 1336 1337 static void insert_pfn_pmd(struct vm_area_struct *vma, unsigned long addr, 1338 pmd_t *pmd, pfn_t pfn, pgprot_t prot, bool write, 1339 pgtable_t pgtable) 1340 { 1341 struct mm_struct *mm = vma->vm_mm; 1342 pmd_t entry; 1343 spinlock_t *ptl; 1344 1345 ptl = pmd_lock(mm, pmd); 1346 if (!pmd_none(*pmd)) { 1347 if (write) { 1348 if (pmd_pfn(*pmd) != pfn_t_to_pfn(pfn)) { 1349 WARN_ON_ONCE(!is_huge_zero_pmd(*pmd)); 1350 goto out_unlock; 1351 } 1352 entry = pmd_mkyoung(*pmd); 1353 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); 1354 if (pmdp_set_access_flags(vma, addr, pmd, entry, 1)) 1355 update_mmu_cache_pmd(vma, addr, pmd); 1356 } 1357 1358 goto out_unlock; 1359 } 1360 1361 entry = pmd_mkhuge(pfn_t_pmd(pfn, prot)); 1362 if (pfn_t_devmap(pfn)) 1363 entry = pmd_mkdevmap(entry); 1364 else 1365 entry = pmd_mkspecial(entry); 1366 if (write) { 1367 entry = pmd_mkyoung(pmd_mkdirty(entry)); 1368 entry = maybe_pmd_mkwrite(entry, vma); 1369 } 1370 1371 if (pgtable) { 1372 pgtable_trans_huge_deposit(mm, pmd, pgtable); 1373 mm_inc_nr_ptes(mm); 1374 pgtable = NULL; 1375 } 1376 1377 set_pmd_at(mm, addr, pmd, entry); 1378 update_mmu_cache_pmd(vma, addr, pmd); 1379 1380 out_unlock: 1381 spin_unlock(ptl); 1382 if (pgtable) 1383 pte_free(mm, pgtable); 1384 } 1385 1386 /** 1387 * vmf_insert_pfn_pmd - insert a pmd size pfn 1388 * @vmf: Structure describing the fault 1389 * @pfn: pfn to insert 1390 * @write: whether it's a write fault 1391 * 1392 * Insert a pmd size pfn. See vmf_insert_pfn() for additional info. 1393 * 1394 * Return: vm_fault_t value. 1395 */ 1396 vm_fault_t vmf_insert_pfn_pmd(struct vm_fault *vmf, pfn_t pfn, bool write) 1397 { 1398 unsigned long addr = vmf->address & PMD_MASK; 1399 struct vm_area_struct *vma = vmf->vma; 1400 pgprot_t pgprot = vma->vm_page_prot; 1401 pgtable_t pgtable = NULL; 1402 1403 /* 1404 * If we had pmd_special, we could avoid all these restrictions, 1405 * but we need to be consistent with PTEs and architectures that 1406 * can't support a 'special' bit. 1407 */ 1408 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) && 1409 !pfn_t_devmap(pfn)); 1410 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) == 1411 (VM_PFNMAP|VM_MIXEDMAP)); 1412 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags)); 1413 1414 if (addr < vma->vm_start || addr >= vma->vm_end) 1415 return VM_FAULT_SIGBUS; 1416 1417 if (arch_needs_pgtable_deposit()) { 1418 pgtable = pte_alloc_one(vma->vm_mm); 1419 if (!pgtable) 1420 return VM_FAULT_OOM; 1421 } 1422 1423 track_pfn_insert(vma, &pgprot, pfn); 1424 1425 insert_pfn_pmd(vma, addr, vmf->pmd, pfn, pgprot, write, pgtable); 1426 return VM_FAULT_NOPAGE; 1427 } 1428 EXPORT_SYMBOL_GPL(vmf_insert_pfn_pmd); 1429 1430 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD 1431 static pud_t maybe_pud_mkwrite(pud_t pud, struct vm_area_struct *vma) 1432 { 1433 if (likely(vma->vm_flags & VM_WRITE)) 1434 pud = pud_mkwrite(pud); 1435 return pud; 1436 } 1437 1438 static void insert_pfn_pud(struct vm_area_struct *vma, unsigned long addr, 1439 pud_t *pud, pfn_t pfn, bool write) 1440 { 1441 struct mm_struct *mm = vma->vm_mm; 1442 pgprot_t prot = vma->vm_page_prot; 1443 pud_t entry; 1444 spinlock_t *ptl; 1445 1446 ptl = pud_lock(mm, pud); 1447 if (!pud_none(*pud)) { 1448 if (write) { 1449 if (WARN_ON_ONCE(pud_pfn(*pud) != pfn_t_to_pfn(pfn))) 1450 goto out_unlock; 1451 entry = pud_mkyoung(*pud); 1452 entry = maybe_pud_mkwrite(pud_mkdirty(entry), vma); 1453 if (pudp_set_access_flags(vma, addr, pud, entry, 1)) 1454 update_mmu_cache_pud(vma, addr, pud); 1455 } 1456 goto out_unlock; 1457 } 1458 1459 entry = pud_mkhuge(pfn_t_pud(pfn, prot)); 1460 if (pfn_t_devmap(pfn)) 1461 entry = pud_mkdevmap(entry); 1462 else 1463 entry = pud_mkspecial(entry); 1464 if (write) { 1465 entry = pud_mkyoung(pud_mkdirty(entry)); 1466 entry = maybe_pud_mkwrite(entry, vma); 1467 } 1468 set_pud_at(mm, addr, pud, entry); 1469 update_mmu_cache_pud(vma, addr, pud); 1470 1471 out_unlock: 1472 spin_unlock(ptl); 1473 } 1474 1475 /** 1476 * vmf_insert_pfn_pud - insert a pud size pfn 1477 * @vmf: Structure describing the fault 1478 * @pfn: pfn to insert 1479 * @write: whether it's a write fault 1480 * 1481 * Insert a pud size pfn. See vmf_insert_pfn() for additional info. 1482 * 1483 * Return: vm_fault_t value. 1484 */ 1485 vm_fault_t vmf_insert_pfn_pud(struct vm_fault *vmf, pfn_t pfn, bool write) 1486 { 1487 unsigned long addr = vmf->address & PUD_MASK; 1488 struct vm_area_struct *vma = vmf->vma; 1489 pgprot_t pgprot = vma->vm_page_prot; 1490 1491 /* 1492 * If we had pud_special, we could avoid all these restrictions, 1493 * but we need to be consistent with PTEs and architectures that 1494 * can't support a 'special' bit. 1495 */ 1496 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) && 1497 !pfn_t_devmap(pfn)); 1498 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) == 1499 (VM_PFNMAP|VM_MIXEDMAP)); 1500 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags)); 1501 1502 if (addr < vma->vm_start || addr >= vma->vm_end) 1503 return VM_FAULT_SIGBUS; 1504 1505 track_pfn_insert(vma, &pgprot, pfn); 1506 1507 insert_pfn_pud(vma, addr, vmf->pud, pfn, write); 1508 return VM_FAULT_NOPAGE; 1509 } 1510 EXPORT_SYMBOL_GPL(vmf_insert_pfn_pud); 1511 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */ 1512 1513 void touch_pmd(struct vm_area_struct *vma, unsigned long addr, 1514 pmd_t *pmd, bool write) 1515 { 1516 pmd_t _pmd; 1517 1518 _pmd = pmd_mkyoung(*pmd); 1519 if (write) 1520 _pmd = pmd_mkdirty(_pmd); 1521 if (pmdp_set_access_flags(vma, addr & HPAGE_PMD_MASK, 1522 pmd, _pmd, write)) 1523 update_mmu_cache_pmd(vma, addr, pmd); 1524 } 1525 1526 struct page *follow_devmap_pmd(struct vm_area_struct *vma, unsigned long addr, 1527 pmd_t *pmd, int flags, struct dev_pagemap **pgmap) 1528 { 1529 unsigned long pfn = pmd_pfn(*pmd); 1530 struct mm_struct *mm = vma->vm_mm; 1531 struct page *page; 1532 int ret; 1533 1534 assert_spin_locked(pmd_lockptr(mm, pmd)); 1535 1536 if (flags & FOLL_WRITE && !pmd_write(*pmd)) 1537 return NULL; 1538 1539 if (pmd_present(*pmd) && pmd_devmap(*pmd)) 1540 /* pass */; 1541 else 1542 return NULL; 1543 1544 if (flags & FOLL_TOUCH) 1545 touch_pmd(vma, addr, pmd, flags & FOLL_WRITE); 1546 1547 /* 1548 * device mapped pages can only be returned if the 1549 * caller will manage the page reference count. 1550 */ 1551 if (!(flags & (FOLL_GET | FOLL_PIN))) 1552 return ERR_PTR(-EEXIST); 1553 1554 pfn += (addr & ~PMD_MASK) >> PAGE_SHIFT; 1555 *pgmap = get_dev_pagemap(pfn, *pgmap); 1556 if (!*pgmap) 1557 return ERR_PTR(-EFAULT); 1558 page = pfn_to_page(pfn); 1559 ret = try_grab_folio(page_folio(page), 1, flags); 1560 if (ret) 1561 page = ERR_PTR(ret); 1562 1563 return page; 1564 } 1565 1566 int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm, 1567 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr, 1568 struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma) 1569 { 1570 spinlock_t *dst_ptl, *src_ptl; 1571 struct page *src_page; 1572 struct folio *src_folio; 1573 pmd_t pmd; 1574 pgtable_t pgtable = NULL; 1575 int ret = -ENOMEM; 1576 1577 pmd = pmdp_get_lockless(src_pmd); 1578 if (unlikely(pmd_present(pmd) && pmd_special(pmd))) { 1579 dst_ptl = pmd_lock(dst_mm, dst_pmd); 1580 src_ptl = pmd_lockptr(src_mm, src_pmd); 1581 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING); 1582 /* 1583 * No need to recheck the pmd, it can't change with write 1584 * mmap lock held here. 1585 * 1586 * Meanwhile, making sure it's not a CoW VMA with writable 1587 * mapping, otherwise it means either the anon page wrongly 1588 * applied special bit, or we made the PRIVATE mapping be 1589 * able to wrongly write to the backend MMIO. 1590 */ 1591 VM_WARN_ON_ONCE(is_cow_mapping(src_vma->vm_flags) && pmd_write(pmd)); 1592 goto set_pmd; 1593 } 1594 1595 /* Skip if can be re-fill on fault */ 1596 if (!vma_is_anonymous(dst_vma)) 1597 return 0; 1598 1599 pgtable = pte_alloc_one(dst_mm); 1600 if (unlikely(!pgtable)) 1601 goto out; 1602 1603 dst_ptl = pmd_lock(dst_mm, dst_pmd); 1604 src_ptl = pmd_lockptr(src_mm, src_pmd); 1605 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING); 1606 1607 ret = -EAGAIN; 1608 pmd = *src_pmd; 1609 1610 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION 1611 if (unlikely(is_swap_pmd(pmd))) { 1612 swp_entry_t entry = pmd_to_swp_entry(pmd); 1613 1614 VM_BUG_ON(!is_pmd_migration_entry(pmd)); 1615 if (!is_readable_migration_entry(entry)) { 1616 entry = make_readable_migration_entry( 1617 swp_offset(entry)); 1618 pmd = swp_entry_to_pmd(entry); 1619 if (pmd_swp_soft_dirty(*src_pmd)) 1620 pmd = pmd_swp_mksoft_dirty(pmd); 1621 if (pmd_swp_uffd_wp(*src_pmd)) 1622 pmd = pmd_swp_mkuffd_wp(pmd); 1623 set_pmd_at(src_mm, addr, src_pmd, pmd); 1624 } 1625 add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR); 1626 mm_inc_nr_ptes(dst_mm); 1627 pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable); 1628 if (!userfaultfd_wp(dst_vma)) 1629 pmd = pmd_swp_clear_uffd_wp(pmd); 1630 set_pmd_at(dst_mm, addr, dst_pmd, pmd); 1631 ret = 0; 1632 goto out_unlock; 1633 } 1634 #endif 1635 1636 if (unlikely(!pmd_trans_huge(pmd))) { 1637 pte_free(dst_mm, pgtable); 1638 goto out_unlock; 1639 } 1640 /* 1641 * When page table lock is held, the huge zero pmd should not be 1642 * under splitting since we don't split the page itself, only pmd to 1643 * a page table. 1644 */ 1645 if (is_huge_zero_pmd(pmd)) { 1646 /* 1647 * mm_get_huge_zero_folio() will never allocate a new 1648 * folio here, since we already have a zero page to 1649 * copy. It just takes a reference. 1650 */ 1651 mm_get_huge_zero_folio(dst_mm); 1652 goto out_zero_page; 1653 } 1654 1655 src_page = pmd_page(pmd); 1656 VM_BUG_ON_PAGE(!PageHead(src_page), src_page); 1657 src_folio = page_folio(src_page); 1658 1659 folio_get(src_folio); 1660 if (unlikely(folio_try_dup_anon_rmap_pmd(src_folio, src_page, src_vma))) { 1661 /* Page maybe pinned: split and retry the fault on PTEs. */ 1662 folio_put(src_folio); 1663 pte_free(dst_mm, pgtable); 1664 spin_unlock(src_ptl); 1665 spin_unlock(dst_ptl); 1666 __split_huge_pmd(src_vma, src_pmd, addr, false, NULL); 1667 return -EAGAIN; 1668 } 1669 add_mm_counter(dst_mm, MM_ANONPAGES, HPAGE_PMD_NR); 1670 out_zero_page: 1671 mm_inc_nr_ptes(dst_mm); 1672 pgtable_trans_huge_deposit(dst_mm, dst_pmd, pgtable); 1673 pmdp_set_wrprotect(src_mm, addr, src_pmd); 1674 if (!userfaultfd_wp(dst_vma)) 1675 pmd = pmd_clear_uffd_wp(pmd); 1676 pmd = pmd_wrprotect(pmd); 1677 set_pmd: 1678 pmd = pmd_mkold(pmd); 1679 set_pmd_at(dst_mm, addr, dst_pmd, pmd); 1680 1681 ret = 0; 1682 out_unlock: 1683 spin_unlock(src_ptl); 1684 spin_unlock(dst_ptl); 1685 out: 1686 return ret; 1687 } 1688 1689 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD 1690 void touch_pud(struct vm_area_struct *vma, unsigned long addr, 1691 pud_t *pud, bool write) 1692 { 1693 pud_t _pud; 1694 1695 _pud = pud_mkyoung(*pud); 1696 if (write) 1697 _pud = pud_mkdirty(_pud); 1698 if (pudp_set_access_flags(vma, addr & HPAGE_PUD_MASK, 1699 pud, _pud, write)) 1700 update_mmu_cache_pud(vma, addr, pud); 1701 } 1702 1703 int copy_huge_pud(struct mm_struct *dst_mm, struct mm_struct *src_mm, 1704 pud_t *dst_pud, pud_t *src_pud, unsigned long addr, 1705 struct vm_area_struct *vma) 1706 { 1707 spinlock_t *dst_ptl, *src_ptl; 1708 pud_t pud; 1709 int ret; 1710 1711 dst_ptl = pud_lock(dst_mm, dst_pud); 1712 src_ptl = pud_lockptr(src_mm, src_pud); 1713 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING); 1714 1715 ret = -EAGAIN; 1716 pud = *src_pud; 1717 if (unlikely(!pud_trans_huge(pud) && !pud_devmap(pud))) 1718 goto out_unlock; 1719 1720 /* 1721 * TODO: once we support anonymous pages, use 1722 * folio_try_dup_anon_rmap_*() and split if duplicating fails. 1723 */ 1724 if (is_cow_mapping(vma->vm_flags) && pud_write(pud)) { 1725 pudp_set_wrprotect(src_mm, addr, src_pud); 1726 pud = pud_wrprotect(pud); 1727 } 1728 pud = pud_mkold(pud); 1729 set_pud_at(dst_mm, addr, dst_pud, pud); 1730 1731 ret = 0; 1732 out_unlock: 1733 spin_unlock(src_ptl); 1734 spin_unlock(dst_ptl); 1735 return ret; 1736 } 1737 1738 void huge_pud_set_accessed(struct vm_fault *vmf, pud_t orig_pud) 1739 { 1740 bool write = vmf->flags & FAULT_FLAG_WRITE; 1741 1742 vmf->ptl = pud_lock(vmf->vma->vm_mm, vmf->pud); 1743 if (unlikely(!pud_same(*vmf->pud, orig_pud))) 1744 goto unlock; 1745 1746 touch_pud(vmf->vma, vmf->address, vmf->pud, write); 1747 unlock: 1748 spin_unlock(vmf->ptl); 1749 } 1750 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */ 1751 1752 void huge_pmd_set_accessed(struct vm_fault *vmf) 1753 { 1754 bool write = vmf->flags & FAULT_FLAG_WRITE; 1755 1756 vmf->ptl = pmd_lock(vmf->vma->vm_mm, vmf->pmd); 1757 if (unlikely(!pmd_same(*vmf->pmd, vmf->orig_pmd))) 1758 goto unlock; 1759 1760 touch_pmd(vmf->vma, vmf->address, vmf->pmd, write); 1761 1762 unlock: 1763 spin_unlock(vmf->ptl); 1764 } 1765 1766 vm_fault_t do_huge_pmd_wp_page(struct vm_fault *vmf) 1767 { 1768 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE; 1769 struct vm_area_struct *vma = vmf->vma; 1770 struct folio *folio; 1771 struct page *page; 1772 unsigned long haddr = vmf->address & HPAGE_PMD_MASK; 1773 pmd_t orig_pmd = vmf->orig_pmd; 1774 1775 vmf->ptl = pmd_lockptr(vma->vm_mm, vmf->pmd); 1776 VM_BUG_ON_VMA(!vma->anon_vma, vma); 1777 1778 if (is_huge_zero_pmd(orig_pmd)) 1779 goto fallback; 1780 1781 spin_lock(vmf->ptl); 1782 1783 if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) { 1784 spin_unlock(vmf->ptl); 1785 return 0; 1786 } 1787 1788 page = pmd_page(orig_pmd); 1789 folio = page_folio(page); 1790 VM_BUG_ON_PAGE(!PageHead(page), page); 1791 1792 /* Early check when only holding the PT lock. */ 1793 if (PageAnonExclusive(page)) 1794 goto reuse; 1795 1796 if (!folio_trylock(folio)) { 1797 folio_get(folio); 1798 spin_unlock(vmf->ptl); 1799 folio_lock(folio); 1800 spin_lock(vmf->ptl); 1801 if (unlikely(!pmd_same(*vmf->pmd, orig_pmd))) { 1802 spin_unlock(vmf->ptl); 1803 folio_unlock(folio); 1804 folio_put(folio); 1805 return 0; 1806 } 1807 folio_put(folio); 1808 } 1809 1810 /* Recheck after temporarily dropping the PT lock. */ 1811 if (PageAnonExclusive(page)) { 1812 folio_unlock(folio); 1813 goto reuse; 1814 } 1815 1816 /* 1817 * See do_wp_page(): we can only reuse the folio exclusively if 1818 * there are no additional references. Note that we always drain 1819 * the LRU cache immediately after adding a THP. 1820 */ 1821 if (folio_ref_count(folio) > 1822 1 + folio_test_swapcache(folio) * folio_nr_pages(folio)) 1823 goto unlock_fallback; 1824 if (folio_test_swapcache(folio)) 1825 folio_free_swap(folio); 1826 if (folio_ref_count(folio) == 1) { 1827 pmd_t entry; 1828 1829 folio_move_anon_rmap(folio, vma); 1830 SetPageAnonExclusive(page); 1831 folio_unlock(folio); 1832 reuse: 1833 if (unlikely(unshare)) { 1834 spin_unlock(vmf->ptl); 1835 return 0; 1836 } 1837 entry = pmd_mkyoung(orig_pmd); 1838 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); 1839 if (pmdp_set_access_flags(vma, haddr, vmf->pmd, entry, 1)) 1840 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd); 1841 spin_unlock(vmf->ptl); 1842 return 0; 1843 } 1844 1845 unlock_fallback: 1846 folio_unlock(folio); 1847 spin_unlock(vmf->ptl); 1848 fallback: 1849 __split_huge_pmd(vma, vmf->pmd, vmf->address, false, NULL); 1850 return VM_FAULT_FALLBACK; 1851 } 1852 1853 static inline bool can_change_pmd_writable(struct vm_area_struct *vma, 1854 unsigned long addr, pmd_t pmd) 1855 { 1856 struct page *page; 1857 1858 if (WARN_ON_ONCE(!(vma->vm_flags & VM_WRITE))) 1859 return false; 1860 1861 /* Don't touch entries that are not even readable (NUMA hinting). */ 1862 if (pmd_protnone(pmd)) 1863 return false; 1864 1865 /* Do we need write faults for softdirty tracking? */ 1866 if (pmd_needs_soft_dirty_wp(vma, pmd)) 1867 return false; 1868 1869 /* Do we need write faults for uffd-wp tracking? */ 1870 if (userfaultfd_huge_pmd_wp(vma, pmd)) 1871 return false; 1872 1873 if (!(vma->vm_flags & VM_SHARED)) { 1874 /* See can_change_pte_writable(). */ 1875 page = vm_normal_page_pmd(vma, addr, pmd); 1876 return page && PageAnon(page) && PageAnonExclusive(page); 1877 } 1878 1879 /* See can_change_pte_writable(). */ 1880 return pmd_dirty(pmd); 1881 } 1882 1883 /* NUMA hinting page fault entry point for trans huge pmds */ 1884 vm_fault_t do_huge_pmd_numa_page(struct vm_fault *vmf) 1885 { 1886 struct vm_area_struct *vma = vmf->vma; 1887 struct folio *folio; 1888 unsigned long haddr = vmf->address & HPAGE_PMD_MASK; 1889 int nid = NUMA_NO_NODE; 1890 int target_nid, last_cpupid; 1891 pmd_t pmd, old_pmd; 1892 bool writable = false; 1893 int flags = 0; 1894 1895 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd); 1896 old_pmd = pmdp_get(vmf->pmd); 1897 1898 if (unlikely(!pmd_same(old_pmd, vmf->orig_pmd))) { 1899 spin_unlock(vmf->ptl); 1900 return 0; 1901 } 1902 1903 pmd = pmd_modify(old_pmd, vma->vm_page_prot); 1904 1905 /* 1906 * Detect now whether the PMD could be writable; this information 1907 * is only valid while holding the PT lock. 1908 */ 1909 writable = pmd_write(pmd); 1910 if (!writable && vma_wants_manual_pte_write_upgrade(vma) && 1911 can_change_pmd_writable(vma, vmf->address, pmd)) 1912 writable = true; 1913 1914 folio = vm_normal_folio_pmd(vma, haddr, pmd); 1915 if (!folio) 1916 goto out_map; 1917 1918 nid = folio_nid(folio); 1919 1920 target_nid = numa_migrate_check(folio, vmf, haddr, &flags, writable, 1921 &last_cpupid); 1922 if (target_nid == NUMA_NO_NODE) 1923 goto out_map; 1924 if (migrate_misplaced_folio_prepare(folio, vma, target_nid)) { 1925 flags |= TNF_MIGRATE_FAIL; 1926 goto out_map; 1927 } 1928 /* The folio is isolated and isolation code holds a folio reference. */ 1929 spin_unlock(vmf->ptl); 1930 writable = false; 1931 1932 if (!migrate_misplaced_folio(folio, vma, target_nid)) { 1933 flags |= TNF_MIGRATED; 1934 nid = target_nid; 1935 task_numa_fault(last_cpupid, nid, HPAGE_PMD_NR, flags); 1936 return 0; 1937 } 1938 1939 flags |= TNF_MIGRATE_FAIL; 1940 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd); 1941 if (unlikely(!pmd_same(pmdp_get(vmf->pmd), vmf->orig_pmd))) { 1942 spin_unlock(vmf->ptl); 1943 return 0; 1944 } 1945 out_map: 1946 /* Restore the PMD */ 1947 pmd = pmd_modify(pmdp_get(vmf->pmd), vma->vm_page_prot); 1948 pmd = pmd_mkyoung(pmd); 1949 if (writable) 1950 pmd = pmd_mkwrite(pmd, vma); 1951 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, pmd); 1952 update_mmu_cache_pmd(vma, vmf->address, vmf->pmd); 1953 spin_unlock(vmf->ptl); 1954 1955 if (nid != NUMA_NO_NODE) 1956 task_numa_fault(last_cpupid, nid, HPAGE_PMD_NR, flags); 1957 return 0; 1958 } 1959 1960 /* 1961 * Return true if we do MADV_FREE successfully on entire pmd page. 1962 * Otherwise, return false. 1963 */ 1964 bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, 1965 pmd_t *pmd, unsigned long addr, unsigned long next) 1966 { 1967 spinlock_t *ptl; 1968 pmd_t orig_pmd; 1969 struct folio *folio; 1970 struct mm_struct *mm = tlb->mm; 1971 bool ret = false; 1972 1973 tlb_change_page_size(tlb, HPAGE_PMD_SIZE); 1974 1975 ptl = pmd_trans_huge_lock(pmd, vma); 1976 if (!ptl) 1977 goto out_unlocked; 1978 1979 orig_pmd = *pmd; 1980 if (is_huge_zero_pmd(orig_pmd)) 1981 goto out; 1982 1983 if (unlikely(!pmd_present(orig_pmd))) { 1984 VM_BUG_ON(thp_migration_supported() && 1985 !is_pmd_migration_entry(orig_pmd)); 1986 goto out; 1987 } 1988 1989 folio = pmd_folio(orig_pmd); 1990 /* 1991 * If other processes are mapping this folio, we couldn't discard 1992 * the folio unless they all do MADV_FREE so let's skip the folio. 1993 */ 1994 if (folio_likely_mapped_shared(folio)) 1995 goto out; 1996 1997 if (!folio_trylock(folio)) 1998 goto out; 1999 2000 /* 2001 * If user want to discard part-pages of THP, split it so MADV_FREE 2002 * will deactivate only them. 2003 */ 2004 if (next - addr != HPAGE_PMD_SIZE) { 2005 folio_get(folio); 2006 spin_unlock(ptl); 2007 split_folio(folio); 2008 folio_unlock(folio); 2009 folio_put(folio); 2010 goto out_unlocked; 2011 } 2012 2013 if (folio_test_dirty(folio)) 2014 folio_clear_dirty(folio); 2015 folio_unlock(folio); 2016 2017 if (pmd_young(orig_pmd) || pmd_dirty(orig_pmd)) { 2018 pmdp_invalidate(vma, addr, pmd); 2019 orig_pmd = pmd_mkold(orig_pmd); 2020 orig_pmd = pmd_mkclean(orig_pmd); 2021 2022 set_pmd_at(mm, addr, pmd, orig_pmd); 2023 tlb_remove_pmd_tlb_entry(tlb, pmd, addr); 2024 } 2025 2026 folio_mark_lazyfree(folio); 2027 ret = true; 2028 out: 2029 spin_unlock(ptl); 2030 out_unlocked: 2031 return ret; 2032 } 2033 2034 static inline void zap_deposited_table(struct mm_struct *mm, pmd_t *pmd) 2035 { 2036 pgtable_t pgtable; 2037 2038 pgtable = pgtable_trans_huge_withdraw(mm, pmd); 2039 pte_free(mm, pgtable); 2040 mm_dec_nr_ptes(mm); 2041 } 2042 2043 int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, 2044 pmd_t *pmd, unsigned long addr) 2045 { 2046 pmd_t orig_pmd; 2047 spinlock_t *ptl; 2048 2049 tlb_change_page_size(tlb, HPAGE_PMD_SIZE); 2050 2051 ptl = __pmd_trans_huge_lock(pmd, vma); 2052 if (!ptl) 2053 return 0; 2054 /* 2055 * For architectures like ppc64 we look at deposited pgtable 2056 * when calling pmdp_huge_get_and_clear. So do the 2057 * pgtable_trans_huge_withdraw after finishing pmdp related 2058 * operations. 2059 */ 2060 orig_pmd = pmdp_huge_get_and_clear_full(vma, addr, pmd, 2061 tlb->fullmm); 2062 arch_check_zapped_pmd(vma, orig_pmd); 2063 tlb_remove_pmd_tlb_entry(tlb, pmd, addr); 2064 if (vma_is_special_huge(vma)) { 2065 if (arch_needs_pgtable_deposit()) 2066 zap_deposited_table(tlb->mm, pmd); 2067 spin_unlock(ptl); 2068 } else if (is_huge_zero_pmd(orig_pmd)) { 2069 zap_deposited_table(tlb->mm, pmd); 2070 spin_unlock(ptl); 2071 } else { 2072 struct folio *folio = NULL; 2073 int flush_needed = 1; 2074 2075 if (pmd_present(orig_pmd)) { 2076 struct page *page = pmd_page(orig_pmd); 2077 2078 folio = page_folio(page); 2079 folio_remove_rmap_pmd(folio, page, vma); 2080 WARN_ON_ONCE(folio_mapcount(folio) < 0); 2081 VM_BUG_ON_PAGE(!PageHead(page), page); 2082 } else if (thp_migration_supported()) { 2083 swp_entry_t entry; 2084 2085 VM_BUG_ON(!is_pmd_migration_entry(orig_pmd)); 2086 entry = pmd_to_swp_entry(orig_pmd); 2087 folio = pfn_swap_entry_folio(entry); 2088 flush_needed = 0; 2089 } else 2090 WARN_ONCE(1, "Non present huge pmd without pmd migration enabled!"); 2091 2092 if (folio_test_anon(folio)) { 2093 zap_deposited_table(tlb->mm, pmd); 2094 add_mm_counter(tlb->mm, MM_ANONPAGES, -HPAGE_PMD_NR); 2095 } else { 2096 if (arch_needs_pgtable_deposit()) 2097 zap_deposited_table(tlb->mm, pmd); 2098 add_mm_counter(tlb->mm, mm_counter_file(folio), 2099 -HPAGE_PMD_NR); 2100 } 2101 2102 spin_unlock(ptl); 2103 if (flush_needed) 2104 tlb_remove_page_size(tlb, &folio->page, HPAGE_PMD_SIZE); 2105 } 2106 return 1; 2107 } 2108 2109 #ifndef pmd_move_must_withdraw 2110 static inline int pmd_move_must_withdraw(spinlock_t *new_pmd_ptl, 2111 spinlock_t *old_pmd_ptl, 2112 struct vm_area_struct *vma) 2113 { 2114 /* 2115 * With split pmd lock we also need to move preallocated 2116 * PTE page table if new_pmd is on different PMD page table. 2117 * 2118 * We also don't deposit and withdraw tables for file pages. 2119 */ 2120 return (new_pmd_ptl != old_pmd_ptl) && vma_is_anonymous(vma); 2121 } 2122 #endif 2123 2124 static pmd_t move_soft_dirty_pmd(pmd_t pmd) 2125 { 2126 #ifdef CONFIG_MEM_SOFT_DIRTY 2127 if (unlikely(is_pmd_migration_entry(pmd))) 2128 pmd = pmd_swp_mksoft_dirty(pmd); 2129 else if (pmd_present(pmd)) 2130 pmd = pmd_mksoft_dirty(pmd); 2131 #endif 2132 return pmd; 2133 } 2134 2135 bool move_huge_pmd(struct vm_area_struct *vma, unsigned long old_addr, 2136 unsigned long new_addr, pmd_t *old_pmd, pmd_t *new_pmd) 2137 { 2138 spinlock_t *old_ptl, *new_ptl; 2139 pmd_t pmd; 2140 struct mm_struct *mm = vma->vm_mm; 2141 bool force_flush = false; 2142 2143 /* 2144 * The destination pmd shouldn't be established, free_pgtables() 2145 * should have released it; but move_page_tables() might have already 2146 * inserted a page table, if racing against shmem/file collapse. 2147 */ 2148 if (!pmd_none(*new_pmd)) { 2149 VM_BUG_ON(pmd_trans_huge(*new_pmd)); 2150 return false; 2151 } 2152 2153 /* 2154 * We don't have to worry about the ordering of src and dst 2155 * ptlocks because exclusive mmap_lock prevents deadlock. 2156 */ 2157 old_ptl = __pmd_trans_huge_lock(old_pmd, vma); 2158 if (old_ptl) { 2159 new_ptl = pmd_lockptr(mm, new_pmd); 2160 if (new_ptl != old_ptl) 2161 spin_lock_nested(new_ptl, SINGLE_DEPTH_NESTING); 2162 pmd = pmdp_huge_get_and_clear(mm, old_addr, old_pmd); 2163 if (pmd_present(pmd)) 2164 force_flush = true; 2165 VM_BUG_ON(!pmd_none(*new_pmd)); 2166 2167 if (pmd_move_must_withdraw(new_ptl, old_ptl, vma)) { 2168 pgtable_t pgtable; 2169 pgtable = pgtable_trans_huge_withdraw(mm, old_pmd); 2170 pgtable_trans_huge_deposit(mm, new_pmd, pgtable); 2171 } 2172 pmd = move_soft_dirty_pmd(pmd); 2173 set_pmd_at(mm, new_addr, new_pmd, pmd); 2174 if (force_flush) 2175 flush_pmd_tlb_range(vma, old_addr, old_addr + PMD_SIZE); 2176 if (new_ptl != old_ptl) 2177 spin_unlock(new_ptl); 2178 spin_unlock(old_ptl); 2179 return true; 2180 } 2181 return false; 2182 } 2183 2184 /* 2185 * Returns 2186 * - 0 if PMD could not be locked 2187 * - 1 if PMD was locked but protections unchanged and TLB flush unnecessary 2188 * or if prot_numa but THP migration is not supported 2189 * - HPAGE_PMD_NR if protections changed and TLB flush necessary 2190 */ 2191 int change_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, 2192 pmd_t *pmd, unsigned long addr, pgprot_t newprot, 2193 unsigned long cp_flags) 2194 { 2195 struct mm_struct *mm = vma->vm_mm; 2196 spinlock_t *ptl; 2197 pmd_t oldpmd, entry; 2198 bool prot_numa = cp_flags & MM_CP_PROT_NUMA; 2199 bool uffd_wp = cp_flags & MM_CP_UFFD_WP; 2200 bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE; 2201 int ret = 1; 2202 2203 tlb_change_page_size(tlb, HPAGE_PMD_SIZE); 2204 2205 if (prot_numa && !thp_migration_supported()) 2206 return 1; 2207 2208 ptl = __pmd_trans_huge_lock(pmd, vma); 2209 if (!ptl) 2210 return 0; 2211 2212 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION 2213 if (is_swap_pmd(*pmd)) { 2214 swp_entry_t entry = pmd_to_swp_entry(*pmd); 2215 struct folio *folio = pfn_swap_entry_folio(entry); 2216 pmd_t newpmd; 2217 2218 VM_BUG_ON(!is_pmd_migration_entry(*pmd)); 2219 if (is_writable_migration_entry(entry)) { 2220 /* 2221 * A protection check is difficult so 2222 * just be safe and disable write 2223 */ 2224 if (folio_test_anon(folio)) 2225 entry = make_readable_exclusive_migration_entry(swp_offset(entry)); 2226 else 2227 entry = make_readable_migration_entry(swp_offset(entry)); 2228 newpmd = swp_entry_to_pmd(entry); 2229 if (pmd_swp_soft_dirty(*pmd)) 2230 newpmd = pmd_swp_mksoft_dirty(newpmd); 2231 } else { 2232 newpmd = *pmd; 2233 } 2234 2235 if (uffd_wp) 2236 newpmd = pmd_swp_mkuffd_wp(newpmd); 2237 else if (uffd_wp_resolve) 2238 newpmd = pmd_swp_clear_uffd_wp(newpmd); 2239 if (!pmd_same(*pmd, newpmd)) 2240 set_pmd_at(mm, addr, pmd, newpmd); 2241 goto unlock; 2242 } 2243 #endif 2244 2245 if (prot_numa) { 2246 struct folio *folio; 2247 bool toptier; 2248 /* 2249 * Avoid trapping faults against the zero page. The read-only 2250 * data is likely to be read-cached on the local CPU and 2251 * local/remote hits to the zero page are not interesting. 2252 */ 2253 if (is_huge_zero_pmd(*pmd)) 2254 goto unlock; 2255 2256 if (pmd_protnone(*pmd)) 2257 goto unlock; 2258 2259 folio = pmd_folio(*pmd); 2260 toptier = node_is_toptier(folio_nid(folio)); 2261 /* 2262 * Skip scanning top tier node if normal numa 2263 * balancing is disabled 2264 */ 2265 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_NORMAL) && 2266 toptier) 2267 goto unlock; 2268 2269 if (folio_use_access_time(folio)) 2270 folio_xchg_access_time(folio, 2271 jiffies_to_msecs(jiffies)); 2272 } 2273 /* 2274 * In case prot_numa, we are under mmap_read_lock(mm). It's critical 2275 * to not clear pmd intermittently to avoid race with MADV_DONTNEED 2276 * which is also under mmap_read_lock(mm): 2277 * 2278 * CPU0: CPU1: 2279 * change_huge_pmd(prot_numa=1) 2280 * pmdp_huge_get_and_clear_notify() 2281 * madvise_dontneed() 2282 * zap_pmd_range() 2283 * pmd_trans_huge(*pmd) == 0 (without ptl) 2284 * // skip the pmd 2285 * set_pmd_at(); 2286 * // pmd is re-established 2287 * 2288 * The race makes MADV_DONTNEED miss the huge pmd and don't clear it 2289 * which may break userspace. 2290 * 2291 * pmdp_invalidate_ad() is required to make sure we don't miss 2292 * dirty/young flags set by hardware. 2293 */ 2294 oldpmd = pmdp_invalidate_ad(vma, addr, pmd); 2295 2296 entry = pmd_modify(oldpmd, newprot); 2297 if (uffd_wp) 2298 entry = pmd_mkuffd_wp(entry); 2299 else if (uffd_wp_resolve) 2300 /* 2301 * Leave the write bit to be handled by PF interrupt 2302 * handler, then things like COW could be properly 2303 * handled. 2304 */ 2305 entry = pmd_clear_uffd_wp(entry); 2306 2307 /* See change_pte_range(). */ 2308 if ((cp_flags & MM_CP_TRY_CHANGE_WRITABLE) && !pmd_write(entry) && 2309 can_change_pmd_writable(vma, addr, entry)) 2310 entry = pmd_mkwrite(entry, vma); 2311 2312 ret = HPAGE_PMD_NR; 2313 set_pmd_at(mm, addr, pmd, entry); 2314 2315 if (huge_pmd_needs_flush(oldpmd, entry)) 2316 tlb_flush_pmd_range(tlb, addr, HPAGE_PMD_SIZE); 2317 unlock: 2318 spin_unlock(ptl); 2319 return ret; 2320 } 2321 2322 /* 2323 * Returns: 2324 * 2325 * - 0: if pud leaf changed from under us 2326 * - 1: if pud can be skipped 2327 * - HPAGE_PUD_NR: if pud was successfully processed 2328 */ 2329 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD 2330 int change_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma, 2331 pud_t *pudp, unsigned long addr, pgprot_t newprot, 2332 unsigned long cp_flags) 2333 { 2334 struct mm_struct *mm = vma->vm_mm; 2335 pud_t oldpud, entry; 2336 spinlock_t *ptl; 2337 2338 tlb_change_page_size(tlb, HPAGE_PUD_SIZE); 2339 2340 /* NUMA balancing doesn't apply to dax */ 2341 if (cp_flags & MM_CP_PROT_NUMA) 2342 return 1; 2343 2344 /* 2345 * Huge entries on userfault-wp only works with anonymous, while we 2346 * don't have anonymous PUDs yet. 2347 */ 2348 if (WARN_ON_ONCE(cp_flags & MM_CP_UFFD_WP_ALL)) 2349 return 1; 2350 2351 ptl = __pud_trans_huge_lock(pudp, vma); 2352 if (!ptl) 2353 return 0; 2354 2355 /* 2356 * Can't clear PUD or it can race with concurrent zapping. See 2357 * change_huge_pmd(). 2358 */ 2359 oldpud = pudp_invalidate(vma, addr, pudp); 2360 entry = pud_modify(oldpud, newprot); 2361 set_pud_at(mm, addr, pudp, entry); 2362 tlb_flush_pud_range(tlb, addr, HPAGE_PUD_SIZE); 2363 2364 spin_unlock(ptl); 2365 return HPAGE_PUD_NR; 2366 } 2367 #endif 2368 2369 #ifdef CONFIG_USERFAULTFD 2370 /* 2371 * The PT lock for src_pmd and dst_vma/src_vma (for reading) are locked by 2372 * the caller, but it must return after releasing the page_table_lock. 2373 * Just move the page from src_pmd to dst_pmd if possible. 2374 * Return zero if succeeded in moving the page, -EAGAIN if it needs to be 2375 * repeated by the caller, or other errors in case of failure. 2376 */ 2377 int move_pages_huge_pmd(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd, pmd_t dst_pmdval, 2378 struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma, 2379 unsigned long dst_addr, unsigned long src_addr) 2380 { 2381 pmd_t _dst_pmd, src_pmdval; 2382 struct page *src_page; 2383 struct folio *src_folio; 2384 struct anon_vma *src_anon_vma; 2385 spinlock_t *src_ptl, *dst_ptl; 2386 pgtable_t src_pgtable; 2387 struct mmu_notifier_range range; 2388 int err = 0; 2389 2390 src_pmdval = *src_pmd; 2391 src_ptl = pmd_lockptr(mm, src_pmd); 2392 2393 lockdep_assert_held(src_ptl); 2394 vma_assert_locked(src_vma); 2395 vma_assert_locked(dst_vma); 2396 2397 /* Sanity checks before the operation */ 2398 if (WARN_ON_ONCE(!pmd_none(dst_pmdval)) || WARN_ON_ONCE(src_addr & ~HPAGE_PMD_MASK) || 2399 WARN_ON_ONCE(dst_addr & ~HPAGE_PMD_MASK)) { 2400 spin_unlock(src_ptl); 2401 return -EINVAL; 2402 } 2403 2404 if (!pmd_trans_huge(src_pmdval)) { 2405 spin_unlock(src_ptl); 2406 if (is_pmd_migration_entry(src_pmdval)) { 2407 pmd_migration_entry_wait(mm, &src_pmdval); 2408 return -EAGAIN; 2409 } 2410 return -ENOENT; 2411 } 2412 2413 src_page = pmd_page(src_pmdval); 2414 2415 if (!is_huge_zero_pmd(src_pmdval)) { 2416 if (unlikely(!PageAnonExclusive(src_page))) { 2417 spin_unlock(src_ptl); 2418 return -EBUSY; 2419 } 2420 2421 src_folio = page_folio(src_page); 2422 folio_get(src_folio); 2423 } else 2424 src_folio = NULL; 2425 2426 spin_unlock(src_ptl); 2427 2428 flush_cache_range(src_vma, src_addr, src_addr + HPAGE_PMD_SIZE); 2429 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, src_addr, 2430 src_addr + HPAGE_PMD_SIZE); 2431 mmu_notifier_invalidate_range_start(&range); 2432 2433 if (src_folio) { 2434 folio_lock(src_folio); 2435 2436 /* 2437 * split_huge_page walks the anon_vma chain without the page 2438 * lock. Serialize against it with the anon_vma lock, the page 2439 * lock is not enough. 2440 */ 2441 src_anon_vma = folio_get_anon_vma(src_folio); 2442 if (!src_anon_vma) { 2443 err = -EAGAIN; 2444 goto unlock_folio; 2445 } 2446 anon_vma_lock_write(src_anon_vma); 2447 } else 2448 src_anon_vma = NULL; 2449 2450 dst_ptl = pmd_lockptr(mm, dst_pmd); 2451 double_pt_lock(src_ptl, dst_ptl); 2452 if (unlikely(!pmd_same(*src_pmd, src_pmdval) || 2453 !pmd_same(*dst_pmd, dst_pmdval))) { 2454 err = -EAGAIN; 2455 goto unlock_ptls; 2456 } 2457 if (src_folio) { 2458 if (folio_maybe_dma_pinned(src_folio) || 2459 !PageAnonExclusive(&src_folio->page)) { 2460 err = -EBUSY; 2461 goto unlock_ptls; 2462 } 2463 2464 if (WARN_ON_ONCE(!folio_test_head(src_folio)) || 2465 WARN_ON_ONCE(!folio_test_anon(src_folio))) { 2466 err = -EBUSY; 2467 goto unlock_ptls; 2468 } 2469 2470 src_pmdval = pmdp_huge_clear_flush(src_vma, src_addr, src_pmd); 2471 /* Folio got pinned from under us. Put it back and fail the move. */ 2472 if (folio_maybe_dma_pinned(src_folio)) { 2473 set_pmd_at(mm, src_addr, src_pmd, src_pmdval); 2474 err = -EBUSY; 2475 goto unlock_ptls; 2476 } 2477 2478 folio_move_anon_rmap(src_folio, dst_vma); 2479 src_folio->index = linear_page_index(dst_vma, dst_addr); 2480 2481 _dst_pmd = mk_huge_pmd(&src_folio->page, dst_vma->vm_page_prot); 2482 /* Follow mremap() behavior and treat the entry dirty after the move */ 2483 _dst_pmd = pmd_mkwrite(pmd_mkdirty(_dst_pmd), dst_vma); 2484 } else { 2485 src_pmdval = pmdp_huge_clear_flush(src_vma, src_addr, src_pmd); 2486 _dst_pmd = mk_huge_pmd(src_page, dst_vma->vm_page_prot); 2487 } 2488 set_pmd_at(mm, dst_addr, dst_pmd, _dst_pmd); 2489 2490 src_pgtable = pgtable_trans_huge_withdraw(mm, src_pmd); 2491 pgtable_trans_huge_deposit(mm, dst_pmd, src_pgtable); 2492 unlock_ptls: 2493 double_pt_unlock(src_ptl, dst_ptl); 2494 if (src_anon_vma) { 2495 anon_vma_unlock_write(src_anon_vma); 2496 put_anon_vma(src_anon_vma); 2497 } 2498 unlock_folio: 2499 /* unblock rmap walks */ 2500 if (src_folio) 2501 folio_unlock(src_folio); 2502 mmu_notifier_invalidate_range_end(&range); 2503 if (src_folio) 2504 folio_put(src_folio); 2505 return err; 2506 } 2507 #endif /* CONFIG_USERFAULTFD */ 2508 2509 /* 2510 * Returns page table lock pointer if a given pmd maps a thp, NULL otherwise. 2511 * 2512 * Note that if it returns page table lock pointer, this routine returns without 2513 * unlocking page table lock. So callers must unlock it. 2514 */ 2515 spinlock_t *__pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma) 2516 { 2517 spinlock_t *ptl; 2518 ptl = pmd_lock(vma->vm_mm, pmd); 2519 if (likely(is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || 2520 pmd_devmap(*pmd))) 2521 return ptl; 2522 spin_unlock(ptl); 2523 return NULL; 2524 } 2525 2526 /* 2527 * Returns page table lock pointer if a given pud maps a thp, NULL otherwise. 2528 * 2529 * Note that if it returns page table lock pointer, this routine returns without 2530 * unlocking page table lock. So callers must unlock it. 2531 */ 2532 spinlock_t *__pud_trans_huge_lock(pud_t *pud, struct vm_area_struct *vma) 2533 { 2534 spinlock_t *ptl; 2535 2536 ptl = pud_lock(vma->vm_mm, pud); 2537 if (likely(pud_trans_huge(*pud) || pud_devmap(*pud))) 2538 return ptl; 2539 spin_unlock(ptl); 2540 return NULL; 2541 } 2542 2543 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD 2544 int zap_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma, 2545 pud_t *pud, unsigned long addr) 2546 { 2547 spinlock_t *ptl; 2548 pud_t orig_pud; 2549 2550 ptl = __pud_trans_huge_lock(pud, vma); 2551 if (!ptl) 2552 return 0; 2553 2554 orig_pud = pudp_huge_get_and_clear_full(vma, addr, pud, tlb->fullmm); 2555 arch_check_zapped_pud(vma, orig_pud); 2556 tlb_remove_pud_tlb_entry(tlb, pud, addr); 2557 if (vma_is_special_huge(vma)) { 2558 spin_unlock(ptl); 2559 /* No zero page support yet */ 2560 } else { 2561 /* No support for anonymous PUD pages yet */ 2562 BUG(); 2563 } 2564 return 1; 2565 } 2566 2567 static void __split_huge_pud_locked(struct vm_area_struct *vma, pud_t *pud, 2568 unsigned long haddr) 2569 { 2570 VM_BUG_ON(haddr & ~HPAGE_PUD_MASK); 2571 VM_BUG_ON_VMA(vma->vm_start > haddr, vma); 2572 VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PUD_SIZE, vma); 2573 VM_BUG_ON(!pud_trans_huge(*pud) && !pud_devmap(*pud)); 2574 2575 count_vm_event(THP_SPLIT_PUD); 2576 2577 pudp_huge_clear_flush(vma, haddr, pud); 2578 } 2579 2580 void __split_huge_pud(struct vm_area_struct *vma, pud_t *pud, 2581 unsigned long address) 2582 { 2583 spinlock_t *ptl; 2584 struct mmu_notifier_range range; 2585 2586 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm, 2587 address & HPAGE_PUD_MASK, 2588 (address & HPAGE_PUD_MASK) + HPAGE_PUD_SIZE); 2589 mmu_notifier_invalidate_range_start(&range); 2590 ptl = pud_lock(vma->vm_mm, pud); 2591 if (unlikely(!pud_trans_huge(*pud) && !pud_devmap(*pud))) 2592 goto out; 2593 __split_huge_pud_locked(vma, pud, range.start); 2594 2595 out: 2596 spin_unlock(ptl); 2597 mmu_notifier_invalidate_range_end(&range); 2598 } 2599 #else 2600 void __split_huge_pud(struct vm_area_struct *vma, pud_t *pud, 2601 unsigned long address) 2602 { 2603 } 2604 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */ 2605 2606 static void __split_huge_zero_page_pmd(struct vm_area_struct *vma, 2607 unsigned long haddr, pmd_t *pmd) 2608 { 2609 struct mm_struct *mm = vma->vm_mm; 2610 pgtable_t pgtable; 2611 pmd_t _pmd, old_pmd; 2612 unsigned long addr; 2613 pte_t *pte; 2614 int i; 2615 2616 /* 2617 * Leave pmd empty until pte is filled note that it is fine to delay 2618 * notification until mmu_notifier_invalidate_range_end() as we are 2619 * replacing a zero pmd write protected page with a zero pte write 2620 * protected page. 2621 * 2622 * See Documentation/mm/mmu_notifier.rst 2623 */ 2624 old_pmd = pmdp_huge_clear_flush(vma, haddr, pmd); 2625 2626 pgtable = pgtable_trans_huge_withdraw(mm, pmd); 2627 pmd_populate(mm, &_pmd, pgtable); 2628 2629 pte = pte_offset_map(&_pmd, haddr); 2630 VM_BUG_ON(!pte); 2631 for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) { 2632 pte_t entry; 2633 2634 entry = pfn_pte(my_zero_pfn(addr), vma->vm_page_prot); 2635 entry = pte_mkspecial(entry); 2636 if (pmd_uffd_wp(old_pmd)) 2637 entry = pte_mkuffd_wp(entry); 2638 VM_BUG_ON(!pte_none(ptep_get(pte))); 2639 set_pte_at(mm, addr, pte, entry); 2640 pte++; 2641 } 2642 pte_unmap(pte - 1); 2643 smp_wmb(); /* make pte visible before pmd */ 2644 pmd_populate(mm, pmd, pgtable); 2645 } 2646 2647 static void __split_huge_pmd_locked(struct vm_area_struct *vma, pmd_t *pmd, 2648 unsigned long haddr, bool freeze) 2649 { 2650 struct mm_struct *mm = vma->vm_mm; 2651 struct folio *folio; 2652 struct page *page; 2653 pgtable_t pgtable; 2654 pmd_t old_pmd, _pmd; 2655 bool young, write, soft_dirty, pmd_migration = false, uffd_wp = false; 2656 bool anon_exclusive = false, dirty = false; 2657 unsigned long addr; 2658 pte_t *pte; 2659 int i; 2660 2661 VM_BUG_ON(haddr & ~HPAGE_PMD_MASK); 2662 VM_BUG_ON_VMA(vma->vm_start > haddr, vma); 2663 VM_BUG_ON_VMA(vma->vm_end < haddr + HPAGE_PMD_SIZE, vma); 2664 VM_BUG_ON(!is_pmd_migration_entry(*pmd) && !pmd_trans_huge(*pmd) 2665 && !pmd_devmap(*pmd)); 2666 2667 count_vm_event(THP_SPLIT_PMD); 2668 2669 if (!vma_is_anonymous(vma)) { 2670 old_pmd = pmdp_huge_clear_flush(vma, haddr, pmd); 2671 /* 2672 * We are going to unmap this huge page. So 2673 * just go ahead and zap it 2674 */ 2675 if (arch_needs_pgtable_deposit()) 2676 zap_deposited_table(mm, pmd); 2677 if (vma_is_special_huge(vma)) 2678 return; 2679 if (unlikely(is_pmd_migration_entry(old_pmd))) { 2680 swp_entry_t entry; 2681 2682 entry = pmd_to_swp_entry(old_pmd); 2683 folio = pfn_swap_entry_folio(entry); 2684 } else { 2685 page = pmd_page(old_pmd); 2686 folio = page_folio(page); 2687 if (!folio_test_dirty(folio) && pmd_dirty(old_pmd)) 2688 folio_mark_dirty(folio); 2689 if (!folio_test_referenced(folio) && pmd_young(old_pmd)) 2690 folio_set_referenced(folio); 2691 folio_remove_rmap_pmd(folio, page, vma); 2692 folio_put(folio); 2693 } 2694 add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR); 2695 return; 2696 } 2697 2698 if (is_huge_zero_pmd(*pmd)) { 2699 /* 2700 * FIXME: Do we want to invalidate secondary mmu by calling 2701 * mmu_notifier_arch_invalidate_secondary_tlbs() see comments below 2702 * inside __split_huge_pmd() ? 2703 * 2704 * We are going from a zero huge page write protected to zero 2705 * small page also write protected so it does not seems useful 2706 * to invalidate secondary mmu at this time. 2707 */ 2708 return __split_huge_zero_page_pmd(vma, haddr, pmd); 2709 } 2710 2711 pmd_migration = is_pmd_migration_entry(*pmd); 2712 if (unlikely(pmd_migration)) { 2713 swp_entry_t entry; 2714 2715 old_pmd = *pmd; 2716 entry = pmd_to_swp_entry(old_pmd); 2717 page = pfn_swap_entry_to_page(entry); 2718 write = is_writable_migration_entry(entry); 2719 if (PageAnon(page)) 2720 anon_exclusive = is_readable_exclusive_migration_entry(entry); 2721 young = is_migration_entry_young(entry); 2722 dirty = is_migration_entry_dirty(entry); 2723 soft_dirty = pmd_swp_soft_dirty(old_pmd); 2724 uffd_wp = pmd_swp_uffd_wp(old_pmd); 2725 } else { 2726 /* 2727 * Up to this point the pmd is present and huge and userland has 2728 * the whole access to the hugepage during the split (which 2729 * happens in place). If we overwrite the pmd with the not-huge 2730 * version pointing to the pte here (which of course we could if 2731 * all CPUs were bug free), userland could trigger a small page 2732 * size TLB miss on the small sized TLB while the hugepage TLB 2733 * entry is still established in the huge TLB. Some CPU doesn't 2734 * like that. See 2735 * http://support.amd.com/TechDocs/41322_10h_Rev_Gd.pdf, Erratum 2736 * 383 on page 105. Intel should be safe but is also warns that 2737 * it's only safe if the permission and cache attributes of the 2738 * two entries loaded in the two TLB is identical (which should 2739 * be the case here). But it is generally safer to never allow 2740 * small and huge TLB entries for the same virtual address to be 2741 * loaded simultaneously. So instead of doing "pmd_populate(); 2742 * flush_pmd_tlb_range();" we first mark the current pmd 2743 * notpresent (atomically because here the pmd_trans_huge must 2744 * remain set at all times on the pmd until the split is 2745 * complete for this pmd), then we flush the SMP TLB and finally 2746 * we write the non-huge version of the pmd entry with 2747 * pmd_populate. 2748 */ 2749 old_pmd = pmdp_invalidate(vma, haddr, pmd); 2750 page = pmd_page(old_pmd); 2751 folio = page_folio(page); 2752 if (pmd_dirty(old_pmd)) { 2753 dirty = true; 2754 folio_set_dirty(folio); 2755 } 2756 write = pmd_write(old_pmd); 2757 young = pmd_young(old_pmd); 2758 soft_dirty = pmd_soft_dirty(old_pmd); 2759 uffd_wp = pmd_uffd_wp(old_pmd); 2760 2761 VM_WARN_ON_FOLIO(!folio_ref_count(folio), folio); 2762 VM_WARN_ON_FOLIO(!folio_test_anon(folio), folio); 2763 2764 /* 2765 * Without "freeze", we'll simply split the PMD, propagating the 2766 * PageAnonExclusive() flag for each PTE by setting it for 2767 * each subpage -- no need to (temporarily) clear. 2768 * 2769 * With "freeze" we want to replace mapped pages by 2770 * migration entries right away. This is only possible if we 2771 * managed to clear PageAnonExclusive() -- see 2772 * set_pmd_migration_entry(). 2773 * 2774 * In case we cannot clear PageAnonExclusive(), split the PMD 2775 * only and let try_to_migrate_one() fail later. 2776 * 2777 * See folio_try_share_anon_rmap_pmd(): invalidate PMD first. 2778 */ 2779 anon_exclusive = PageAnonExclusive(page); 2780 if (freeze && anon_exclusive && 2781 folio_try_share_anon_rmap_pmd(folio, page)) 2782 freeze = false; 2783 if (!freeze) { 2784 rmap_t rmap_flags = RMAP_NONE; 2785 2786 folio_ref_add(folio, HPAGE_PMD_NR - 1); 2787 if (anon_exclusive) 2788 rmap_flags |= RMAP_EXCLUSIVE; 2789 folio_add_anon_rmap_ptes(folio, page, HPAGE_PMD_NR, 2790 vma, haddr, rmap_flags); 2791 } 2792 } 2793 2794 /* 2795 * Withdraw the table only after we mark the pmd entry invalid. 2796 * This's critical for some architectures (Power). 2797 */ 2798 pgtable = pgtable_trans_huge_withdraw(mm, pmd); 2799 pmd_populate(mm, &_pmd, pgtable); 2800 2801 pte = pte_offset_map(&_pmd, haddr); 2802 VM_BUG_ON(!pte); 2803 2804 /* 2805 * Note that NUMA hinting access restrictions are not transferred to 2806 * avoid any possibility of altering permissions across VMAs. 2807 */ 2808 if (freeze || pmd_migration) { 2809 for (i = 0, addr = haddr; i < HPAGE_PMD_NR; i++, addr += PAGE_SIZE) { 2810 pte_t entry; 2811 swp_entry_t swp_entry; 2812 2813 if (write) 2814 swp_entry = make_writable_migration_entry( 2815 page_to_pfn(page + i)); 2816 else if (anon_exclusive) 2817 swp_entry = make_readable_exclusive_migration_entry( 2818 page_to_pfn(page + i)); 2819 else 2820 swp_entry = make_readable_migration_entry( 2821 page_to_pfn(page + i)); 2822 if (young) 2823 swp_entry = make_migration_entry_young(swp_entry); 2824 if (dirty) 2825 swp_entry = make_migration_entry_dirty(swp_entry); 2826 entry = swp_entry_to_pte(swp_entry); 2827 if (soft_dirty) 2828 entry = pte_swp_mksoft_dirty(entry); 2829 if (uffd_wp) 2830 entry = pte_swp_mkuffd_wp(entry); 2831 2832 VM_WARN_ON(!pte_none(ptep_get(pte + i))); 2833 set_pte_at(mm, addr, pte + i, entry); 2834 } 2835 } else { 2836 pte_t entry; 2837 2838 entry = mk_pte(page, READ_ONCE(vma->vm_page_prot)); 2839 if (write) 2840 entry = pte_mkwrite(entry, vma); 2841 if (!young) 2842 entry = pte_mkold(entry); 2843 /* NOTE: this may set soft-dirty too on some archs */ 2844 if (dirty) 2845 entry = pte_mkdirty(entry); 2846 if (soft_dirty) 2847 entry = pte_mksoft_dirty(entry); 2848 if (uffd_wp) 2849 entry = pte_mkuffd_wp(entry); 2850 2851 for (i = 0; i < HPAGE_PMD_NR; i++) 2852 VM_WARN_ON(!pte_none(ptep_get(pte + i))); 2853 2854 set_ptes(mm, haddr, pte, entry, HPAGE_PMD_NR); 2855 } 2856 pte_unmap(pte); 2857 2858 if (!pmd_migration) 2859 folio_remove_rmap_pmd(folio, page, vma); 2860 if (freeze) 2861 put_page(page); 2862 2863 smp_wmb(); /* make pte visible before pmd */ 2864 pmd_populate(mm, pmd, pgtable); 2865 } 2866 2867 void split_huge_pmd_locked(struct vm_area_struct *vma, unsigned long address, 2868 pmd_t *pmd, bool freeze, struct folio *folio) 2869 { 2870 VM_WARN_ON_ONCE(folio && !folio_test_pmd_mappable(folio)); 2871 VM_WARN_ON_ONCE(!IS_ALIGNED(address, HPAGE_PMD_SIZE)); 2872 VM_WARN_ON_ONCE(folio && !folio_test_locked(folio)); 2873 VM_BUG_ON(freeze && !folio); 2874 2875 /* 2876 * When the caller requests to set up a migration entry, we 2877 * require a folio to check the PMD against. Otherwise, there 2878 * is a risk of replacing the wrong folio. 2879 */ 2880 if (pmd_trans_huge(*pmd) || pmd_devmap(*pmd) || 2881 is_pmd_migration_entry(*pmd)) { 2882 if (folio && folio != pmd_folio(*pmd)) 2883 return; 2884 __split_huge_pmd_locked(vma, pmd, address, freeze); 2885 } 2886 } 2887 2888 void __split_huge_pmd(struct vm_area_struct *vma, pmd_t *pmd, 2889 unsigned long address, bool freeze, struct folio *folio) 2890 { 2891 spinlock_t *ptl; 2892 struct mmu_notifier_range range; 2893 2894 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm, 2895 address & HPAGE_PMD_MASK, 2896 (address & HPAGE_PMD_MASK) + HPAGE_PMD_SIZE); 2897 mmu_notifier_invalidate_range_start(&range); 2898 ptl = pmd_lock(vma->vm_mm, pmd); 2899 split_huge_pmd_locked(vma, range.start, pmd, freeze, folio); 2900 spin_unlock(ptl); 2901 mmu_notifier_invalidate_range_end(&range); 2902 } 2903 2904 void split_huge_pmd_address(struct vm_area_struct *vma, unsigned long address, 2905 bool freeze, struct folio *folio) 2906 { 2907 pmd_t *pmd = mm_find_pmd(vma->vm_mm, address); 2908 2909 if (!pmd) 2910 return; 2911 2912 __split_huge_pmd(vma, pmd, address, freeze, folio); 2913 } 2914 2915 static inline void split_huge_pmd_if_needed(struct vm_area_struct *vma, unsigned long address) 2916 { 2917 /* 2918 * If the new address isn't hpage aligned and it could previously 2919 * contain an hugepage: check if we need to split an huge pmd. 2920 */ 2921 if (!IS_ALIGNED(address, HPAGE_PMD_SIZE) && 2922 range_in_vma(vma, ALIGN_DOWN(address, HPAGE_PMD_SIZE), 2923 ALIGN(address, HPAGE_PMD_SIZE))) 2924 split_huge_pmd_address(vma, address, false, NULL); 2925 } 2926 2927 void vma_adjust_trans_huge(struct vm_area_struct *vma, 2928 unsigned long start, 2929 unsigned long end, 2930 long adjust_next) 2931 { 2932 /* Check if we need to split start first. */ 2933 split_huge_pmd_if_needed(vma, start); 2934 2935 /* Check if we need to split end next. */ 2936 split_huge_pmd_if_needed(vma, end); 2937 2938 /* 2939 * If we're also updating the next vma vm_start, 2940 * check if we need to split it. 2941 */ 2942 if (adjust_next > 0) { 2943 struct vm_area_struct *next = find_vma(vma->vm_mm, vma->vm_end); 2944 unsigned long nstart = next->vm_start; 2945 nstart += adjust_next; 2946 split_huge_pmd_if_needed(next, nstart); 2947 } 2948 } 2949 2950 static void unmap_folio(struct folio *folio) 2951 { 2952 enum ttu_flags ttu_flags = TTU_RMAP_LOCKED | TTU_SYNC | 2953 TTU_BATCH_FLUSH; 2954 2955 VM_BUG_ON_FOLIO(!folio_test_large(folio), folio); 2956 2957 if (folio_test_pmd_mappable(folio)) 2958 ttu_flags |= TTU_SPLIT_HUGE_PMD; 2959 2960 /* 2961 * Anon pages need migration entries to preserve them, but file 2962 * pages can simply be left unmapped, then faulted back on demand. 2963 * If that is ever changed (perhaps for mlock), update remap_page(). 2964 */ 2965 if (folio_test_anon(folio)) 2966 try_to_migrate(folio, ttu_flags); 2967 else 2968 try_to_unmap(folio, ttu_flags | TTU_IGNORE_MLOCK); 2969 2970 try_to_unmap_flush(); 2971 } 2972 2973 static bool __discard_anon_folio_pmd_locked(struct vm_area_struct *vma, 2974 unsigned long addr, pmd_t *pmdp, 2975 struct folio *folio) 2976 { 2977 struct mm_struct *mm = vma->vm_mm; 2978 int ref_count, map_count; 2979 pmd_t orig_pmd = *pmdp; 2980 2981 if (folio_test_dirty(folio) || pmd_dirty(orig_pmd)) 2982 return false; 2983 2984 orig_pmd = pmdp_huge_clear_flush(vma, addr, pmdp); 2985 2986 /* 2987 * Syncing against concurrent GUP-fast: 2988 * - clear PMD; barrier; read refcount 2989 * - inc refcount; barrier; read PMD 2990 */ 2991 smp_mb(); 2992 2993 ref_count = folio_ref_count(folio); 2994 map_count = folio_mapcount(folio); 2995 2996 /* 2997 * Order reads for folio refcount and dirty flag 2998 * (see comments in __remove_mapping()). 2999 */ 3000 smp_rmb(); 3001 3002 /* 3003 * If the folio or its PMD is redirtied at this point, or if there 3004 * are unexpected references, we will give up to discard this folio 3005 * and remap it. 3006 * 3007 * The only folio refs must be one from isolation plus the rmap(s). 3008 */ 3009 if (folio_test_dirty(folio) || pmd_dirty(orig_pmd) || 3010 ref_count != map_count + 1) { 3011 set_pmd_at(mm, addr, pmdp, orig_pmd); 3012 return false; 3013 } 3014 3015 folio_remove_rmap_pmd(folio, pmd_page(orig_pmd), vma); 3016 zap_deposited_table(mm, pmdp); 3017 add_mm_counter(mm, MM_ANONPAGES, -HPAGE_PMD_NR); 3018 if (vma->vm_flags & VM_LOCKED) 3019 mlock_drain_local(); 3020 folio_put(folio); 3021 3022 return true; 3023 } 3024 3025 bool unmap_huge_pmd_locked(struct vm_area_struct *vma, unsigned long addr, 3026 pmd_t *pmdp, struct folio *folio) 3027 { 3028 VM_WARN_ON_FOLIO(!folio_test_pmd_mappable(folio), folio); 3029 VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio); 3030 VM_WARN_ON_ONCE(!IS_ALIGNED(addr, HPAGE_PMD_SIZE)); 3031 3032 if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) 3033 return __discard_anon_folio_pmd_locked(vma, addr, pmdp, folio); 3034 3035 return false; 3036 } 3037 3038 static void remap_page(struct folio *folio, unsigned long nr, int flags) 3039 { 3040 int i = 0; 3041 3042 /* If unmap_folio() uses try_to_migrate() on file, remove this check */ 3043 if (!folio_test_anon(folio)) 3044 return; 3045 for (;;) { 3046 remove_migration_ptes(folio, folio, RMP_LOCKED | flags); 3047 i += folio_nr_pages(folio); 3048 if (i >= nr) 3049 break; 3050 folio = folio_next(folio); 3051 } 3052 } 3053 3054 static void lru_add_page_tail(struct folio *folio, struct page *tail, 3055 struct lruvec *lruvec, struct list_head *list) 3056 { 3057 VM_BUG_ON_FOLIO(!folio_test_large(folio), folio); 3058 VM_BUG_ON_FOLIO(PageLRU(tail), folio); 3059 lockdep_assert_held(&lruvec->lru_lock); 3060 3061 if (list) { 3062 /* page reclaim is reclaiming a huge page */ 3063 VM_WARN_ON(folio_test_lru(folio)); 3064 get_page(tail); 3065 list_add_tail(&tail->lru, list); 3066 } else { 3067 /* head is still on lru (and we have it frozen) */ 3068 VM_WARN_ON(!folio_test_lru(folio)); 3069 if (folio_test_unevictable(folio)) 3070 tail->mlock_count = 0; 3071 else 3072 list_add_tail(&tail->lru, &folio->lru); 3073 SetPageLRU(tail); 3074 } 3075 } 3076 3077 static void __split_huge_page_tail(struct folio *folio, int tail, 3078 struct lruvec *lruvec, struct list_head *list, 3079 unsigned int new_order) 3080 { 3081 struct page *head = &folio->page; 3082 struct page *page_tail = head + tail; 3083 /* 3084 * Careful: new_folio is not a "real" folio before we cleared PageTail. 3085 * Don't pass it around before clear_compound_head(). 3086 */ 3087 struct folio *new_folio = (struct folio *)page_tail; 3088 3089 VM_BUG_ON_PAGE(atomic_read(&page_tail->_mapcount) != -1, page_tail); 3090 3091 /* 3092 * Clone page flags before unfreezing refcount. 3093 * 3094 * After successful get_page_unless_zero() might follow flags change, 3095 * for example lock_page() which set PG_waiters. 3096 * 3097 * Note that for mapped sub-pages of an anonymous THP, 3098 * PG_anon_exclusive has been cleared in unmap_folio() and is stored in 3099 * the migration entry instead from where remap_page() will restore it. 3100 * We can still have PG_anon_exclusive set on effectively unmapped and 3101 * unreferenced sub-pages of an anonymous THP: we can simply drop 3102 * PG_anon_exclusive (-> PG_mappedtodisk) for these here. 3103 */ 3104 page_tail->flags &= ~PAGE_FLAGS_CHECK_AT_PREP; 3105 page_tail->flags |= (head->flags & 3106 ((1L << PG_referenced) | 3107 (1L << PG_swapbacked) | 3108 (1L << PG_swapcache) | 3109 (1L << PG_mlocked) | 3110 (1L << PG_uptodate) | 3111 (1L << PG_active) | 3112 (1L << PG_workingset) | 3113 (1L << PG_locked) | 3114 (1L << PG_unevictable) | 3115 #ifdef CONFIG_ARCH_USES_PG_ARCH_2 3116 (1L << PG_arch_2) | 3117 #endif 3118 #ifdef CONFIG_ARCH_USES_PG_ARCH_3 3119 (1L << PG_arch_3) | 3120 #endif 3121 (1L << PG_dirty) | 3122 LRU_GEN_MASK | LRU_REFS_MASK)); 3123 3124 /* ->mapping in first and second tail page is replaced by other uses */ 3125 VM_BUG_ON_PAGE(tail > 2 && page_tail->mapping != TAIL_MAPPING, 3126 page_tail); 3127 page_tail->mapping = head->mapping; 3128 page_tail->index = head->index + tail; 3129 3130 /* 3131 * page->private should not be set in tail pages. Fix up and warn once 3132 * if private is unexpectedly set. 3133 */ 3134 if (unlikely(page_tail->private)) { 3135 VM_WARN_ON_ONCE_PAGE(true, page_tail); 3136 page_tail->private = 0; 3137 } 3138 if (folio_test_swapcache(folio)) 3139 new_folio->swap.val = folio->swap.val + tail; 3140 3141 /* Page flags must be visible before we make the page non-compound. */ 3142 smp_wmb(); 3143 3144 /* 3145 * Clear PageTail before unfreezing page refcount. 3146 * 3147 * After successful get_page_unless_zero() might follow put_page() 3148 * which needs correct compound_head(). 3149 */ 3150 clear_compound_head(page_tail); 3151 if (new_order) { 3152 prep_compound_page(page_tail, new_order); 3153 folio_set_large_rmappable(new_folio); 3154 } 3155 3156 /* Finally unfreeze refcount. Additional reference from page cache. */ 3157 page_ref_unfreeze(page_tail, 3158 1 + ((!folio_test_anon(folio) || folio_test_swapcache(folio)) ? 3159 folio_nr_pages(new_folio) : 0)); 3160 3161 if (folio_test_young(folio)) 3162 folio_set_young(new_folio); 3163 if (folio_test_idle(folio)) 3164 folio_set_idle(new_folio); 3165 3166 folio_xchg_last_cpupid(new_folio, folio_last_cpupid(folio)); 3167 3168 /* 3169 * always add to the tail because some iterators expect new 3170 * pages to show after the currently processed elements - e.g. 3171 * migrate_pages 3172 */ 3173 lru_add_page_tail(folio, page_tail, lruvec, list); 3174 } 3175 3176 static void __split_huge_page(struct page *page, struct list_head *list, 3177 pgoff_t end, unsigned int new_order) 3178 { 3179 struct folio *folio = page_folio(page); 3180 struct page *head = &folio->page; 3181 struct lruvec *lruvec; 3182 struct address_space *swap_cache = NULL; 3183 unsigned long offset = 0; 3184 int i, nr_dropped = 0; 3185 unsigned int new_nr = 1 << new_order; 3186 int order = folio_order(folio); 3187 unsigned int nr = 1 << order; 3188 3189 /* complete memcg works before add pages to LRU */ 3190 split_page_memcg(head, order, new_order); 3191 3192 if (folio_test_anon(folio) && folio_test_swapcache(folio)) { 3193 offset = swap_cache_index(folio->swap); 3194 swap_cache = swap_address_space(folio->swap); 3195 xa_lock(&swap_cache->i_pages); 3196 } 3197 3198 /* lock lru list/PageCompound, ref frozen by page_ref_freeze */ 3199 lruvec = folio_lruvec_lock(folio); 3200 3201 ClearPageHasHWPoisoned(head); 3202 3203 for (i = nr - new_nr; i >= new_nr; i -= new_nr) { 3204 __split_huge_page_tail(folio, i, lruvec, list, new_order); 3205 /* Some pages can be beyond EOF: drop them from page cache */ 3206 if (head[i].index >= end) { 3207 struct folio *tail = page_folio(head + i); 3208 3209 if (shmem_mapping(folio->mapping)) 3210 nr_dropped++; 3211 else if (folio_test_clear_dirty(tail)) 3212 folio_account_cleaned(tail, 3213 inode_to_wb(folio->mapping->host)); 3214 __filemap_remove_folio(tail, NULL); 3215 folio_put(tail); 3216 } else if (!PageAnon(page)) { 3217 __xa_store(&folio->mapping->i_pages, head[i].index, 3218 head + i, 0); 3219 } else if (swap_cache) { 3220 __xa_store(&swap_cache->i_pages, offset + i, 3221 head + i, 0); 3222 } 3223 } 3224 3225 if (!new_order) 3226 ClearPageCompound(head); 3227 else { 3228 struct folio *new_folio = (struct folio *)head; 3229 3230 folio_set_order(new_folio, new_order); 3231 } 3232 unlock_page_lruvec(lruvec); 3233 /* Caller disabled irqs, so they are still disabled here */ 3234 3235 split_page_owner(head, order, new_order); 3236 pgalloc_tag_split(folio, order, new_order); 3237 3238 /* See comment in __split_huge_page_tail() */ 3239 if (folio_test_anon(folio)) { 3240 /* Additional pin to swap cache */ 3241 if (folio_test_swapcache(folio)) { 3242 folio_ref_add(folio, 1 + new_nr); 3243 xa_unlock(&swap_cache->i_pages); 3244 } else { 3245 folio_ref_inc(folio); 3246 } 3247 } else { 3248 /* Additional pin to page cache */ 3249 folio_ref_add(folio, 1 + new_nr); 3250 xa_unlock(&folio->mapping->i_pages); 3251 } 3252 local_irq_enable(); 3253 3254 if (nr_dropped) 3255 shmem_uncharge(folio->mapping->host, nr_dropped); 3256 remap_page(folio, nr, PageAnon(head) ? RMP_USE_SHARED_ZEROPAGE : 0); 3257 3258 /* 3259 * set page to its compound_head when split to non order-0 pages, so 3260 * we can skip unlocking it below, since PG_locked is transferred to 3261 * the compound_head of the page and the caller will unlock it. 3262 */ 3263 if (new_order) 3264 page = compound_head(page); 3265 3266 for (i = 0; i < nr; i += new_nr) { 3267 struct page *subpage = head + i; 3268 struct folio *new_folio = page_folio(subpage); 3269 if (subpage == page) 3270 continue; 3271 folio_unlock(new_folio); 3272 3273 /* 3274 * Subpages may be freed if there wasn't any mapping 3275 * like if add_to_swap() is running on a lru page that 3276 * had its mapping zapped. And freeing these pages 3277 * requires taking the lru_lock so we do the put_page 3278 * of the tail pages after the split is complete. 3279 */ 3280 free_page_and_swap_cache(subpage); 3281 } 3282 } 3283 3284 /* Racy check whether the huge page can be split */ 3285 bool can_split_folio(struct folio *folio, int caller_pins, int *pextra_pins) 3286 { 3287 int extra_pins; 3288 3289 /* Additional pins from page cache */ 3290 if (folio_test_anon(folio)) 3291 extra_pins = folio_test_swapcache(folio) ? 3292 folio_nr_pages(folio) : 0; 3293 else 3294 extra_pins = folio_nr_pages(folio); 3295 if (pextra_pins) 3296 *pextra_pins = extra_pins; 3297 return folio_mapcount(folio) == folio_ref_count(folio) - extra_pins - 3298 caller_pins; 3299 } 3300 3301 /* 3302 * This function splits a large folio into smaller folios of order @new_order. 3303 * @page can point to any page of the large folio to split. The split operation 3304 * does not change the position of @page. 3305 * 3306 * Prerequisites: 3307 * 3308 * 1) The caller must hold a reference on the @page's owning folio, also known 3309 * as the large folio. 3310 * 3311 * 2) The large folio must be locked. 3312 * 3313 * 3) The folio must not be pinned. Any unexpected folio references, including 3314 * GUP pins, will result in the folio not getting split; instead, the caller 3315 * will receive an -EAGAIN. 3316 * 3317 * 4) @new_order > 1, usually. Splitting to order-1 anonymous folios is not 3318 * supported for non-file-backed folios, because folio->_deferred_list, which 3319 * is used by partially mapped folios, is stored in subpage 2, but an order-1 3320 * folio only has subpages 0 and 1. File-backed order-1 folios are supported, 3321 * since they do not use _deferred_list. 3322 * 3323 * After splitting, the caller's folio reference will be transferred to @page, 3324 * resulting in a raised refcount of @page after this call. The other pages may 3325 * be freed if they are not mapped. 3326 * 3327 * If @list is null, tail pages will be added to LRU list, otherwise, to @list. 3328 * 3329 * Pages in @new_order will inherit the mapping, flags, and so on from the 3330 * huge page. 3331 * 3332 * Returns 0 if the huge page was split successfully. 3333 * 3334 * Returns -EAGAIN if the folio has unexpected reference (e.g., GUP) or if 3335 * the folio was concurrently removed from the page cache. 3336 * 3337 * Returns -EBUSY when trying to split the huge zeropage, if the folio is 3338 * under writeback, if fs-specific folio metadata cannot currently be 3339 * released, or if some unexpected race happened (e.g., anon VMA disappeared, 3340 * truncation). 3341 * 3342 * Callers should ensure that the order respects the address space mapping 3343 * min-order if one is set for non-anonymous folios. 3344 * 3345 * Returns -EINVAL when trying to split to an order that is incompatible 3346 * with the folio. Splitting to order 0 is compatible with all folios. 3347 */ 3348 int split_huge_page_to_list_to_order(struct page *page, struct list_head *list, 3349 unsigned int new_order) 3350 { 3351 struct folio *folio = page_folio(page); 3352 struct deferred_split *ds_queue = get_deferred_split_queue(folio); 3353 /* reset xarray order to new order after split */ 3354 XA_STATE_ORDER(xas, &folio->mapping->i_pages, folio->index, new_order); 3355 bool is_anon = folio_test_anon(folio); 3356 struct address_space *mapping = NULL; 3357 struct anon_vma *anon_vma = NULL; 3358 int order = folio_order(folio); 3359 int extra_pins, ret; 3360 pgoff_t end; 3361 bool is_hzp; 3362 3363 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 3364 VM_BUG_ON_FOLIO(!folio_test_large(folio), folio); 3365 3366 if (new_order >= folio_order(folio)) 3367 return -EINVAL; 3368 3369 if (is_anon) { 3370 /* order-1 is not supported for anonymous THP. */ 3371 if (new_order == 1) { 3372 VM_WARN_ONCE(1, "Cannot split to order-1 folio"); 3373 return -EINVAL; 3374 } 3375 } else if (new_order) { 3376 /* Split shmem folio to non-zero order not supported */ 3377 if (shmem_mapping(folio->mapping)) { 3378 VM_WARN_ONCE(1, 3379 "Cannot split shmem folio to non-0 order"); 3380 return -EINVAL; 3381 } 3382 /* 3383 * No split if the file system does not support large folio. 3384 * Note that we might still have THPs in such mappings due to 3385 * CONFIG_READ_ONLY_THP_FOR_FS. But in that case, the mapping 3386 * does not actually support large folios properly. 3387 */ 3388 if (IS_ENABLED(CONFIG_READ_ONLY_THP_FOR_FS) && 3389 !mapping_large_folio_support(folio->mapping)) { 3390 VM_WARN_ONCE(1, 3391 "Cannot split file folio to non-0 order"); 3392 return -EINVAL; 3393 } 3394 } 3395 3396 /* Only swapping a whole PMD-mapped folio is supported */ 3397 if (folio_test_swapcache(folio) && new_order) 3398 return -EINVAL; 3399 3400 is_hzp = is_huge_zero_folio(folio); 3401 if (is_hzp) { 3402 pr_warn_ratelimited("Called split_huge_page for huge zero page\n"); 3403 return -EBUSY; 3404 } 3405 3406 if (folio_test_writeback(folio)) 3407 return -EBUSY; 3408 3409 if (is_anon) { 3410 /* 3411 * The caller does not necessarily hold an mmap_lock that would 3412 * prevent the anon_vma disappearing so we first we take a 3413 * reference to it and then lock the anon_vma for write. This 3414 * is similar to folio_lock_anon_vma_read except the write lock 3415 * is taken to serialise against parallel split or collapse 3416 * operations. 3417 */ 3418 anon_vma = folio_get_anon_vma(folio); 3419 if (!anon_vma) { 3420 ret = -EBUSY; 3421 goto out; 3422 } 3423 end = -1; 3424 mapping = NULL; 3425 anon_vma_lock_write(anon_vma); 3426 } else { 3427 unsigned int min_order; 3428 gfp_t gfp; 3429 3430 mapping = folio->mapping; 3431 3432 /* Truncated ? */ 3433 if (!mapping) { 3434 ret = -EBUSY; 3435 goto out; 3436 } 3437 3438 min_order = mapping_min_folio_order(folio->mapping); 3439 if (new_order < min_order) { 3440 VM_WARN_ONCE(1, "Cannot split mapped folio below min-order: %u", 3441 min_order); 3442 ret = -EINVAL; 3443 goto out; 3444 } 3445 3446 gfp = current_gfp_context(mapping_gfp_mask(mapping) & 3447 GFP_RECLAIM_MASK); 3448 3449 if (!filemap_release_folio(folio, gfp)) { 3450 ret = -EBUSY; 3451 goto out; 3452 } 3453 3454 xas_split_alloc(&xas, folio, folio_order(folio), gfp); 3455 if (xas_error(&xas)) { 3456 ret = xas_error(&xas); 3457 goto out; 3458 } 3459 3460 anon_vma = NULL; 3461 i_mmap_lock_read(mapping); 3462 3463 /* 3464 *__split_huge_page() may need to trim off pages beyond EOF: 3465 * but on 32-bit, i_size_read() takes an irq-unsafe seqlock, 3466 * which cannot be nested inside the page tree lock. So note 3467 * end now: i_size itself may be changed at any moment, but 3468 * folio lock is good enough to serialize the trimming. 3469 */ 3470 end = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE); 3471 if (shmem_mapping(mapping)) 3472 end = shmem_fallocend(mapping->host, end); 3473 } 3474 3475 /* 3476 * Racy check if we can split the page, before unmap_folio() will 3477 * split PMDs 3478 */ 3479 if (!can_split_folio(folio, 1, &extra_pins)) { 3480 ret = -EAGAIN; 3481 goto out_unlock; 3482 } 3483 3484 unmap_folio(folio); 3485 3486 /* block interrupt reentry in xa_lock and spinlock */ 3487 local_irq_disable(); 3488 if (mapping) { 3489 /* 3490 * Check if the folio is present in page cache. 3491 * We assume all tail are present too, if folio is there. 3492 */ 3493 xas_lock(&xas); 3494 xas_reset(&xas); 3495 if (xas_load(&xas) != folio) 3496 goto fail; 3497 } 3498 3499 /* Prevent deferred_split_scan() touching ->_refcount */ 3500 spin_lock(&ds_queue->split_queue_lock); 3501 if (folio_ref_freeze(folio, 1 + extra_pins)) { 3502 if (folio_order(folio) > 1 && 3503 !list_empty(&folio->_deferred_list)) { 3504 ds_queue->split_queue_len--; 3505 if (folio_test_partially_mapped(folio)) { 3506 __folio_clear_partially_mapped(folio); 3507 mod_mthp_stat(folio_order(folio), 3508 MTHP_STAT_NR_ANON_PARTIALLY_MAPPED, -1); 3509 } 3510 /* 3511 * Reinitialize page_deferred_list after removing the 3512 * page from the split_queue, otherwise a subsequent 3513 * split will see list corruption when checking the 3514 * page_deferred_list. 3515 */ 3516 list_del_init(&folio->_deferred_list); 3517 } 3518 spin_unlock(&ds_queue->split_queue_lock); 3519 if (mapping) { 3520 int nr = folio_nr_pages(folio); 3521 3522 xas_split(&xas, folio, folio_order(folio)); 3523 if (folio_test_pmd_mappable(folio) && 3524 new_order < HPAGE_PMD_ORDER) { 3525 if (folio_test_swapbacked(folio)) { 3526 __lruvec_stat_mod_folio(folio, 3527 NR_SHMEM_THPS, -nr); 3528 } else { 3529 __lruvec_stat_mod_folio(folio, 3530 NR_FILE_THPS, -nr); 3531 filemap_nr_thps_dec(mapping); 3532 } 3533 } 3534 } 3535 3536 if (is_anon) { 3537 mod_mthp_stat(order, MTHP_STAT_NR_ANON, -1); 3538 mod_mthp_stat(new_order, MTHP_STAT_NR_ANON, 1 << (order - new_order)); 3539 } 3540 __split_huge_page(page, list, end, new_order); 3541 ret = 0; 3542 } else { 3543 spin_unlock(&ds_queue->split_queue_lock); 3544 fail: 3545 if (mapping) 3546 xas_unlock(&xas); 3547 local_irq_enable(); 3548 remap_page(folio, folio_nr_pages(folio), 0); 3549 ret = -EAGAIN; 3550 } 3551 3552 out_unlock: 3553 if (anon_vma) { 3554 anon_vma_unlock_write(anon_vma); 3555 put_anon_vma(anon_vma); 3556 } 3557 if (mapping) 3558 i_mmap_unlock_read(mapping); 3559 out: 3560 xas_destroy(&xas); 3561 if (order == HPAGE_PMD_ORDER) 3562 count_vm_event(!ret ? THP_SPLIT_PAGE : THP_SPLIT_PAGE_FAILED); 3563 count_mthp_stat(order, !ret ? MTHP_STAT_SPLIT : MTHP_STAT_SPLIT_FAILED); 3564 return ret; 3565 } 3566 3567 int min_order_for_split(struct folio *folio) 3568 { 3569 if (folio_test_anon(folio)) 3570 return 0; 3571 3572 if (!folio->mapping) { 3573 if (folio_test_pmd_mappable(folio)) 3574 count_vm_event(THP_SPLIT_PAGE_FAILED); 3575 return -EBUSY; 3576 } 3577 3578 return mapping_min_folio_order(folio->mapping); 3579 } 3580 3581 int split_folio_to_list(struct folio *folio, struct list_head *list) 3582 { 3583 int ret = min_order_for_split(folio); 3584 3585 if (ret < 0) 3586 return ret; 3587 3588 return split_huge_page_to_list_to_order(&folio->page, list, ret); 3589 } 3590 3591 void __folio_undo_large_rmappable(struct folio *folio) 3592 { 3593 struct deferred_split *ds_queue; 3594 unsigned long flags; 3595 3596 ds_queue = get_deferred_split_queue(folio); 3597 spin_lock_irqsave(&ds_queue->split_queue_lock, flags); 3598 if (!list_empty(&folio->_deferred_list)) { 3599 ds_queue->split_queue_len--; 3600 if (folio_test_partially_mapped(folio)) { 3601 __folio_clear_partially_mapped(folio); 3602 mod_mthp_stat(folio_order(folio), 3603 MTHP_STAT_NR_ANON_PARTIALLY_MAPPED, -1); 3604 } 3605 list_del_init(&folio->_deferred_list); 3606 } 3607 spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags); 3608 } 3609 3610 /* partially_mapped=false won't clear PG_partially_mapped folio flag */ 3611 void deferred_split_folio(struct folio *folio, bool partially_mapped) 3612 { 3613 struct deferred_split *ds_queue = get_deferred_split_queue(folio); 3614 #ifdef CONFIG_MEMCG 3615 struct mem_cgroup *memcg = folio_memcg(folio); 3616 #endif 3617 unsigned long flags; 3618 3619 /* 3620 * Order 1 folios have no space for a deferred list, but we also 3621 * won't waste much memory by not adding them to the deferred list. 3622 */ 3623 if (folio_order(folio) <= 1) 3624 return; 3625 3626 if (!partially_mapped && !split_underused_thp) 3627 return; 3628 3629 /* 3630 * The try_to_unmap() in page reclaim path might reach here too, 3631 * this may cause a race condition to corrupt deferred split queue. 3632 * And, if page reclaim is already handling the same folio, it is 3633 * unnecessary to handle it again in shrinker. 3634 * 3635 * Check the swapcache flag to determine if the folio is being 3636 * handled by page reclaim since THP swap would add the folio into 3637 * swap cache before calling try_to_unmap(). 3638 */ 3639 if (folio_test_swapcache(folio)) 3640 return; 3641 3642 spin_lock_irqsave(&ds_queue->split_queue_lock, flags); 3643 if (partially_mapped) { 3644 if (!folio_test_partially_mapped(folio)) { 3645 __folio_set_partially_mapped(folio); 3646 if (folio_test_pmd_mappable(folio)) 3647 count_vm_event(THP_DEFERRED_SPLIT_PAGE); 3648 count_mthp_stat(folio_order(folio), MTHP_STAT_SPLIT_DEFERRED); 3649 mod_mthp_stat(folio_order(folio), MTHP_STAT_NR_ANON_PARTIALLY_MAPPED, 1); 3650 3651 } 3652 } else { 3653 /* partially mapped folios cannot become non-partially mapped */ 3654 VM_WARN_ON_FOLIO(folio_test_partially_mapped(folio), folio); 3655 } 3656 if (list_empty(&folio->_deferred_list)) { 3657 list_add_tail(&folio->_deferred_list, &ds_queue->split_queue); 3658 ds_queue->split_queue_len++; 3659 #ifdef CONFIG_MEMCG 3660 if (memcg) 3661 set_shrinker_bit(memcg, folio_nid(folio), 3662 deferred_split_shrinker->id); 3663 #endif 3664 } 3665 spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags); 3666 } 3667 3668 static unsigned long deferred_split_count(struct shrinker *shrink, 3669 struct shrink_control *sc) 3670 { 3671 struct pglist_data *pgdata = NODE_DATA(sc->nid); 3672 struct deferred_split *ds_queue = &pgdata->deferred_split_queue; 3673 3674 #ifdef CONFIG_MEMCG 3675 if (sc->memcg) 3676 ds_queue = &sc->memcg->deferred_split_queue; 3677 #endif 3678 return READ_ONCE(ds_queue->split_queue_len); 3679 } 3680 3681 static bool thp_underused(struct folio *folio) 3682 { 3683 int num_zero_pages = 0, num_filled_pages = 0; 3684 void *kaddr; 3685 int i; 3686 3687 if (khugepaged_max_ptes_none == HPAGE_PMD_NR - 1) 3688 return false; 3689 3690 for (i = 0; i < folio_nr_pages(folio); i++) { 3691 kaddr = kmap_local_folio(folio, i * PAGE_SIZE); 3692 if (!memchr_inv(kaddr, 0, PAGE_SIZE)) { 3693 num_zero_pages++; 3694 if (num_zero_pages > khugepaged_max_ptes_none) { 3695 kunmap_local(kaddr); 3696 return true; 3697 } 3698 } else { 3699 /* 3700 * Another path for early exit once the number 3701 * of non-zero filled pages exceeds threshold. 3702 */ 3703 num_filled_pages++; 3704 if (num_filled_pages >= HPAGE_PMD_NR - khugepaged_max_ptes_none) { 3705 kunmap_local(kaddr); 3706 return false; 3707 } 3708 } 3709 kunmap_local(kaddr); 3710 } 3711 return false; 3712 } 3713 3714 static unsigned long deferred_split_scan(struct shrinker *shrink, 3715 struct shrink_control *sc) 3716 { 3717 struct pglist_data *pgdata = NODE_DATA(sc->nid); 3718 struct deferred_split *ds_queue = &pgdata->deferred_split_queue; 3719 unsigned long flags; 3720 LIST_HEAD(list); 3721 struct folio *folio, *next; 3722 int split = 0; 3723 3724 #ifdef CONFIG_MEMCG 3725 if (sc->memcg) 3726 ds_queue = &sc->memcg->deferred_split_queue; 3727 #endif 3728 3729 spin_lock_irqsave(&ds_queue->split_queue_lock, flags); 3730 /* Take pin on all head pages to avoid freeing them under us */ 3731 list_for_each_entry_safe(folio, next, &ds_queue->split_queue, 3732 _deferred_list) { 3733 if (folio_try_get(folio)) { 3734 list_move(&folio->_deferred_list, &list); 3735 } else { 3736 /* We lost race with folio_put() */ 3737 if (folio_test_partially_mapped(folio)) { 3738 __folio_clear_partially_mapped(folio); 3739 mod_mthp_stat(folio_order(folio), 3740 MTHP_STAT_NR_ANON_PARTIALLY_MAPPED, -1); 3741 } 3742 list_del_init(&folio->_deferred_list); 3743 ds_queue->split_queue_len--; 3744 } 3745 if (!--sc->nr_to_scan) 3746 break; 3747 } 3748 spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags); 3749 3750 list_for_each_entry_safe(folio, next, &list, _deferred_list) { 3751 bool did_split = false; 3752 bool underused = false; 3753 3754 if (!folio_test_partially_mapped(folio)) { 3755 underused = thp_underused(folio); 3756 if (!underused) 3757 goto next; 3758 } 3759 if (!folio_trylock(folio)) 3760 goto next; 3761 if (!split_folio(folio)) { 3762 did_split = true; 3763 if (underused) 3764 count_vm_event(THP_UNDERUSED_SPLIT_PAGE); 3765 split++; 3766 } 3767 folio_unlock(folio); 3768 next: 3769 /* 3770 * split_folio() removes folio from list on success. 3771 * Only add back to the queue if folio is partially mapped. 3772 * If thp_underused returns false, or if split_folio fails 3773 * in the case it was underused, then consider it used and 3774 * don't add it back to split_queue. 3775 */ 3776 if (!did_split && !folio_test_partially_mapped(folio)) { 3777 list_del_init(&folio->_deferred_list); 3778 ds_queue->split_queue_len--; 3779 } 3780 folio_put(folio); 3781 } 3782 3783 spin_lock_irqsave(&ds_queue->split_queue_lock, flags); 3784 list_splice_tail(&list, &ds_queue->split_queue); 3785 spin_unlock_irqrestore(&ds_queue->split_queue_lock, flags); 3786 3787 /* 3788 * Stop shrinker if we didn't split any page, but the queue is empty. 3789 * This can happen if pages were freed under us. 3790 */ 3791 if (!split && list_empty(&ds_queue->split_queue)) 3792 return SHRINK_STOP; 3793 return split; 3794 } 3795 3796 #ifdef CONFIG_DEBUG_FS 3797 static void split_huge_pages_all(void) 3798 { 3799 struct zone *zone; 3800 struct page *page; 3801 struct folio *folio; 3802 unsigned long pfn, max_zone_pfn; 3803 unsigned long total = 0, split = 0; 3804 3805 pr_debug("Split all THPs\n"); 3806 for_each_zone(zone) { 3807 if (!managed_zone(zone)) 3808 continue; 3809 max_zone_pfn = zone_end_pfn(zone); 3810 for (pfn = zone->zone_start_pfn; pfn < max_zone_pfn; pfn++) { 3811 int nr_pages; 3812 3813 page = pfn_to_online_page(pfn); 3814 if (!page || PageTail(page)) 3815 continue; 3816 folio = page_folio(page); 3817 if (!folio_try_get(folio)) 3818 continue; 3819 3820 if (unlikely(page_folio(page) != folio)) 3821 goto next; 3822 3823 if (zone != folio_zone(folio)) 3824 goto next; 3825 3826 if (!folio_test_large(folio) 3827 || folio_test_hugetlb(folio) 3828 || !folio_test_lru(folio)) 3829 goto next; 3830 3831 total++; 3832 folio_lock(folio); 3833 nr_pages = folio_nr_pages(folio); 3834 if (!split_folio(folio)) 3835 split++; 3836 pfn += nr_pages - 1; 3837 folio_unlock(folio); 3838 next: 3839 folio_put(folio); 3840 cond_resched(); 3841 } 3842 } 3843 3844 pr_debug("%lu of %lu THP split\n", split, total); 3845 } 3846 3847 static inline bool vma_not_suitable_for_thp_split(struct vm_area_struct *vma) 3848 { 3849 return vma_is_special_huge(vma) || (vma->vm_flags & VM_IO) || 3850 is_vm_hugetlb_page(vma); 3851 } 3852 3853 static int split_huge_pages_pid(int pid, unsigned long vaddr_start, 3854 unsigned long vaddr_end, unsigned int new_order) 3855 { 3856 int ret = 0; 3857 struct task_struct *task; 3858 struct mm_struct *mm; 3859 unsigned long total = 0, split = 0; 3860 unsigned long addr; 3861 3862 vaddr_start &= PAGE_MASK; 3863 vaddr_end &= PAGE_MASK; 3864 3865 task = find_get_task_by_vpid(pid); 3866 if (!task) { 3867 ret = -ESRCH; 3868 goto out; 3869 } 3870 3871 /* Find the mm_struct */ 3872 mm = get_task_mm(task); 3873 put_task_struct(task); 3874 3875 if (!mm) { 3876 ret = -EINVAL; 3877 goto out; 3878 } 3879 3880 pr_debug("Split huge pages in pid: %d, vaddr: [0x%lx - 0x%lx]\n", 3881 pid, vaddr_start, vaddr_end); 3882 3883 mmap_read_lock(mm); 3884 /* 3885 * always increase addr by PAGE_SIZE, since we could have a PTE page 3886 * table filled with PTE-mapped THPs, each of which is distinct. 3887 */ 3888 for (addr = vaddr_start; addr < vaddr_end; addr += PAGE_SIZE) { 3889 struct vm_area_struct *vma = vma_lookup(mm, addr); 3890 struct folio_walk fw; 3891 struct folio *folio; 3892 struct address_space *mapping; 3893 unsigned int target_order = new_order; 3894 3895 if (!vma) 3896 break; 3897 3898 /* skip special VMA and hugetlb VMA */ 3899 if (vma_not_suitable_for_thp_split(vma)) { 3900 addr = vma->vm_end; 3901 continue; 3902 } 3903 3904 folio = folio_walk_start(&fw, vma, addr, 0); 3905 if (!folio) 3906 continue; 3907 3908 if (!is_transparent_hugepage(folio)) 3909 goto next; 3910 3911 if (!folio_test_anon(folio)) { 3912 mapping = folio->mapping; 3913 target_order = max(new_order, 3914 mapping_min_folio_order(mapping)); 3915 } 3916 3917 if (target_order >= folio_order(folio)) 3918 goto next; 3919 3920 total++; 3921 /* 3922 * For folios with private, split_huge_page_to_list_to_order() 3923 * will try to drop it before split and then check if the folio 3924 * can be split or not. So skip the check here. 3925 */ 3926 if (!folio_test_private(folio) && 3927 !can_split_folio(folio, 0, NULL)) 3928 goto next; 3929 3930 if (!folio_trylock(folio)) 3931 goto next; 3932 folio_get(folio); 3933 folio_walk_end(&fw, vma); 3934 3935 if (!folio_test_anon(folio) && folio->mapping != mapping) 3936 goto unlock; 3937 3938 if (!split_folio_to_order(folio, target_order)) 3939 split++; 3940 3941 unlock: 3942 3943 folio_unlock(folio); 3944 folio_put(folio); 3945 3946 cond_resched(); 3947 continue; 3948 next: 3949 folio_walk_end(&fw, vma); 3950 cond_resched(); 3951 } 3952 mmap_read_unlock(mm); 3953 mmput(mm); 3954 3955 pr_debug("%lu of %lu THP split\n", split, total); 3956 3957 out: 3958 return ret; 3959 } 3960 3961 static int split_huge_pages_in_file(const char *file_path, pgoff_t off_start, 3962 pgoff_t off_end, unsigned int new_order) 3963 { 3964 struct filename *file; 3965 struct file *candidate; 3966 struct address_space *mapping; 3967 int ret = -EINVAL; 3968 pgoff_t index; 3969 int nr_pages = 1; 3970 unsigned long total = 0, split = 0; 3971 unsigned int min_order; 3972 unsigned int target_order; 3973 3974 file = getname_kernel(file_path); 3975 if (IS_ERR(file)) 3976 return ret; 3977 3978 candidate = file_open_name(file, O_RDONLY, 0); 3979 if (IS_ERR(candidate)) 3980 goto out; 3981 3982 pr_debug("split file-backed THPs in file: %s, page offset: [0x%lx - 0x%lx]\n", 3983 file_path, off_start, off_end); 3984 3985 mapping = candidate->f_mapping; 3986 min_order = mapping_min_folio_order(mapping); 3987 target_order = max(new_order, min_order); 3988 3989 for (index = off_start; index < off_end; index += nr_pages) { 3990 struct folio *folio = filemap_get_folio(mapping, index); 3991 3992 nr_pages = 1; 3993 if (IS_ERR(folio)) 3994 continue; 3995 3996 if (!folio_test_large(folio)) 3997 goto next; 3998 3999 total++; 4000 nr_pages = folio_nr_pages(folio); 4001 4002 if (target_order >= folio_order(folio)) 4003 goto next; 4004 4005 if (!folio_trylock(folio)) 4006 goto next; 4007 4008 if (folio->mapping != mapping) 4009 goto unlock; 4010 4011 if (!split_folio_to_order(folio, target_order)) 4012 split++; 4013 4014 unlock: 4015 folio_unlock(folio); 4016 next: 4017 folio_put(folio); 4018 cond_resched(); 4019 } 4020 4021 filp_close(candidate, NULL); 4022 ret = 0; 4023 4024 pr_debug("%lu of %lu file-backed THP split\n", split, total); 4025 out: 4026 putname(file); 4027 return ret; 4028 } 4029 4030 #define MAX_INPUT_BUF_SZ 255 4031 4032 static ssize_t split_huge_pages_write(struct file *file, const char __user *buf, 4033 size_t count, loff_t *ppops) 4034 { 4035 static DEFINE_MUTEX(split_debug_mutex); 4036 ssize_t ret; 4037 /* 4038 * hold pid, start_vaddr, end_vaddr, new_order or 4039 * file_path, off_start, off_end, new_order 4040 */ 4041 char input_buf[MAX_INPUT_BUF_SZ]; 4042 int pid; 4043 unsigned long vaddr_start, vaddr_end; 4044 unsigned int new_order = 0; 4045 4046 ret = mutex_lock_interruptible(&split_debug_mutex); 4047 if (ret) 4048 return ret; 4049 4050 ret = -EFAULT; 4051 4052 memset(input_buf, 0, MAX_INPUT_BUF_SZ); 4053 if (copy_from_user(input_buf, buf, min_t(size_t, count, MAX_INPUT_BUF_SZ))) 4054 goto out; 4055 4056 input_buf[MAX_INPUT_BUF_SZ - 1] = '\0'; 4057 4058 if (input_buf[0] == '/') { 4059 char *tok; 4060 char *buf = input_buf; 4061 char file_path[MAX_INPUT_BUF_SZ]; 4062 pgoff_t off_start = 0, off_end = 0; 4063 size_t input_len = strlen(input_buf); 4064 4065 tok = strsep(&buf, ","); 4066 if (tok) { 4067 strcpy(file_path, tok); 4068 } else { 4069 ret = -EINVAL; 4070 goto out; 4071 } 4072 4073 ret = sscanf(buf, "0x%lx,0x%lx,%d", &off_start, &off_end, &new_order); 4074 if (ret != 2 && ret != 3) { 4075 ret = -EINVAL; 4076 goto out; 4077 } 4078 ret = split_huge_pages_in_file(file_path, off_start, off_end, new_order); 4079 if (!ret) 4080 ret = input_len; 4081 4082 goto out; 4083 } 4084 4085 ret = sscanf(input_buf, "%d,0x%lx,0x%lx,%d", &pid, &vaddr_start, &vaddr_end, &new_order); 4086 if (ret == 1 && pid == 1) { 4087 split_huge_pages_all(); 4088 ret = strlen(input_buf); 4089 goto out; 4090 } else if (ret != 3 && ret != 4) { 4091 ret = -EINVAL; 4092 goto out; 4093 } 4094 4095 ret = split_huge_pages_pid(pid, vaddr_start, vaddr_end, new_order); 4096 if (!ret) 4097 ret = strlen(input_buf); 4098 out: 4099 mutex_unlock(&split_debug_mutex); 4100 return ret; 4101 4102 } 4103 4104 static const struct file_operations split_huge_pages_fops = { 4105 .owner = THIS_MODULE, 4106 .write = split_huge_pages_write, 4107 }; 4108 4109 static int __init split_huge_pages_debugfs(void) 4110 { 4111 debugfs_create_file("split_huge_pages", 0200, NULL, NULL, 4112 &split_huge_pages_fops); 4113 return 0; 4114 } 4115 late_initcall(split_huge_pages_debugfs); 4116 #endif 4117 4118 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION 4119 int set_pmd_migration_entry(struct page_vma_mapped_walk *pvmw, 4120 struct page *page) 4121 { 4122 struct folio *folio = page_folio(page); 4123 struct vm_area_struct *vma = pvmw->vma; 4124 struct mm_struct *mm = vma->vm_mm; 4125 unsigned long address = pvmw->address; 4126 bool anon_exclusive; 4127 pmd_t pmdval; 4128 swp_entry_t entry; 4129 pmd_t pmdswp; 4130 4131 if (!(pvmw->pmd && !pvmw->pte)) 4132 return 0; 4133 4134 flush_cache_range(vma, address, address + HPAGE_PMD_SIZE); 4135 pmdval = pmdp_invalidate(vma, address, pvmw->pmd); 4136 4137 /* See folio_try_share_anon_rmap_pmd(): invalidate PMD first. */ 4138 anon_exclusive = folio_test_anon(folio) && PageAnonExclusive(page); 4139 if (anon_exclusive && folio_try_share_anon_rmap_pmd(folio, page)) { 4140 set_pmd_at(mm, address, pvmw->pmd, pmdval); 4141 return -EBUSY; 4142 } 4143 4144 if (pmd_dirty(pmdval)) 4145 folio_mark_dirty(folio); 4146 if (pmd_write(pmdval)) 4147 entry = make_writable_migration_entry(page_to_pfn(page)); 4148 else if (anon_exclusive) 4149 entry = make_readable_exclusive_migration_entry(page_to_pfn(page)); 4150 else 4151 entry = make_readable_migration_entry(page_to_pfn(page)); 4152 if (pmd_young(pmdval)) 4153 entry = make_migration_entry_young(entry); 4154 if (pmd_dirty(pmdval)) 4155 entry = make_migration_entry_dirty(entry); 4156 pmdswp = swp_entry_to_pmd(entry); 4157 if (pmd_soft_dirty(pmdval)) 4158 pmdswp = pmd_swp_mksoft_dirty(pmdswp); 4159 if (pmd_uffd_wp(pmdval)) 4160 pmdswp = pmd_swp_mkuffd_wp(pmdswp); 4161 set_pmd_at(mm, address, pvmw->pmd, pmdswp); 4162 folio_remove_rmap_pmd(folio, page, vma); 4163 folio_put(folio); 4164 trace_set_migration_pmd(address, pmd_val(pmdswp)); 4165 4166 return 0; 4167 } 4168 4169 void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct page *new) 4170 { 4171 struct folio *folio = page_folio(new); 4172 struct vm_area_struct *vma = pvmw->vma; 4173 struct mm_struct *mm = vma->vm_mm; 4174 unsigned long address = pvmw->address; 4175 unsigned long haddr = address & HPAGE_PMD_MASK; 4176 pmd_t pmde; 4177 swp_entry_t entry; 4178 4179 if (!(pvmw->pmd && !pvmw->pte)) 4180 return; 4181 4182 entry = pmd_to_swp_entry(*pvmw->pmd); 4183 folio_get(folio); 4184 pmde = mk_huge_pmd(new, READ_ONCE(vma->vm_page_prot)); 4185 if (pmd_swp_soft_dirty(*pvmw->pmd)) 4186 pmde = pmd_mksoft_dirty(pmde); 4187 if (is_writable_migration_entry(entry)) 4188 pmde = pmd_mkwrite(pmde, vma); 4189 if (pmd_swp_uffd_wp(*pvmw->pmd)) 4190 pmde = pmd_mkuffd_wp(pmde); 4191 if (!is_migration_entry_young(entry)) 4192 pmde = pmd_mkold(pmde); 4193 /* NOTE: this may contain setting soft-dirty on some archs */ 4194 if (folio_test_dirty(folio) && is_migration_entry_dirty(entry)) 4195 pmde = pmd_mkdirty(pmde); 4196 4197 if (folio_test_anon(folio)) { 4198 rmap_t rmap_flags = RMAP_NONE; 4199 4200 if (!is_readable_migration_entry(entry)) 4201 rmap_flags |= RMAP_EXCLUSIVE; 4202 4203 folio_add_anon_rmap_pmd(folio, new, vma, haddr, rmap_flags); 4204 } else { 4205 folio_add_file_rmap_pmd(folio, new, vma); 4206 } 4207 VM_BUG_ON(pmd_write(pmde) && folio_test_anon(folio) && !PageAnonExclusive(new)); 4208 set_pmd_at(mm, haddr, pvmw->pmd, pmde); 4209 4210 /* No need to invalidate - it was non-present before */ 4211 update_mmu_cache_pmd(vma, address, pvmw->pmd); 4212 trace_remove_migration_pmd(address, pmd_val(pmde)); 4213 } 4214 #endif 4215