1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * Generic hugetlb support. 4 * (C) Nadia Yvette Chambers, April 2004 5 */ 6 #define pr_fmt(fmt) "HugeTLB: " fmt 7 8 #include <linux/list.h> 9 #include <linux/init.h> 10 #include <linux/mm.h> 11 #include <linux/seq_file.h> 12 #include <linux/highmem.h> 13 #include <linux/mmu_notifier.h> 14 #include <linux/nodemask.h> 15 #include <linux/pagemap.h> 16 #include <linux/mempolicy.h> 17 #include <linux/compiler.h> 18 #include <linux/cpumask.h> 19 #include <linux/cpuset.h> 20 #include <linux/mutex.h> 21 #include <linux/memblock.h> 22 #include <linux/minmax.h> 23 #include <linux/slab.h> 24 #include <linux/sched/mm.h> 25 #include <linux/mmdebug.h> 26 #include <linux/sched/signal.h> 27 #include <linux/rmap.h> 28 #include <linux/rcupdate.h> 29 #include <linux/string_choices.h> 30 #include <linux/string_helpers.h> 31 #include <linux/swap.h> 32 #include <linux/leafops.h> 33 #include <linux/jhash.h> 34 #include <linux/numa.h> 35 #include <linux/llist.h> 36 #include <linux/cma.h> 37 #include <linux/migrate.h> 38 #include <linux/nospec.h> 39 #include <linux/delayacct.h> 40 #include <linux/memory.h> 41 #include <linux/mm_inline.h> 42 #include <linux/padata.h> 43 #include <linux/pgalloc.h> 44 #include <linux/vmemmap-optimization.h> 45 46 #include <asm/page.h> 47 #include <asm/tlb.h> 48 #include <asm/setup.h> 49 50 #include <linux/io.h> 51 #include <linux/node.h> 52 #include <linux/page_owner.h> 53 #include "internal.h" 54 #include "page_alloc.h" 55 #include "hugetlb_vmemmap.h" 56 #include "hugetlb_cma.h" 57 #include "hugetlb_internal.h" 58 #include "mm_init.h" 59 #include <linux/page-isolation.h> 60 61 #define HUGE_BOOTMEM_ZONES_VALID BIT(0) 62 63 struct huge_bootmem_page { 64 struct list_head list; 65 struct hstate *hstate; 66 unsigned long flags; 67 }; 68 69 int hugetlb_max_hstate __read_mostly; 70 unsigned int default_hstate_idx; 71 struct hstate hstates[HUGE_MAX_HSTATE]; 72 73 __initdata nodemask_t hugetlb_bootmem_nodes; 74 static struct list_head huge_boot_pages[MAX_NUMNODES] __initdata; 75 76 /* 77 * Due to ordering constraints across the init code for various 78 * architectures, hugetlb hstate cmdline parameters can't simply 79 * be early_param. early_param might call the setup function 80 * before valid hugetlb page sizes are determined, leading to 81 * incorrect rejection of valid hugepagesz= options. 82 * 83 * So, record the parameters early and consume them whenever the 84 * init code is ready for them, by calling hugetlb_parse_params(). 85 */ 86 87 /* one (hugepagesz=,hugepages=) pair per hstate, one default_hugepagesz */ 88 #define HUGE_MAX_CMDLINE_ARGS (2 * HUGE_MAX_HSTATE + 1) 89 struct hugetlb_cmdline { 90 char *val; 91 int (*setup)(char *val); 92 }; 93 94 /* for command line parsing */ 95 static struct hstate * __initdata parsed_hstate; 96 static unsigned long __initdata default_hstate_max_huge_pages; 97 static bool __initdata parsed_valid_hugepagesz = true; 98 static bool __initdata parsed_default_hugepagesz; 99 static unsigned int default_hugepages_in_node[MAX_NUMNODES] __initdata; 100 static unsigned long hugepage_allocation_threads __initdata; 101 102 static char hstate_cmdline_buf[COMMAND_LINE_SIZE] __initdata; 103 static int hstate_cmdline_index __initdata; 104 static struct hugetlb_cmdline hugetlb_params[HUGE_MAX_CMDLINE_ARGS] __initdata; 105 static int hugetlb_param_index __initdata; 106 static __init int hugetlb_add_param(char *s, int (*setup)(char *val)); 107 static __init void hugetlb_parse_params(void); 108 109 #define hugetlb_early_param(str, func) \ 110 static __init int func##args(char *s) \ 111 { \ 112 return hugetlb_add_param(s, func); \ 113 } \ 114 early_param(str, func##args) 115 116 /* 117 * Protects updates to hugepage_freelists, hugepage_activelist, nr_huge_pages, 118 * free_huge_pages, and surplus_huge_pages. 119 */ 120 __cacheline_aligned_in_smp DEFINE_SPINLOCK(hugetlb_lock); 121 122 /* 123 * Serializes faults on the same logical page. This is used to 124 * prevent spurious OOMs when the hugepage pool is fully utilized. 125 */ 126 static int num_fault_mutexes __ro_after_init; 127 struct mutex *hugetlb_fault_mutex_table __ro_after_init; 128 129 /* Forward declaration */ 130 static int hugetlb_acct_memory(struct hstate *h, long delta); 131 static unsigned int allowed_mems_nr(struct hstate *h); 132 static void hugetlb_vma_lock_free(struct vm_area_struct *vma); 133 static void hugetlb_vma_lock_alloc(struct vm_area_struct *vma); 134 static void __hugetlb_vma_unlock_write_free(struct vm_area_struct *vma); 135 static int __huge_pmd_unshare(struct mmu_gather *tlb, 136 struct vm_area_struct *vma, unsigned long addr, pte_t *ptep, 137 bool check_locks); 138 static void hugetlb_unshare_pmds(struct vm_area_struct *vma, 139 unsigned long start, unsigned long end, bool take_locks); 140 static void hugetlb_unmap_range(struct mmu_gather *tlb, 141 struct vm_area_struct *vma, unsigned long start, 142 unsigned long end, struct folio *folio, 143 zap_flags_t zap_flags); 144 static struct resv_map *vma_resv_map(struct vm_area_struct *vma); 145 146 static inline bool subpool_is_free(struct hugepage_subpool *spool) 147 { 148 if (spool->count) 149 return false; 150 if (spool->max_hpages != -1) 151 return spool->used_hpages == 0; 152 if (spool->min_hpages != -1) 153 return spool->rsv_hpages == spool->min_hpages; 154 155 return true; 156 } 157 158 static inline void unlock_or_release_subpool(struct hugepage_subpool *spool, 159 unsigned long irq_flags) 160 { 161 bool free_subpool = subpool_is_free(spool); 162 163 /* If no pages are used, and no other handles to the subpool 164 * remain, give up any reservations based on minimum size and 165 * free the subpool */ 166 spin_unlock_irqrestore(&spool->lock, irq_flags); 167 168 if (free_subpool) { 169 if (spool->min_hpages != -1) 170 hugetlb_acct_memory(spool->hstate, 171 -spool->min_hpages); 172 kfree(spool); 173 } 174 } 175 176 struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages, 177 long min_hpages) 178 { 179 struct hugepage_subpool *spool; 180 181 spool = kzalloc_obj(*spool); 182 if (!spool) 183 return NULL; 184 185 spin_lock_init(&spool->lock); 186 spool->count = 1; 187 spool->max_hpages = max_hpages; 188 spool->hstate = h; 189 spool->min_hpages = min_hpages; 190 191 if (min_hpages != -1 && hugetlb_acct_memory(h, min_hpages)) { 192 kfree(spool); 193 return NULL; 194 } 195 spool->rsv_hpages = min_hpages; 196 197 return spool; 198 } 199 200 void hugepage_put_subpool(struct hugepage_subpool *spool) 201 { 202 unsigned long flags; 203 204 if (!spool) 205 return; 206 207 spin_lock_irqsave(&spool->lock, flags); 208 BUG_ON(!spool->count); 209 spool->count--; 210 unlock_or_release_subpool(spool, flags); 211 } 212 213 /* 214 * Subpool accounting for allocating and reserving pages. 215 * Return -ENOMEM if there are not enough resources to satisfy the 216 * request. Otherwise, return the number of pages by which the 217 * global pools must be adjusted (upward). The returned value may 218 * only be different than the passed value (delta) in the case where 219 * a subpool minimum size must be maintained. 220 */ 221 static long hugepage_subpool_get_pages(struct hugepage_subpool *spool, 222 long delta) 223 { 224 long ret = delta; 225 226 if (!spool) 227 return ret; 228 229 spin_lock_irq(&spool->lock); 230 231 if (spool->max_hpages != -1) { /* maximum size accounting */ 232 if ((spool->used_hpages + delta) <= spool->max_hpages) 233 spool->used_hpages += delta; 234 else { 235 ret = -ENOMEM; 236 goto unlock_ret; 237 } 238 } 239 240 /* minimum size accounting */ 241 if (spool->min_hpages != -1 && spool->rsv_hpages) { 242 if (delta > spool->rsv_hpages) { 243 /* 244 * Asking for more reserves than those already taken on 245 * behalf of subpool. Return difference. 246 */ 247 ret = delta - spool->rsv_hpages; 248 spool->rsv_hpages = 0; 249 } else { 250 ret = 0; /* reserves already accounted for */ 251 spool->rsv_hpages -= delta; 252 } 253 } 254 255 unlock_ret: 256 spin_unlock_irq(&spool->lock); 257 return ret; 258 } 259 260 /* 261 * Subpool accounting for freeing and unreserving pages. 262 * Return the number of global page reservations that must be dropped. 263 * The return value may only be different than the passed value (delta) 264 * in the case where a subpool minimum size must be maintained. 265 */ 266 static long hugepage_subpool_put_pages(struct hugepage_subpool *spool, 267 long delta) 268 { 269 long ret = delta; 270 unsigned long flags; 271 272 if (!spool) 273 return delta; 274 275 spin_lock_irqsave(&spool->lock, flags); 276 277 if (spool->max_hpages != -1) /* maximum size accounting */ 278 spool->used_hpages -= delta; 279 280 /* minimum size accounting */ 281 if (spool->min_hpages != -1 && spool->used_hpages < spool->min_hpages) { 282 if (spool->rsv_hpages + delta <= spool->min_hpages) 283 ret = 0; 284 else 285 ret = spool->rsv_hpages + delta - spool->min_hpages; 286 287 spool->rsv_hpages += delta; 288 if (spool->rsv_hpages > spool->min_hpages) 289 spool->rsv_hpages = spool->min_hpages; 290 } 291 292 /* 293 * If hugetlbfs_put_super couldn't free spool due to an outstanding 294 * quota reference, free it now. 295 */ 296 unlock_or_release_subpool(spool, flags); 297 298 return ret; 299 } 300 301 static inline struct hugepage_subpool *subpool_vma(struct vm_area_struct *vma) 302 { 303 return subpool_inode(file_inode(vma->vm_file)); 304 } 305 306 /* 307 * hugetlb vma_lock helper routines 308 */ 309 void hugetlb_vma_lock_read(struct vm_area_struct *vma) 310 { 311 if (__vma_shareable_lock(vma)) { 312 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data; 313 314 down_read(&vma_lock->rw_sema); 315 } else if (__vma_private_lock(vma)) { 316 struct resv_map *resv_map = vma_resv_map(vma); 317 318 down_read(&resv_map->rw_sema); 319 } 320 } 321 322 void hugetlb_vma_unlock_read(struct vm_area_struct *vma) 323 { 324 if (__vma_shareable_lock(vma)) { 325 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data; 326 327 up_read(&vma_lock->rw_sema); 328 } else if (__vma_private_lock(vma)) { 329 struct resv_map *resv_map = vma_resv_map(vma); 330 331 up_read(&resv_map->rw_sema); 332 } 333 } 334 335 void hugetlb_vma_lock_write(struct vm_area_struct *vma) 336 { 337 if (__vma_shareable_lock(vma)) { 338 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data; 339 340 down_write(&vma_lock->rw_sema); 341 } else if (__vma_private_lock(vma)) { 342 struct resv_map *resv_map = vma_resv_map(vma); 343 344 down_write(&resv_map->rw_sema); 345 } 346 } 347 348 void hugetlb_vma_unlock_write(struct vm_area_struct *vma) 349 { 350 if (__vma_shareable_lock(vma)) { 351 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data; 352 353 up_write(&vma_lock->rw_sema); 354 } else if (__vma_private_lock(vma)) { 355 struct resv_map *resv_map = vma_resv_map(vma); 356 357 up_write(&resv_map->rw_sema); 358 } 359 } 360 361 int hugetlb_vma_trylock_write(struct vm_area_struct *vma) 362 { 363 364 if (__vma_shareable_lock(vma)) { 365 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data; 366 367 return down_write_trylock(&vma_lock->rw_sema); 368 } else if (__vma_private_lock(vma)) { 369 struct resv_map *resv_map = vma_resv_map(vma); 370 371 return down_write_trylock(&resv_map->rw_sema); 372 } 373 374 return 1; 375 } 376 377 void hugetlb_vma_assert_locked(struct vm_area_struct *vma) 378 { 379 if (__vma_shareable_lock(vma)) { 380 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data; 381 382 lockdep_assert_held(&vma_lock->rw_sema); 383 } else if (__vma_private_lock(vma)) { 384 struct resv_map *resv_map = vma_resv_map(vma); 385 386 lockdep_assert_held(&resv_map->rw_sema); 387 } 388 } 389 390 void hugetlb_vma_lock_release(struct kref *kref) 391 { 392 struct hugetlb_vma_lock *vma_lock = container_of(kref, 393 struct hugetlb_vma_lock, refs); 394 395 kfree(vma_lock); 396 } 397 398 static void __hugetlb_vma_unlock_write_put(struct hugetlb_vma_lock *vma_lock) 399 { 400 struct vm_area_struct *vma = vma_lock->vma; 401 402 /* 403 * vma_lock structure may or not be released as a result of put, 404 * it certainly will no longer be attached to vma so clear pointer. 405 * Semaphore synchronizes access to vma_lock->vma field. 406 */ 407 vma_lock->vma = NULL; 408 vma->vm_private_data = NULL; 409 up_write(&vma_lock->rw_sema); 410 kref_put(&vma_lock->refs, hugetlb_vma_lock_release); 411 } 412 413 static void __hugetlb_vma_unlock_write_free(struct vm_area_struct *vma) 414 { 415 if (__vma_shareable_lock(vma)) { 416 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data; 417 418 __hugetlb_vma_unlock_write_put(vma_lock); 419 } else if (__vma_private_lock(vma)) { 420 struct resv_map *resv_map = vma_resv_map(vma); 421 422 /* no free for anon vmas, but still need to unlock */ 423 up_write(&resv_map->rw_sema); 424 } 425 } 426 427 static void hugetlb_vma_lock_free(struct vm_area_struct *vma) 428 { 429 /* 430 * Only present in sharable vmas. 431 */ 432 if (!vma || !__vma_shareable_lock(vma)) 433 return; 434 435 if (vma->vm_private_data) { 436 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data; 437 438 down_write(&vma_lock->rw_sema); 439 __hugetlb_vma_unlock_write_put(vma_lock); 440 } 441 } 442 443 static void hugetlb_vma_lock_alloc(struct vm_area_struct *vma) 444 { 445 struct hugetlb_vma_lock *vma_lock; 446 447 /* Only establish in (flags) sharable vmas */ 448 if (!vma || !(vma->vm_flags & VM_MAYSHARE)) 449 return; 450 451 /* Should never get here with non-NULL vm_private_data */ 452 if (vma->vm_private_data) 453 return; 454 455 vma_lock = kmalloc_obj(*vma_lock); 456 if (!vma_lock) { 457 /* 458 * If we can not allocate structure, then vma can not 459 * participate in pmd sharing. This is only a possible 460 * performance enhancement and memory saving issue. 461 * However, the lock is also used to synchronize page 462 * faults with truncation. If the lock is not present, 463 * unlikely races could leave pages in a file past i_size 464 * until the file is removed. Warn in the unlikely case of 465 * allocation failure. 466 */ 467 pr_warn_once("unable to allocate vma specific lock\n"); 468 return; 469 } 470 471 kref_init(&vma_lock->refs); 472 init_rwsem(&vma_lock->rw_sema); 473 vma_lock->vma = vma; 474 vma->vm_private_data = vma_lock; 475 } 476 477 /* Helper that removes a struct file_region from the resv_map cache and returns 478 * it for use. 479 */ 480 static struct file_region * 481 get_file_region_entry_from_cache(struct resv_map *resv, long from, long to) 482 { 483 struct file_region *nrg; 484 485 VM_BUG_ON(resv->region_cache_count <= 0); 486 487 resv->region_cache_count--; 488 nrg = list_first_entry(&resv->region_cache, struct file_region, link); 489 list_del(&nrg->link); 490 491 nrg->from = from; 492 nrg->to = to; 493 494 return nrg; 495 } 496 497 static void copy_hugetlb_cgroup_uncharge_info(struct file_region *nrg, 498 struct file_region *rg) 499 { 500 #ifdef CONFIG_CGROUP_HUGETLB 501 nrg->reservation_counter = rg->reservation_counter; 502 nrg->css = rg->css; 503 if (rg->css) 504 css_get(rg->css); 505 #endif 506 } 507 508 /* Helper that records hugetlb_cgroup uncharge info. */ 509 static void record_hugetlb_cgroup_uncharge_info(struct hugetlb_cgroup *h_cg, 510 struct hstate *h, 511 struct resv_map *resv, 512 struct file_region *nrg) 513 { 514 #ifdef CONFIG_CGROUP_HUGETLB 515 if (h_cg) { 516 nrg->reservation_counter = 517 &h_cg->rsvd_hugepage[hstate_index(h)]; 518 nrg->css = &h_cg->css; 519 /* 520 * The caller will hold exactly one h_cg->css reference for the 521 * whole contiguous reservation region. But this area might be 522 * scattered when there are already some file_regions reside in 523 * it. As a result, many file_regions may share only one css 524 * reference. In order to ensure that one file_region must hold 525 * exactly one h_cg->css reference, we should do css_get for 526 * each file_region and leave the reference held by caller 527 * untouched. 528 */ 529 css_get(&h_cg->css); 530 if (!resv->pages_per_hpage) 531 resv->pages_per_hpage = pages_per_huge_page(h); 532 /* pages_per_hpage should be the same for all entries in 533 * a resv_map. 534 */ 535 VM_BUG_ON(resv->pages_per_hpage != pages_per_huge_page(h)); 536 } else { 537 nrg->reservation_counter = NULL; 538 nrg->css = NULL; 539 } 540 #endif 541 } 542 543 static void put_uncharge_info(struct file_region *rg) 544 { 545 #ifdef CONFIG_CGROUP_HUGETLB 546 if (rg->css) 547 css_put(rg->css); 548 #endif 549 } 550 551 static bool has_same_uncharge_info(struct file_region *rg, 552 struct file_region *org) 553 { 554 #ifdef CONFIG_CGROUP_HUGETLB 555 return rg->reservation_counter == org->reservation_counter && 556 rg->css == org->css; 557 558 #else 559 return true; 560 #endif 561 } 562 563 static void coalesce_file_region(struct resv_map *resv, struct file_region *rg) 564 { 565 struct file_region *nrg, *prg; 566 567 prg = list_prev_entry(rg, link); 568 if (&prg->link != &resv->regions && prg->to == rg->from && 569 has_same_uncharge_info(prg, rg)) { 570 prg->to = rg->to; 571 572 list_del(&rg->link); 573 put_uncharge_info(rg); 574 kfree(rg); 575 576 rg = prg; 577 } 578 579 nrg = list_next_entry(rg, link); 580 if (&nrg->link != &resv->regions && nrg->from == rg->to && 581 has_same_uncharge_info(nrg, rg)) { 582 nrg->from = rg->from; 583 584 list_del(&rg->link); 585 put_uncharge_info(rg); 586 kfree(rg); 587 } 588 } 589 590 static inline long 591 hugetlb_resv_map_add(struct resv_map *map, struct list_head *rg, long from, 592 long to, struct hstate *h, struct hugetlb_cgroup *cg, 593 long *regions_needed) 594 { 595 struct file_region *nrg; 596 597 if (!regions_needed) { 598 nrg = get_file_region_entry_from_cache(map, from, to); 599 record_hugetlb_cgroup_uncharge_info(cg, h, map, nrg); 600 list_add(&nrg->link, rg); 601 coalesce_file_region(map, nrg); 602 } else { 603 *regions_needed += 1; 604 } 605 606 return to - from; 607 } 608 609 /* 610 * Must be called with resv->lock held. 611 * 612 * Calling this with regions_needed != NULL will count the number of pages 613 * to be added but will not modify the linked list. And regions_needed will 614 * indicate the number of file_regions needed in the cache to carry out to add 615 * the regions for this range. 616 */ 617 static long add_reservation_in_range(struct resv_map *resv, long f, long t, 618 struct hugetlb_cgroup *h_cg, 619 struct hstate *h, long *regions_needed) 620 { 621 long add = 0; 622 struct list_head *head = &resv->regions; 623 long last_accounted_offset = f; 624 struct file_region *iter, *trg = NULL; 625 struct list_head *rg = NULL; 626 627 if (regions_needed) 628 *regions_needed = 0; 629 630 /* In this loop, we essentially handle an entry for the range 631 * [last_accounted_offset, iter->from), at every iteration, with some 632 * bounds checking. 633 */ 634 list_for_each_entry_safe(iter, trg, head, link) { 635 /* Skip irrelevant regions that start before our range. */ 636 if (iter->from < f) { 637 /* If this region ends after the last accounted offset, 638 * then we need to update last_accounted_offset. 639 */ 640 if (iter->to > last_accounted_offset) 641 last_accounted_offset = iter->to; 642 continue; 643 } 644 645 /* When we find a region that starts beyond our range, we've 646 * finished. 647 */ 648 if (iter->from >= t) { 649 rg = iter->link.prev; 650 break; 651 } 652 653 /* Add an entry for last_accounted_offset -> iter->from, and 654 * update last_accounted_offset. 655 */ 656 if (iter->from > last_accounted_offset) 657 add += hugetlb_resv_map_add(resv, iter->link.prev, 658 last_accounted_offset, 659 iter->from, h, h_cg, 660 regions_needed); 661 662 last_accounted_offset = iter->to; 663 } 664 665 /* Handle the case where our range extends beyond 666 * last_accounted_offset. 667 */ 668 if (!rg) 669 rg = head->prev; 670 if (last_accounted_offset < t) 671 add += hugetlb_resv_map_add(resv, rg, last_accounted_offset, 672 t, h, h_cg, regions_needed); 673 674 return add; 675 } 676 677 /* Must be called with resv->lock acquired. Will drop lock to allocate entries. 678 */ 679 static int allocate_file_region_entries(struct resv_map *resv, 680 int regions_needed) 681 __must_hold(&resv->lock) 682 { 683 LIST_HEAD(allocated_regions); 684 int to_allocate = 0, i = 0; 685 struct file_region *trg = NULL, *rg = NULL; 686 687 VM_BUG_ON(regions_needed < 0); 688 689 /* 690 * Check for sufficient descriptors in the cache to accommodate 691 * the number of in progress add operations plus regions_needed. 692 * 693 * This is a while loop because when we drop the lock, some other call 694 * to region_add or region_del may have consumed some region_entries, 695 * so we keep looping here until we finally have enough entries for 696 * (adds_in_progress + regions_needed). 697 */ 698 while (resv->region_cache_count < 699 (resv->adds_in_progress + regions_needed)) { 700 to_allocate = resv->adds_in_progress + regions_needed - 701 resv->region_cache_count; 702 703 /* At this point, we should have enough entries in the cache 704 * for all the existing adds_in_progress. We should only be 705 * needing to allocate for regions_needed. 706 */ 707 VM_BUG_ON(resv->region_cache_count < resv->adds_in_progress); 708 709 spin_unlock(&resv->lock); 710 for (i = 0; i < to_allocate; i++) { 711 trg = kmalloc_obj(*trg); 712 if (!trg) 713 goto out_of_memory; 714 list_add(&trg->link, &allocated_regions); 715 } 716 717 spin_lock(&resv->lock); 718 719 list_splice_init(&allocated_regions, &resv->region_cache); 720 resv->region_cache_count += to_allocate; 721 } 722 723 return 0; 724 725 out_of_memory: 726 list_for_each_entry_safe(rg, trg, &allocated_regions, link) { 727 list_del(&rg->link); 728 kfree(rg); 729 } 730 return -ENOMEM; 731 } 732 733 /* 734 * Add the huge page range represented by [f, t) to the reserve 735 * map. Regions will be taken from the cache to fill in this range. 736 * Sufficient regions should exist in the cache due to the previous 737 * call to region_chg with the same range, but in some cases the cache will not 738 * have sufficient entries due to races with other code doing region_add or 739 * region_del. The extra needed entries will be allocated. 740 * 741 * regions_needed is the out value provided by a previous call to region_chg. 742 * 743 * Return the number of new huge pages added to the map. This number is greater 744 * than or equal to zero. If file_region entries needed to be allocated for 745 * this operation and we were not able to allocate, it returns -ENOMEM. 746 * region_add of regions of length 1 never allocate file_regions and cannot 747 * fail; region_chg will always allocate at least 1 entry and a region_add for 748 * 1 page will only require at most 1 entry. 749 */ 750 static long region_add(struct resv_map *resv, long f, long t, 751 long in_regions_needed, struct hstate *h, 752 struct hugetlb_cgroup *h_cg) 753 { 754 long add = 0, actual_regions_needed = 0; 755 756 spin_lock(&resv->lock); 757 retry: 758 759 /* Count how many regions are actually needed to execute this add. */ 760 add_reservation_in_range(resv, f, t, NULL, NULL, 761 &actual_regions_needed); 762 763 /* 764 * Check for sufficient descriptors in the cache to accommodate 765 * this add operation. Note that actual_regions_needed may be greater 766 * than in_regions_needed, as the resv_map may have been modified since 767 * the region_chg call. In this case, we need to make sure that we 768 * allocate extra entries, such that we have enough for all the 769 * existing adds_in_progress, plus the excess needed for this 770 * operation. 771 */ 772 if (actual_regions_needed > in_regions_needed && 773 resv->region_cache_count < 774 resv->adds_in_progress + 775 (actual_regions_needed - in_regions_needed)) { 776 /* region_add operation of range 1 should never need to 777 * allocate file_region entries. 778 */ 779 VM_BUG_ON(t - f <= 1); 780 781 if (allocate_file_region_entries( 782 resv, actual_regions_needed - in_regions_needed)) { 783 return -ENOMEM; 784 } 785 786 goto retry; 787 } 788 789 add = add_reservation_in_range(resv, f, t, h_cg, h, NULL); 790 791 resv->adds_in_progress -= in_regions_needed; 792 793 spin_unlock(&resv->lock); 794 return add; 795 } 796 797 /* 798 * Examine the existing reserve map and determine how many 799 * huge pages in the specified range [f, t) are NOT currently 800 * represented. This routine is called before a subsequent 801 * call to region_add that will actually modify the reserve 802 * map to add the specified range [f, t). region_chg does 803 * not change the number of huge pages represented by the 804 * map. A number of new file_region structures is added to the cache as a 805 * placeholder, for the subsequent region_add call to use. At least 1 806 * file_region structure is added. 807 * 808 * out_regions_needed is the number of regions added to the 809 * resv->adds_in_progress. This value needs to be provided to a follow up call 810 * to region_add or region_abort for proper accounting. 811 * 812 * Returns the number of huge pages that need to be added to the existing 813 * reservation map for the range [f, t). This number is greater or equal to 814 * zero. -ENOMEM is returned if a new file_region structure or cache entry 815 * is needed and can not be allocated. 816 */ 817 static long region_chg(struct resv_map *resv, long f, long t, 818 long *out_regions_needed) 819 { 820 long chg = 0; 821 822 spin_lock(&resv->lock); 823 824 /* Count how many hugepages in this range are NOT represented. */ 825 chg = add_reservation_in_range(resv, f, t, NULL, NULL, 826 out_regions_needed); 827 828 if (*out_regions_needed == 0) 829 *out_regions_needed = 1; 830 831 if (allocate_file_region_entries(resv, *out_regions_needed)) 832 return -ENOMEM; 833 834 resv->adds_in_progress += *out_regions_needed; 835 836 spin_unlock(&resv->lock); 837 return chg; 838 } 839 840 /* 841 * Abort the in progress add operation. The adds_in_progress field 842 * of the resv_map keeps track of the operations in progress between 843 * calls to region_chg and region_add. Operations are sometimes 844 * aborted after the call to region_chg. In such cases, region_abort 845 * is called to decrement the adds_in_progress counter. regions_needed 846 * is the value returned by the region_chg call, it is used to decrement 847 * the adds_in_progress counter. 848 * 849 * NOTE: The range arguments [f, t) are not needed or used in this 850 * routine. They are kept to make reading the calling code easier as 851 * arguments will match the associated region_chg call. 852 */ 853 static void region_abort(struct resv_map *resv, long f, long t, 854 long regions_needed) 855 { 856 spin_lock(&resv->lock); 857 VM_BUG_ON(!resv->region_cache_count); 858 resv->adds_in_progress -= regions_needed; 859 spin_unlock(&resv->lock); 860 } 861 862 /* 863 * Delete the specified range [f, t) from the reserve map. If the 864 * t parameter is LONG_MAX, this indicates that ALL regions after f 865 * should be deleted. Locate the regions which intersect [f, t) 866 * and either trim, delete or split the existing regions. 867 * 868 * Returns the number of huge pages deleted from the reserve map. 869 * In the normal case, the return value is zero or more. In the 870 * case where a region must be split, a new region descriptor must 871 * be allocated. If the allocation fails, -ENOMEM will be returned. 872 * NOTE: If the parameter t == LONG_MAX, then we will never split 873 * a region and possibly return -ENOMEM. Callers specifying 874 * t == LONG_MAX do not need to check for -ENOMEM error. 875 */ 876 static long region_del(struct resv_map *resv, long f, long t) 877 { 878 struct list_head *head = &resv->regions; 879 struct file_region *rg, *trg; 880 struct file_region *nrg = NULL; 881 long del = 0; 882 883 retry: 884 spin_lock(&resv->lock); 885 list_for_each_entry_safe(rg, trg, head, link) { 886 /* 887 * Skip regions before the range to be deleted. file_region 888 * ranges are normally of the form [from, to). However, there 889 * may be a "placeholder" entry in the map which is of the form 890 * (from, to) with from == to. Check for placeholder entries 891 * at the beginning of the range to be deleted. 892 */ 893 if (rg->to <= f && (rg->to != rg->from || rg->to != f)) 894 continue; 895 896 if (rg->from >= t) 897 break; 898 899 if (f > rg->from && t < rg->to) { /* Must split region */ 900 /* 901 * Check for an entry in the cache before dropping 902 * lock and attempting allocation. 903 */ 904 if (!nrg && 905 resv->region_cache_count > resv->adds_in_progress) { 906 nrg = list_first_entry(&resv->region_cache, 907 struct file_region, 908 link); 909 list_del(&nrg->link); 910 resv->region_cache_count--; 911 } 912 913 if (!nrg) { 914 spin_unlock(&resv->lock); 915 nrg = kmalloc_obj(*nrg); 916 if (!nrg) 917 return -ENOMEM; 918 goto retry; 919 } 920 921 del += t - f; 922 hugetlb_cgroup_uncharge_file_region( 923 resv, rg, t - f, false); 924 925 /* New entry for end of split region */ 926 nrg->from = t; 927 nrg->to = rg->to; 928 929 copy_hugetlb_cgroup_uncharge_info(nrg, rg); 930 931 INIT_LIST_HEAD(&nrg->link); 932 933 /* Original entry is trimmed */ 934 rg->to = f; 935 936 list_add(&nrg->link, &rg->link); 937 nrg = NULL; 938 break; 939 } 940 941 if (f <= rg->from && t >= rg->to) { /* Remove entire region */ 942 del += rg->to - rg->from; 943 hugetlb_cgroup_uncharge_file_region(resv, rg, 944 rg->to - rg->from, true); 945 list_del(&rg->link); 946 kfree(rg); 947 continue; 948 } 949 950 if (f <= rg->from) { /* Trim beginning of region */ 951 hugetlb_cgroup_uncharge_file_region(resv, rg, 952 t - rg->from, false); 953 954 del += t - rg->from; 955 rg->from = t; 956 } else { /* Trim end of region */ 957 hugetlb_cgroup_uncharge_file_region(resv, rg, 958 rg->to - f, false); 959 960 del += rg->to - f; 961 rg->to = f; 962 } 963 } 964 965 spin_unlock(&resv->lock); 966 kfree(nrg); 967 return del; 968 } 969 970 /* 971 * A rare out of memory error was encountered which prevented removal of 972 * the reserve map region for a page. The huge page itself was free'ed 973 * and removed from the page cache. This routine will adjust the subpool 974 * usage count, and the global reserve count if needed. By incrementing 975 * these counts, the reserve map entry which could not be deleted will 976 * appear as a "reserved" entry instead of simply dangling with incorrect 977 * counts. 978 */ 979 void hugetlb_fix_reserve_counts(struct inode *inode) 980 { 981 struct hugepage_subpool *spool = subpool_inode(inode); 982 long rsv_adjust; 983 bool reserved = false; 984 985 rsv_adjust = hugepage_subpool_get_pages(spool, 1); 986 if (rsv_adjust > 0) { 987 struct hstate *h = hstate_inode(inode); 988 989 if (!hugetlb_acct_memory(h, 1)) 990 reserved = true; 991 } else if (!rsv_adjust) { 992 reserved = true; 993 } 994 995 if (!reserved) 996 pr_warn("Huge Page Reserved count may go negative.\n"); 997 } 998 999 /* 1000 * Count and return the number of huge pages in the reserve map 1001 * that intersect with the range [f, t). 1002 */ 1003 static long region_count(struct resv_map *resv, long f, long t) 1004 { 1005 struct list_head *head = &resv->regions; 1006 struct file_region *rg; 1007 long chg = 0; 1008 1009 spin_lock(&resv->lock); 1010 /* Locate each segment we overlap with, and count that overlap. */ 1011 list_for_each_entry(rg, head, link) { 1012 long seg_from; 1013 long seg_to; 1014 1015 if (rg->to <= f) 1016 continue; 1017 if (rg->from >= t) 1018 break; 1019 1020 seg_from = max(rg->from, f); 1021 seg_to = min(rg->to, t); 1022 1023 chg += seg_to - seg_from; 1024 } 1025 spin_unlock(&resv->lock); 1026 1027 return chg; 1028 } 1029 1030 /* 1031 * Convert the address within this vma to the page offset within 1032 * the mapping, huge page units here. 1033 */ 1034 static pgoff_t vma_hugecache_offset(struct hstate *h, 1035 struct vm_area_struct *vma, unsigned long address) 1036 { 1037 return linear_page_index(vma, address) >> huge_page_order(h); 1038 } 1039 1040 /* 1041 * Flags for MAP_PRIVATE reservations. These are stored in the bottom 1042 * bits of the reservation map pointer, which are always clear due to 1043 * alignment. 1044 */ 1045 #define HPAGE_RESV_OWNER (1UL << 0) 1046 #define HPAGE_RESV_UNMAPPED (1UL << 1) 1047 #define HPAGE_RESV_MASK (HPAGE_RESV_OWNER | HPAGE_RESV_UNMAPPED) 1048 1049 /* 1050 * These helpers are used to track how many pages are reserved for 1051 * faults in a MAP_PRIVATE mapping. Only the process that called mmap() 1052 * is guaranteed to have their future faults succeed. 1053 * 1054 * With the exception of hugetlb_dup_vma_private() which is called at fork(), 1055 * the reserve counters are updated with the hugetlb_lock held. It is safe 1056 * to reset the VMA at fork() time as it is not in use yet and there is no 1057 * chance of the global counters getting corrupted as a result of the values. 1058 * 1059 * The private mapping reservation is represented in a subtly different 1060 * manner to a shared mapping. A shared mapping has a region map associated 1061 * with the underlying file, this region map represents the backing file 1062 * pages which have ever had a reservation assigned which this persists even 1063 * after the page is instantiated. A private mapping has a region map 1064 * associated with the original mmap which is attached to all VMAs which 1065 * reference it, this region map represents those offsets which have consumed 1066 * reservation ie. where pages have been instantiated. 1067 */ 1068 static unsigned long get_vma_private_data(struct vm_area_struct *vma) 1069 { 1070 return (unsigned long)vma->vm_private_data; 1071 } 1072 1073 static void set_vma_private_data(struct vm_area_struct *vma, 1074 unsigned long value) 1075 { 1076 vma->vm_private_data = (void *)value; 1077 } 1078 1079 static void 1080 resv_map_set_hugetlb_cgroup_uncharge_info(struct resv_map *resv_map, 1081 struct hugetlb_cgroup *h_cg, 1082 struct hstate *h) 1083 { 1084 #ifdef CONFIG_CGROUP_HUGETLB 1085 if (!h_cg || !h) { 1086 resv_map->reservation_counter = NULL; 1087 resv_map->pages_per_hpage = 0; 1088 resv_map->css = NULL; 1089 } else { 1090 resv_map->reservation_counter = 1091 &h_cg->rsvd_hugepage[hstate_index(h)]; 1092 resv_map->pages_per_hpage = pages_per_huge_page(h); 1093 resv_map->css = &h_cg->css; 1094 } 1095 #endif 1096 } 1097 1098 struct resv_map *resv_map_alloc(void) 1099 { 1100 struct resv_map *resv_map = kmalloc_obj(*resv_map); 1101 struct file_region *rg = kmalloc_obj(*rg); 1102 1103 if (!resv_map || !rg) { 1104 kfree(resv_map); 1105 kfree(rg); 1106 return NULL; 1107 } 1108 1109 kref_init(&resv_map->refs); 1110 spin_lock_init(&resv_map->lock); 1111 INIT_LIST_HEAD(&resv_map->regions); 1112 init_rwsem(&resv_map->rw_sema); 1113 1114 resv_map->adds_in_progress = 0; 1115 /* 1116 * Initialize these to 0. On shared mappings, 0's here indicate these 1117 * fields don't do cgroup accounting. On private mappings, these will be 1118 * re-initialized to the proper values, to indicate that hugetlb cgroup 1119 * reservations are to be un-charged from here. 1120 */ 1121 resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, NULL, NULL); 1122 1123 INIT_LIST_HEAD(&resv_map->region_cache); 1124 list_add(&rg->link, &resv_map->region_cache); 1125 resv_map->region_cache_count = 1; 1126 1127 return resv_map; 1128 } 1129 1130 void resv_map_release(struct kref *ref) 1131 { 1132 struct resv_map *resv_map = container_of(ref, struct resv_map, refs); 1133 struct list_head *head = &resv_map->region_cache; 1134 struct file_region *rg, *trg; 1135 1136 /* Clear out any active regions before we release the map. */ 1137 region_del(resv_map, 0, LONG_MAX); 1138 1139 /* ... and any entries left in the cache */ 1140 list_for_each_entry_safe(rg, trg, head, link) { 1141 list_del(&rg->link); 1142 kfree(rg); 1143 } 1144 1145 VM_BUG_ON(resv_map->adds_in_progress); 1146 1147 kfree(resv_map); 1148 } 1149 1150 static inline struct resv_map *inode_resv_map(struct inode *inode) 1151 { 1152 return HUGETLBFS_I(inode)->resv_map; 1153 } 1154 1155 static struct resv_map *vma_resv_map(struct vm_area_struct *vma) 1156 { 1157 VM_WARN_ON_ONCE_VMA(!vma_is_hugetlb(vma), vma); 1158 if (vma->vm_flags & VM_MAYSHARE) { 1159 struct address_space *mapping = vma->vm_file->f_mapping; 1160 struct inode *inode = mapping->host; 1161 1162 return inode_resv_map(inode); 1163 1164 } else { 1165 return (struct resv_map *)(get_vma_private_data(vma) & 1166 ~HPAGE_RESV_MASK); 1167 } 1168 } 1169 1170 static void set_vma_resv_map(struct vm_area_struct *vma, struct resv_map *map) 1171 { 1172 VM_WARN_ON_ONCE_VMA(!vma_is_hugetlb(vma), vma); 1173 VM_WARN_ON_ONCE_VMA(vma_test(vma, VMA_MAYSHARE_BIT), vma); 1174 1175 set_vma_private_data(vma, (unsigned long)map); 1176 } 1177 1178 static void set_vma_resv_flags(struct vm_area_struct *vma, unsigned long flags) 1179 { 1180 VM_WARN_ON_ONCE_VMA(!vma_is_hugetlb(vma), vma); 1181 VM_WARN_ON_ONCE_VMA(vma_test(vma, VMA_MAYSHARE_BIT), vma); 1182 1183 set_vma_private_data(vma, get_vma_private_data(vma) | flags); 1184 } 1185 1186 static int is_vma_resv_set(struct vm_area_struct *vma, unsigned long flag) 1187 { 1188 VM_WARN_ON_ONCE_VMA(!vma_is_hugetlb(vma), vma); 1189 1190 return (get_vma_private_data(vma) & flag) != 0; 1191 } 1192 1193 bool __vma_private_lock(struct vm_area_struct *vma) 1194 { 1195 return !(vma->vm_flags & VM_MAYSHARE) && 1196 get_vma_private_data(vma) & ~HPAGE_RESV_MASK && 1197 is_vma_resv_set(vma, HPAGE_RESV_OWNER); 1198 } 1199 1200 void hugetlb_dup_vma_private(struct vm_area_struct *vma) 1201 { 1202 VM_WARN_ON_ONCE_VMA(!vma_is_hugetlb(vma), vma); 1203 /* 1204 * Clear vm_private_data 1205 * - For shared mappings this is a per-vma semaphore that may be 1206 * allocated in a subsequent call to hugetlb_vm_op_open. 1207 * Before clearing, make sure pointer is not associated with vma 1208 * as this will leak the structure. This is the case when called 1209 * via clear_vma_resv_huge_pages() and hugetlb_vm_op_open has already 1210 * been called to allocate a new structure. 1211 * - For MAP_PRIVATE mappings, this is the reserve map which does 1212 * not apply to children. Faults generated by the children are 1213 * not guaranteed to succeed, even if read-only. 1214 */ 1215 if (vma->vm_flags & VM_MAYSHARE) { 1216 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data; 1217 1218 if (vma_lock && vma_lock->vma != vma) 1219 vma->vm_private_data = NULL; 1220 } else { 1221 vma->vm_private_data = NULL; 1222 } 1223 } 1224 1225 /* 1226 * Reset and decrement one ref on hugepage private reservation. 1227 * Called with mm->mmap_lock writer semaphore held. 1228 * This function should be only used by mremap and operate on 1229 * same sized vma. It should never come here with last ref on the 1230 * reservation. 1231 */ 1232 void clear_vma_resv_huge_pages(struct vm_area_struct *vma) 1233 { 1234 /* 1235 * Clear the old hugetlb private page reservation. 1236 * It has already been transferred to new_vma. 1237 * 1238 * During a mremap() operation of a hugetlb vma we call move_vma() 1239 * which copies vma into new_vma and unmaps vma. After the copy 1240 * operation both new_vma and vma share a reference to the resv_map 1241 * struct, and at that point vma is about to be unmapped. We don't 1242 * want to return the reservation to the pool at unmap of vma because 1243 * the reservation still lives on in new_vma, so simply decrement the 1244 * ref here and remove the resv_map reference from this vma. 1245 */ 1246 struct resv_map *reservations = vma_resv_map(vma); 1247 1248 if (reservations && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) { 1249 resv_map_put_hugetlb_cgroup_uncharge_info(reservations); 1250 kref_put(&reservations->refs, resv_map_release); 1251 } 1252 1253 hugetlb_dup_vma_private(vma); 1254 } 1255 1256 static void enqueue_hugetlb_folio(struct hstate *h, struct folio *folio) 1257 { 1258 int nid = folio_nid(folio); 1259 1260 lockdep_assert_held(&hugetlb_lock); 1261 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio); 1262 1263 list_move(&folio->lru, &h->hugepage_freelists[nid]); 1264 h->free_huge_pages++; 1265 h->free_huge_pages_node[nid]++; 1266 folio_set_hugetlb_freed(folio); 1267 } 1268 1269 static struct folio *dequeue_hugetlb_folio_node_exact(struct hstate *h, 1270 int nid) 1271 { 1272 struct folio *folio; 1273 bool pin = !!(current->flags & PF_MEMALLOC_PIN); 1274 1275 lockdep_assert_held(&hugetlb_lock); 1276 list_for_each_entry(folio, &h->hugepage_freelists[nid], lru) { 1277 if (pin && !folio_is_longterm_pinnable(folio)) 1278 continue; 1279 1280 if (folio_test_hwpoison(folio)) 1281 continue; 1282 1283 if (is_migrate_isolate_page(&folio->page)) 1284 continue; 1285 1286 list_move(&folio->lru, &h->hugepage_activelist); 1287 folio_ref_unfreeze(folio, 1); 1288 folio_clear_hugetlb_freed(folio); 1289 h->free_huge_pages--; 1290 h->free_huge_pages_node[nid]--; 1291 return folio; 1292 } 1293 1294 return NULL; 1295 } 1296 1297 static struct folio *dequeue_hugetlb_folio_nodemask(struct hstate *h, gfp_t gfp_mask, 1298 int nid, nodemask_t *nmask) 1299 { 1300 unsigned int cpuset_mems_cookie, zonelist_cookie; 1301 struct zonelist *zonelist; 1302 struct zone *zone; 1303 struct zoneref *z; 1304 int node; 1305 1306 /* 'nid' should not be NUMA_NO_NODE. Try to catch any misuse of it and rectifiy. */ 1307 if (nid == NUMA_NO_NODE) 1308 nid = numa_node_id(); 1309 1310 zonelist = node_zonelist(nid, gfp_mask); 1311 1312 retry_cpuset: 1313 node = NUMA_NO_NODE; 1314 cpuset_mems_cookie = read_mems_allowed_begin(); 1315 zonelist_cookie = zonelist_iter_begin(); 1316 for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nmask) { 1317 struct folio *folio; 1318 1319 /* A rebuild may have shifted a node outside @nmask into this slot. */ 1320 if (unlikely(check_retry_zonelist(zonelist_cookie))) 1321 goto retry_cpuset; 1322 1323 if (!cpuset_zone_allowed(zone, gfp_mask)) 1324 continue; 1325 /* 1326 * no need to ask again on the same node. Pool is node rather than 1327 * zone aware 1328 */ 1329 if (zone_to_nid(zone) == node) 1330 continue; 1331 node = zone_to_nid(zone); 1332 1333 folio = dequeue_hugetlb_folio_node_exact(h, node); 1334 if (folio) 1335 return folio; 1336 } 1337 if (unlikely(read_mems_allowed_retry(cpuset_mems_cookie) || 1338 check_retry_zonelist(zonelist_cookie))) 1339 goto retry_cpuset; 1340 1341 return NULL; 1342 } 1343 1344 static unsigned long available_huge_pages(struct hstate *h) 1345 { 1346 return h->free_huge_pages - h->resv_huge_pages; 1347 } 1348 1349 static struct folio *dequeue_hugetlb_folio(struct hstate *h, gfp_t gfp_mask, 1350 struct mempolicy_interpreted *mpoli) 1351 { 1352 nodemask_t *nodemask = mpoli->nodemask; 1353 struct folio *folio = NULL; 1354 1355 if (mpoli->mode == MPOL_PREFERRED_MANY) { 1356 folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask, 1357 mpoli->nid, 1358 nodemask); 1359 1360 /* Fallback to all nodes if page==NULL */ 1361 nodemask = NULL; 1362 } 1363 1364 if (!folio) { 1365 folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask, 1366 mpoli->nid, 1367 nodemask); 1368 } 1369 return folio; 1370 } 1371 1372 #if defined(CONFIG_ARCH_HAS_GIGANTIC_PAGE) && defined(CONFIG_CONTIG_ALLOC) 1373 static struct folio *alloc_gigantic_frozen_folio(int order, gfp_t gfp_mask, 1374 int nid, nodemask_t *nodemask) 1375 { 1376 struct folio *folio; 1377 1378 folio = hugetlb_cma_alloc_frozen_folio(order, gfp_mask, nid, nodemask); 1379 if (folio) 1380 return folio; 1381 1382 if (hugetlb_cma_exclusive_alloc()) 1383 return NULL; 1384 1385 folio = (struct folio *)alloc_contig_frozen_pages(1 << order, gfp_mask, 1386 nid, nodemask); 1387 return folio; 1388 } 1389 #else /* !CONFIG_ARCH_HAS_GIGANTIC_PAGE || !CONFIG_CONTIG_ALLOC */ 1390 static struct folio *alloc_gigantic_frozen_folio(int order, gfp_t gfp_mask, int nid, 1391 nodemask_t *nodemask) 1392 { 1393 return NULL; 1394 } 1395 #endif 1396 1397 /* 1398 * Remove hugetlb folio from lists. 1399 * If vmemmap exists for the folio, clear the hugetlb flag so that the 1400 * folio appears as just a compound page. Otherwise, wait until after 1401 * allocating vmemmap to clear the flag. 1402 * 1403 * Must be called with hugetlb lock held. 1404 */ 1405 void remove_hugetlb_folio(struct hstate *h, struct folio *folio, 1406 bool adjust_surplus) 1407 { 1408 int nid = folio_nid(folio); 1409 1410 VM_BUG_ON_FOLIO(hugetlb_cgroup_from_folio(folio), folio); 1411 VM_BUG_ON_FOLIO(hugetlb_cgroup_from_folio_rsvd(folio), folio); 1412 1413 lockdep_assert_held(&hugetlb_lock); 1414 if (hstate_is_gigantic_no_runtime(h)) { 1415 /* Callers must filter gigantic_no_runtime upstream. */ 1416 VM_WARN_ON_ONCE(1); 1417 return; 1418 } 1419 1420 list_del(&folio->lru); 1421 1422 if (folio_test_hugetlb_freed(folio)) { 1423 folio_clear_hugetlb_freed(folio); 1424 h->free_huge_pages--; 1425 h->free_huge_pages_node[nid]--; 1426 } 1427 if (adjust_surplus) { 1428 h->surplus_huge_pages--; 1429 h->surplus_huge_pages_node[nid]--; 1430 } 1431 1432 /* 1433 * We can only clear the hugetlb flag after allocating vmemmap 1434 * pages. Otherwise, someone (memory error handling) may try to write 1435 * to tail struct pages. 1436 */ 1437 if (!folio_test_hugetlb_vmemmap_optimized(folio)) 1438 __folio_clear_hugetlb(folio); 1439 1440 h->nr_huge_pages--; 1441 h->nr_huge_pages_node[nid]--; 1442 } 1443 1444 void add_hugetlb_folio(struct hstate *h, struct folio *folio, 1445 bool adjust_surplus) 1446 { 1447 int nid = folio_nid(folio); 1448 1449 VM_BUG_ON_FOLIO(!folio_test_hugetlb_vmemmap_optimized(folio), folio); 1450 1451 lockdep_assert_held(&hugetlb_lock); 1452 1453 INIT_LIST_HEAD(&folio->lru); 1454 h->nr_huge_pages++; 1455 h->nr_huge_pages_node[nid]++; 1456 1457 if (adjust_surplus) { 1458 h->surplus_huge_pages++; 1459 h->surplus_huge_pages_node[nid]++; 1460 } 1461 1462 __folio_set_hugetlb(folio); 1463 /* Clear all folio->private flags except hugetlb_vmemmap_optimized. */ 1464 folio->private = NULL; 1465 folio_set_hugetlb_vmemmap_optimized(folio); 1466 1467 arch_clear_hugetlb_flags(folio); 1468 enqueue_hugetlb_folio(h, folio); 1469 } 1470 1471 static void __update_and_free_hugetlb_folio(struct hstate *h, 1472 struct folio *folio) 1473 { 1474 bool clear_flag = folio_test_hugetlb_vmemmap_optimized(folio); 1475 1476 if (hstate_is_gigantic_no_runtime(h)) { 1477 /* Callers must filter gigantic_no_runtime upstream. */ 1478 VM_WARN_ON_ONCE(1); 1479 return; 1480 } 1481 1482 /* 1483 * If we don't know which subpages are hwpoisoned, we can't free 1484 * the hugepage, so it's leaked intentionally. 1485 */ 1486 if (folio_test_hugetlb_raw_hwp_unreliable(folio)) 1487 return; 1488 1489 /* 1490 * If folio is not vmemmap optimized (!clear_flag), then the folio 1491 * is no longer identified as a hugetlb page. hugetlb_vmemmap_restore_folio 1492 * can only be passed hugetlb pages and will BUG otherwise. 1493 */ 1494 if (clear_flag && hugetlb_vmemmap_restore_folio(h, folio)) { 1495 spin_lock_irq(&hugetlb_lock); 1496 /* 1497 * If we cannot allocate vmemmap pages, just refuse to free the 1498 * page and put the page back on the hugetlb free list and treat 1499 * as a surplus page. 1500 */ 1501 add_hugetlb_folio(h, folio, true); 1502 spin_unlock_irq(&hugetlb_lock); 1503 return; 1504 } 1505 1506 /* 1507 * If vmemmap pages were allocated above, then we need to clear the 1508 * hugetlb flag under the hugetlb lock. 1509 */ 1510 if (folio_test_hugetlb(folio)) { 1511 spin_lock_irq(&hugetlb_lock); 1512 __folio_clear_hugetlb(folio); 1513 spin_unlock_irq(&hugetlb_lock); 1514 } 1515 1516 /* 1517 * Move PageHWPoison flag from head page to the raw error pages, 1518 * which makes any healthy subpages reusable. 1519 */ 1520 if (unlikely(folio_test_hwpoison(folio))) 1521 folio_clear_hugetlb_hwpoison(folio); 1522 1523 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio); 1524 if (folio_test_hugetlb_cma(folio)) 1525 hugetlb_cma_free_frozen_folio(folio); 1526 else 1527 free_frozen_pages(&folio->page, folio_order(folio)); 1528 } 1529 1530 /* 1531 * As update_and_free_hugetlb_folio() can be called under any context, so we cannot 1532 * use GFP_KERNEL to allocate vmemmap pages. However, we can defer the 1533 * actual freeing in a workqueue to prevent from using GFP_ATOMIC to allocate 1534 * the vmemmap pages. 1535 * 1536 * free_hpage_workfn() locklessly retrieves the linked list of pages to be 1537 * freed and frees them one-by-one. As the page->mapping pointer is going 1538 * to be cleared in free_hpage_workfn() anyway, it is reused as the llist_node 1539 * structure of a lockless linked list of huge pages to be freed. 1540 */ 1541 static LLIST_HEAD(hpage_freelist); 1542 1543 static void free_hpage_workfn(struct work_struct *work) 1544 { 1545 struct llist_node *node; 1546 1547 node = llist_del_all(&hpage_freelist); 1548 1549 while (node) { 1550 struct folio *folio; 1551 struct hstate *h; 1552 1553 folio = container_of((struct address_space **)node, 1554 struct folio, mapping); 1555 node = node->next; 1556 folio->mapping = NULL; 1557 /* 1558 * The VM_BUG_ON_FOLIO(!folio_test_hugetlb(folio), folio) in 1559 * folio_hstate() is going to trigger because a previous call to 1560 * remove_hugetlb_folio() will clear the hugetlb bit, so do 1561 * not use folio_hstate() directly. 1562 */ 1563 h = size_to_hstate(folio_size(folio)); 1564 1565 __update_and_free_hugetlb_folio(h, folio); 1566 1567 cond_resched(); 1568 } 1569 } 1570 static DECLARE_WORK(free_hpage_work, free_hpage_workfn); 1571 1572 static inline void flush_free_hpage_work(struct hstate *h) 1573 { 1574 if (hugetlb_vmemmap_optimizable(h)) 1575 flush_work(&free_hpage_work); 1576 } 1577 1578 static void update_and_free_hugetlb_folio(struct hstate *h, struct folio *folio, 1579 bool atomic) 1580 { 1581 if (!folio_test_hugetlb_vmemmap_optimized(folio) || !atomic) { 1582 __update_and_free_hugetlb_folio(h, folio); 1583 return; 1584 } 1585 1586 /* 1587 * Defer freeing to avoid using GFP_ATOMIC to allocate vmemmap pages. 1588 * 1589 * Only call schedule_work() if hpage_freelist is previously 1590 * empty. Otherwise, schedule_work() had been called but the workfn 1591 * hasn't retrieved the list yet. 1592 */ 1593 if (llist_add((struct llist_node *)&folio->mapping, &hpage_freelist)) 1594 schedule_work(&free_hpage_work); 1595 } 1596 1597 static void bulk_vmemmap_restore_error(struct hstate *h, 1598 struct list_head *folio_list, 1599 struct list_head *non_hvo_folios) 1600 { 1601 struct folio *folio, *t_folio; 1602 1603 if (!list_empty(non_hvo_folios)) { 1604 /* 1605 * Free any restored hugetlb pages so that restore of the 1606 * entire list can be retried. 1607 * The idea is that in the common case of ENOMEM errors freeing 1608 * hugetlb pages with vmemmap we will free up memory so that we 1609 * can allocate vmemmap for more hugetlb pages. 1610 */ 1611 list_for_each_entry_safe(folio, t_folio, non_hvo_folios, lru) { 1612 list_del(&folio->lru); 1613 spin_lock_irq(&hugetlb_lock); 1614 __folio_clear_hugetlb(folio); 1615 spin_unlock_irq(&hugetlb_lock); 1616 update_and_free_hugetlb_folio(h, folio, false); 1617 cond_resched(); 1618 } 1619 } else { 1620 /* 1621 * In the case where there are no folios which can be 1622 * immediately freed, we loop through the list trying to restore 1623 * vmemmap individually in the hope that someone elsewhere may 1624 * have done something to cause success (such as freeing some 1625 * memory). If unable to restore a hugetlb page, the hugetlb 1626 * page is made a surplus page and removed from the list. 1627 * If are able to restore vmemmap and free one hugetlb page, we 1628 * quit processing the list to retry the bulk operation. 1629 */ 1630 list_for_each_entry_safe(folio, t_folio, folio_list, lru) 1631 if (hugetlb_vmemmap_restore_folio(h, folio)) { 1632 list_del(&folio->lru); 1633 spin_lock_irq(&hugetlb_lock); 1634 add_hugetlb_folio(h, folio, true); 1635 spin_unlock_irq(&hugetlb_lock); 1636 } else { 1637 list_del(&folio->lru); 1638 spin_lock_irq(&hugetlb_lock); 1639 __folio_clear_hugetlb(folio); 1640 spin_unlock_irq(&hugetlb_lock); 1641 update_and_free_hugetlb_folio(h, folio, false); 1642 cond_resched(); 1643 break; 1644 } 1645 } 1646 } 1647 1648 static void update_and_free_pages_bulk(struct hstate *h, 1649 struct list_head *folio_list) 1650 { 1651 long ret; 1652 struct folio *folio, *t_folio; 1653 LIST_HEAD(non_hvo_folios); 1654 1655 /* 1656 * First allocate required vmemmmap (if necessary) for all folios. 1657 * Carefully handle errors and free up any available hugetlb pages 1658 * in an effort to make forward progress. 1659 */ 1660 retry: 1661 ret = hugetlb_vmemmap_restore_folios(h, folio_list, &non_hvo_folios); 1662 if (ret < 0) { 1663 bulk_vmemmap_restore_error(h, folio_list, &non_hvo_folios); 1664 goto retry; 1665 } 1666 1667 /* 1668 * At this point, list should be empty, ret should be >= 0 and there 1669 * should only be pages on the non_hvo_folios list. 1670 * Do note that the non_hvo_folios list could be empty. 1671 * Without HVO enabled, ret will be 0 and there is no need to call 1672 * __folio_clear_hugetlb as this was done previously. 1673 */ 1674 VM_WARN_ON(!list_empty(folio_list)); 1675 VM_WARN_ON(ret < 0); 1676 if (!list_empty(&non_hvo_folios) && ret) { 1677 spin_lock_irq(&hugetlb_lock); 1678 list_for_each_entry(folio, &non_hvo_folios, lru) 1679 __folio_clear_hugetlb(folio); 1680 spin_unlock_irq(&hugetlb_lock); 1681 } 1682 1683 list_for_each_entry_safe(folio, t_folio, &non_hvo_folios, lru) { 1684 update_and_free_hugetlb_folio(h, folio, false); 1685 cond_resched(); 1686 } 1687 } 1688 1689 struct hstate *size_to_hstate(unsigned long size) 1690 { 1691 struct hstate *h; 1692 1693 for_each_hstate(h) { 1694 if (huge_page_size(h) == size) 1695 return h; 1696 } 1697 return NULL; 1698 } 1699 1700 void free_huge_folio(struct folio *folio) 1701 { 1702 /* 1703 * Can't pass hstate in here because it is called from the 1704 * generic mm code. 1705 */ 1706 struct hstate *h = folio_hstate(folio); 1707 int nid = folio_nid(folio); 1708 struct hugepage_subpool *spool = hugetlb_folio_subpool(folio); 1709 bool restore_reserve; 1710 unsigned long flags; 1711 1712 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio); 1713 VM_BUG_ON_FOLIO(folio_mapcount(folio), folio); 1714 1715 hugetlb_set_folio_subpool(folio, NULL); 1716 if (folio_test_anon(folio)) 1717 __ClearPageAnonExclusive(&folio->page); 1718 folio->mapping = NULL; 1719 restore_reserve = folio_test_hugetlb_restore_reserve(folio); 1720 folio_clear_hugetlb_restore_reserve(folio); 1721 1722 /* 1723 * If HPageRestoreReserve was set on page, page allocation consumed a 1724 * reservation. If the page was associated with a subpool, there 1725 * would have been a page reserved in the subpool before allocation 1726 * via hugepage_subpool_get_pages(). Since we are 'restoring' the 1727 * reservation, do not call hugepage_subpool_put_pages() as this will 1728 * remove the reserved page from the subpool. 1729 */ 1730 if (!restore_reserve) { 1731 /* 1732 * A return code of zero implies that the subpool will be 1733 * under its minimum size if the reservation is not restored 1734 * after page is free. Therefore, force restore_reserve 1735 * operation. 1736 */ 1737 if (hugepage_subpool_put_pages(spool, 1) == 0) 1738 restore_reserve = true; 1739 } 1740 1741 spin_lock_irqsave(&hugetlb_lock, flags); 1742 folio_clear_hugetlb_migratable(folio); 1743 hugetlb_cgroup_uncharge_folio(hstate_index(h), 1744 pages_per_huge_page(h), folio); 1745 hugetlb_cgroup_uncharge_folio_rsvd(hstate_index(h), 1746 pages_per_huge_page(h), folio); 1747 lruvec_stat_mod_folio(folio, NR_HUGETLB, -pages_per_huge_page(h)); 1748 mem_cgroup_uncharge(folio); 1749 if (restore_reserve) 1750 h->resv_huge_pages++; 1751 1752 if (folio_test_hugetlb_temporary(folio)) { 1753 remove_hugetlb_folio(h, folio, false); 1754 spin_unlock_irqrestore(&hugetlb_lock, flags); 1755 update_and_free_hugetlb_folio(h, folio, true); 1756 } else if (h->surplus_huge_pages_node[nid]) { 1757 /* remove the page from active list */ 1758 remove_hugetlb_folio(h, folio, true); 1759 spin_unlock_irqrestore(&hugetlb_lock, flags); 1760 update_and_free_hugetlb_folio(h, folio, true); 1761 } else { 1762 arch_clear_hugetlb_flags(folio); 1763 enqueue_hugetlb_folio(h, folio); 1764 spin_unlock_irqrestore(&hugetlb_lock, flags); 1765 } 1766 } 1767 1768 /* 1769 * Must be called with the hugetlb lock held 1770 */ 1771 static void account_new_hugetlb_folio(struct hstate *h, struct folio *folio) 1772 { 1773 lockdep_assert_held(&hugetlb_lock); 1774 h->nr_huge_pages++; 1775 h->nr_huge_pages_node[folio_nid(folio)]++; 1776 } 1777 1778 void init_new_hugetlb_folio(struct folio *folio) 1779 { 1780 __folio_set_hugetlb(folio); 1781 INIT_LIST_HEAD(&folio->lru); 1782 hugetlb_set_folio_subpool(folio, NULL); 1783 set_hugetlb_cgroup(folio, NULL); 1784 set_hugetlb_cgroup_rsvd(folio, NULL); 1785 } 1786 1787 /* 1788 * Find and lock address space (mapping) in write mode. 1789 * 1790 * Upon entry, the folio is locked which means that folio_mapping() is 1791 * stable. Due to locking order, we can only trylock_write. If we can 1792 * not get the lock, simply return NULL to caller. 1793 */ 1794 struct address_space *hugetlb_folio_mapping_lock_write(struct folio *folio) 1795 { 1796 struct address_space *mapping = folio_mapping(folio); 1797 1798 if (!mapping) 1799 return mapping; 1800 1801 if (i_mmap_trylock_write(mapping)) 1802 return mapping; 1803 1804 return NULL; 1805 } 1806 1807 static struct folio *alloc_buddy_frozen_folio(int order, gfp_t gfp_mask, 1808 int nid, nodemask_t *nmask, nodemask_t *node_alloc_noretry) 1809 { 1810 struct folio *folio; 1811 bool alloc_try_hard = true; 1812 1813 /* 1814 * By default we always try hard to allocate the folio with 1815 * __GFP_RETRY_MAYFAIL flag. However, if we are allocating folios in 1816 * a loop (to adjust global huge page counts) and previous allocation 1817 * failed, do not continue to try hard on the same node. Use the 1818 * node_alloc_noretry bitmap to manage this state information. 1819 */ 1820 if (node_alloc_noretry && node_isset(nid, *node_alloc_noretry)) 1821 alloc_try_hard = false; 1822 if (alloc_try_hard) 1823 gfp_mask |= __GFP_RETRY_MAYFAIL; 1824 1825 folio = (struct folio *)__alloc_frozen_pages(gfp_mask, order, nid, nmask, 1826 ALLOC_DEFAULT); 1827 1828 /* 1829 * If we did not specify __GFP_RETRY_MAYFAIL, but still got a 1830 * folio this indicates an overall state change. Clear bit so 1831 * that we resume normal 'try hard' allocations. 1832 */ 1833 if (node_alloc_noretry && folio && !alloc_try_hard) 1834 node_clear(nid, *node_alloc_noretry); 1835 1836 /* 1837 * If we tried hard to get a folio but failed, set bit so that 1838 * subsequent attempts will not try as hard until there is an 1839 * overall state change. 1840 */ 1841 if (node_alloc_noretry && !folio && alloc_try_hard) 1842 node_set(nid, *node_alloc_noretry); 1843 1844 if (!folio) { 1845 __count_vm_event(HTLB_BUDDY_PGALLOC_FAIL); 1846 return NULL; 1847 } 1848 1849 __count_vm_event(HTLB_BUDDY_PGALLOC); 1850 return folio; 1851 } 1852 1853 static struct folio *only_alloc_fresh_hugetlb_folio(struct hstate *h, 1854 gfp_t gfp_mask, int nid, nodemask_t *nmask, 1855 nodemask_t *node_alloc_noretry) 1856 { 1857 struct folio *folio; 1858 int order = huge_page_order(h); 1859 1860 if (nid == NUMA_NO_NODE) 1861 nid = numa_mem_id(); 1862 1863 if (order_is_gigantic(order)) 1864 folio = alloc_gigantic_frozen_folio(order, gfp_mask, nid, nmask); 1865 else 1866 folio = alloc_buddy_frozen_folio(order, gfp_mask, nid, nmask, 1867 node_alloc_noretry); 1868 if (folio) 1869 init_new_hugetlb_folio(folio); 1870 return folio; 1871 } 1872 1873 /* 1874 * Common helper to allocate a fresh hugetlb folio. All specific allocators 1875 * should use this function to get new hugetlb folio 1876 * 1877 * Note that returned folio is 'frozen': ref count of head page and all tail 1878 * pages is zero, and the accounting must be done in the caller. 1879 */ 1880 static struct folio *alloc_fresh_hugetlb_folio(struct hstate *h, 1881 gfp_t gfp_mask, int nid, nodemask_t *nmask) 1882 { 1883 struct folio *folio; 1884 1885 folio = only_alloc_fresh_hugetlb_folio(h, gfp_mask, nid, nmask, NULL); 1886 if (folio) 1887 hugetlb_vmemmap_optimize_folio(h, folio); 1888 return folio; 1889 } 1890 1891 void prep_and_add_allocated_folios(struct hstate *h, 1892 struct list_head *folio_list) 1893 { 1894 unsigned long flags; 1895 struct folio *folio, *tmp_f; 1896 1897 /* Send list for bulk vmemmap optimization processing */ 1898 hugetlb_vmemmap_optimize_folios(h, folio_list); 1899 1900 /* Add all new pool pages to free lists in one lock cycle */ 1901 spin_lock_irqsave(&hugetlb_lock, flags); 1902 list_for_each_entry_safe(folio, tmp_f, folio_list, lru) { 1903 account_new_hugetlb_folio(h, folio); 1904 enqueue_hugetlb_folio(h, folio); 1905 } 1906 spin_unlock_irqrestore(&hugetlb_lock, flags); 1907 } 1908 1909 /* 1910 * Allocates a fresh hugetlb page in a node interleaved manner. The page 1911 * will later be added to the appropriate hugetlb pool. 1912 */ 1913 static struct folio *alloc_pool_huge_folio(struct hstate *h, 1914 nodemask_t *nodes_allowed, 1915 nodemask_t *node_alloc_noretry, 1916 int *next_node) 1917 { 1918 gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE; 1919 int nr_nodes, node; 1920 1921 for_each_node_mask_to_alloc(next_node, nr_nodes, node, nodes_allowed) { 1922 struct folio *folio; 1923 1924 folio = only_alloc_fresh_hugetlb_folio(h, gfp_mask, node, 1925 nodes_allowed, node_alloc_noretry); 1926 if (folio) 1927 return folio; 1928 } 1929 1930 return NULL; 1931 } 1932 1933 /* 1934 * Remove huge page from pool from next node to free. Attempt to keep 1935 * persistent huge pages more or less balanced over allowed nodes. 1936 * This routine only 'removes' the hugetlb page. The caller must make 1937 * an additional call to free the page to low level allocators. 1938 * Called with hugetlb_lock locked. 1939 */ 1940 static struct folio *remove_pool_hugetlb_folio(struct hstate *h, 1941 nodemask_t *nodes_allowed, bool acct_surplus) 1942 { 1943 int nr_nodes, node; 1944 struct folio *folio = NULL; 1945 1946 lockdep_assert_held(&hugetlb_lock); 1947 for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) { 1948 /* 1949 * If we're returning unused surplus pages, only examine 1950 * nodes with surplus pages. 1951 */ 1952 if ((!acct_surplus || h->surplus_huge_pages_node[node]) && 1953 !list_empty(&h->hugepage_freelists[node])) { 1954 folio = list_entry(h->hugepage_freelists[node].next, 1955 struct folio, lru); 1956 remove_hugetlb_folio(h, folio, acct_surplus); 1957 break; 1958 } 1959 } 1960 1961 return folio; 1962 } 1963 1964 /* 1965 * Dissolve a given free hugetlb folio into free buddy pages. This function 1966 * does nothing for in-use hugetlb folios and non-hugetlb folios. 1967 * This function returns values like below: 1968 * 1969 * -ENOMEM: failed to allocate vmemmap pages to free the freed hugepages 1970 * when the system is under memory pressure and the feature of 1971 * freeing unused vmemmap pages associated with each hugetlb page 1972 * is enabled. 1973 * -EBUSY: failed to dissolved free hugepages or the hugepage is in-use 1974 * (allocated or reserved.) 1975 * 0: successfully dissolved free hugepages or the page is not a 1976 * hugepage (considered as already dissolved) 1977 */ 1978 int dissolve_free_hugetlb_folio(struct folio *folio) 1979 { 1980 int rc = -EBUSY; 1981 1982 retry: 1983 /* Not to disrupt normal path by vainly holding hugetlb_lock */ 1984 if (!folio_test_hugetlb(folio)) 1985 return 0; 1986 1987 spin_lock_irq(&hugetlb_lock); 1988 if (!folio_test_hugetlb(folio)) { 1989 rc = 0; 1990 goto out; 1991 } 1992 1993 if (!folio_ref_count(folio)) { 1994 struct hstate *h = folio_hstate(folio); 1995 bool adjust_surplus = false; 1996 1997 /* 1998 * remove_hugetlb_folio()/update_and_free_hugetlb_folio() bail 1999 * for gigantic hstates without runtime support, so dissolving one 2000 * here would leave it on the free list and, on vmemmap restore 2001 * failure, the add_hugetlb_folio() rollback corrupts that list. 2002 */ 2003 if (hstate_is_gigantic_no_runtime(h)) 2004 goto out; 2005 2006 if (!available_huge_pages(h)) 2007 goto out; 2008 2009 /* 2010 * We should make sure that the page is already on the free list 2011 * when it is dissolved. 2012 */ 2013 if (unlikely(!folio_test_hugetlb_freed(folio))) { 2014 spin_unlock_irq(&hugetlb_lock); 2015 cond_resched(); 2016 2017 /* 2018 * Theoretically, we should return -EBUSY when we 2019 * encounter this race. In fact, we have a chance 2020 * to successfully dissolve the page if we do a 2021 * retry. Because the race window is quite small. 2022 * If we seize this opportunity, it is an optimization 2023 * for increasing the success rate of dissolving page. 2024 */ 2025 goto retry; 2026 } 2027 2028 if (h->surplus_huge_pages_node[folio_nid(folio)]) 2029 adjust_surplus = true; 2030 remove_hugetlb_folio(h, folio, adjust_surplus); 2031 if (!adjust_surplus) 2032 h->max_huge_pages--; 2033 spin_unlock_irq(&hugetlb_lock); 2034 2035 /* 2036 * Normally update_and_free_hugtlb_folio will allocate required vmemmmap 2037 * before freeing the page. update_and_free_hugtlb_folio will fail to 2038 * free the page if it can not allocate required vmemmap. We 2039 * need to adjust max_huge_pages if the page is not freed. 2040 * Attempt to allocate vmemmmap here so that we can take 2041 * appropriate action on failure. 2042 * 2043 * The folio_test_hugetlb check here is because 2044 * remove_hugetlb_folio will clear hugetlb folio flag for 2045 * non-vmemmap optimized hugetlb folios. 2046 */ 2047 if (folio_test_hugetlb(folio)) { 2048 rc = hugetlb_vmemmap_restore_folio(h, folio); 2049 if (rc) { 2050 spin_lock_irq(&hugetlb_lock); 2051 add_hugetlb_folio(h, folio, adjust_surplus); 2052 if (!adjust_surplus) 2053 h->max_huge_pages++; 2054 goto out; 2055 } 2056 } else { 2057 rc = 0; 2058 } 2059 2060 update_and_free_hugetlb_folio(h, folio, false); 2061 return rc; 2062 } 2063 out: 2064 spin_unlock_irq(&hugetlb_lock); 2065 return rc; 2066 } 2067 2068 /* 2069 * Dissolve free hugepages in a given pfn range. Used by memory hotplug to 2070 * make specified memory blocks removable from the system. 2071 * Note that this will dissolve a free gigantic hugepage completely, if any 2072 * part of it lies within the given range. 2073 * Also note that if dissolve_free_hugetlb_folio() returns with an error, all 2074 * free hugetlb folios that were dissolved before that error are lost. 2075 */ 2076 int dissolve_free_hugetlb_folios(unsigned long start_pfn, unsigned long end_pfn) 2077 { 2078 unsigned long pfn; 2079 struct folio *folio; 2080 int rc = 0; 2081 unsigned int order; 2082 struct hstate *h; 2083 2084 if (!hugepages_supported()) 2085 return rc; 2086 2087 order = huge_page_order(&default_hstate); 2088 for_each_hstate(h) 2089 order = min(order, huge_page_order(h)); 2090 2091 for (pfn = start_pfn; pfn < end_pfn; pfn += 1 << order) { 2092 folio = pfn_folio(pfn); 2093 rc = dissolve_free_hugetlb_folio(folio); 2094 if (rc) 2095 break; 2096 } 2097 2098 return rc; 2099 } 2100 2101 /* 2102 * Allocates a fresh surplus page from the page allocator. 2103 */ 2104 static struct folio *alloc_surplus_hugetlb_folio(struct hstate *h, 2105 gfp_t gfp_mask, int nid, nodemask_t *nmask) 2106 { 2107 struct folio *folio = NULL; 2108 2109 if (hstate_is_gigantic_no_runtime(h)) 2110 return NULL; 2111 2112 spin_lock_irq(&hugetlb_lock); 2113 if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) 2114 goto out_unlock; 2115 spin_unlock_irq(&hugetlb_lock); 2116 2117 folio = alloc_fresh_hugetlb_folio(h, gfp_mask, nid, nmask); 2118 if (!folio) 2119 return NULL; 2120 2121 spin_lock_irq(&hugetlb_lock); 2122 /* 2123 * nr_huge_pages needs to be adjusted within the same lock cycle 2124 * as surplus_pages, otherwise it might confuse 2125 * persistent_huge_pages() momentarily. 2126 */ 2127 account_new_hugetlb_folio(h, folio); 2128 2129 /* 2130 * We could have raced with the pool size change. 2131 * Double check that and simply deallocate the new page 2132 * if we would end up overcommiting the surpluses. Abuse 2133 * temporary page to workaround the nasty free_huge_folio 2134 * codeflow 2135 */ 2136 if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) { 2137 folio_set_hugetlb_temporary(folio); 2138 spin_unlock_irq(&hugetlb_lock); 2139 free_huge_folio(folio); 2140 return NULL; 2141 } 2142 2143 h->surplus_huge_pages++; 2144 h->surplus_huge_pages_node[folio_nid(folio)]++; 2145 2146 out_unlock: 2147 spin_unlock_irq(&hugetlb_lock); 2148 2149 return folio; 2150 } 2151 2152 static struct folio *alloc_migrate_hugetlb_folio(struct hstate *h, gfp_t gfp_mask, 2153 int nid, nodemask_t *nmask) 2154 { 2155 struct folio *folio; 2156 2157 if (hstate_is_gigantic(h)) 2158 return NULL; 2159 2160 folio = alloc_fresh_hugetlb_folio(h, gfp_mask, nid, nmask); 2161 if (!folio) 2162 return NULL; 2163 2164 spin_lock_irq(&hugetlb_lock); 2165 account_new_hugetlb_folio(h, folio); 2166 spin_unlock_irq(&hugetlb_lock); 2167 2168 /* fresh huge pages are frozen */ 2169 folio_ref_unfreeze(folio, 1); 2170 /* 2171 * We do not account these pages as surplus because they are only 2172 * temporary and will be released properly on the last reference 2173 */ 2174 folio_set_hugetlb_temporary(folio); 2175 2176 return folio; 2177 } 2178 2179 static 2180 struct folio *alloc_buddy_hugetlb_folio(struct hstate *h, 2181 gfp_t gfp_mask, struct mempolicy_interpreted *mpoli) 2182 { 2183 struct folio *folio = NULL; 2184 nodemask_t *nodemask = mpoli->nodemask; 2185 2186 if (mpoli->mode == MPOL_PREFERRED_MANY) { 2187 gfp_t gfp = gfp_mask & ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL); 2188 2189 folio = alloc_surplus_hugetlb_folio(h, gfp, mpoli->nid, 2190 nodemask); 2191 2192 /* Fallback to all nodes if page==NULL */ 2193 nodemask = NULL; 2194 } 2195 2196 if (!folio) { 2197 folio = alloc_surplus_hugetlb_folio(h, gfp_mask, mpoli->nid, 2198 nodemask); 2199 } 2200 2201 return folio; 2202 } 2203 2204 struct folio *alloc_hugetlb_folio_reserve(struct hstate *h, int preferred_nid, 2205 nodemask_t *nmask, gfp_t gfp_mask) 2206 { 2207 struct folio *folio; 2208 2209 spin_lock_irq(&hugetlb_lock); 2210 if (!h->resv_huge_pages) { 2211 spin_unlock_irq(&hugetlb_lock); 2212 return NULL; 2213 } 2214 2215 folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask, preferred_nid, 2216 nmask); 2217 if (folio) { 2218 folio_set_hugetlb_restore_reserve(folio); 2219 h->resv_huge_pages--; 2220 } 2221 2222 spin_unlock_irq(&hugetlb_lock); 2223 2224 if (folio) 2225 lruvec_stat_mod_folio(folio, NR_HUGETLB, 2226 folio_nr_pages(folio)); 2227 2228 return folio; 2229 } 2230 2231 /* folio migration callback function */ 2232 struct folio *alloc_hugetlb_folio_nodemask(struct hstate *h, int preferred_nid, 2233 nodemask_t *nmask, gfp_t gfp_mask, bool allow_alloc_fallback) 2234 { 2235 struct folio *folio = NULL; 2236 2237 spin_lock_irq(&hugetlb_lock); 2238 if (available_huge_pages(h)) 2239 folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask, 2240 preferred_nid, nmask); 2241 spin_unlock_irq(&hugetlb_lock); 2242 2243 if (!folio) { 2244 /* 2245 * We cannot fallback to other nodes, as we could break the 2246 * per-node pool. 2247 */ 2248 if (!allow_alloc_fallback) 2249 gfp_mask |= __GFP_THISNODE; 2250 2251 folio = alloc_migrate_hugetlb_folio(h, gfp_mask, preferred_nid, 2252 nmask); 2253 } 2254 2255 if (folio) 2256 lruvec_stat_mod_folio(folio, NR_HUGETLB, folio_nr_pages(folio)); 2257 2258 return folio; 2259 } 2260 2261 static nodemask_t *policy_mbind_nodemask(gfp_t gfp) 2262 { 2263 #ifdef CONFIG_NUMA 2264 struct mempolicy *mpol = get_task_policy(current); 2265 2266 /* 2267 * Only enforce MPOL_BIND policy which overlaps with cpuset policy 2268 * (from policy_nodemask) specifically for hugetlb case 2269 */ 2270 if (mpol->mode == MPOL_BIND && 2271 (apply_policy_zone(mpol, gfp_zone(gfp)) && 2272 cpuset_nodemask_valid_mems_allowed(&mpol->nodes))) 2273 return &mpol->nodes; 2274 #endif 2275 return NULL; 2276 } 2277 2278 /* 2279 * Reservations are globally accounted, but they must also be backed by free 2280 * pages on nodes allowed by the current cpuset and MPOL_BIND policy. 2281 */ 2282 static long surplus_pages_needed(struct hstate *h, long delta, long allocated) 2283 { 2284 long global_free = (long)h->free_huge_pages + allocated; 2285 long allowed_free = (long)allowed_mems_nr(h) + allocated; 2286 2287 return max((long)h->resv_huge_pages + delta - global_free, 2288 delta - allowed_free); 2289 } 2290 2291 /* 2292 * Increase the hugetlb pool such that it can accommodate a reservation 2293 * of size 'delta'. 2294 */ 2295 static int gather_surplus_pages(struct hstate *h, long delta) 2296 __must_hold(&hugetlb_lock) 2297 { 2298 LIST_HEAD(surplus_list); 2299 struct folio *folio, *tmp; 2300 int ret; 2301 long i; 2302 long needed, allocated; 2303 bool alloc_ok = true; 2304 nodemask_t *mbind_nodemask, alloc_nodemask; 2305 2306 mbind_nodemask = policy_mbind_nodemask(htlb_alloc_mask(h)); 2307 if (mbind_nodemask) 2308 nodes_and(alloc_nodemask, *mbind_nodemask, cpuset_current_mems_allowed); 2309 else 2310 alloc_nodemask = cpuset_current_mems_allowed; 2311 2312 lockdep_assert_held(&hugetlb_lock); 2313 needed = surplus_pages_needed(h, delta, 0); 2314 if (needed <= 0) { 2315 h->resv_huge_pages += delta; 2316 return 0; 2317 } 2318 2319 allocated = 0; 2320 2321 ret = -ENOMEM; 2322 retry: 2323 spin_unlock_irq(&hugetlb_lock); 2324 for (i = 0; i < needed; i++) { 2325 folio = NULL; 2326 2327 /* 2328 * It is okay to use NUMA_NO_NODE because we use numa_mem_id() 2329 * down the road to pick the current node if that is the case. 2330 */ 2331 folio = alloc_surplus_hugetlb_folio(h, htlb_alloc_mask(h), 2332 NUMA_NO_NODE, &alloc_nodemask); 2333 if (!folio) { 2334 alloc_ok = false; 2335 break; 2336 } 2337 list_add(&folio->lru, &surplus_list); 2338 cond_resched(); 2339 } 2340 allocated += i; 2341 2342 /* 2343 * After retaking hugetlb_lock, we need to recalculate 'needed' 2344 * because either resv_huge_pages or the free page counts may have changed. 2345 */ 2346 spin_lock_irq(&hugetlb_lock); 2347 needed = surplus_pages_needed(h, delta, allocated); 2348 if (needed > 0) { 2349 if (alloc_ok) 2350 goto retry; 2351 /* 2352 * We were not able to allocate enough pages to 2353 * satisfy the entire reservation so we free what 2354 * we've allocated so far. 2355 */ 2356 goto free; 2357 } 2358 /* 2359 * The surplus_list now contains _at_least_ the number of extra pages 2360 * needed to accommodate the reservation. Add the appropriate number 2361 * of pages to the hugetlb pool and free the extras back to the buddy 2362 * allocator. Commit the entire reservation here to prevent another 2363 * process from stealing the pages as they are added to the pool but 2364 * before they are reserved. 2365 */ 2366 needed += allocated; 2367 h->resv_huge_pages += delta; 2368 ret = 0; 2369 2370 /* Free the needed pages to the hugetlb pool */ 2371 list_for_each_entry_safe(folio, tmp, &surplus_list, lru) { 2372 if ((--needed) < 0) 2373 break; 2374 /* Add the page to the hugetlb allocator */ 2375 enqueue_hugetlb_folio(h, folio); 2376 } 2377 free: 2378 spin_unlock_irq(&hugetlb_lock); 2379 2380 /* 2381 * Free unnecessary surplus pages to the buddy allocator. 2382 * Pages have no ref count, call free_huge_folio directly. 2383 */ 2384 list_for_each_entry_safe(folio, tmp, &surplus_list, lru) 2385 free_huge_folio(folio); 2386 spin_lock_irq(&hugetlb_lock); 2387 2388 return ret; 2389 } 2390 2391 /* 2392 * This routine has two main purposes: 2393 * 1) Decrement the reservation count (resv_huge_pages) by the value passed 2394 * in unused_resv_pages. This corresponds to the prior adjustments made 2395 * to the associated reservation map. 2396 * 2) Free any unused surplus pages that may have been allocated to satisfy 2397 * the reservation. As many as unused_resv_pages may be freed. 2398 */ 2399 static void return_unused_surplus_pages(struct hstate *h, 2400 unsigned long unused_resv_pages) 2401 { 2402 unsigned long nr_pages; 2403 LIST_HEAD(page_list); 2404 2405 lockdep_assert_held(&hugetlb_lock); 2406 /* Uncommit the reservation */ 2407 h->resv_huge_pages -= unused_resv_pages; 2408 2409 if (hstate_is_gigantic_no_runtime(h)) 2410 goto out; 2411 2412 /* 2413 * Part (or even all) of the reservation could have been backed 2414 * by pre-allocated pages. Only free surplus pages. 2415 */ 2416 nr_pages = min(unused_resv_pages, h->surplus_huge_pages); 2417 2418 /* 2419 * We want to release as many surplus pages as possible, spread 2420 * evenly across all nodes with memory. Iterate across these nodes 2421 * until we can no longer free unreserved surplus pages. This occurs 2422 * when the nodes with surplus pages have no free pages. 2423 * remove_pool_hugetlb_folio() will balance the freed pages across the 2424 * on-line nodes with memory and will handle the hstate accounting. 2425 */ 2426 while (nr_pages--) { 2427 struct folio *folio; 2428 2429 folio = remove_pool_hugetlb_folio(h, &node_states[N_MEMORY], 1); 2430 if (!folio) 2431 goto out; 2432 2433 list_add(&folio->lru, &page_list); 2434 } 2435 2436 out: 2437 spin_unlock_irq(&hugetlb_lock); 2438 update_and_free_pages_bulk(h, &page_list); 2439 spin_lock_irq(&hugetlb_lock); 2440 } 2441 2442 2443 /* 2444 * vma_needs_reservation, vma_commit_reservation and vma_end_reservation 2445 * are used by the huge page allocation routines to manage reservations. 2446 * 2447 * vma_needs_reservation is called to determine if the huge page at addr 2448 * within the vma has an associated reservation. If a reservation is 2449 * needed, the value 1 is returned. The caller is then responsible for 2450 * managing the global reservation and subpool usage counts. After 2451 * the huge page has been allocated, vma_commit_reservation is called 2452 * to add the page to the reservation map. If the page allocation fails, 2453 * the reservation must be ended instead of committed. vma_end_reservation 2454 * is called in such cases. 2455 * 2456 * In the normal case, vma_commit_reservation returns the same value 2457 * as the preceding vma_needs_reservation call. The only time this 2458 * is not the case is if a reserve map was changed between calls. It 2459 * is the responsibility of the caller to notice the difference and 2460 * take appropriate action. 2461 * 2462 * vma_add_reservation is used in error paths where a reservation must 2463 * be restored when a newly allocated huge page must be freed. It is 2464 * to be called after calling vma_needs_reservation to determine if a 2465 * reservation exists. 2466 * 2467 * vma_del_reservation is used in error paths where an entry in the reserve 2468 * map was created during huge page allocation and must be removed. It is to 2469 * be called after calling vma_needs_reservation to determine if a reservation 2470 * exists. 2471 */ 2472 enum vma_resv_mode { 2473 VMA_NEEDS_RESV, 2474 VMA_COMMIT_RESV, 2475 VMA_END_RESV, 2476 VMA_ADD_RESV, 2477 VMA_DEL_RESV, 2478 }; 2479 static long __vma_reservation_common(struct hstate *h, 2480 struct vm_area_struct *vma, unsigned long addr, 2481 enum vma_resv_mode mode) 2482 { 2483 struct resv_map *resv; 2484 pgoff_t idx; 2485 long ret; 2486 long dummy_out_regions_needed; 2487 2488 resv = vma_resv_map(vma); 2489 if (!resv) 2490 return 1; 2491 2492 idx = vma_hugecache_offset(h, vma, addr); 2493 switch (mode) { 2494 case VMA_NEEDS_RESV: 2495 ret = region_chg(resv, idx, idx + 1, &dummy_out_regions_needed); 2496 /* We assume that vma_reservation_* routines always operate on 2497 * 1 page, and that adding to resv map a 1 page entry can only 2498 * ever require 1 region. 2499 */ 2500 VM_BUG_ON(dummy_out_regions_needed != 1); 2501 break; 2502 case VMA_COMMIT_RESV: 2503 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL); 2504 /* region_add calls of range 1 should never fail. */ 2505 VM_BUG_ON(ret < 0); 2506 break; 2507 case VMA_END_RESV: 2508 region_abort(resv, idx, idx + 1, 1); 2509 ret = 0; 2510 break; 2511 case VMA_ADD_RESV: 2512 if (vma->vm_flags & VM_MAYSHARE) { 2513 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL); 2514 /* region_add calls of range 1 should never fail. */ 2515 VM_BUG_ON(ret < 0); 2516 } else { 2517 region_abort(resv, idx, idx + 1, 1); 2518 ret = region_del(resv, idx, idx + 1); 2519 } 2520 break; 2521 case VMA_DEL_RESV: 2522 if (vma->vm_flags & VM_MAYSHARE) { 2523 region_abort(resv, idx, idx + 1, 1); 2524 ret = region_del(resv, idx, idx + 1); 2525 } else { 2526 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL); 2527 /* region_add calls of range 1 should never fail. */ 2528 VM_BUG_ON(ret < 0); 2529 } 2530 break; 2531 default: 2532 BUG(); 2533 } 2534 2535 if (vma->vm_flags & VM_MAYSHARE || mode == VMA_DEL_RESV) 2536 return ret; 2537 /* 2538 * We know private mapping must have HPAGE_RESV_OWNER set. 2539 * 2540 * In most cases, reserves always exist for private mappings. 2541 * However, a file associated with mapping could have been 2542 * hole punched or truncated after reserves were consumed. 2543 * As subsequent fault on such a range will not use reserves. 2544 * Subtle - The reserve map for private mappings has the 2545 * opposite meaning than that of shared mappings. If NO 2546 * entry is in the reserve map, it means a reservation exists. 2547 * If an entry exists in the reserve map, it means the 2548 * reservation has already been consumed. As a result, the 2549 * return value of this routine is the opposite of the 2550 * value returned from reserve map manipulation routines above. 2551 */ 2552 if (ret > 0) 2553 return 0; 2554 if (ret == 0) 2555 return 1; 2556 return ret; 2557 } 2558 2559 static long vma_needs_reservation(struct hstate *h, 2560 struct vm_area_struct *vma, unsigned long addr) 2561 { 2562 return __vma_reservation_common(h, vma, addr, VMA_NEEDS_RESV); 2563 } 2564 2565 static long vma_commit_reservation(struct hstate *h, 2566 struct vm_area_struct *vma, unsigned long addr) 2567 { 2568 return __vma_reservation_common(h, vma, addr, VMA_COMMIT_RESV); 2569 } 2570 2571 static void vma_end_reservation(struct hstate *h, 2572 struct vm_area_struct *vma, unsigned long addr) 2573 { 2574 (void)__vma_reservation_common(h, vma, addr, VMA_END_RESV); 2575 } 2576 2577 static long vma_add_reservation(struct hstate *h, 2578 struct vm_area_struct *vma, unsigned long addr) 2579 { 2580 return __vma_reservation_common(h, vma, addr, VMA_ADD_RESV); 2581 } 2582 2583 static long vma_del_reservation(struct hstate *h, 2584 struct vm_area_struct *vma, unsigned long addr) 2585 { 2586 return __vma_reservation_common(h, vma, addr, VMA_DEL_RESV); 2587 } 2588 2589 /* 2590 * This routine is called to restore reservation information on error paths. 2591 * It should ONLY be called for folios allocated via alloc_hugetlb_folio(), 2592 * and the hugetlb mutex should remain held when calling this routine. 2593 * 2594 * It handles two specific cases: 2595 * 1) A reservation was in place and the folio consumed the reservation. 2596 * hugetlb_restore_reserve is set in the folio. 2597 * 2) No reservation was in place for the page, so hugetlb_restore_reserve is 2598 * not set. However, alloc_hugetlb_folio always updates the reserve map. 2599 * 2600 * In case 1, free_huge_folio later in the error path will increment the 2601 * global reserve count. But, free_huge_folio does not have enough context 2602 * to adjust the reservation map. This case deals primarily with private 2603 * mappings. Adjust the reserve map here to be consistent with global 2604 * reserve count adjustments to be made by free_huge_folio. Make sure the 2605 * reserve map indicates there is a reservation present. 2606 * 2607 * In case 2, simply undo reserve map modifications done by alloc_hugetlb_folio. 2608 */ 2609 void restore_reserve_on_error(struct hstate *h, struct vm_area_struct *vma, 2610 unsigned long address, struct folio *folio) 2611 { 2612 long rc = vma_needs_reservation(h, vma, address); 2613 2614 if (folio_test_hugetlb_restore_reserve(folio)) { 2615 if (unlikely(rc < 0)) 2616 /* 2617 * Rare out of memory condition in reserve map 2618 * manipulation. Clear hugetlb_restore_reserve so 2619 * that global reserve count will not be incremented 2620 * by free_huge_folio. This will make it appear 2621 * as though the reservation for this folio was 2622 * consumed. This may prevent the task from 2623 * faulting in the folio at a later time. This 2624 * is better than inconsistent global huge page 2625 * accounting of reserve counts. 2626 */ 2627 folio_clear_hugetlb_restore_reserve(folio); 2628 else if (rc) 2629 (void)vma_add_reservation(h, vma, address); 2630 else 2631 vma_end_reservation(h, vma, address); 2632 } else { 2633 if (!rc) { 2634 /* 2635 * This indicates there is an entry in the reserve map 2636 * not added by alloc_hugetlb_folio. We know it was added 2637 * before the alloc_hugetlb_folio call, otherwise 2638 * hugetlb_restore_reserve would be set on the folio. 2639 * Remove the entry so that a subsequent allocation 2640 * does not consume a reservation. 2641 */ 2642 rc = vma_del_reservation(h, vma, address); 2643 if (rc < 0) 2644 /* 2645 * VERY rare out of memory condition. Since 2646 * we can not delete the entry, set 2647 * hugetlb_restore_reserve so that the reserve 2648 * count will be incremented when the folio 2649 * is freed. This reserve will be consumed 2650 * on a subsequent allocation. 2651 */ 2652 folio_set_hugetlb_restore_reserve(folio); 2653 } else if (rc < 0) { 2654 /* 2655 * Rare out of memory condition from 2656 * vma_needs_reservation call. Memory allocation is 2657 * only attempted if a new entry is needed. Therefore, 2658 * this implies there is not an entry in the 2659 * reserve map. 2660 * 2661 * For shared mappings, no entry in the map indicates 2662 * no reservation. We are done. 2663 */ 2664 if (!(vma->vm_flags & VM_MAYSHARE)) 2665 /* 2666 * For private mappings, no entry indicates 2667 * a reservation is present. Since we can 2668 * not add an entry, set hugetlb_restore_reserve 2669 * on the folio so reserve count will be 2670 * incremented when freed. This reserve will 2671 * be consumed on a subsequent allocation. 2672 */ 2673 folio_set_hugetlb_restore_reserve(folio); 2674 } else { 2675 /* 2676 * No reservation present, do nothing 2677 */ 2678 vma_end_reservation(h, vma, address); 2679 } 2680 } 2681 } 2682 2683 /* 2684 * alloc_and_dissolve_hugetlb_folio - Allocate a new folio and dissolve 2685 * the old one 2686 * @old_folio: Old folio to dissolve 2687 * @list: List to isolate the page in case we need to 2688 * Returns 0 on success, otherwise negated error. 2689 */ 2690 static int alloc_and_dissolve_hugetlb_folio(struct folio *old_folio, 2691 struct list_head *list) 2692 { 2693 gfp_t gfp_mask; 2694 struct hstate *h; 2695 int nid = folio_nid(old_folio); 2696 struct folio *new_folio = NULL; 2697 int ret = 0; 2698 2699 retry: 2700 /* 2701 * The old_folio might have been dissolved from under our feet, so make sure 2702 * to carefully check the state under the lock. 2703 */ 2704 spin_lock_irq(&hugetlb_lock); 2705 if (!folio_test_hugetlb(old_folio)) { 2706 /* 2707 * Freed from under us. Drop new_folio too. 2708 */ 2709 goto free_new; 2710 } else if (folio_ref_count(old_folio)) { 2711 bool isolated; 2712 2713 /* 2714 * Someone has grabbed the folio, try to isolate it here. 2715 * Fail with -EBUSY if not possible. 2716 */ 2717 spin_unlock_irq(&hugetlb_lock); 2718 isolated = folio_isolate_hugetlb(old_folio, list); 2719 ret = isolated ? 0 : -EBUSY; 2720 spin_lock_irq(&hugetlb_lock); 2721 goto free_new; 2722 } else if (!folio_test_hugetlb_freed(old_folio)) { 2723 /* 2724 * Folio's refcount is 0 but it has not been enqueued in the 2725 * freelist yet. Race window is small, so we can succeed here if 2726 * we retry. 2727 */ 2728 spin_unlock_irq(&hugetlb_lock); 2729 cond_resched(); 2730 goto retry; 2731 } else { 2732 h = folio_hstate(old_folio); 2733 if (!new_folio) { 2734 spin_unlock_irq(&hugetlb_lock); 2735 gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE; 2736 new_folio = alloc_fresh_hugetlb_folio(h, gfp_mask, 2737 nid, NULL); 2738 if (!new_folio) 2739 return -ENOMEM; 2740 goto retry; 2741 } 2742 2743 /* 2744 * Ok, old_folio is still a genuine free hugepage. Remove it from 2745 * the freelist and decrease the counters. These will be 2746 * incremented again when calling account_new_hugetlb_folio() 2747 * and enqueue_hugetlb_folio() for new_folio. The counters will 2748 * remain stable since this happens under the lock. 2749 */ 2750 remove_hugetlb_folio(h, old_folio, false); 2751 2752 /* 2753 * Ref count on new_folio is already zero as it was dropped 2754 * earlier. It can be directly added to the pool free list. 2755 */ 2756 account_new_hugetlb_folio(h, new_folio); 2757 enqueue_hugetlb_folio(h, new_folio); 2758 2759 /* 2760 * Folio has been replaced, we can safely free the old one. 2761 */ 2762 spin_unlock_irq(&hugetlb_lock); 2763 update_and_free_hugetlb_folio(h, old_folio, false); 2764 } 2765 2766 return ret; 2767 2768 free_new: 2769 spin_unlock_irq(&hugetlb_lock); 2770 if (new_folio) 2771 update_and_free_hugetlb_folio(h, new_folio, false); 2772 2773 return ret; 2774 } 2775 2776 int isolate_or_dissolve_huge_folio(struct folio *folio, struct list_head *list) 2777 { 2778 int ret = -EBUSY; 2779 2780 /* Not to disrupt normal path by vainly holding hugetlb_lock */ 2781 if (!folio_test_hugetlb(folio)) 2782 return 0; 2783 2784 /* 2785 * Fence off gigantic pages as there is a cyclic dependency between 2786 * alloc_contig_range and them. Return -ENOMEM as this has the effect 2787 * of bailing out right away without further retrying. 2788 */ 2789 if (order_is_gigantic(folio_order(folio))) 2790 return -ENOMEM; 2791 2792 if (folio_ref_count(folio) && folio_isolate_hugetlb(folio, list)) 2793 ret = 0; 2794 else if (!folio_ref_count(folio)) 2795 ret = alloc_and_dissolve_hugetlb_folio(folio, list); 2796 2797 return ret; 2798 } 2799 2800 /* 2801 * replace_free_hugepage_folios - Replace free hugepage folios in a given pfn 2802 * range with new folios. 2803 * @start_pfn: start pfn of the given pfn range 2804 * @end_pfn: end pfn of the given pfn range 2805 * Returns 0 on success, otherwise negated error. 2806 */ 2807 int replace_free_hugepage_folios(unsigned long start_pfn, unsigned long end_pfn) 2808 { 2809 unsigned long nr = 0; 2810 struct page *page; 2811 struct hstate *h; 2812 LIST_HEAD(list); 2813 int ret = 0; 2814 2815 /* Avoid pfn iterations if no free non-gigantic huge pages */ 2816 for_each_hstate(h) { 2817 if (hstate_is_gigantic(h)) 2818 continue; 2819 2820 nr += h->free_huge_pages; 2821 if (nr) 2822 break; 2823 } 2824 2825 if (!nr) 2826 return 0; 2827 2828 while (start_pfn < end_pfn) { 2829 page = pfn_to_page(start_pfn); 2830 nr = 1; 2831 2832 if (PageHuge(page) || PageCompound(page)) { 2833 struct folio *folio = page_folio(page); 2834 2835 nr = folio_nr_pages(folio) - folio_page_idx(folio, page); 2836 2837 /* 2838 * Don't disrupt normal path by vainly holding 2839 * hugetlb_lock 2840 */ 2841 if (folio_test_hugetlb(folio) && !folio_ref_count(folio)) { 2842 if (order_is_gigantic(folio_order(folio))) { 2843 ret = -ENOMEM; 2844 break; 2845 } 2846 2847 ret = alloc_and_dissolve_hugetlb_folio(folio, &list); 2848 if (ret) 2849 break; 2850 2851 putback_movable_pages(&list); 2852 } 2853 } else if (PageBuddy(page)) { 2854 /* 2855 * Buddy order check without zone lock is unsafe and 2856 * the order is maybe invalid, but race should be 2857 * small, and the worst thing is skipping free hugetlb. 2858 */ 2859 const unsigned int order = buddy_order_unsafe(page); 2860 2861 if (order <= MAX_PAGE_ORDER) 2862 nr = 1UL << order; 2863 } 2864 start_pfn += nr; 2865 } 2866 2867 return ret; 2868 } 2869 2870 void wait_for_freed_hugetlb_folios(void) 2871 { 2872 if (llist_empty(&hpage_freelist)) 2873 return; 2874 2875 flush_work(&free_hpage_work); 2876 } 2877 2878 /** 2879 * hugetlb_alloc_folio - Allocate a hugetlb folio. 2880 * @h: Hugetlb state control block. 2881 * @mpoli: Interpreted memory policy to use for allocation. 2882 * @mm: Memory descriptor of the allocation target. 2883 * @alloc_flags: Flags controlling the allocation behavior. 2884 * 2885 * Allocates a hugetlb folio and handles cgroup charging and global hstate 2886 * reservations. 2887 * 2888 * Return: A pointer to the allocated folio, or an ERR_PTR on failure. 2889 * -ENOSPC if cgroup charging fails or no folio is available. 2890 */ 2891 struct folio *hugetlb_alloc_folio(struct hstate *h, 2892 struct mempolicy_interpreted *mpoli, struct mm_struct *mm, 2893 u8 alloc_flags) 2894 { 2895 bool charge_hugetlb_cgroup_rsvd = alloc_flags & 2896 HUGETLB_ALLOC_CHARG_CGROUP_RSVD; 2897 bool use_global_reservation = alloc_flags & 2898 HUGETLB_ALLOC_USE_GLOBAL_RESERVATIONS; 2899 size_t nr_pages = pages_per_huge_page(h); 2900 struct hugetlb_cgroup *h_cg_rsvd = NULL; 2901 struct hugetlb_cgroup *h_cg = NULL; 2902 gfp_t gfp = htlb_alloc_mask(h); 2903 int idx = hstate_index(h); 2904 struct folio *folio; 2905 int ret; 2906 2907 if (charge_hugetlb_cgroup_rsvd && 2908 hugetlb_cgroup_charge_cgroup_rsvd(idx, nr_pages, &h_cg_rsvd)) 2909 return ERR_PTR(-ENOSPC); 2910 2911 if (hugetlb_cgroup_charge_cgroup(idx, nr_pages, &h_cg)) { 2912 ret = -ENOSPC; 2913 goto err_uncharge_hugetlb_cgroup_rsvd; 2914 } 2915 2916 spin_lock_irq(&hugetlb_lock); 2917 2918 folio = NULL; 2919 if (use_global_reservation || available_huge_pages(h)) 2920 folio = dequeue_hugetlb_folio(h, gfp, mpoli); 2921 2922 if (!folio) { 2923 spin_unlock_irq(&hugetlb_lock); 2924 folio = alloc_buddy_hugetlb_folio(h, gfp, mpoli); 2925 if (!folio) { 2926 ret = -ENOSPC; 2927 goto err_uncharge_hugetlb_cgroup; 2928 } 2929 spin_lock_irq(&hugetlb_lock); 2930 list_add(&folio->lru, &h->hugepage_activelist); 2931 folio_ref_unfreeze(folio, 1); 2932 } 2933 2934 if (use_global_reservation) { 2935 folio_set_hugetlb_restore_reserve(folio); 2936 h->resv_huge_pages--; 2937 } 2938 2939 hugetlb_cgroup_commit_charge(idx, nr_pages, h_cg, folio); 2940 2941 if (charge_hugetlb_cgroup_rsvd) { 2942 hugetlb_cgroup_commit_charge_rsvd(idx, nr_pages, h_cg_rsvd, 2943 folio); 2944 } 2945 2946 spin_unlock_irq(&hugetlb_lock); 2947 2948 ret = mem_cgroup_charge_hugetlb(folio, mm, 2949 gfp | __GFP_RETRY_MAYFAIL); 2950 /* 2951 * Unconditionally increment NR_HUGETLB here because if 2952 * mem_cgroup_charge_hugetlb failed, freeing the page will 2953 * decrement NR_HUGETLB. 2954 */ 2955 lruvec_stat_mod_folio(folio, NR_HUGETLB, nr_pages); 2956 2957 if (ret == -ENOMEM) { 2958 folio_put(folio); 2959 /* 2960 * Skip uncharging hugetlb_cgroup since the charges 2961 * were committed to the folio and freeing the folio 2962 * would have cleared those up. 2963 */ 2964 /* 2965 * Return -ENOSPC, since retrying the fault is futile: 2966 * the OOM killer is not triggered for HugeTLB. 2967 */ 2968 return ERR_PTR(-ENOSPC); 2969 } 2970 2971 return folio; 2972 2973 err_uncharge_hugetlb_cgroup: 2974 hugetlb_cgroup_uncharge_cgroup(idx, nr_pages, h_cg); 2975 err_uncharge_hugetlb_cgroup_rsvd: 2976 if (charge_hugetlb_cgroup_rsvd) 2977 hugetlb_cgroup_uncharge_cgroup_rsvd(idx, nr_pages, h_cg_rsvd); 2978 2979 return ERR_PTR(ret); 2980 } 2981 2982 typedef enum { 2983 /* 2984 * For either 0/1: we checked the per-vma resv map, and one resv 2985 * count either can be reused (0), or an extra needed (1). 2986 */ 2987 MAP_CHG_REUSE = 0, 2988 MAP_CHG_NEEDED = 1, 2989 /* 2990 * Cannot use per-vma resv count can be used, hence a new resv 2991 * count is enforced. 2992 * 2993 * NOTE: This is mostly identical to MAP_CHG_NEEDED, except 2994 * that currently vma_needs_reservation() has an unwanted side 2995 * effect to either use end() or commit() to complete the 2996 * transaction. Hence it needs to differentiate from NEEDED. 2997 */ 2998 MAP_CHG_ENFORCED = 2, 2999 } map_chg_state; 3000 3001 /* 3002 * NOTE! "cow_from_owner" represents a very hacky usage only used in CoW 3003 * faults of hugetlb private mappings on top of a non-page-cache folio (in 3004 * which case even if there's a private vma resv map it won't cover such 3005 * allocation). New call sites should (probably) never set it to true!! 3006 * When it's set, the allocation will bypass all vma level reservations. 3007 */ 3008 struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma, 3009 unsigned long addr, bool cow_from_owner) 3010 { 3011 struct hugepage_subpool *spool = subpool_vma(vma); 3012 struct hstate *h = hstate_vma(vma); 3013 struct folio *folio; 3014 long retval, gbl_chg, gbl_reserve; 3015 map_chg_state map_chg; 3016 struct mempolicy_interpreted mpoli; 3017 gfp_t gfp = htlb_alloc_mask(h); 3018 struct mempolicy *mpol; 3019 nodemask_t *nodemask; 3020 u8 alloc_flags = 0; 3021 int nid; 3022 int ret; 3023 3024 /* Whether we need a separate per-vma reservation? */ 3025 if (cow_from_owner) { 3026 /* 3027 * Special case! Since it's a CoW on top of a reserved 3028 * page, the private resv map doesn't count. So it cannot 3029 * consume the per-vma resv map even if it's reserved. 3030 */ 3031 map_chg = MAP_CHG_ENFORCED; 3032 } else { 3033 /* 3034 * Examine the region/reserve map to determine if the process 3035 * has a reservation for the page to be allocated. A return 3036 * code of zero indicates a reservation exists (no change). 3037 */ 3038 retval = vma_needs_reservation(h, vma, addr); 3039 if (retval < 0) 3040 return ERR_PTR(-ENOMEM); 3041 map_chg = retval ? MAP_CHG_NEEDED : MAP_CHG_REUSE; 3042 } 3043 3044 /* 3045 * Whether we need a separate global reservation? 3046 * 3047 * Processes that did not create the mapping will have no 3048 * reserves as indicated by the region/reserve map. Check 3049 * that the allocation will not exceed the subpool limit. 3050 * Or if it can get one from the pool reservation directly. 3051 */ 3052 if (map_chg) { 3053 gbl_chg = hugepage_subpool_get_pages(spool, 1); 3054 if (gbl_chg < 0) { 3055 ret = -ENOSPC; 3056 goto out_end_reservation; 3057 } 3058 } else { 3059 /* 3060 * If we have the vma reservation ready, no need for extra 3061 * global reservation. 3062 */ 3063 gbl_chg = 0; 3064 } 3065 3066 /* 3067 * If allocation doesn't reuse a reservation in the resv_map, 3068 * charge for the reservation. 3069 */ 3070 if (map_chg != MAP_CHG_REUSE) 3071 alloc_flags |= HUGETLB_ALLOC_CHARG_CGROUP_RSVD; 3072 3073 /* 3074 * gbl_chg == 0 indicates a reservation exists for this 3075 * allocation, so try to use it. 3076 */ 3077 if (gbl_chg == 0) 3078 alloc_flags |= HUGETLB_ALLOC_USE_GLOBAL_RESERVATIONS; 3079 3080 /* Takes reference on mpol. */ 3081 nid = huge_node(vma, addr, gfp, &mpol, &nodemask); 3082 mpoli = (struct mempolicy_interpreted){ 3083 .nid = nid, 3084 #ifdef CONFIG_NUMA 3085 .mode = mpol ? mpol->mode : MPOL_DEFAULT, 3086 #else 3087 .mode = MPOL_DEFAULT, 3088 #endif 3089 .nodemask = nodemask, 3090 }; 3091 3092 folio = hugetlb_alloc_folio(h, &mpoli, vma->vm_mm, alloc_flags); 3093 3094 mpol_cond_put(mpol); 3095 3096 if (IS_ERR(folio)) { 3097 ret = PTR_ERR(folio); 3098 goto out_subpool_put; 3099 } 3100 3101 hugetlb_set_folio_subpool(folio, spool); 3102 3103 if (map_chg != MAP_CHG_ENFORCED) { 3104 /* commit() is only needed if the map_chg is not enforced */ 3105 retval = vma_commit_reservation(h, vma, addr); 3106 /* 3107 * Check for possible race conditions. When it happens.. 3108 * The page was added to the reservation map between 3109 * vma_needs_reservation and vma_commit_reservation. 3110 * This indicates a race with hugetlb_reserve_pages. 3111 * Adjust for the subpool count incremented above AND 3112 * in hugetlb_reserve_pages for the same page. Also, 3113 * the reservation count added in hugetlb_reserve_pages 3114 * no longer applies. 3115 */ 3116 if (unlikely(map_chg == MAP_CHG_NEEDED && retval == 0)) { 3117 long rsv_adjust; 3118 3119 rsv_adjust = hugepage_subpool_put_pages(spool, 1); 3120 hugetlb_acct_memory(h, -rsv_adjust); 3121 spin_lock_irq(&hugetlb_lock); 3122 hugetlb_cgroup_uncharge_folio_rsvd( 3123 hstate_index(h), pages_per_huge_page(h), folio); 3124 spin_unlock_irq(&hugetlb_lock); 3125 } 3126 } 3127 3128 return folio; 3129 3130 out_subpool_put: 3131 /* 3132 * put page to subpool iff the quota of subpool's rsv_hpages is used 3133 * during hugepage_subpool_get_pages. 3134 */ 3135 if (map_chg && !gbl_chg) { 3136 gbl_reserve = hugepage_subpool_put_pages(spool, 1); 3137 hugetlb_acct_memory(h, -gbl_reserve); 3138 } 3139 3140 out_end_reservation: 3141 if (map_chg != MAP_CHG_ENFORCED) 3142 vma_end_reservation(h, vma, addr); 3143 return ERR_PTR(ret); 3144 } 3145 3146 static __init void *alloc_bootmem(struct hstate *h, int nid, bool node_exact) 3147 { 3148 if (hugetlb_early_cma(h)) 3149 return hugetlb_cma_alloc_bootmem(h, nid, node_exact); 3150 3151 return memblock_alloc_hugetlb(huge_page_size(h), nid, node_exact); 3152 } 3153 3154 void *__init arch_alloc_bootmem_huge_page(struct hstate *h, int nid) 3155 __attribute__ ((weak, alias("__alloc_bootmem_huge_page"))); 3156 void *__init __alloc_bootmem_huge_page(struct hstate *h, int nid) 3157 { 3158 int nr_nodes, node = nid; 3159 3160 /* do node specific alloc */ 3161 if (nid != NUMA_NO_NODE) 3162 return alloc_bootmem(h, node, true); 3163 3164 /* allocate from next node when distributing huge pages */ 3165 for_each_node_mask_to_alloc(&h->next_nid_to_alloc, nr_nodes, node, 3166 &hugetlb_bootmem_nodes) 3167 return alloc_bootmem(h, node, false); 3168 3169 return NULL; 3170 } 3171 3172 static bool __init alloc_bootmem_huge_page(struct hstate *h, int nid) 3173 { 3174 unsigned long pfn; 3175 unsigned int nid_request = nid; 3176 struct huge_bootmem_page *m = arch_alloc_bootmem_huge_page(h, nid); 3177 3178 if (!m) 3179 return false; 3180 3181 pfn = PHYS_PFN(__pa(m)); 3182 nid = early_pfn_to_nid(pfn); 3183 /* 3184 * Use the beginning of the huge page to store the huge_bootmem_page 3185 * struct (until gather_bootmem puts them into the mem_map). 3186 * 3187 * Put them into a private list first because mem_map is not up yet. 3188 */ 3189 INIT_LIST_HEAD(&m->list); 3190 m->hstate = h; 3191 m->flags = 0; 3192 3193 /* CMA pages: zone-crossing is validated in hugetlb_cma_reserve(). */ 3194 if (!hugetlb_early_cma(h) && 3195 pfn_range_intersects_zones(nid, pfn, pages_per_huge_page(h))) { 3196 /* 3197 * If the allocated page is on a different node than requested 3198 * (e.g., on PowerPC LPARs), put it on the requested node's list, 3199 * because hugetlb_free_cross_zone_pages() only frees cross-zone 3200 * pages belonging to the requested node. 3201 */ 3202 if (WARN_ON_ONCE(nid_request != NUMA_NO_NODE && nid != nid_request)) 3203 list_add(&m->list, &huge_boot_pages[nid_request]); 3204 else 3205 list_add(&m->list, &huge_boot_pages[nid]); 3206 } else { 3207 list_add_tail(&m->list, &huge_boot_pages[nid]); 3208 m->flags |= HUGE_BOOTMEM_ZONES_VALID; 3209 hugetlb_vmemmap_optimize_bootmem_page(pfn, huge_page_order(h)); 3210 /* 3211 * Only initialize the head struct page in memmap_init_reserved_pages, 3212 * rest of the struct pages will be initialized by the HugeTLB 3213 * subsystem itself. 3214 * The head struct page is used to get folio information by the HugeTLB 3215 * subsystem like zone id and node id. 3216 */ 3217 memblock_reserved_mark_noinit(__pa((void *)m + PAGE_SIZE), 3218 huge_page_size(h) - PAGE_SIZE); 3219 } 3220 3221 return true; 3222 } 3223 3224 /* Initialize [start_page:end_page_number] tail struct pages of a hugepage */ 3225 static void __init hugetlb_folio_init_tail_vmemmap(struct folio *folio, 3226 struct hstate *h, 3227 unsigned long start_page_number, 3228 unsigned long end_page_number) 3229 { 3230 enum zone_type zone = folio_zonenum(folio); 3231 int nid = folio_nid(folio); 3232 struct page *page = folio_page(folio, start_page_number); 3233 unsigned long head_pfn = folio_pfn(folio); 3234 unsigned long pfn, end_pfn = head_pfn + end_page_number; 3235 unsigned int order = huge_page_order(h); 3236 3237 /* 3238 * As we marked all tail pages with memblock_reserved_mark_noinit(), 3239 * we must initialize them ourselves here. 3240 */ 3241 for (pfn = head_pfn + start_page_number; pfn < end_pfn; page++, pfn++) { 3242 __init_single_page(page, pfn, zone, nid); 3243 prep_compound_tail(page, &folio->page, order); 3244 set_page_count(page, 0); 3245 } 3246 } 3247 3248 static void __init hugetlb_folio_init_vmemmap(struct folio *folio, 3249 struct hstate *h, 3250 unsigned long nr_pages) 3251 { 3252 int ret; 3253 3254 /* 3255 * This is an open-coded prep_compound_page() whereby we avoid 3256 * walking pages twice by initializing/preparing+freezing them in the 3257 * same go. 3258 */ 3259 __folio_clear_reserved(folio); 3260 __folio_set_head(folio); 3261 ret = folio_ref_freeze(folio, 1); 3262 VM_BUG_ON(!ret); 3263 hugetlb_folio_init_tail_vmemmap(folio, h, 1, nr_pages); 3264 prep_compound_head(&folio->page, huge_page_order(h)); 3265 } 3266 3267 /* 3268 * memblock-allocated pageblocks might not have the migrate type set 3269 * if marked with the 'noinit' flag. Set it to the default (MIGRATE_MOVABLE) 3270 * here, or MIGRATE_CMA if this was a page allocated through an early CMA 3271 * reservation. 3272 * 3273 * In case of vmemmap optimized folios, the tail vmemmap pages are mapped 3274 * read-only, but that's ok - for sparse vmemmap this does not write to 3275 * the page structure. 3276 */ 3277 static void __init hugetlb_bootmem_init_migratetype(struct folio *folio, 3278 struct hstate *h) 3279 { 3280 unsigned long nr_pages = pages_per_huge_page(h), i; 3281 3282 WARN_ON_ONCE(!pageblock_aligned(folio_pfn(folio))); 3283 3284 for (i = 0; i < nr_pages; i += pageblock_nr_pages) { 3285 if (folio_test_hugetlb_cma(folio)) 3286 init_cma_pageblock(folio_page(folio, i)); 3287 else 3288 init_pageblock_migratetype(folio_page(folio, i), 3289 MIGRATE_MOVABLE, false); 3290 } 3291 } 3292 3293 static void __init prep_and_add_bootmem_folios(struct hstate *h, 3294 struct list_head *folio_list) 3295 { 3296 unsigned long flags; 3297 struct folio *folio, *tmp_f; 3298 3299 /* Send list for bulk vmemmap optimization processing */ 3300 hugetlb_vmemmap_optimize_bootmem_folios(h, folio_list); 3301 3302 list_for_each_entry_safe(folio, tmp_f, folio_list, lru) { 3303 if (!folio_test_hugetlb_vmemmap_optimized(folio)) { 3304 /* 3305 * If HVO fails, initialize all tail struct pages 3306 * We do not worry about potential long lock hold 3307 * time as this is early in boot and there should 3308 * be no contention. 3309 */ 3310 hugetlb_folio_init_tail_vmemmap(folio, h, 3311 HUGETLB_VMEMMAP_RESERVE_PAGES, 3312 pages_per_huge_page(h)); 3313 } 3314 hugetlb_bootmem_init_migratetype(folio, h); 3315 /* Subdivide locks to achieve better parallel performance */ 3316 spin_lock_irqsave(&hugetlb_lock, flags); 3317 account_new_hugetlb_folio(h, folio); 3318 enqueue_hugetlb_folio(h, folio); 3319 spin_unlock_irqrestore(&hugetlb_lock, flags); 3320 } 3321 } 3322 3323 /* 3324 * Put bootmem huge pages into the standard lists after mem_map is up. 3325 * Note: This only applies to gigantic (order > MAX_PAGE_ORDER) pages. 3326 */ 3327 static void __init gather_bootmem_prealloc_node(unsigned long nid) 3328 { 3329 LIST_HEAD(folio_list); 3330 struct huge_bootmem_page *m, *tm; 3331 struct hstate *h = NULL, *prev_h = NULL; 3332 3333 list_for_each_entry_safe(m, tm, &huge_boot_pages[nid], list) { 3334 struct page *page = virt_to_page(m); 3335 struct folio *folio = (void *)page; 3336 const unsigned long pfn = folio_pfn(folio); 3337 3338 h = m->hstate; 3339 /* 3340 * It is possible to have multiple huge page sizes (hstates) 3341 * in this list. If so, process each size separately. 3342 */ 3343 if (h != prev_h && prev_h != NULL) 3344 prep_and_add_bootmem_folios(prev_h, &folio_list); 3345 prev_h = h; 3346 3347 VM_BUG_ON(!hstate_is_gigantic(h)); 3348 WARN_ON(folio_ref_count(folio) != 1); 3349 3350 hugetlb_folio_init_vmemmap(folio, h, 3351 HUGETLB_VMEMMAP_RESERVE_PAGES); 3352 init_new_hugetlb_folio(folio); 3353 3354 if (vmemmap_optimizable_order(pfn_to_section_compound_order(pfn))) 3355 folio_set_hugetlb_vmemmap_optimized(folio); 3356 section_set_compound_order_range(pfn, folio_nr_pages(folio), 0); 3357 3358 list_add(&folio->lru, &folio_list); 3359 3360 /* 3361 * We need to restore the 'stolen' pages to totalram_pages 3362 * in order to fix confusing memory reports from free(1) and 3363 * other side-effects, like CommitLimit going negative. 3364 * 3365 * For CMA pages, this is done in init_cma_pageblock 3366 * (via hugetlb_bootmem_init_migratetype), so skip it here. 3367 */ 3368 if (hugetlb_early_cma(h)) 3369 folio_set_hugetlb_cma(folio); 3370 else 3371 adjust_managed_page_count(page, pages_per_huge_page(h)); 3372 cond_resched(); 3373 } 3374 3375 prep_and_add_bootmem_folios(h, &folio_list); 3376 } 3377 3378 static void __init gather_bootmem_prealloc_parallel(unsigned long start, 3379 unsigned long end, void *arg) 3380 { 3381 int nid; 3382 3383 for (nid = start; nid < end; nid++) 3384 gather_bootmem_prealloc_node(nid); 3385 } 3386 3387 void __init hugetlb_bootmem_struct_page_init(void) 3388 { 3389 struct padata_mt_job job = { 3390 .thread_fn = gather_bootmem_prealloc_parallel, 3391 .fn_arg = NULL, 3392 .start = 0, 3393 .size = nr_node_ids, 3394 .align = 1, 3395 .min_chunk = 1, 3396 .max_threads = num_node_state(N_MEMORY), 3397 .numa_aware = true, 3398 }; 3399 3400 padata_do_multithreaded(&job); 3401 } 3402 3403 static unsigned long __init hugetlb_free_cross_zone_pages(struct hstate *h, int nid) 3404 { 3405 unsigned long freed = 0; 3406 struct huge_bootmem_page *m, *tmp; 3407 3408 if (!hstate_is_gigantic(h)) 3409 return freed; 3410 3411 list_for_each_entry_safe(m, tmp, &huge_boot_pages[nid], list) { 3412 if (m->flags & HUGE_BOOTMEM_ZONES_VALID) 3413 break; 3414 3415 list_del(&m->list); 3416 memblock_free(m, huge_page_size(h)); 3417 freed++; 3418 } 3419 3420 if (freed) { 3421 char buf[32]; 3422 3423 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, sizeof(buf)); 3424 pr_warn("freed %lu cross-zone hugepages of size %s on node %d.\n", 3425 freed, buf, nid); 3426 } 3427 3428 return freed; 3429 } 3430 3431 static void __init hugetlb_hstate_alloc_pages_onenode(struct hstate *h, int nid) 3432 { 3433 unsigned long i; 3434 char buf[32]; 3435 LIST_HEAD(folio_list); 3436 3437 for (i = 0; i < h->max_huge_pages_node[nid]; ++i) { 3438 if (hstate_is_gigantic(h)) { 3439 if (!alloc_bootmem_huge_page(h, nid)) 3440 break; 3441 } else { 3442 struct folio *folio; 3443 gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE; 3444 3445 folio = only_alloc_fresh_hugetlb_folio(h, gfp_mask, nid, 3446 &node_states[N_MEMORY], NULL); 3447 if (!folio && !list_empty(&folio_list) && 3448 hugetlb_vmemmap_optimizable(h)) { 3449 prep_and_add_allocated_folios(h, &folio_list); 3450 INIT_LIST_HEAD(&folio_list); 3451 folio = only_alloc_fresh_hugetlb_folio(h, gfp_mask, nid, 3452 &node_states[N_MEMORY], NULL); 3453 } 3454 if (!folio) 3455 break; 3456 list_add(&folio->lru, &folio_list); 3457 } 3458 cond_resched(); 3459 } 3460 3461 i -= hugetlb_free_cross_zone_pages(h, nid); 3462 3463 if (!list_empty(&folio_list)) 3464 prep_and_add_allocated_folios(h, &folio_list); 3465 3466 if (i == h->max_huge_pages_node[nid]) 3467 return; 3468 3469 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, sizeof(buf)); 3470 pr_warn("allocating %u of page size %s failed node%d. Only allocated %lu hugepages.\n", 3471 h->max_huge_pages_node[nid], buf, nid, i); 3472 h->max_huge_pages -= (h->max_huge_pages_node[nid] - i); 3473 h->max_huge_pages_node[nid] = i; 3474 } 3475 3476 static bool __init hugetlb_hstate_alloc_pages_specific_nodes(struct hstate *h) 3477 { 3478 int i; 3479 bool node_specific_alloc = false; 3480 3481 for_each_online_node(i) { 3482 if (h->max_huge_pages_node[i] > 0) { 3483 hugetlb_hstate_alloc_pages_onenode(h, i); 3484 node_specific_alloc = true; 3485 } 3486 } 3487 3488 return node_specific_alloc; 3489 } 3490 3491 static void __init hugetlb_hstate_alloc_pages_errcheck(unsigned long allocated, struct hstate *h) 3492 { 3493 if (allocated < h->max_huge_pages) { 3494 char buf[32]; 3495 3496 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, sizeof(buf)); 3497 pr_warn("allocating %lu of page size %s failed. Only allocated %lu hugepages.\n", 3498 h->max_huge_pages, buf, allocated); 3499 h->max_huge_pages = allocated; 3500 } 3501 } 3502 3503 static void __init hugetlb_pages_alloc_boot_node(unsigned long start, unsigned long end, void *arg) 3504 { 3505 struct hstate *h = (struct hstate *)arg; 3506 int i, num = end - start; 3507 nodemask_t node_alloc_noretry; 3508 LIST_HEAD(folio_list); 3509 int next_node = first_online_node; 3510 3511 /* Bit mask controlling how hard we retry per-node allocations.*/ 3512 nodes_clear(node_alloc_noretry); 3513 3514 for (i = 0; i < num; ++i) { 3515 struct folio *folio; 3516 3517 if (hugetlb_vmemmap_optimizable(h) && 3518 (si_mem_available() == 0) && !list_empty(&folio_list)) { 3519 prep_and_add_allocated_folios(h, &folio_list); 3520 INIT_LIST_HEAD(&folio_list); 3521 } 3522 folio = alloc_pool_huge_folio(h, &node_states[N_MEMORY], 3523 &node_alloc_noretry, &next_node); 3524 if (!folio) 3525 break; 3526 3527 list_move(&folio->lru, &folio_list); 3528 cond_resched(); 3529 } 3530 3531 prep_and_add_allocated_folios(h, &folio_list); 3532 } 3533 3534 static unsigned long __init hugetlb_gigantic_pages_alloc_boot(struct hstate *h) 3535 { 3536 int nid; 3537 unsigned long i; 3538 3539 for (i = 0; i < h->max_huge_pages; ++i) { 3540 if (!alloc_bootmem_huge_page(h, NUMA_NO_NODE)) 3541 break; 3542 cond_resched(); 3543 } 3544 3545 for_each_node(nid) 3546 i -= hugetlb_free_cross_zone_pages(h, nid); 3547 3548 return i; 3549 } 3550 3551 static unsigned long __init hugetlb_pages_alloc_boot(struct hstate *h) 3552 { 3553 struct padata_mt_job job = { 3554 .fn_arg = h, 3555 .align = 1, 3556 .numa_aware = true 3557 }; 3558 3559 unsigned long jiffies_start; 3560 unsigned long jiffies_end; 3561 unsigned long remaining; 3562 3563 job.thread_fn = hugetlb_pages_alloc_boot_node; 3564 3565 /* 3566 * job.max_threads is 25% of the available cpu threads by default. 3567 * 3568 * On large servers with terabytes of memory, huge page allocation 3569 * can consume a considerably amount of time. 3570 * 3571 * Tests below show how long it takes to allocate 1 TiB of memory with 2MiB huge pages. 3572 * 2MiB huge pages. Using more threads can significantly improve allocation time. 3573 * 3574 * +-----------------------+-------+-------+-------+-------+-------+ 3575 * | threads | 8 | 16 | 32 | 64 | 128 | 3576 * +-----------------------+-------+-------+-------+-------+-------+ 3577 * | skylake 144 cpus | 44s | 22s | 16s | 19s | 20s | 3578 * | cascade lake 192 cpus | 39s | 20s | 11s | 10s | 9s | 3579 * +-----------------------+-------+-------+-------+-------+-------+ 3580 */ 3581 if (hugepage_allocation_threads == 0) { 3582 hugepage_allocation_threads = num_online_cpus() / 4; 3583 hugepage_allocation_threads = max(hugepage_allocation_threads, 1); 3584 } 3585 3586 job.max_threads = hugepage_allocation_threads; 3587 3588 jiffies_start = jiffies; 3589 do { 3590 remaining = h->max_huge_pages - h->nr_huge_pages; 3591 3592 job.start = h->nr_huge_pages; 3593 job.size = remaining; 3594 job.min_chunk = remaining / hugepage_allocation_threads; 3595 padata_do_multithreaded(&job); 3596 3597 if (h->nr_huge_pages == h->max_huge_pages) 3598 break; 3599 3600 /* 3601 * Retry only if the vmemmap optimization might have been able to free 3602 * some memory back to the system. 3603 */ 3604 if (!hugetlb_vmemmap_optimizable(h)) 3605 break; 3606 3607 /* Continue if progress was made in last iteration */ 3608 } while (remaining != (h->max_huge_pages - h->nr_huge_pages)); 3609 3610 jiffies_end = jiffies; 3611 3612 pr_info("allocation took %dms with hugepage_allocation_threads=%ld\n", 3613 jiffies_to_msecs(jiffies_end - jiffies_start), 3614 hugepage_allocation_threads); 3615 3616 return h->nr_huge_pages; 3617 } 3618 3619 /* 3620 * NOTE: this routine is called in different contexts for gigantic and 3621 * non-gigantic pages. 3622 * - For gigantic pages, this is called early in the boot process and 3623 * pages are allocated from memblock allocated or something similar. 3624 * Gigantic pages are actually added to pools later with the routine 3625 * hugetlb_bootmem_struct_page_init. 3626 * - For non-gigantic pages, this is called later in the boot process after 3627 * all of mm is up and functional. Pages are allocated from buddy and 3628 * then added to hugetlb pools. 3629 */ 3630 static void __init hugetlb_hstate_alloc_pages(struct hstate *h) 3631 { 3632 unsigned long allocated; 3633 3634 /* 3635 * Skip gigantic hugepages allocation if early CMA 3636 * reservations are not available. 3637 */ 3638 if (hstate_is_gigantic(h) && hugetlb_cma_total_size() && 3639 !hugetlb_early_cma(h)) { 3640 pr_warn_once("hugetlb_cma is enabled, skip boot time allocation\n"); 3641 return; 3642 } 3643 3644 if (!h->max_huge_pages) 3645 return; 3646 3647 /* do node specific alloc */ 3648 if (hugetlb_hstate_alloc_pages_specific_nodes(h)) 3649 return; 3650 3651 /* below will do all node balanced alloc */ 3652 if (hstate_is_gigantic(h)) 3653 allocated = hugetlb_gigantic_pages_alloc_boot(h); 3654 else 3655 allocated = hugetlb_pages_alloc_boot(h); 3656 3657 hugetlb_hstate_alloc_pages_errcheck(allocated, h); 3658 } 3659 3660 static void __init hugetlb_init_hstates(void) 3661 { 3662 struct hstate *h, *h2; 3663 3664 for_each_hstate(h) { 3665 /* 3666 * Always reset to first_memory_node here, even if 3667 * next_nid_to_alloc was set before - we can't 3668 * reference hugetlb_bootmem_nodes after init, and 3669 * first_memory_node is right for all further allocations. 3670 */ 3671 h->next_nid_to_alloc = first_memory_node; 3672 h->next_nid_to_free = first_memory_node; 3673 3674 /* oversize hugepages were init'ed in early boot */ 3675 if (!hstate_is_gigantic(h)) 3676 hugetlb_hstate_alloc_pages(h); 3677 3678 /* 3679 * Set demote order for each hstate. Note that 3680 * h->demote_order is initially 0. 3681 * - We can not demote gigantic pages if runtime freeing 3682 * is not supported, so skip this. 3683 * - If CMA allocation is possible, we can not demote 3684 * HUGETLB_PAGE_ORDER or smaller size pages. 3685 */ 3686 if (hstate_is_gigantic_no_runtime(h)) 3687 continue; 3688 if (hugetlb_cma_total_size() && h->order <= HUGETLB_PAGE_ORDER) 3689 continue; 3690 for_each_hstate(h2) { 3691 if (h2 == h) 3692 continue; 3693 if (h2->order < h->order && 3694 h2->order > h->demote_order) 3695 h->demote_order = h2->order; 3696 } 3697 } 3698 } 3699 3700 static void __init report_hugepages(void) 3701 { 3702 struct hstate *h; 3703 3704 for_each_hstate(h) { 3705 char buf[32]; 3706 3707 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, sizeof(buf)); 3708 pr_info("registered %s page size, pre-allocated %ld pages\n", 3709 buf, h->nr_huge_pages); 3710 pr_info("%d KiB vmemmap can be freed for a %s page\n", 3711 hugetlb_vmemmap_optimizable_size(h) / SZ_1K, buf); 3712 } 3713 } 3714 3715 #ifdef CONFIG_HIGHMEM 3716 static void try_to_free_low(struct hstate *h, unsigned long count, 3717 nodemask_t *nodes_allowed) 3718 { 3719 int i; 3720 LIST_HEAD(page_list); 3721 3722 lockdep_assert_held(&hugetlb_lock); 3723 if (hstate_is_gigantic(h)) 3724 return; 3725 3726 /* 3727 * Collect pages to be freed on a list, and free after dropping lock 3728 */ 3729 for_each_node_mask(i, *nodes_allowed) { 3730 struct folio *folio, *next; 3731 struct list_head *freel = &h->hugepage_freelists[i]; 3732 list_for_each_entry_safe(folio, next, freel, lru) { 3733 if (count >= h->nr_huge_pages) 3734 goto out; 3735 if (folio_test_highmem(folio)) 3736 continue; 3737 remove_hugetlb_folio(h, folio, false); 3738 list_add(&folio->lru, &page_list); 3739 } 3740 } 3741 3742 out: 3743 spin_unlock_irq(&hugetlb_lock); 3744 update_and_free_pages_bulk(h, &page_list); 3745 spin_lock_irq(&hugetlb_lock); 3746 } 3747 #else 3748 static inline void try_to_free_low(struct hstate *h, unsigned long count, 3749 nodemask_t *nodes_allowed) 3750 { 3751 } 3752 #endif 3753 3754 /* 3755 * Increment or decrement surplus_huge_pages. Keep node-specific counters 3756 * balanced by operating on them in a round-robin fashion. 3757 * Returns 1 if an adjustment was made. 3758 */ 3759 static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed, 3760 int delta) 3761 { 3762 int nr_nodes, node; 3763 3764 lockdep_assert_held(&hugetlb_lock); 3765 VM_BUG_ON(delta != -1 && delta != 1); 3766 3767 if (delta < 0) { 3768 for_each_node_mask_to_alloc(&h->next_nid_to_alloc, nr_nodes, node, nodes_allowed) { 3769 if (h->surplus_huge_pages_node[node]) 3770 goto found; 3771 } 3772 } else { 3773 for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) { 3774 if (h->surplus_huge_pages_node[node] < 3775 h->nr_huge_pages_node[node]) 3776 goto found; 3777 } 3778 } 3779 return 0; 3780 3781 found: 3782 h->surplus_huge_pages += delta; 3783 h->surplus_huge_pages_node[node] += delta; 3784 return 1; 3785 } 3786 3787 #define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages) 3788 static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid, 3789 nodemask_t *nodes_allowed) 3790 { 3791 unsigned long persistent_free_count; 3792 unsigned long min_count; 3793 unsigned long allocated; 3794 struct folio *folio; 3795 LIST_HEAD(page_list); 3796 NODEMASK_ALLOC(nodemask_t, node_alloc_noretry, GFP_KERNEL); 3797 3798 /* 3799 * Bit mask controlling how hard we retry per-node allocations. 3800 * If we can not allocate the bit mask, do not attempt to allocate 3801 * the requested huge pages. 3802 */ 3803 if (node_alloc_noretry) 3804 nodes_clear(*node_alloc_noretry); 3805 else 3806 return -ENOMEM; 3807 3808 /* 3809 * resize_lock mutex prevents concurrent adjustments to number of 3810 * pages in hstate via the proc/sysfs interfaces. 3811 */ 3812 mutex_lock(&h->resize_lock); 3813 flush_free_hpage_work(h); 3814 spin_lock_irq(&hugetlb_lock); 3815 3816 /* 3817 * Check for a node specific request. 3818 * Changing node specific huge page count may require a corresponding 3819 * change to the global count. In any case, the passed node mask 3820 * (nodes_allowed) will restrict alloc/free to the specified node. 3821 */ 3822 if (nid != NUMA_NO_NODE) { 3823 unsigned long old_count = count; 3824 3825 count += persistent_huge_pages(h) - 3826 (h->nr_huge_pages_node[nid] - 3827 h->surplus_huge_pages_node[nid]); 3828 /* 3829 * User may have specified a large count value which caused the 3830 * above calculation to overflow. In this case, they wanted 3831 * to allocate as many huge pages as possible. Set count to 3832 * largest possible value to align with their intention. 3833 */ 3834 if (count < old_count) 3835 count = ULONG_MAX; 3836 } 3837 3838 /* 3839 * Gigantic pages runtime allocation depend on the capability for large 3840 * page range allocation. 3841 * If the system does not provide this feature, return an error when 3842 * the user tries to allocate gigantic pages but let the user free the 3843 * boottime allocated gigantic pages. 3844 */ 3845 if (hstate_is_gigantic(h) && !IS_ENABLED(CONFIG_CONTIG_ALLOC)) { 3846 if (count > persistent_huge_pages(h)) { 3847 spin_unlock_irq(&hugetlb_lock); 3848 mutex_unlock(&h->resize_lock); 3849 NODEMASK_FREE(node_alloc_noretry); 3850 return -EINVAL; 3851 } 3852 /* Fall through to decrease pool */ 3853 } 3854 3855 /* 3856 * Increase the pool size 3857 * First take pages out of surplus state. Then make up the 3858 * remaining difference by allocating fresh huge pages. 3859 * 3860 * We might race with alloc_surplus_hugetlb_folio() here and be unable 3861 * to convert a surplus huge page to a normal huge page. That is 3862 * not critical, though, it just means the overall size of the 3863 * pool might be one hugepage larger than it needs to be, but 3864 * within all the constraints specified by the sysctls. 3865 */ 3866 while (h->surplus_huge_pages && count > persistent_huge_pages(h)) { 3867 if (!adjust_pool_surplus(h, nodes_allowed, -1)) 3868 break; 3869 } 3870 3871 allocated = 0; 3872 while (count > (persistent_huge_pages(h) + allocated)) { 3873 /* 3874 * If this allocation races such that we no longer need the 3875 * page, free_huge_folio will handle it by freeing the page 3876 * and reducing the surplus. 3877 */ 3878 spin_unlock_irq(&hugetlb_lock); 3879 3880 /* yield cpu to avoid soft lockup */ 3881 cond_resched(); 3882 3883 folio = alloc_pool_huge_folio(h, nodes_allowed, 3884 node_alloc_noretry, 3885 &h->next_nid_to_alloc); 3886 if (!folio) { 3887 prep_and_add_allocated_folios(h, &page_list); 3888 spin_lock_irq(&hugetlb_lock); 3889 goto out; 3890 } 3891 3892 list_add(&folio->lru, &page_list); 3893 allocated++; 3894 3895 /* Bail for signals. Probably ctrl-c from user */ 3896 if (signal_pending(current)) { 3897 prep_and_add_allocated_folios(h, &page_list); 3898 spin_lock_irq(&hugetlb_lock); 3899 goto out; 3900 } 3901 3902 spin_lock_irq(&hugetlb_lock); 3903 } 3904 3905 /* Add allocated pages to the pool */ 3906 if (!list_empty(&page_list)) { 3907 spin_unlock_irq(&hugetlb_lock); 3908 prep_and_add_allocated_folios(h, &page_list); 3909 spin_lock_irq(&hugetlb_lock); 3910 } 3911 3912 /* 3913 * Decrease the pool size 3914 * First return free pages to the buddy allocator (being careful 3915 * to keep enough around to satisfy reservations). Then place 3916 * pages into surplus state as needed so the pool will shrink 3917 * to the desired size as pages become free. 3918 * 3919 * By placing pages into the surplus state independent of the 3920 * overcommit value, we are allowing the surplus pool size to 3921 * exceed overcommit. There are few sane options here. Since 3922 * alloc_surplus_hugetlb_folio() is checking the global counter, 3923 * though, we'll note that we're not allowed to exceed surplus 3924 * and won't grow the pool anywhere else. Not until one of the 3925 * sysctls are changed, or the surplus pages go out of use. 3926 * 3927 * min_count is the expected number of persistent pages, we 3928 * shouldn't calculate min_count by using 3929 * resv_huge_pages + persistent_huge_pages() - free_huge_pages, 3930 * because there may exist free surplus huge pages, and this will 3931 * lead to subtracting twice. Free surplus huge pages come from HVO 3932 * failing to restore vmemmap, see comments in the callers of 3933 * hugetlb_vmemmap_restore_folio(). Thus, we should calculate 3934 * persistent free count first. 3935 */ 3936 persistent_free_count = h->free_huge_pages; 3937 if (h->free_huge_pages > persistent_huge_pages(h)) { 3938 if (h->free_huge_pages > h->surplus_huge_pages) 3939 persistent_free_count -= h->surplus_huge_pages; 3940 else 3941 persistent_free_count = 0; 3942 } 3943 min_count = h->resv_huge_pages + persistent_huge_pages(h) - persistent_free_count; 3944 min_count = max(count, min_count); 3945 try_to_free_low(h, min_count, nodes_allowed); 3946 3947 /* 3948 * Collect pages to be removed on list without dropping lock 3949 */ 3950 while (min_count < persistent_huge_pages(h)) { 3951 folio = remove_pool_hugetlb_folio(h, nodes_allowed, 0); 3952 if (!folio) 3953 break; 3954 3955 list_add(&folio->lru, &page_list); 3956 } 3957 /* free the pages after dropping lock */ 3958 spin_unlock_irq(&hugetlb_lock); 3959 update_and_free_pages_bulk(h, &page_list); 3960 flush_free_hpage_work(h); 3961 spin_lock_irq(&hugetlb_lock); 3962 3963 while (count < persistent_huge_pages(h)) { 3964 if (!adjust_pool_surplus(h, nodes_allowed, 1)) 3965 break; 3966 } 3967 out: 3968 h->max_huge_pages = persistent_huge_pages(h); 3969 spin_unlock_irq(&hugetlb_lock); 3970 mutex_unlock(&h->resize_lock); 3971 3972 NODEMASK_FREE(node_alloc_noretry); 3973 3974 return 0; 3975 } 3976 3977 static long demote_free_hugetlb_folios(struct hstate *src, struct hstate *dst, 3978 struct list_head *src_list) 3979 { 3980 long rc; 3981 struct folio *folio, *next; 3982 LIST_HEAD(dst_list); 3983 LIST_HEAD(ret_list); 3984 3985 rc = hugetlb_vmemmap_restore_folios(src, src_list, &ret_list); 3986 list_splice_init(&ret_list, src_list); 3987 3988 /* 3989 * Taking target hstate mutex synchronizes with set_max_huge_pages. 3990 * Without the mutex, pages added to target hstate could be marked 3991 * as surplus. 3992 * 3993 * Note that we already hold src->resize_lock. To prevent deadlock, 3994 * use the convention of always taking larger size hstate mutex first. 3995 */ 3996 mutex_lock(&dst->resize_lock); 3997 3998 list_for_each_entry_safe(folio, next, src_list, lru) { 3999 int i; 4000 bool cma; 4001 4002 if (folio_test_hugetlb_vmemmap_optimized(folio)) 4003 continue; 4004 4005 cma = folio_test_hugetlb_cma(folio); 4006 4007 list_del(&folio->lru); 4008 4009 split_page_owner(&folio->page, huge_page_order(src), huge_page_order(dst)); 4010 pgalloc_tag_split(folio, huge_page_order(src), huge_page_order(dst)); 4011 4012 for (i = 0; i < pages_per_huge_page(src); i += pages_per_huge_page(dst)) { 4013 struct page *page = folio_page(folio, i); 4014 /* Careful: see __split_huge_page_tail() */ 4015 struct folio *new_folio = (struct folio *)page; 4016 4017 clear_compound_head(page); 4018 prep_compound_page(page, dst->order); 4019 4020 new_folio->mapping = NULL; 4021 init_new_hugetlb_folio(new_folio); 4022 /* Copy the CMA flag so that it is freed correctly */ 4023 if (cma) 4024 folio_set_hugetlb_cma(new_folio); 4025 list_add(&new_folio->lru, &dst_list); 4026 } 4027 } 4028 4029 prep_and_add_allocated_folios(dst, &dst_list); 4030 4031 mutex_unlock(&dst->resize_lock); 4032 4033 return rc; 4034 } 4035 4036 long demote_pool_huge_page(struct hstate *src, nodemask_t *nodes_allowed, 4037 unsigned long nr_to_demote) 4038 __must_hold(&hugetlb_lock) 4039 { 4040 int nr_nodes, node; 4041 struct hstate *dst; 4042 long rc = 0; 4043 long nr_demoted = 0; 4044 long nr_persistent = 0; 4045 4046 lockdep_assert_held(&hugetlb_lock); 4047 4048 /* We should never get here if no demote order */ 4049 if (!src->demote_order) { 4050 pr_warn("NULL demote order passed to demote_pool_huge_page.\n"); 4051 return -EINVAL; /* internal error */ 4052 } 4053 dst = size_to_hstate(PAGE_SIZE << src->demote_order); 4054 4055 for_each_node_mask_to_free(src, nr_nodes, node, nodes_allowed) { 4056 LIST_HEAD(list); 4057 LIST_HEAD(surplus_list); 4058 struct folio *folio, *next; 4059 unsigned long nr_available, nr_target; 4060 4061 /* 4062 * Re-check available each node batch: the previous 4063 * batch released hugetlb_lock for vmemmap restore/split, 4064 * and a new reservation could have been added in that 4065 * window, shrinking the budget. available is global 4066 * (resv is not per-node), so 0 means no node can 4067 * contribute -- stop the whole scan. 4068 */ 4069 nr_available = available_huge_pages(src); 4070 if (!nr_available) 4071 break; 4072 4073 /* 4074 * Cap this batch at the current budget; expressed as a 4075 * cumulative stop point because nr_demoted is running. 4076 */ 4077 nr_target = nr_demoted + min_t(unsigned long, 4078 nr_to_demote - nr_demoted, nr_available); 4079 4080 list_for_each_entry_safe(folio, next, &src->hugepage_freelists[node], lru) { 4081 bool adjust_surplus; 4082 4083 if (folio_test_hwpoison(folio)) 4084 continue; 4085 4086 /* Surplus accounting is maintained per node, not per folio. */ 4087 adjust_surplus = src->surplus_huge_pages_node[node] > 0; 4088 remove_hugetlb_folio(src, folio, adjust_surplus); 4089 list_add(&folio->lru, adjust_surplus ? &surplus_list : &list); 4090 if (!adjust_surplus) 4091 nr_persistent++; 4092 4093 if (++nr_demoted == nr_target) 4094 break; 4095 } 4096 4097 if (list_empty(&list) && list_empty(&surplus_list)) 4098 continue; 4099 4100 spin_unlock_irq(&hugetlb_lock); 4101 4102 if (!list_empty(&list)) 4103 rc = demote_free_hugetlb_folios(src, dst, &list); 4104 if (!list_empty(&surplus_list)) { 4105 long tmp_rc; 4106 4107 tmp_rc = demote_free_hugetlb_folios(src, dst, &surplus_list); 4108 if (rc >= 0) 4109 rc = tmp_rc; 4110 } 4111 4112 spin_lock_irq(&hugetlb_lock); 4113 4114 list_for_each_entry_safe(folio, next, &list, lru) { 4115 list_del(&folio->lru); 4116 add_hugetlb_folio(src, folio, false); 4117 4118 nr_demoted--; 4119 nr_persistent--; 4120 } 4121 4122 list_for_each_entry_safe(folio, next, &surplus_list, lru) { 4123 list_del(&folio->lru); 4124 add_hugetlb_folio(src, folio, true); 4125 4126 nr_demoted--; 4127 } 4128 4129 if (rc < 0 || nr_demoted == nr_to_demote) 4130 break; 4131 } 4132 4133 /* 4134 * Not absolutely necessary, but for consistency update max_huge_pages 4135 * based on pool changes for the demoted page. 4136 */ 4137 src->max_huge_pages -= nr_persistent; 4138 dst->max_huge_pages += nr_demoted << (huge_page_order(src) - huge_page_order(dst)); 4139 4140 if (rc < 0) 4141 return rc; 4142 4143 if (nr_demoted) 4144 return nr_demoted; 4145 /* 4146 * Only way to get here is if all pages on free lists are poisoned. 4147 * Return -EBUSY so that caller will not retry. 4148 */ 4149 return -EBUSY; 4150 } 4151 4152 ssize_t __nr_hugepages_store_common(bool obey_mempolicy, 4153 struct hstate *h, int nid, 4154 unsigned long count, size_t len) 4155 { 4156 int err; 4157 nodemask_t nodes_allowed, *n_mask; 4158 4159 if (hstate_is_gigantic_no_runtime(h)) 4160 return -EINVAL; 4161 4162 if (nid == NUMA_NO_NODE) { 4163 /* 4164 * global hstate attribute 4165 */ 4166 if (!(obey_mempolicy && 4167 init_nodemask_of_mempolicy(&nodes_allowed))) 4168 n_mask = &node_states[N_MEMORY]; 4169 else 4170 n_mask = &nodes_allowed; 4171 } else { 4172 /* 4173 * Node specific request. count adjustment happens in 4174 * set_max_huge_pages() after acquiring hugetlb_lock. 4175 */ 4176 init_nodemask_of_node(&nodes_allowed, nid); 4177 n_mask = &nodes_allowed; 4178 } 4179 4180 err = set_max_huge_pages(h, count, nid, n_mask); 4181 4182 return err ? err : len; 4183 } 4184 4185 static int __init hugetlb_init(void) 4186 { 4187 int i; 4188 4189 BUILD_BUG_ON(sizeof_field(struct page, private) * BITS_PER_BYTE < 4190 __NR_HPAGEFLAGS); 4191 BUILD_BUG_ON_INVALID(HUGETLB_PAGE_ORDER > MAX_FOLIO_ORDER); 4192 4193 if (!hugepages_supported()) { 4194 if (hugetlb_max_hstate || default_hstate_max_huge_pages) 4195 pr_warn("huge pages not supported, ignoring associated command-line parameters\n"); 4196 return 0; 4197 } 4198 4199 /* 4200 * Make sure HPAGE_SIZE (HUGETLB_PAGE_ORDER) hstate exists. Some 4201 * architectures depend on setup being done here. 4202 */ 4203 hugetlb_add_hstate(HUGETLB_PAGE_ORDER); 4204 if (!parsed_default_hugepagesz) { 4205 /* 4206 * If we did not parse a default huge page size, set 4207 * default_hstate_idx to HPAGE_SIZE hstate. And, if the 4208 * number of huge pages for this default size was implicitly 4209 * specified, set that here as well. 4210 * Note that the implicit setting will overwrite an explicit 4211 * setting. A warning will be printed in this case. 4212 */ 4213 default_hstate_idx = hstate_index(size_to_hstate(HPAGE_SIZE)); 4214 if (default_hstate_max_huge_pages) { 4215 if (default_hstate.max_huge_pages) { 4216 char buf[32]; 4217 4218 string_get_size(huge_page_size(&default_hstate), 4219 1, STRING_UNITS_2, buf, sizeof(buf)); 4220 pr_warn("Ignoring hugepages=%lu associated with %s page size\n", 4221 default_hstate.max_huge_pages, buf); 4222 pr_warn("Using hugepages=%lu for number of default huge pages\n", 4223 default_hstate_max_huge_pages); 4224 } 4225 default_hstate.max_huge_pages = 4226 default_hstate_max_huge_pages; 4227 4228 for_each_online_node(i) 4229 default_hstate.max_huge_pages_node[i] = 4230 default_hugepages_in_node[i]; 4231 } 4232 } 4233 4234 hugetlb_init_hstates(); 4235 report_hugepages(); 4236 4237 hugetlb_sysfs_init(); 4238 hugetlb_cgroup_file_init(); 4239 hugetlb_sysctl_init(); 4240 4241 #ifdef CONFIG_SMP 4242 num_fault_mutexes = roundup_pow_of_two(8 * num_possible_cpus()); 4243 #else 4244 num_fault_mutexes = 1; 4245 #endif 4246 hugetlb_fault_mutex_table = 4247 kvmalloc_objs(struct mutex, num_fault_mutexes); 4248 BUG_ON(!hugetlb_fault_mutex_table); 4249 4250 for (i = 0; i < num_fault_mutexes; i++) 4251 mutex_init(&hugetlb_fault_mutex_table[i]); 4252 return 0; 4253 } 4254 subsys_initcall(hugetlb_init); 4255 4256 /* Overwritten by architectures with more huge page sizes */ 4257 bool __init __attribute((weak)) arch_hugetlb_valid_size(unsigned long size) 4258 { 4259 return size == HPAGE_SIZE; 4260 } 4261 4262 void __init hugetlb_add_hstate(unsigned int order) 4263 { 4264 struct hstate *h; 4265 unsigned long i; 4266 4267 if (size_to_hstate(PAGE_SIZE << order)) { 4268 return; 4269 } 4270 BUG_ON(hugetlb_max_hstate >= HUGE_MAX_HSTATE); 4271 BUG_ON(order < order_base_2(__NR_USED_SUBPAGE)); 4272 WARN_ON(order > MAX_FOLIO_ORDER); 4273 h = &hstates[hugetlb_max_hstate++]; 4274 __mutex_init(&h->resize_lock, "resize mutex", &h->resize_key); 4275 h->order = order; 4276 h->mask = ~(huge_page_size(h) - 1); 4277 for (i = 0; i < MAX_NUMNODES; ++i) 4278 INIT_LIST_HEAD(&h->hugepage_freelists[i]); 4279 INIT_LIST_HEAD(&h->hugepage_activelist); 4280 snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB", 4281 huge_page_size(h)/SZ_1K); 4282 4283 parsed_hstate = h; 4284 } 4285 4286 bool __init __weak hugetlb_node_alloc_supported(void) 4287 { 4288 return true; 4289 } 4290 4291 static void __init hugepages_clear_pages_in_node(void) 4292 { 4293 if (!hugetlb_max_hstate) { 4294 default_hstate_max_huge_pages = 0; 4295 memset(default_hugepages_in_node, 0, 4296 sizeof(default_hugepages_in_node)); 4297 } else { 4298 parsed_hstate->max_huge_pages = 0; 4299 memset(parsed_hstate->max_huge_pages_node, 0, 4300 sizeof(parsed_hstate->max_huge_pages_node)); 4301 } 4302 } 4303 4304 static __init int hugetlb_add_param(char *s, int (*setup)(char *)) 4305 { 4306 size_t len; 4307 char *p; 4308 4309 if (!s) 4310 return -EINVAL; 4311 4312 if (hugetlb_param_index >= HUGE_MAX_CMDLINE_ARGS) 4313 return -EINVAL; 4314 4315 len = strlen(s) + 1; 4316 if (len + hstate_cmdline_index > sizeof(hstate_cmdline_buf)) 4317 return -EINVAL; 4318 4319 p = &hstate_cmdline_buf[hstate_cmdline_index]; 4320 memcpy(p, s, len); 4321 hstate_cmdline_index += len; 4322 4323 hugetlb_params[hugetlb_param_index].val = p; 4324 hugetlb_params[hugetlb_param_index].setup = setup; 4325 4326 hugetlb_param_index++; 4327 4328 return 0; 4329 } 4330 4331 static __init void hugetlb_parse_params(void) 4332 { 4333 int i; 4334 struct hugetlb_cmdline *hcp; 4335 4336 for (i = 0; i < hugetlb_param_index; i++) { 4337 hcp = &hugetlb_params[i]; 4338 4339 hcp->setup(hcp->val); 4340 } 4341 4342 hugetlb_cma_validate_params(); 4343 } 4344 4345 /* 4346 * hugepages command line processing 4347 * hugepages normally follows a valid hugepagesz or default_hugepagesz 4348 * specification. If not, ignore the hugepages value. hugepages can also 4349 * be the first huge page command line option in which case it implicitly 4350 * specifies the number of huge pages for the default size. 4351 */ 4352 static int __init hugepages_setup(char *s) 4353 { 4354 unsigned long *mhp; 4355 static unsigned long *last_mhp; 4356 int node = NUMA_NO_NODE; 4357 int count; 4358 unsigned long tmp; 4359 char *p = s; 4360 4361 if (!hugepages_supported()) { 4362 pr_warn("hugepages unsupported, ignoring hugepages=%s cmdline\n", s); 4363 return 0; 4364 } 4365 4366 if (!parsed_valid_hugepagesz) { 4367 pr_warn("hugepages=%s does not follow a valid hugepagesz, ignoring\n", s); 4368 parsed_valid_hugepagesz = true; 4369 return -EINVAL; 4370 } 4371 4372 /* 4373 * !hugetlb_max_hstate means we haven't parsed a hugepagesz= parameter 4374 * yet, so this hugepages= parameter goes to the "default hstate". 4375 * Otherwise, it goes with the previously parsed hugepagesz or 4376 * default_hugepagesz. 4377 */ 4378 else if (!hugetlb_max_hstate) 4379 mhp = &default_hstate_max_huge_pages; 4380 else 4381 mhp = &parsed_hstate->max_huge_pages; 4382 4383 if (mhp == last_mhp) { 4384 pr_warn("hugepages= specified twice without interleaving hugepagesz=, ignoring hugepages=%s\n", s); 4385 return 1; 4386 } 4387 4388 while (*p) { 4389 count = 0; 4390 if (sscanf(p, "%lu%n", &tmp, &count) != 1) 4391 goto invalid; 4392 /* Parameter is node format */ 4393 if (p[count] == ':') { 4394 if (!hugetlb_node_alloc_supported()) { 4395 pr_warn("architecture can't support node specific alloc, ignoring!\n"); 4396 return 1; 4397 } 4398 if (tmp >= MAX_NUMNODES || !node_online(tmp)) 4399 goto invalid; 4400 node = array_index_nospec(tmp, MAX_NUMNODES); 4401 p += count + 1; 4402 /* Parse hugepages */ 4403 if (sscanf(p, "%lu%n", &tmp, &count) != 1) 4404 goto invalid; 4405 if (!hugetlb_max_hstate) 4406 default_hugepages_in_node[node] = tmp; 4407 else 4408 parsed_hstate->max_huge_pages_node[node] = tmp; 4409 *mhp += tmp; 4410 /* Go to parse next node*/ 4411 if (p[count] == ',') 4412 p += count + 1; 4413 else 4414 break; 4415 } else { 4416 if (p != s) 4417 goto invalid; 4418 *mhp = tmp; 4419 break; 4420 } 4421 } 4422 4423 last_mhp = mhp; 4424 4425 return 0; 4426 4427 invalid: 4428 pr_warn("Invalid hugepages parameter %s\n", p); 4429 hugepages_clear_pages_in_node(); 4430 return -EINVAL; 4431 } 4432 hugetlb_early_param("hugepages", hugepages_setup); 4433 4434 /* 4435 * hugepagesz command line processing 4436 * A specific huge page size can only be specified once with hugepagesz. 4437 * hugepagesz is followed by hugepages on the command line. The global 4438 * variable 'parsed_valid_hugepagesz' is used to determine if prior 4439 * hugepagesz argument was valid. 4440 */ 4441 static int __init hugepagesz_setup(char *s) 4442 { 4443 unsigned long size; 4444 struct hstate *h; 4445 4446 if (!hugepages_supported()) { 4447 pr_warn("hugepages unsupported, ignoring hugepagesz=%s cmdline\n", s); 4448 return 0; 4449 } 4450 4451 parsed_valid_hugepagesz = false; 4452 size = (unsigned long)memparse(s, NULL); 4453 4454 if (!arch_hugetlb_valid_size(size)) { 4455 pr_err("unsupported hugepagesz=%s\n", s); 4456 return -EINVAL; 4457 } 4458 4459 h = size_to_hstate(size); 4460 if (h) { 4461 /* 4462 * hstate for this size already exists. This is normally 4463 * an error, but is allowed if the existing hstate is the 4464 * default hstate. More specifically, it is only allowed if 4465 * the number of huge pages for the default hstate was not 4466 * previously specified. 4467 */ 4468 if (!parsed_default_hugepagesz || h != &default_hstate || 4469 default_hstate.max_huge_pages) { 4470 pr_warn("hugepagesz=%s specified twice, ignoring\n", s); 4471 return -EINVAL; 4472 } 4473 4474 /* 4475 * No need to call hugetlb_add_hstate() as hstate already 4476 * exists. But, do set parsed_hstate so that a following 4477 * hugepages= parameter will be applied to this hstate. 4478 */ 4479 parsed_hstate = h; 4480 parsed_valid_hugepagesz = true; 4481 return 0; 4482 } 4483 4484 hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT); 4485 parsed_valid_hugepagesz = true; 4486 return 0; 4487 } 4488 hugetlb_early_param("hugepagesz", hugepagesz_setup); 4489 4490 /* 4491 * default_hugepagesz command line input 4492 * Only one instance of default_hugepagesz allowed on command line. 4493 */ 4494 static int __init default_hugepagesz_setup(char *s) 4495 { 4496 unsigned long size; 4497 int i; 4498 4499 if (!hugepages_supported()) { 4500 pr_warn("hugepages unsupported, ignoring default_hugepagesz=%s cmdline\n", 4501 s); 4502 return 0; 4503 } 4504 4505 parsed_valid_hugepagesz = false; 4506 if (parsed_default_hugepagesz) { 4507 pr_err("default_hugepagesz previously specified, ignoring %s\n", s); 4508 return -EINVAL; 4509 } 4510 4511 size = (unsigned long)memparse(s, NULL); 4512 4513 if (!arch_hugetlb_valid_size(size)) { 4514 pr_err("unsupported default_hugepagesz=%s\n", s); 4515 return -EINVAL; 4516 } 4517 4518 hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT); 4519 parsed_valid_hugepagesz = true; 4520 parsed_default_hugepagesz = true; 4521 default_hstate_idx = hstate_index(size_to_hstate(size)); 4522 4523 /* 4524 * The number of default huge pages (for this size) could have been 4525 * specified as the first hugetlb parameter: hugepages=X. If so, 4526 * then default_hstate_max_huge_pages is set. If the default huge 4527 * page size is gigantic (> MAX_PAGE_ORDER), then the pages must be 4528 * allocated here from bootmem allocator. 4529 */ 4530 if (default_hstate_max_huge_pages) { 4531 default_hstate.max_huge_pages = default_hstate_max_huge_pages; 4532 /* 4533 * Since this is an early parameter, we can't check 4534 * NUMA node state yet, so loop through MAX_NUMNODES. 4535 */ 4536 for (i = 0; i < MAX_NUMNODES; i++) { 4537 if (default_hugepages_in_node[i] != 0) 4538 default_hstate.max_huge_pages_node[i] = 4539 default_hugepages_in_node[i]; 4540 } 4541 default_hstate_max_huge_pages = 0; 4542 } 4543 4544 return 0; 4545 } 4546 hugetlb_early_param("default_hugepagesz", default_hugepagesz_setup); 4547 4548 void __init hugetlb_bootmem_set_nodes(void) 4549 { 4550 int i, nid; 4551 4552 if (!nodes_empty(hugetlb_bootmem_nodes)) 4553 return; 4554 4555 for_each_mem_pfn_range(i, MAX_NUMNODES, NULL, NULL, &nid) 4556 node_set(nid, hugetlb_bootmem_nodes); 4557 } 4558 4559 void __init hugetlb_bootmem_alloc(void) 4560 { 4561 struct hstate *h; 4562 int i; 4563 4564 hugetlb_bootmem_set_nodes(); 4565 4566 for (i = 0; i < MAX_NUMNODES; i++) 4567 INIT_LIST_HEAD(&huge_boot_pages[i]); 4568 4569 hugetlb_parse_params(); 4570 4571 for_each_hstate(h) { 4572 h->next_nid_to_alloc = first_online_node; 4573 4574 if (hstate_is_gigantic(h)) 4575 hugetlb_hstate_alloc_pages(h); 4576 } 4577 } 4578 4579 /* 4580 * hugepage_alloc_threads command line parsing. 4581 * 4582 * When set, use this specific number of threads for the boot 4583 * allocation of hugepages. 4584 */ 4585 static int __init hugepage_alloc_threads_setup(char *s) 4586 { 4587 unsigned long allocation_threads; 4588 4589 if (kstrtoul(s, 0, &allocation_threads) != 0) 4590 return 1; 4591 4592 if (allocation_threads == 0) 4593 return 1; 4594 4595 hugepage_allocation_threads = allocation_threads; 4596 4597 return 1; 4598 } 4599 __setup("hugepage_alloc_threads=", hugepage_alloc_threads_setup); 4600 4601 static unsigned int allowed_mems_nr(struct hstate *h) 4602 { 4603 int node; 4604 unsigned int nr = 0; 4605 nodemask_t *mbind_nodemask; 4606 unsigned int *array = h->free_huge_pages_node; 4607 gfp_t gfp_mask = htlb_alloc_mask(h); 4608 4609 mbind_nodemask = policy_mbind_nodemask(gfp_mask); 4610 for_each_node_mask(node, cpuset_current_mems_allowed) { 4611 if (!mbind_nodemask || node_isset(node, *mbind_nodemask)) 4612 nr += array[node]; 4613 } 4614 4615 return nr; 4616 } 4617 4618 void hugetlb_report_meminfo(struct seq_file *m) 4619 { 4620 struct hstate *h; 4621 unsigned long total = 0; 4622 4623 if (!hugepages_supported()) 4624 return; 4625 4626 for_each_hstate(h) { 4627 unsigned long count = h->nr_huge_pages; 4628 4629 total += huge_page_size(h) * count; 4630 4631 if (h == &default_hstate) 4632 seq_printf(m, 4633 "HugePages_Total: %5lu\n" 4634 "HugePages_Free: %5lu\n" 4635 "HugePages_Rsvd: %5lu\n" 4636 "HugePages_Surp: %5lu\n" 4637 "Hugepagesize: %8lu kB\n", 4638 count, 4639 h->free_huge_pages, 4640 h->resv_huge_pages, 4641 h->surplus_huge_pages, 4642 huge_page_size(h) / SZ_1K); 4643 } 4644 4645 seq_printf(m, "Hugetlb: %8lu kB\n", total / SZ_1K); 4646 } 4647 4648 int hugetlb_report_node_meminfo(char *buf, int len, int nid) 4649 { 4650 struct hstate *h = &default_hstate; 4651 4652 if (!hugepages_supported()) 4653 return 0; 4654 4655 return sysfs_emit_at(buf, len, 4656 "Node %d HugePages_Total: %5u\n" 4657 "Node %d HugePages_Free: %5u\n" 4658 "Node %d HugePages_Surp: %5u\n", 4659 nid, h->nr_huge_pages_node[nid], 4660 nid, h->free_huge_pages_node[nid], 4661 nid, h->surplus_huge_pages_node[nid]); 4662 } 4663 4664 void hugetlb_show_meminfo_node(int nid) 4665 { 4666 struct hstate *h; 4667 4668 if (!hugepages_supported()) 4669 return; 4670 4671 for_each_hstate(h) 4672 printk("Node %d hugepages_total=%u hugepages_free=%u hugepages_surp=%u hugepages_size=%lukB\n", 4673 nid, 4674 h->nr_huge_pages_node[nid], 4675 h->free_huge_pages_node[nid], 4676 h->surplus_huge_pages_node[nid], 4677 huge_page_size(h) / SZ_1K); 4678 } 4679 4680 void hugetlb_report_usage(struct seq_file *m, struct mm_struct *mm) 4681 { 4682 seq_printf(m, "HugetlbPages:\t%8lu kB\n", 4683 K(atomic_long_read(&mm->hugetlb_usage))); 4684 } 4685 4686 /* Return the number pages of memory we physically have, in PAGE_SIZE units. */ 4687 unsigned long hugetlb_total_pages(void) 4688 { 4689 struct hstate *h; 4690 unsigned long nr_total_pages = 0; 4691 4692 for_each_hstate(h) 4693 nr_total_pages += h->nr_huge_pages * pages_per_huge_page(h); 4694 return nr_total_pages; 4695 } 4696 4697 static int hugetlb_acct_memory(struct hstate *h, long delta) 4698 { 4699 int ret = -ENOMEM; 4700 4701 if (!delta) 4702 return 0; 4703 4704 spin_lock_irq(&hugetlb_lock); 4705 /* 4706 * When cpuset is configured, it breaks the strict hugetlb page 4707 * reservation as the accounting is done on a global variable. Such 4708 * reservation is completely rubbish in the presence of cpuset because 4709 * the reservation is not checked against page availability for the 4710 * current cpuset. Application can still potentially OOM'ed by kernel 4711 * with lack of free htlb page in cpuset that the task is in. 4712 * Attempt to enforce strict accounting with cpuset is almost 4713 * impossible (or too ugly) because cpuset is too fluid that 4714 * task or memory node can be dynamically moved between cpusets. 4715 * 4716 * The change of semantics for shared hugetlb mapping with cpuset is 4717 * undesirable. However, in order to preserve some of the semantics, 4718 * we fall back to check against current free page availability as 4719 * a best attempt and hopefully to minimize the impact of changing 4720 * semantics that cpuset has. 4721 * 4722 * Apart from cpuset, we also have memory policy mechanism that 4723 * also determines from which node the kernel will allocate memory 4724 * in a NUMA system. So similar to cpuset, we also should consider 4725 * the memory policy of the current task. Similar to the description 4726 * above. 4727 */ 4728 if (delta > 0) { 4729 if (gather_surplus_pages(h, delta) < 0) 4730 goto out; 4731 4732 if (delta > allowed_mems_nr(h)) { 4733 return_unused_surplus_pages(h, delta); 4734 goto out; 4735 } 4736 } 4737 4738 ret = 0; 4739 if (delta < 0) 4740 return_unused_surplus_pages(h, (unsigned long) -delta); 4741 4742 out: 4743 spin_unlock_irq(&hugetlb_lock); 4744 return ret; 4745 } 4746 4747 static void hugetlb_vm_op_open(struct vm_area_struct *vma) 4748 { 4749 struct resv_map *resv = vma_resv_map(vma); 4750 4751 /* 4752 * HPAGE_RESV_OWNER indicates a private mapping. 4753 * This new VMA should share its siblings reservation map if present. 4754 * The VMA will only ever have a valid reservation map pointer where 4755 * it is being copied for another still existing VMA. As that VMA 4756 * has a reference to the reservation map it cannot disappear until 4757 * after this open call completes. It is therefore safe to take a 4758 * new reference here without additional locking. 4759 */ 4760 if (resv && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) { 4761 resv_map_dup_hugetlb_cgroup_uncharge_info(resv); 4762 kref_get(&resv->refs); 4763 } 4764 4765 /* 4766 * vma_lock structure for sharable mappings is vma specific. 4767 * Clear old pointer (if copied via vm_area_dup) and allocate 4768 * new structure. Before clearing, make sure vma_lock is not 4769 * for this vma. 4770 */ 4771 if (vma->vm_flags & VM_MAYSHARE) { 4772 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data; 4773 4774 if (vma_lock) { 4775 if (vma_lock->vma != vma) { 4776 vma->vm_private_data = NULL; 4777 hugetlb_vma_lock_alloc(vma); 4778 } else { 4779 pr_warn("vma_lock already exists in %s.\n", __func__); 4780 } 4781 } else { 4782 hugetlb_vma_lock_alloc(vma); 4783 } 4784 } 4785 } 4786 4787 static void hugetlb_vm_op_close(struct vm_area_struct *vma) 4788 { 4789 struct hstate *h = hstate_vma(vma); 4790 struct resv_map *resv; 4791 struct hugepage_subpool *spool = subpool_vma(vma); 4792 unsigned long reserve, start, end; 4793 long gbl_reserve; 4794 4795 hugetlb_vma_lock_free(vma); 4796 4797 resv = vma_resv_map(vma); 4798 if (!resv || !is_vma_resv_set(vma, HPAGE_RESV_OWNER)) 4799 return; 4800 4801 start = vma_hugecache_offset(h, vma, vma->vm_start); 4802 end = vma_hugecache_offset(h, vma, vma->vm_end); 4803 4804 reserve = (end - start) - region_count(resv, start, end); 4805 hugetlb_cgroup_uncharge_counter(resv, start, end); 4806 if (reserve) { 4807 /* 4808 * Decrement reserve counts. The global reserve count may be 4809 * adjusted if the subpool has a minimum size. 4810 */ 4811 gbl_reserve = hugepage_subpool_put_pages(spool, reserve); 4812 hugetlb_acct_memory(h, -gbl_reserve); 4813 } 4814 4815 kref_put(&resv->refs, resv_map_release); 4816 } 4817 4818 static int hugetlb_vm_op_split(struct vm_area_struct *vma, unsigned long addr) 4819 { 4820 if (addr & ~(huge_page_mask(hstate_vma(vma)))) 4821 return -EINVAL; 4822 return 0; 4823 } 4824 4825 void hugetlb_split(struct vm_area_struct *vma, unsigned long addr) 4826 { 4827 /* 4828 * PMD sharing is only possible for PUD_SIZE-aligned address ranges 4829 * in HugeTLB VMAs. If we will lose PUD_SIZE alignment due to this 4830 * split, unshare PMDs in the PUD_SIZE interval surrounding addr now. 4831 * This function is called in the middle of a VMA split operation, with 4832 * MM, VMA and rmap all write-locked to prevent concurrent page table 4833 * walks (except hardware and gup_fast()). 4834 */ 4835 vma_assert_write_locked(vma); 4836 i_mmap_assert_write_locked(vma->vm_file->f_mapping); 4837 4838 if (addr & ~PUD_MASK) { 4839 unsigned long floor = addr & PUD_MASK; 4840 unsigned long ceil = floor + PUD_SIZE; 4841 4842 if (floor >= vma->vm_start && ceil <= vma->vm_end) { 4843 /* 4844 * Locking: 4845 * Use take_locks=false here. 4846 * The file rmap lock is already held. 4847 * The hugetlb VMA lock can't be taken when we already 4848 * hold the file rmap lock, and we don't need it because 4849 * its purpose is to synchronize against concurrent page 4850 * table walks, which are not possible thanks to the 4851 * locks held by our caller. 4852 */ 4853 hugetlb_unshare_pmds(vma, floor, ceil, /* take_locks = */ false); 4854 } 4855 } 4856 } 4857 4858 static unsigned long hugetlb_vm_op_pagesize(struct vm_area_struct *vma) 4859 { 4860 return huge_page_size(hstate_vma(vma)); 4861 } 4862 4863 /* 4864 * We cannot handle pagefaults against hugetlb pages at all. They cause 4865 * handle_mm_fault() to try to instantiate regular-sized pages in the 4866 * hugepage VMA. do_page_fault() is supposed to trap this, so BUG is we get 4867 * this far. 4868 */ 4869 static vm_fault_t hugetlb_vm_op_fault(struct vm_fault *vmf) 4870 { 4871 BUG(); 4872 return 0; 4873 } 4874 4875 #ifdef CONFIG_USERFAULTFD 4876 static bool hugetlb_can_userfault(struct vm_area_struct *vma, 4877 vm_flags_t vm_flags) 4878 { 4879 return true; 4880 } 4881 4882 static const struct vm_uffd_ops hugetlb_uffd_ops = { 4883 .can_userfault = hugetlb_can_userfault, 4884 }; 4885 #endif 4886 4887 /* 4888 * When a new function is introduced to vm_operations_struct and added 4889 * to hugetlb_vm_ops, please consider adding the function to shm_vm_ops. 4890 * This is because under System V memory model, mappings created via 4891 * shmget/shmat with "huge page" specified are backed by hugetlbfs files, 4892 * their original vm_ops are overwritten with shm_vm_ops. 4893 */ 4894 const struct vm_operations_struct hugetlb_vm_ops = { 4895 .fault = hugetlb_vm_op_fault, 4896 .open = hugetlb_vm_op_open, 4897 .close = hugetlb_vm_op_close, 4898 .may_split = hugetlb_vm_op_split, 4899 .pagesize = hugetlb_vm_op_pagesize, 4900 #ifdef CONFIG_USERFAULTFD 4901 .uffd_ops = &hugetlb_uffd_ops, 4902 #endif 4903 }; 4904 4905 static pte_t make_huge_pte(struct vm_area_struct *vma, struct folio *folio, 4906 bool try_mkwrite) 4907 { 4908 pte_t entry = folio_mk_pte(folio, vma->vm_page_prot); 4909 unsigned int shift = huge_page_shift(hstate_vma(vma)); 4910 4911 if (try_mkwrite && (vma->vm_flags & VM_WRITE)) { 4912 entry = pte_mkwrite_novma(pte_mkdirty(entry)); 4913 } else { 4914 entry = pte_wrprotect(entry); 4915 } 4916 entry = pte_mkyoung(entry); 4917 entry = arch_make_huge_pte(entry, shift, vma->vm_flags); 4918 4919 return entry; 4920 } 4921 4922 static void set_huge_ptep_writable(struct vm_area_struct *vma, 4923 unsigned long address, pte_t *ptep) 4924 { 4925 pte_t entry; 4926 4927 entry = huge_pte_mkwrite(huge_pte_mkdirty(huge_ptep_get(vma->vm_mm, address, ptep))); 4928 if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1)) 4929 update_mmu_cache(vma, address, ptep); 4930 } 4931 4932 static void set_huge_ptep_maybe_writable(struct vm_area_struct *vma, 4933 unsigned long address, pte_t *ptep) 4934 { 4935 if (vma->vm_flags & VM_WRITE) 4936 set_huge_ptep_writable(vma, address, ptep); 4937 } 4938 4939 static void 4940 hugetlb_install_folio(struct vm_area_struct *vma, pte_t *ptep, unsigned long addr, 4941 struct folio *new_folio, pte_t old, unsigned long sz) 4942 { 4943 pte_t newpte = make_huge_pte(vma, new_folio, true); 4944 4945 __folio_mark_uptodate(new_folio); 4946 hugetlb_add_new_anon_rmap(new_folio, vma, addr); 4947 if (userfaultfd_protected(vma) && huge_pte_uffd(old)) { 4948 newpte = huge_pte_mkuffd(newpte); 4949 /* Restore PAGE_NONE so the RWP marker keeps trapping. */ 4950 if (userfaultfd_rwp(vma)) { 4951 unsigned int shift = huge_page_shift(hstate_vma(vma)); 4952 4953 newpte = huge_pte_modify(newpte, PAGE_NONE); 4954 newpte = arch_make_huge_pte(newpte, shift, vma->vm_flags); 4955 } 4956 } 4957 set_huge_pte_at(vma->vm_mm, addr, ptep, newpte, sz); 4958 hugetlb_count_add(pages_per_huge_page(hstate_vma(vma)), vma->vm_mm); 4959 folio_set_hugetlb_migratable(new_folio); 4960 } 4961 4962 int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src, 4963 struct vm_area_struct *dst_vma, 4964 struct vm_area_struct *src_vma) 4965 { 4966 pte_t *src_pte, *dst_pte, entry; 4967 struct folio *pte_folio; 4968 unsigned long addr; 4969 bool cow = vma_is_cow_mapping(src_vma); 4970 struct hstate *h = hstate_vma(src_vma); 4971 unsigned long sz = huge_page_size(h); 4972 unsigned long npages = pages_per_huge_page(h); 4973 struct mmu_notifier_range range; 4974 unsigned long last_addr_mask; 4975 softleaf_t softleaf; 4976 int ret = 0; 4977 4978 if (cow) { 4979 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, src, 4980 src_vma->vm_start, 4981 src_vma->vm_end); 4982 mmu_notifier_invalidate_range_start(&range); 4983 vma_assert_write_locked(src_vma); 4984 raw_write_seqcount_begin(&src->write_protect_seq); 4985 } else { 4986 /* 4987 * Shared mappings only need copying when we could have 4988 * information stored in page tables (e.g., userfaultfd PTE 4989 * bits or markers), which is incompatible with PMD sharing. 4990 * Still take the hugetlb VMA lock for now to satisfy 4991 * hugetlb_walk()'s locking requirements. 4992 */ 4993 hugetlb_vma_lock_read(src_vma); 4994 } 4995 4996 last_addr_mask = hugetlb_mask_last_page(h); 4997 for (addr = src_vma->vm_start; addr < src_vma->vm_end; addr += sz) { 4998 spinlock_t *src_ptl, *dst_ptl; 4999 5000 if (WARN_ON_ONCE(want_pmd_share(src_vma, addr) || 5001 want_pmd_share(dst_vma, addr))) { 5002 ret = -EINVAL; 5003 break; 5004 } 5005 5006 src_pte = hugetlb_walk(src_vma, addr, sz); 5007 if (!src_pte) { 5008 addr |= last_addr_mask; 5009 continue; 5010 } 5011 dst_pte = huge_pte_alloc(dst, dst_vma, addr, sz); 5012 if (!dst_pte) { 5013 ret = -ENOMEM; 5014 break; 5015 } 5016 5017 dst_ptl = huge_pte_lock(h, dst, dst_pte); 5018 src_ptl = huge_pte_lockptr(h, src, src_pte); 5019 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING); 5020 entry = huge_ptep_get(src_vma->vm_mm, addr, src_pte); 5021 again: 5022 if (huge_pte_none(entry)) { 5023 /* Skip if src entry none. */ 5024 goto next; 5025 } 5026 5027 softleaf = softleaf_from_pte(entry); 5028 if (unlikely(softleaf_is_hwpoison(softleaf))) { 5029 /* 5030 * A hwpoison entry never carries the uffd-wp bit: it is 5031 * installed fresh by make_hwpoison_entry() and 5032 * hugetlb_change_protection() leaves it untouched, so 5033 * there is nothing to clear for the child. 5034 */ 5035 set_huge_pte_at(dst, addr, dst_pte, entry, sz); 5036 } else if (unlikely(softleaf_is_migration(softleaf))) { 5037 bool uffd = pte_swp_uffd(entry); 5038 5039 if (!softleaf_is_migration_read(softleaf) && cow) { 5040 /* 5041 * COW mappings require pages in both 5042 * parent and child to be set to read. 5043 */ 5044 softleaf = make_readable_migration_entry( 5045 swp_offset(softleaf)); 5046 entry = swp_entry_to_pte(softleaf); 5047 if (userfaultfd_protected(src_vma) && uffd) 5048 entry = pte_swp_mkuffd(entry); 5049 set_huge_pte_at(src, addr, src_pte, entry, sz); 5050 } 5051 if (!userfaultfd_protected(dst_vma)) 5052 entry = pte_swp_clear_uffd(entry); 5053 set_huge_pte_at(dst, addr, dst_pte, entry, sz); 5054 } else if (unlikely(pte_is_marker(entry))) { 5055 const pte_marker marker = copy_pte_marker(softleaf, dst_vma); 5056 5057 if (marker) 5058 set_huge_pte_at(dst, addr, dst_pte, 5059 make_pte_marker(marker), sz); 5060 } else { 5061 entry = huge_ptep_get(src_vma->vm_mm, addr, src_pte); 5062 pte_folio = page_folio(pte_page(entry)); 5063 folio_get(pte_folio); 5064 5065 /* 5066 * Failing to duplicate the anon rmap is a rare case 5067 * where we see pinned hugetlb pages while they're 5068 * prone to COW. We need to do the COW earlier during 5069 * fork. 5070 * 5071 * When pre-allocating the page or copying data, we 5072 * need to be without the pgtable locks since we could 5073 * sleep during the process. 5074 */ 5075 if (!folio_test_anon(pte_folio)) { 5076 hugetlb_add_file_rmap(pte_folio); 5077 } else if (hugetlb_try_dup_anon_rmap(pte_folio, src_vma)) { 5078 pte_t src_pte_old = entry; 5079 struct folio *new_folio; 5080 5081 spin_unlock(src_ptl); 5082 spin_unlock(dst_ptl); 5083 /* Do not use reserve as it's private owned */ 5084 new_folio = alloc_hugetlb_folio(dst_vma, addr, false); 5085 if (IS_ERR(new_folio)) { 5086 folio_put(pte_folio); 5087 ret = PTR_ERR(new_folio); 5088 break; 5089 } 5090 ret = copy_user_large_folio(new_folio, pte_folio, 5091 addr, dst_vma); 5092 folio_put(pte_folio); 5093 if (ret) { 5094 restore_reserve_on_error(h, dst_vma, addr, new_folio); 5095 folio_put(new_folio); 5096 break; 5097 } 5098 5099 /* Install the new hugetlb folio if src pte stable */ 5100 dst_ptl = huge_pte_lock(h, dst, dst_pte); 5101 src_ptl = huge_pte_lockptr(h, src, src_pte); 5102 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING); 5103 entry = huge_ptep_get(src_vma->vm_mm, addr, src_pte); 5104 if (!pte_same(src_pte_old, entry)) { 5105 restore_reserve_on_error(h, dst_vma, addr, 5106 new_folio); 5107 folio_put(new_folio); 5108 /* huge_ptep of dst_pte won't change as in child */ 5109 goto again; 5110 } 5111 hugetlb_install_folio(dst_vma, dst_pte, addr, 5112 new_folio, src_pte_old, sz); 5113 goto next; 5114 } 5115 5116 /* See __copy_present_ptes(): restore accessible protection. */ 5117 if (!userfaultfd_protected(dst_vma)) { 5118 if (userfaultfd_rwp(src_vma) && huge_pte_uffd(entry)) { 5119 entry = huge_pte_modify(entry, dst_vma->vm_page_prot); 5120 entry = arch_make_huge_pte(entry, huge_page_shift(h), 5121 dst_vma->vm_flags); 5122 } 5123 entry = huge_pte_clear_uffd(entry); 5124 } 5125 5126 if (cow) { 5127 /* 5128 * No need to notify as we are downgrading page 5129 * table protection not changing it to point 5130 * to a new page. 5131 * 5132 * See Documentation/mm/mmu_notifier.rst 5133 */ 5134 huge_ptep_set_wrprotect(src, addr, src_pte); 5135 entry = huge_pte_wrprotect(entry); 5136 } 5137 5138 set_huge_pte_at(dst, addr, dst_pte, entry, sz); 5139 hugetlb_count_add(npages, dst); 5140 } 5141 5142 next: 5143 spin_unlock(src_ptl); 5144 spin_unlock(dst_ptl); 5145 } 5146 5147 if (cow) { 5148 raw_write_seqcount_end(&src->write_protect_seq); 5149 mmu_notifier_invalidate_range_end(&range); 5150 } else { 5151 hugetlb_vma_unlock_read(src_vma); 5152 } 5153 5154 return ret; 5155 } 5156 5157 static void move_huge_pte(struct vm_area_struct *vma, unsigned long old_addr, 5158 unsigned long new_addr, pte_t *src_pte, pte_t *dst_pte, 5159 unsigned long sz) 5160 { 5161 bool need_clear_uffd_wp = vma_has_uffd_without_event_remap(vma); 5162 struct hstate *h = hstate_vma(vma); 5163 struct mm_struct *mm = vma->vm_mm; 5164 spinlock_t *src_ptl, *dst_ptl; 5165 pte_t pte; 5166 5167 dst_ptl = huge_pte_lockptr(h, mm, dst_pte); 5168 src_ptl = huge_pte_lockptr(h, mm, src_pte); 5169 double_pt_lock(dst_ptl, src_ptl); 5170 5171 pte = huge_ptep_get_and_clear(mm, old_addr, src_pte, sz); 5172 5173 if (need_clear_uffd_wp && pte_is_uffd_wp_marker(pte)) { 5174 huge_pte_clear(mm, new_addr, dst_pte, sz); 5175 } else { 5176 if (need_clear_uffd_wp) { 5177 if (pte_present(pte)) { 5178 /* 5179 * See __copy_present_ptes(): normalise the RWP 5180 * marker so the destination starts accessible 5181 * instead of taking a numa-hinting fault on 5182 * first access. Only the marker (protnone + uffd) 5183 * needs it; leave other present PTEs untouched. 5184 */ 5185 if (userfaultfd_rwp(vma) && huge_pte_uffd(pte)) { 5186 pte = huge_pte_modify(pte, vma->vm_page_prot); 5187 pte = arch_make_huge_pte(pte, huge_page_shift(h), 5188 vma->vm_flags); 5189 } 5190 pte = huge_pte_clear_uffd(pte); 5191 } else { 5192 pte = pte_swp_clear_uffd(pte); 5193 } 5194 } 5195 set_huge_pte_at(mm, new_addr, dst_pte, pte, sz); 5196 } 5197 5198 double_pt_unlock(dst_ptl, src_ptl); 5199 } 5200 5201 unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma, 5202 struct vm_area_struct *new_vma, unsigned long old_addr, 5203 unsigned long new_addr, unsigned long len) 5204 { 5205 struct hstate *h = hstate_vma(vma); 5206 struct address_space *mapping = vma->vm_file->f_mapping; 5207 struct anon_vma *anon_vma = vma->anon_vma; 5208 unsigned long sz = huge_page_size(h); 5209 struct mm_struct *mm = vma->vm_mm; 5210 unsigned long old_end = old_addr + len; 5211 unsigned long last_addr_mask; 5212 pte_t *src_pte, *dst_pte; 5213 struct mmu_notifier_range range; 5214 struct mmu_gather tlb; 5215 5216 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, old_addr, 5217 old_end); 5218 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end); 5219 /* 5220 * In case of shared PMDs, we should cover the maximum possible 5221 * range. 5222 */ 5223 flush_cache_range(vma, range.start, range.end); 5224 tlb_gather_mmu_vma(&tlb, vma); 5225 5226 mmu_notifier_invalidate_range_start(&range); 5227 last_addr_mask = hugetlb_mask_last_page(h); 5228 /* Prevent race with file truncation */ 5229 hugetlb_vma_lock_write(vma); 5230 i_mmap_lock_write(mapping); 5231 if (anon_vma) 5232 anon_vma_lock_write(anon_vma); 5233 for (; old_addr < old_end; old_addr += sz, new_addr += sz) { 5234 const unsigned long offset_to_last_entry = 5235 (old_addr | last_addr_mask) - old_addr; 5236 const unsigned long offset_to_last_dst_entry = 5237 (new_addr | last_addr_mask) - new_addr; 5238 5239 src_pte = hugetlb_walk(vma, old_addr, sz); 5240 if (!src_pte) { 5241 old_addr += offset_to_last_entry; 5242 new_addr += offset_to_last_entry; 5243 continue; 5244 } 5245 if (huge_pte_none(huge_ptep_get(mm, old_addr, src_pte))) 5246 continue; 5247 5248 if (huge_pmd_unshare(&tlb, vma, old_addr, src_pte)) { 5249 old_addr += offset_to_last_entry; 5250 new_addr += offset_to_last_entry; 5251 continue; 5252 } 5253 5254 /* 5255 * Avoid entering the destination PMD sharing path while holding 5256 * i_mmap_rwsem for write. Leave destination page table 5257 * population to the fault path, which can share the PMD lazily. 5258 */ 5259 if (sz == PMD_SIZE && want_pmd_share(new_vma, new_addr)) { 5260 const unsigned long unmap_size = 5261 min(old_end - old_addr, 5262 offset_to_last_dst_entry + sz); 5263 5264 hugetlb_unmap_range(&tlb, vma, old_addr, 5265 old_addr + unmap_size, NULL, 5266 ZAP_FLAG_DROP_MARKER); 5267 old_addr += unmap_size - sz; 5268 new_addr += unmap_size - sz; 5269 continue; 5270 } 5271 5272 dst_pte = hugetlb_walk(new_vma, new_addr, sz); 5273 if (!dst_pte) { 5274 /* 5275 * We can allocate memory under anon_vma lock with hugetlb, 5276 * but lockdep does not know about that. So for now we simply 5277 * flush the TLB and temporarily drop the lock. 5278 */ 5279 tlb_flush_mmu_tlbonly(&tlb); 5280 if (anon_vma) 5281 anon_vma_unlock_write(anon_vma); 5282 dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz); 5283 if (anon_vma) 5284 anon_vma_lock_write(anon_vma); 5285 } 5286 if (!dst_pte) 5287 break; 5288 5289 move_huge_pte(vma, old_addr, new_addr, src_pte, dst_pte, sz); 5290 tlb_remove_huge_tlb_entry(h, &tlb, src_pte, old_addr); 5291 } 5292 5293 /* Flush pending moves before allowing migration to walk the entries. */ 5294 tlb_flush_mmu_tlbonly(&tlb); 5295 if (anon_vma) 5296 anon_vma_unlock_write(anon_vma); 5297 huge_pmd_unshare_flush(&tlb, vma); 5298 5299 mmu_notifier_invalidate_range_end(&range); 5300 i_mmap_unlock_write(mapping); 5301 hugetlb_vma_unlock_write(vma); 5302 tlb_finish_mmu(&tlb); 5303 5304 return len + old_addr - old_end; 5305 } 5306 5307 static void hugetlb_unmap_range(struct mmu_gather *tlb, 5308 struct vm_area_struct *vma, unsigned long start, 5309 unsigned long end, struct folio *folio, 5310 zap_flags_t zap_flags) 5311 { 5312 struct mm_struct *mm = vma->vm_mm; 5313 const bool folio_provided = !!folio; 5314 unsigned long address; 5315 pte_t *ptep; 5316 pte_t pte; 5317 spinlock_t *ptl; 5318 struct hstate *h = hstate_vma(vma); 5319 unsigned long sz = huge_page_size(h); 5320 bool adjust_reservation; 5321 unsigned long last_addr_mask; 5322 5323 i_mmap_assert_write_locked(vma->vm_file->f_mapping); 5324 WARN_ON(!vma_is_hugetlb(vma)); 5325 BUG_ON(start & ~huge_page_mask(h)); 5326 BUG_ON(end & ~huge_page_mask(h)); 5327 5328 last_addr_mask = hugetlb_mask_last_page(h); 5329 address = start; 5330 for (; address < end; address += sz) { 5331 ptep = hugetlb_walk(vma, address, sz); 5332 if (!ptep) { 5333 address |= last_addr_mask; 5334 continue; 5335 } 5336 5337 ptl = huge_pte_lock(h, mm, ptep); 5338 if (huge_pmd_unshare(tlb, vma, address, ptep)) { 5339 spin_unlock(ptl); 5340 address |= last_addr_mask; 5341 continue; 5342 } 5343 5344 pte = huge_ptep_get(mm, address, ptep); 5345 if (huge_pte_none(pte)) { 5346 spin_unlock(ptl); 5347 continue; 5348 } 5349 5350 /* 5351 * Migrating hugepage or HWPoisoned hugepage is already 5352 * unmapped and its refcount is dropped, so just clear pte here. 5353 */ 5354 if (unlikely(!pte_present(pte))) { 5355 /* 5356 * If the pte was wr-protected by uffd-wp in any of the 5357 * swap forms, meanwhile the caller does not want to 5358 * drop the uffd-wp bit in this zap, then replace the 5359 * pte with a marker. 5360 */ 5361 if (userfaultfd_wp(vma) && pte_swp_uffd_any(pte) && 5362 !(zap_flags & ZAP_FLAG_DROP_MARKER)) 5363 set_huge_pte_at(mm, address, ptep, 5364 make_pte_marker(PTE_MARKER_UFFD_WP), 5365 sz); 5366 else 5367 huge_pte_clear(mm, address, ptep, sz); 5368 spin_unlock(ptl); 5369 continue; 5370 } 5371 5372 /* 5373 * If a folio is supplied, it is because a specific 5374 * folio is being unmapped, not a range. Ensure the folio we 5375 * are about to unmap is the actual folio of interest. 5376 */ 5377 if (folio_provided) { 5378 if (folio != page_folio(pte_page(pte))) { 5379 spin_unlock(ptl); 5380 continue; 5381 } 5382 /* 5383 * Mark the VMA as having unmapped its page so that 5384 * future faults in this VMA will fail rather than 5385 * looking like data was lost 5386 */ 5387 set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED); 5388 } else { 5389 folio = page_folio(pte_page(pte)); 5390 } 5391 5392 pte = huge_ptep_get_and_clear(mm, address, ptep, sz); 5393 tlb_remove_huge_tlb_entry(h, tlb, ptep, address); 5394 if (huge_pte_dirty(pte)) 5395 folio_mark_dirty(folio); 5396 /* Leave a uffd-wp pte marker if needed */ 5397 if (userfaultfd_wp(vma) && huge_pte_uffd(pte) && 5398 !(zap_flags & ZAP_FLAG_DROP_MARKER)) 5399 set_huge_pte_at(mm, address, ptep, 5400 make_pte_marker(PTE_MARKER_UFFD_WP), 5401 sz); 5402 hugetlb_count_sub(pages_per_huge_page(h), mm); 5403 hugetlb_remove_rmap(folio); 5404 spin_unlock(ptl); 5405 5406 /* 5407 * Restore the reservation for anonymous page, otherwise the 5408 * backing page could be stolen by someone. Restore only on the 5409 * last unmap, otherwise the owner could empty its resv map 5410 * while the folio is still mapped by a child. Note that holding 5411 * i_mmap_lock_write is needed to check the number of mappings. 5412 * If there we are freeing a surplus, do not set the restore 5413 * reservation bit. 5414 */ 5415 adjust_reservation = false; 5416 5417 spin_lock_irq(&hugetlb_lock); 5418 if (!h->surplus_huge_pages && __vma_private_lock(vma) && 5419 !folio_mapped(folio) && folio_test_anon(folio)) { 5420 folio_set_hugetlb_restore_reserve(folio); 5421 /* Reservation to be adjusted after the spin lock */ 5422 adjust_reservation = true; 5423 } 5424 spin_unlock_irq(&hugetlb_lock); 5425 5426 /* 5427 * Adjust the reservation for the region that will have the 5428 * reserve restored. Keep in mind that vma_needs_reservation() changes 5429 * resv->adds_in_progress if it succeeds. If this is not done, 5430 * do_exit() will not see it, and will keep the reservation 5431 * forever. 5432 */ 5433 if (adjust_reservation) { 5434 int rc = vma_needs_reservation(h, vma, address); 5435 5436 if (rc < 0) 5437 /* Presumably allocate_file_region_entries failed 5438 * to allocate a file_region struct. Clear 5439 * hugetlb_restore_reserve so that global reserve 5440 * count will not be incremented by free_huge_folio. 5441 * Act as if we consumed the reservation. 5442 */ 5443 folio_clear_hugetlb_restore_reserve(folio); 5444 else if (rc) 5445 vma_add_reservation(h, vma, address); 5446 } 5447 5448 tlb_remove_page_size(tlb, folio_page(folio, 0), 5449 folio_size(folio)); 5450 /* 5451 * If we were instructed to unmap a specific folio, we're done. 5452 */ 5453 if (folio_provided) 5454 break; 5455 } 5456 } 5457 5458 void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma, 5459 unsigned long start, unsigned long end, 5460 struct folio *folio, zap_flags_t zap_flags) 5461 { 5462 tlb_change_page_size(tlb, huge_page_size(hstate_vma(vma))); 5463 tlb_start_vma(tlb, vma); 5464 hugetlb_unmap_range(tlb, vma, start, end, folio, zap_flags); 5465 tlb_end_vma(tlb, vma); 5466 5467 huge_pmd_unshare_flush(tlb, vma); 5468 } 5469 5470 void __hugetlb_zap_begin(struct vm_area_struct *vma, 5471 unsigned long *start, unsigned long *end) 5472 { 5473 if (!vma->vm_file) /* hugetlbfs_file_mmap error */ 5474 return; 5475 5476 hugetlb_vma_lock_write(vma); 5477 if (vma->vm_file) { 5478 i_mmap_lock_write(vma->vm_file->f_mapping); 5479 if (hugetlbfs_pmd_sharing_active(file_inode(vma->vm_file))) 5480 adjust_range_if_pmd_sharing_possible(vma, start, end); 5481 } 5482 } 5483 5484 void __hugetlb_zap_end(struct vm_area_struct *vma, 5485 struct zap_details *details) 5486 { 5487 zap_flags_t zap_flags = details ? details->zap_flags : 0; 5488 5489 if (!vma->vm_file) /* hugetlbfs_file_mmap error */ 5490 return; 5491 5492 if (zap_flags & ZAP_FLAG_UNMAP) { /* final unmap */ 5493 /* 5494 * Unlock and free the vma lock before releasing i_mmap_rwsem. 5495 * When the vma_lock is freed, this makes the vma ineligible 5496 * for pmd sharing. And, i_mmap_rwsem is required to set up 5497 * pmd sharing. This is important as page tables for this 5498 * unmapped range will be asynchrously deleted. If the page 5499 * tables are shared, there will be issues when accessed by 5500 * someone else. 5501 */ 5502 __hugetlb_vma_unlock_write_free(vma); 5503 } else { 5504 hugetlb_vma_unlock_write(vma); 5505 } 5506 5507 if (vma->vm_file) 5508 i_mmap_unlock_write(vma->vm_file->f_mapping); 5509 } 5510 5511 void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start, 5512 unsigned long end, struct folio *folio, 5513 zap_flags_t zap_flags) 5514 { 5515 struct mmu_notifier_range range; 5516 struct mmu_gather tlb; 5517 5518 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm, 5519 start, end); 5520 i_mmap_assert_write_locked(vma->vm_file->f_mapping); 5521 if (hugetlbfs_pmd_sharing_active(file_inode(vma->vm_file))) 5522 adjust_range_if_pmd_sharing_possible(vma, &range.start, 5523 &range.end); 5524 mmu_notifier_invalidate_range_start(&range); 5525 tlb_gather_mmu(&tlb, vma->vm_mm); 5526 5527 __unmap_hugepage_range(&tlb, vma, start, end, 5528 folio, zap_flags); 5529 5530 mmu_notifier_invalidate_range_end(&range); 5531 tlb_finish_mmu(&tlb); 5532 } 5533 5534 /* 5535 * This is called when the original mapper is failing to COW a MAP_PRIVATE 5536 * mapping it owns the reserve page for. The intention is to unmap the page 5537 * from other VMAs and let the children be SIGKILLed if they are faulting the 5538 * same region. 5539 */ 5540 static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma, 5541 struct folio *folio, unsigned long address) 5542 { 5543 struct hstate *h = hstate_vma(vma); 5544 struct vm_area_struct *iter_vma; 5545 struct address_space *mapping; 5546 pgoff_t pgoff; 5547 5548 VM_WARN_ON_ONCE(!folio_test_anon(folio)); 5549 5550 /* 5551 * vm_pgoff is in PAGE_SIZE units, hence the different calculation 5552 * from page cache lookup which is in HPAGE_SIZE units. 5553 */ 5554 address = address & huge_page_mask(h); 5555 pgoff = linear_page_index(vma, address); 5556 mapping = vma->vm_file->f_mapping; 5557 5558 /* 5559 * Take the mapping lock for the duration of the table walk. As 5560 * this mapping should be shared between all the VMAs, 5561 * __unmap_hugepage_range() is called as the lock is already held 5562 */ 5563 i_mmap_lock_write(mapping); 5564 mapping_rmap_tree_foreach(iter_vma, mapping, pgoff, pgoff) { 5565 /* Do not unmap the current VMA */ 5566 if (iter_vma == vma) 5567 continue; 5568 5569 /* 5570 * Shared VMAs have their own reserves and do not affect 5571 * MAP_PRIVATE accounting but it is possible that a shared 5572 * VMA is using the same page so check and skip such VMAs. 5573 */ 5574 if (iter_vma->vm_flags & VM_MAYSHARE) 5575 continue; 5576 5577 /* 5578 * Unmap the page from other VMAs without their own reserves. 5579 * They get marked to be SIGKILLed if they fault in these 5580 * areas. This is because a future no-page fault on this VMA 5581 * could insert a zeroed page instead of the data existing 5582 * from the time of fork. This would look like data corruption 5583 */ 5584 if (is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER)) 5585 continue; 5586 5587 /* 5588 * The address in other VMAs can differ. Even though our old 5589 * folio is anon, we always operate on the underlying hugetlb 5590 * file. 5591 */ 5592 address = vma_filebacked_address(iter_vma, pgoff, 1); 5593 unmap_hugepage_range(iter_vma, address, 5594 address + huge_page_size(h), folio, 0); 5595 } 5596 i_mmap_unlock_write(mapping); 5597 } 5598 5599 /* 5600 * hugetlb_wp() should be called with page lock of the original hugepage held. 5601 * Called with hugetlb_fault_mutex_table held and pte_page locked so we 5602 * cannot race with other handlers or page migration. 5603 * Keep the pte_same checks anyway to make transition from the mutex easier. 5604 */ 5605 static vm_fault_t hugetlb_wp(struct vm_fault *vmf) 5606 { 5607 struct vm_area_struct *vma = vmf->vma; 5608 struct mm_struct *mm = vma->vm_mm; 5609 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE; 5610 pte_t pte = huge_ptep_get(mm, vmf->address, vmf->pte); 5611 struct hstate *h = hstate_vma(vma); 5612 struct folio *old_folio; 5613 struct folio *new_folio; 5614 bool cow_from_owner = 0; 5615 vm_fault_t ret = 0; 5616 struct mmu_notifier_range range; 5617 5618 /* 5619 * Never handle CoW for uffd-wp protected pages. It should be only 5620 * handled when the uffd-wp protection is removed. 5621 * 5622 * Note that only the CoW optimization path (in hugetlb_no_page()) 5623 * can trigger this, because hugetlb_fault() will always resolve 5624 * uffd-wp bit first. 5625 */ 5626 if (!unshare && huge_pte_uffd(pte)) 5627 return 0; 5628 5629 /* Let's take out MAP_SHARED mappings first. */ 5630 if (vma->vm_flags & VM_MAYSHARE) { 5631 set_huge_ptep_writable(vma, vmf->address, vmf->pte); 5632 return 0; 5633 } 5634 5635 old_folio = page_folio(pte_page(pte)); 5636 5637 delayacct_wpcopy_start(); 5638 5639 retry_avoidcopy: 5640 /* 5641 * If no-one else is actually using this page, we're the exclusive 5642 * owner and can reuse this page. 5643 * 5644 * Note that we don't rely on the (safer) folio refcount here, because 5645 * copying the hugetlb folio when there are unexpected (temporary) 5646 * folio references could harm simple fork()+exit() users when 5647 * we run out of free hugetlb folios: we would have to kill processes 5648 * in scenarios that used to work. As a side effect, there can still 5649 * be leaks between processes, for example, with FOLL_GET users. 5650 */ 5651 if (folio_mapcount(old_folio) == 1 && folio_test_anon(old_folio)) { 5652 if (!PageAnonExclusive(&old_folio->page)) { 5653 folio_move_anon_rmap(old_folio, vma); 5654 SetPageAnonExclusive(&old_folio->page); 5655 } 5656 if (likely(!unshare)) 5657 set_huge_ptep_maybe_writable(vma, vmf->address, 5658 vmf->pte); 5659 5660 delayacct_wpcopy_end(); 5661 return 0; 5662 } 5663 VM_BUG_ON_PAGE(folio_test_anon(old_folio) && 5664 PageAnonExclusive(&old_folio->page), &old_folio->page); 5665 5666 /* 5667 * If the process that created a MAP_PRIVATE mapping is about to perform 5668 * a COW due to a shared page count, attempt to satisfy the allocation 5669 * without using the existing reserves. 5670 * In order to determine where this is a COW on a MAP_PRIVATE mapping it 5671 * is enough to check whether the old_folio is anonymous. This means that 5672 * the reserve for this address was consumed. If reserves were used, a 5673 * partial faulted mapping at the time of fork() could consume its reserves 5674 * on COW instead of the full address range. 5675 */ 5676 if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) && 5677 folio_test_anon(old_folio)) 5678 cow_from_owner = true; 5679 5680 folio_get(old_folio); 5681 5682 /* 5683 * Drop page table lock as buddy allocator may be called. It will 5684 * be acquired again before returning to the caller, as expected. 5685 */ 5686 spin_unlock(vmf->ptl); 5687 new_folio = alloc_hugetlb_folio(vma, vmf->address, cow_from_owner); 5688 5689 if (IS_ERR(new_folio)) { 5690 /* 5691 * If a process owning a MAP_PRIVATE mapping fails to COW, 5692 * it is due to references held by a child and an insufficient 5693 * huge page pool. To guarantee the original mappers 5694 * reliability, unmap the page from child processes. The child 5695 * may get SIGKILLed if it later faults. 5696 */ 5697 if (cow_from_owner) { 5698 struct address_space *mapping = vma->vm_file->f_mapping; 5699 pgoff_t idx; 5700 u32 hash; 5701 5702 folio_put(old_folio); 5703 /* 5704 * Drop hugetlb_fault_mutex and vma_lock before 5705 * unmapping. unmapping needs to hold vma_lock 5706 * in write mode. Dropping vma_lock in read mode 5707 * here is OK as COW mappings do not interact with 5708 * PMD sharing. 5709 * 5710 * Reacquire both after unmap operation. 5711 */ 5712 idx = vma_hugecache_offset(h, vma, vmf->address); 5713 hash = hugetlb_fault_mutex_hash(mapping, idx); 5714 hugetlb_vma_unlock_read(vma); 5715 mutex_unlock(&hugetlb_fault_mutex_table[hash]); 5716 5717 unmap_ref_private(mm, vma, old_folio, vmf->address); 5718 5719 mutex_lock(&hugetlb_fault_mutex_table[hash]); 5720 hugetlb_vma_lock_read(vma); 5721 spin_lock(vmf->ptl); 5722 vmf->pte = hugetlb_walk(vma, vmf->address, 5723 huge_page_size(h)); 5724 if (likely(vmf->pte && 5725 pte_same(huge_ptep_get(mm, vmf->address, vmf->pte), pte))) 5726 goto retry_avoidcopy; 5727 /* 5728 * race occurs while re-acquiring page table 5729 * lock, and our job is done. 5730 */ 5731 delayacct_wpcopy_end(); 5732 return 0; 5733 } 5734 5735 ret = vmf_error(PTR_ERR(new_folio)); 5736 goto out_release_old; 5737 } 5738 5739 /* 5740 * When the original hugepage is shared one, it does not have 5741 * an anon rmap prepared. 5742 */ 5743 ret = __vmf_anon_prepare(vmf); 5744 if (unlikely(ret)) 5745 goto out_release_all; 5746 5747 if (copy_user_large_folio(new_folio, old_folio, vmf->real_address, vma)) { 5748 ret = VM_FAULT_HWPOISON_LARGE | VM_FAULT_SET_HINDEX(hstate_index(h)); 5749 goto out_release_all; 5750 } 5751 __folio_mark_uptodate(new_folio); 5752 5753 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, vmf->address, 5754 vmf->address + huge_page_size(h)); 5755 mmu_notifier_invalidate_range_start(&range); 5756 5757 /* 5758 * Retake the page table lock to check for racing updates 5759 * before the page tables are altered 5760 */ 5761 spin_lock(vmf->ptl); 5762 vmf->pte = hugetlb_walk(vma, vmf->address, huge_page_size(h)); 5763 if (likely(vmf->pte && pte_same(huge_ptep_get(mm, vmf->address, vmf->pte), pte))) { 5764 pte_t newpte = make_huge_pte(vma, new_folio, !unshare); 5765 5766 /* Break COW or unshare */ 5767 huge_ptep_clear_flush(vma, vmf->address, vmf->pte); 5768 hugetlb_remove_rmap(old_folio); 5769 hugetlb_add_new_anon_rmap(new_folio, vma, vmf->address); 5770 if (huge_pte_uffd(pte)) 5771 newpte = huge_pte_mkuffd(newpte); 5772 set_huge_pte_at(mm, vmf->address, vmf->pte, newpte, 5773 huge_page_size(h)); 5774 folio_set_hugetlb_migratable(new_folio); 5775 /* Make the old page be freed below */ 5776 new_folio = old_folio; 5777 } 5778 spin_unlock(vmf->ptl); 5779 mmu_notifier_invalidate_range_end(&range); 5780 out_release_all: 5781 /* 5782 * No restore in case of successful pagetable update (Break COW or 5783 * unshare) 5784 */ 5785 if (new_folio != old_folio) 5786 restore_reserve_on_error(h, vma, vmf->address, new_folio); 5787 folio_put(new_folio); 5788 out_release_old: 5789 folio_put(old_folio); 5790 5791 spin_lock(vmf->ptl); /* Caller expects lock to be held */ 5792 5793 delayacct_wpcopy_end(); 5794 return ret; 5795 } 5796 5797 /* 5798 * Return whether there is a pagecache page to back given address within VMA. 5799 */ 5800 bool hugetlbfs_pagecache_present(struct hstate *h, 5801 struct vm_area_struct *vma, unsigned long address) 5802 { 5803 struct address_space *mapping = vma->vm_file->f_mapping; 5804 pgoff_t idx = linear_page_index(vma, address); 5805 struct folio *folio; 5806 5807 folio = filemap_get_folio(mapping, idx); 5808 if (IS_ERR(folio)) 5809 return false; 5810 folio_put(folio); 5811 return true; 5812 } 5813 5814 int hugetlb_add_to_page_cache(struct folio *folio, struct address_space *mapping, 5815 pgoff_t idx) 5816 { 5817 struct inode *inode = mapping->host; 5818 struct hstate *h = hstate_inode(inode); 5819 int err; 5820 5821 idx <<= huge_page_order(h); 5822 __folio_set_locked(folio); 5823 err = __filemap_add_folio(mapping, folio, idx, GFP_KERNEL, NULL); 5824 5825 if (unlikely(err)) { 5826 __folio_clear_locked(folio); 5827 return err; 5828 } 5829 folio_clear_hugetlb_restore_reserve(folio); 5830 5831 /* 5832 * mark folio dirty so that it will not be removed from cache/file 5833 * by non-hugetlbfs specific code paths. 5834 */ 5835 folio_mark_dirty(folio); 5836 5837 spin_lock(&inode->i_lock); 5838 inode->i_blocks += blocks_per_huge_page(h); 5839 spin_unlock(&inode->i_lock); 5840 return 0; 5841 } 5842 5843 static inline vm_fault_t hugetlb_handle_userfault(struct vm_fault *vmf, 5844 struct address_space *mapping, 5845 unsigned long reason) 5846 { 5847 u32 hash; 5848 5849 /* 5850 * vma_lock and hugetlb_fault_mutex must be dropped before handling 5851 * userfault. Also mmap_lock could be dropped due to handling 5852 * userfault, any vma operation should be careful from here. 5853 */ 5854 hugetlb_vma_unlock_read(vmf->vma); 5855 hash = hugetlb_fault_mutex_hash(mapping, vmf->pgoff); 5856 mutex_unlock(&hugetlb_fault_mutex_table[hash]); 5857 return handle_userfault(vmf, reason); 5858 } 5859 5860 /* 5861 * Recheck pte with pgtable lock. Returns true if pte didn't change, or 5862 * false if pte changed or is changing. 5863 */ 5864 static bool hugetlb_pte_stable(struct hstate *h, struct mm_struct *mm, unsigned long addr, 5865 pte_t *ptep, pte_t old_pte) 5866 { 5867 spinlock_t *ptl; 5868 bool same; 5869 5870 ptl = huge_pte_lock(h, mm, ptep); 5871 same = pte_same(huge_ptep_get(mm, addr, ptep), old_pte); 5872 spin_unlock(ptl); 5873 5874 return same; 5875 } 5876 5877 static vm_fault_t hugetlb_no_page(struct address_space *mapping, 5878 struct vm_fault *vmf) 5879 { 5880 u32 hash = hugetlb_fault_mutex_hash(mapping, vmf->pgoff); 5881 bool new_folio, new_anon_folio = false; 5882 struct vm_area_struct *vma = vmf->vma; 5883 struct mm_struct *mm = vma->vm_mm; 5884 struct hstate *h = hstate_vma(vma); 5885 vm_fault_t ret = VM_FAULT_SIGBUS; 5886 bool folio_locked = true; 5887 struct folio *folio; 5888 unsigned long size; 5889 pte_t new_pte; 5890 5891 /* 5892 * Currently, we are forced to kill the process in the event the 5893 * original mapper has unmapped pages from the child due to a failed 5894 * COW/unsharing. Warn that such a situation has occurred as it may not 5895 * be obvious. 5896 */ 5897 if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) { 5898 pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n", 5899 current->pid); 5900 goto out; 5901 } 5902 5903 /* 5904 * Use page lock to guard against racing truncation 5905 * before we get page_table_lock. 5906 */ 5907 new_folio = false; 5908 folio = filemap_lock_hugetlb_folio(h, mapping, vmf->pgoff); 5909 if (IS_ERR(folio)) { 5910 size = i_size_read(mapping->host) >> huge_page_shift(h); 5911 if (vmf->pgoff >= size) 5912 goto out; 5913 /* Check for page in userfault range */ 5914 if (userfaultfd_missing(vma)) { 5915 /* 5916 * Since hugetlb_no_page() was examining pte 5917 * without pgtable lock, we need to re-test under 5918 * lock because the pte may not be stable and could 5919 * have changed from under us. Try to detect 5920 * either changed or during-changing ptes and retry 5921 * properly when needed. 5922 * 5923 * Note that userfaultfd is actually fine with 5924 * false positives (e.g. caused by pte changed), 5925 * but not wrong logical events (e.g. caused by 5926 * reading a pte during changing). The latter can 5927 * confuse the userspace, so the strictness is very 5928 * much preferred. E.g., MISSING event should 5929 * never happen on the page after UFFDIO_COPY has 5930 * correctly installed the page and returned. 5931 */ 5932 if (!hugetlb_pte_stable(h, mm, vmf->address, vmf->pte, vmf->orig_pte)) { 5933 ret = 0; 5934 goto out; 5935 } 5936 5937 return hugetlb_handle_userfault(vmf, mapping, 5938 VM_UFFD_MISSING); 5939 } 5940 5941 if (!(vma->vm_flags & VM_MAYSHARE)) { 5942 ret = __vmf_anon_prepare(vmf); 5943 if (unlikely(ret)) 5944 goto out; 5945 } 5946 5947 folio = alloc_hugetlb_folio(vma, vmf->address, false); 5948 if (IS_ERR(folio)) { 5949 /* 5950 * Returning error will result in faulting task being 5951 * sent SIGBUS. The hugetlb fault mutex prevents two 5952 * tasks from racing to fault in the same page which 5953 * could result in false unable to allocate errors. 5954 * Page migration does not take the fault mutex, but 5955 * does a clear then write of pte's under page table 5956 * lock. Page fault code could race with migration, 5957 * notice the clear pte and try to allocate a page 5958 * here. Before returning error, get ptl and make 5959 * sure there really is no pte entry. 5960 */ 5961 if (hugetlb_pte_stable(h, mm, vmf->address, vmf->pte, vmf->orig_pte)) 5962 ret = vmf_error(PTR_ERR(folio)); 5963 else 5964 ret = 0; 5965 goto out; 5966 } 5967 folio_zero_user(folio, vmf->real_address); 5968 __folio_mark_uptodate(folio); 5969 new_folio = true; 5970 5971 if (vma->vm_flags & VM_MAYSHARE) { 5972 int err = hugetlb_add_to_page_cache(folio, mapping, 5973 vmf->pgoff); 5974 if (err) { 5975 /* 5976 * err can't be -EEXIST which implies someone 5977 * else consumed the reservation since hugetlb 5978 * fault mutex is held when add a hugetlb page 5979 * to the page cache. So it's safe to call 5980 * restore_reserve_on_error() here. 5981 */ 5982 restore_reserve_on_error(h, vma, vmf->address, 5983 folio); 5984 folio_put(folio); 5985 ret = VM_FAULT_SIGBUS; 5986 goto out; 5987 } 5988 } else { 5989 new_anon_folio = true; 5990 folio_lock(folio); 5991 } 5992 } else { 5993 /* 5994 * If memory error occurs between mmap() and fault, some process 5995 * don't have hwpoisoned swap entry for errored virtual address. 5996 * So we need to block hugepage fault by PG_hwpoison bit check. 5997 */ 5998 if (unlikely(folio_test_hwpoison(folio))) { 5999 ret = VM_FAULT_HWPOISON_LARGE | 6000 VM_FAULT_SET_HINDEX(hstate_index(h)); 6001 goto backout_unlocked; 6002 } 6003 6004 /* Check for page in userfault range. */ 6005 if (userfaultfd_minor(vma)) { 6006 folio_unlock(folio); 6007 folio_put(folio); 6008 /* See comment in userfaultfd_missing() block above */ 6009 if (!hugetlb_pte_stable(h, mm, vmf->address, vmf->pte, vmf->orig_pte)) { 6010 ret = 0; 6011 goto out; 6012 } 6013 return hugetlb_handle_userfault(vmf, mapping, 6014 VM_UFFD_MINOR); 6015 } 6016 } 6017 6018 /* 6019 * If we are going to COW a private mapping later, we examine the 6020 * pending reservations for this page now. This will ensure that 6021 * any allocations necessary to record that reservation occur outside 6022 * the spinlock. 6023 */ 6024 if ((vmf->flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) { 6025 if (vma_needs_reservation(h, vma, vmf->address) < 0) { 6026 ret = VM_FAULT_OOM; 6027 goto backout_unlocked; 6028 } 6029 /* Just decrements count, does not deallocate */ 6030 vma_end_reservation(h, vma, vmf->address); 6031 } 6032 6033 vmf->ptl = huge_pte_lock(h, mm, vmf->pte); 6034 ret = 0; 6035 /* If pte changed from under us, retry */ 6036 if (!pte_same(huge_ptep_get(mm, vmf->address, vmf->pte), vmf->orig_pte)) 6037 goto backout; 6038 6039 if (new_anon_folio) 6040 hugetlb_add_new_anon_rmap(folio, vma, vmf->address); 6041 else 6042 hugetlb_add_file_rmap(folio); 6043 new_pte = make_huge_pte(vma, folio, vma->vm_flags & VM_SHARED); 6044 /* 6045 * If this pte was previously wr-protected, keep it wr-protected even 6046 * if populated. 6047 * 6048 * TODO: fix all cases where uffd-wp markers remain in VMAs that are no 6049 * longer registered with uffd. 6050 */ 6051 if (unlikely(userfaultfd_wp(vma) && pte_is_uffd_wp_marker(vmf->orig_pte))) 6052 new_pte = huge_pte_mkuffd(new_pte); 6053 set_huge_pte_at(mm, vmf->address, vmf->pte, new_pte, huge_page_size(h)); 6054 6055 hugetlb_count_add(pages_per_huge_page(h), mm); 6056 if ((vmf->flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) { 6057 /* 6058 * No need to keep file folios locked. See comment in 6059 * hugetlb_fault(). 6060 */ 6061 if (!new_anon_folio) { 6062 folio_locked = false; 6063 folio_unlock(folio); 6064 } 6065 /* Optimization, do the COW without a second fault */ 6066 ret = hugetlb_wp(vmf); 6067 } 6068 6069 /* 6070 * Only set hugetlb_migratable in newly allocated pages. Existing pages 6071 * found in the pagecache may not have hugetlb_migratable if they have 6072 * been isolated for migration. 6073 */ 6074 if (new_folio) 6075 folio_set_hugetlb_migratable(folio); 6076 6077 if (folio_locked) 6078 folio_unlock(folio); 6079 6080 /* 6081 * Hold the PTL until we're done with the folio: the page table owns the 6082 * folio reference now. 6083 */ 6084 spin_unlock(vmf->ptl); 6085 out: 6086 hugetlb_vma_unlock_read(vma); 6087 6088 /* 6089 * We must check to release the per-VMA lock. __vmf_anon_prepare() is 6090 * the only way ret can be set to VM_FAULT_RETRY. 6091 */ 6092 if (unlikely(ret & VM_FAULT_RETRY)) 6093 vma_end_read(vma); 6094 6095 mutex_unlock(&hugetlb_fault_mutex_table[hash]); 6096 return ret; 6097 6098 backout: 6099 spin_unlock(vmf->ptl); 6100 backout_unlocked: 6101 /* We only need to restore reservations for private mappings */ 6102 if (new_anon_folio) 6103 restore_reserve_on_error(h, vma, vmf->address, folio); 6104 6105 folio_unlock(folio); 6106 folio_put(folio); 6107 goto out; 6108 } 6109 6110 #ifdef CONFIG_SMP 6111 u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx) 6112 { 6113 unsigned long key[2]; 6114 u32 hash; 6115 6116 key[0] = (unsigned long) mapping; 6117 key[1] = idx; 6118 6119 hash = jhash2((u32 *)&key, sizeof(key)/(sizeof(u32)), 0); 6120 6121 return hash & (num_fault_mutexes - 1); 6122 } 6123 #else 6124 /* 6125 * For uniprocessor systems we always use a single mutex, so just 6126 * return 0 and avoid the hashing overhead. 6127 */ 6128 u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx) 6129 { 6130 return 0; 6131 } 6132 #endif 6133 6134 vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma, 6135 unsigned long address, unsigned int flags) 6136 { 6137 vm_fault_t ret; 6138 u32 hash; 6139 struct folio *folio = NULL; 6140 struct hstate *h = hstate_vma(vma); 6141 struct address_space *mapping; 6142 bool need_wait_lock = false; 6143 struct vm_fault vmf = { 6144 .vma = vma, 6145 .address = address & huge_page_mask(h), 6146 .real_address = address, 6147 .flags = flags, 6148 .pgoff = vma_hugecache_offset(h, vma, 6149 address & huge_page_mask(h)), 6150 /* TODO: Track hugetlb faults using vm_fault */ 6151 6152 /* 6153 * Some fields may not be initialized, be careful as it may 6154 * be hard to debug if called functions make assumptions 6155 */ 6156 }; 6157 6158 /* 6159 * Serialize hugepage allocation and instantiation, so that we don't 6160 * get spurious allocation failures if two CPUs race to instantiate 6161 * the same page in the page cache. 6162 */ 6163 mapping = vma->vm_file->f_mapping; 6164 hash = hugetlb_fault_mutex_hash(mapping, vmf.pgoff); 6165 mutex_lock(&hugetlb_fault_mutex_table[hash]); 6166 6167 /* 6168 * Acquire vma lock before calling huge_pte_alloc and hold 6169 * until finished with vmf.pte. This prevents huge_pmd_unshare from 6170 * being called elsewhere and making the vmf.pte no longer valid. 6171 */ 6172 hugetlb_vma_lock_read(vma); 6173 vmf.pte = huge_pte_alloc(mm, vma, vmf.address, huge_page_size(h)); 6174 if (!vmf.pte) { 6175 hugetlb_vma_unlock_read(vma); 6176 mutex_unlock(&hugetlb_fault_mutex_table[hash]); 6177 return VM_FAULT_OOM; 6178 } 6179 6180 vmf.orig_pte = huge_ptep_get(mm, vmf.address, vmf.pte); 6181 if (huge_pte_none(vmf.orig_pte)) 6182 /* 6183 * hugetlb_no_page will drop vma lock and hugetlb fault 6184 * mutex internally, which make us return immediately. 6185 */ 6186 return hugetlb_no_page(mapping, &vmf); 6187 6188 if (pte_is_marker(vmf.orig_pte)) { 6189 const pte_marker marker = 6190 softleaf_to_marker(softleaf_from_pte(vmf.orig_pte)); 6191 6192 if (marker & PTE_MARKER_POISONED) { 6193 ret = VM_FAULT_HWPOISON_LARGE | 6194 VM_FAULT_SET_HINDEX(hstate_index(h)); 6195 goto out_mutex; 6196 } else if (WARN_ON_ONCE(marker & PTE_MARKER_GUARD)) { 6197 /* This isn't supported in hugetlb. */ 6198 ret = VM_FAULT_SIGSEGV; 6199 goto out_mutex; 6200 } 6201 6202 return hugetlb_no_page(mapping, &vmf); 6203 } 6204 6205 ret = 0; 6206 6207 /* Not present, either a migration or a hwpoisoned entry */ 6208 if (!pte_present(vmf.orig_pte) && !huge_pte_none(vmf.orig_pte)) { 6209 const softleaf_t softleaf = softleaf_from_pte(vmf.orig_pte); 6210 6211 if (softleaf_is_migration(softleaf)) { 6212 /* 6213 * Release the hugetlb fault lock now, but retain 6214 * the vma lock, because it is needed to guard the 6215 * huge_pte_lockptr() later in 6216 * migration_entry_wait_huge(). The vma lock will 6217 * be released there. 6218 */ 6219 mutex_unlock(&hugetlb_fault_mutex_table[hash]); 6220 migration_entry_wait_huge(vma, vmf.address, vmf.pte); 6221 return 0; 6222 } 6223 if (softleaf_is_hwpoison(softleaf)) { 6224 ret = VM_FAULT_HWPOISON_LARGE | 6225 VM_FAULT_SET_HINDEX(hstate_index(h)); 6226 } 6227 6228 goto out_mutex; 6229 } 6230 6231 /* 6232 * Protnone hugetlb PTEs with the uffd bit are used by 6233 * userfaultfd RWP for access tracking. Plain PROT_NONE (without the 6234 * marker) is not an RWP fault and is not expected on hugetlb (no 6235 * NUMA hinting), so let normal hugetlb fault handling proceed. 6236 */ 6237 if (pte_protnone(vmf.orig_pte) && vma_is_accessible(vma) && 6238 huge_pte_uffd(vmf.orig_pte)) { 6239 spinlock_t *ptl; 6240 pte_t pte; 6241 6242 /* Sync: drop hugetlb locks before blocking in handle_userfault() */ 6243 if (userfaultfd_rwp(vma) && !userfaultfd_rwp_async(vma)) 6244 return hugetlb_handle_userfault(&vmf, mapping, VM_UFFD_RWP); 6245 6246 ptl = huge_pte_lock(h, mm, vmf.pte); 6247 pte = huge_ptep_get(mm, vmf.address, vmf.pte); 6248 /* 6249 * TODO: fix all cases where uffd PTE bits remain in VMAs that 6250 * are no longer registered with uffd. 6251 */ 6252 if (pte_protnone(pte) && huge_pte_uffd(pte)) { 6253 unsigned int shift = huge_page_shift(h); 6254 6255 pte = huge_pte_modify(pte, vma->vm_page_prot); 6256 pte = arch_make_huge_pte(pte, shift, vma->vm_flags); 6257 /* huge_pte_modify() preserves _PAGE_UFFD; drop it on resolution */ 6258 pte = huge_pte_clear_uffd(pte); 6259 pte = pte_mkyoung(pte); 6260 /* 6261 * Unlike do_uffd_rwp(), do not upgrade to writable 6262 * here. Hugetlb lacks a can_change_huge_pte_writable() 6263 * equivalent, so a write access will take a separate 6264 * COW fault — acceptable for the rare private hugetlb 6265 * case. 6266 */ 6267 set_huge_pte_at(mm, vmf.address, vmf.pte, pte, 6268 huge_page_size(h)); 6269 update_mmu_cache(vma, vmf.address, vmf.pte); 6270 } 6271 spin_unlock(ptl); 6272 ret = 0; 6273 goto out_mutex; 6274 } 6275 6276 /* 6277 * If we are going to COW/unshare the mapping later, we examine the 6278 * pending reservations for this page now. This will ensure that any 6279 * allocations necessary to record that reservation occur outside the 6280 * spinlock. 6281 */ 6282 if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) && 6283 !(vma->vm_flags & VM_MAYSHARE) && !huge_pte_write(vmf.orig_pte)) { 6284 if (vma_needs_reservation(h, vma, vmf.address) < 0) { 6285 ret = VM_FAULT_OOM; 6286 goto out_mutex; 6287 } 6288 /* Just decrements count, does not deallocate */ 6289 vma_end_reservation(h, vma, vmf.address); 6290 } 6291 6292 vmf.ptl = huge_pte_lock(h, mm, vmf.pte); 6293 6294 /* Check for a racing update before calling hugetlb_wp() */ 6295 if (unlikely(!pte_same(vmf.orig_pte, huge_ptep_get(mm, vmf.address, vmf.pte)))) 6296 goto out_ptl; 6297 6298 /* Handle userfault-wp first, before trying to lock more pages */ 6299 if (huge_pte_uffd(huge_ptep_get(mm, vmf.address, vmf.pte)) && 6300 (flags & FAULT_FLAG_WRITE) && !huge_pte_write(vmf.orig_pte)) { 6301 if (userfaultfd_wp(vma) && !userfaultfd_wp_async(vma)) { 6302 spin_unlock(vmf.ptl); 6303 hugetlb_vma_unlock_read(vma); 6304 mutex_unlock(&hugetlb_fault_mutex_table[hash]); 6305 return handle_userfault(&vmf, VM_UFFD_WP); 6306 } 6307 6308 /* 6309 * TODO: fix all cases where uffd PTE bits remain in VMAs that 6310 * are no longer registered with uffd. 6311 */ 6312 vmf.orig_pte = huge_pte_clear_uffd(vmf.orig_pte); 6313 set_huge_pte_at(mm, vmf.address, vmf.pte, vmf.orig_pte, 6314 huge_page_size(hstate_vma(vma))); 6315 /* Fallthrough to CoW */ 6316 } 6317 6318 if (flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) { 6319 if (!huge_pte_write(vmf.orig_pte)) { 6320 /* 6321 * Anonymous folios need to be lock since hugetlb_wp() 6322 * checks whether we can re-use the folio exclusively 6323 * for us in case we are the only user of it. 6324 */ 6325 folio = page_folio(pte_page(vmf.orig_pte)); 6326 if (folio_test_anon(folio) && !folio_trylock(folio)) { 6327 need_wait_lock = true; 6328 goto out_ptl; 6329 } 6330 folio_get(folio); 6331 ret = hugetlb_wp(&vmf); 6332 if (folio_test_anon(folio)) 6333 folio_unlock(folio); 6334 folio_put(folio); 6335 goto out_ptl; 6336 } else if (likely(flags & FAULT_FLAG_WRITE)) { 6337 vmf.orig_pte = huge_pte_mkdirty(vmf.orig_pte); 6338 } 6339 } 6340 vmf.orig_pte = pte_mkyoung(vmf.orig_pte); 6341 if (huge_ptep_set_access_flags(vma, vmf.address, vmf.pte, vmf.orig_pte, 6342 flags & FAULT_FLAG_WRITE)) 6343 update_mmu_cache(vma, vmf.address, vmf.pte); 6344 out_ptl: 6345 spin_unlock(vmf.ptl); 6346 out_mutex: 6347 hugetlb_vma_unlock_read(vma); 6348 6349 /* 6350 * We must check to release the per-VMA lock. __vmf_anon_prepare() in 6351 * hugetlb_wp() is the only way ret can be set to VM_FAULT_RETRY. 6352 */ 6353 if (unlikely(ret & VM_FAULT_RETRY)) 6354 vma_end_read(vma); 6355 6356 mutex_unlock(&hugetlb_fault_mutex_table[hash]); 6357 /* 6358 * hugetlb_wp drops all the locks, but the folio lock, before trying to 6359 * unmap the folio from other processes. During that window, if another 6360 * process mapping that folio faults in, it will take the mutex and then 6361 * it will wait on folio_lock, causing an ABBA deadlock. 6362 * Use trylock instead and bail out if we fail. 6363 * 6364 * Ideally, we should hold a refcount on the folio we wait for, but we do 6365 * not want to use the folio after it becomes unlocked, but rather just 6366 * wait for it to become unlocked, so hopefully next fault successes on 6367 * the trylock. 6368 */ 6369 if (need_wait_lock) 6370 folio_wait_locked(folio); 6371 return ret; 6372 } 6373 6374 #ifdef CONFIG_USERFAULTFD 6375 /* 6376 * Can probably be eliminated, but still used by hugetlb_mfill_atomic_pte(). 6377 */ 6378 static struct folio *alloc_hugetlb_folio_vma(struct hstate *h, 6379 struct vm_area_struct *vma, unsigned long address) 6380 { 6381 struct mempolicy *mpol; 6382 nodemask_t *nodemask; 6383 struct folio *folio; 6384 gfp_t gfp_mask; 6385 int node; 6386 6387 gfp_mask = htlb_alloc_mask(h); 6388 node = huge_node(vma, address, gfp_mask, &mpol, &nodemask); 6389 /* 6390 * This is used to allocate a temporary hugetlb to hold the copied 6391 * content, which will then be copied again to the final hugetlb 6392 * consuming a reservation. Set the alloc_fallback to false to indicate 6393 * that breaking the per-node hugetlb pool is not allowed in this case. 6394 */ 6395 folio = alloc_hugetlb_folio_nodemask(h, node, nodemask, gfp_mask, false); 6396 mpol_cond_put(mpol); 6397 6398 return folio; 6399 } 6400 6401 /* 6402 * Used by userfaultfd UFFDIO_* ioctls. Based on userfaultfd's mfill_atomic_pte 6403 * with modifications for hugetlb pages. 6404 */ 6405 int hugetlb_mfill_atomic_pte(pte_t *dst_pte, 6406 struct vm_area_struct *dst_vma, 6407 unsigned long dst_addr, 6408 unsigned long src_addr, 6409 uffd_flags_t flags, 6410 struct folio **foliop) 6411 { 6412 struct mm_struct *dst_mm = dst_vma->vm_mm; 6413 bool is_continue = uffd_flags_mode_is(flags, MFILL_ATOMIC_CONTINUE); 6414 bool wp_enabled = (flags & MFILL_ATOMIC_WP); 6415 struct hstate *h = hstate_vma(dst_vma); 6416 struct address_space *mapping = dst_vma->vm_file->f_mapping; 6417 pgoff_t idx = vma_hugecache_offset(h, dst_vma, dst_addr); 6418 unsigned long size = huge_page_size(h); 6419 int vm_shared = dst_vma->vm_flags & VM_SHARED; 6420 pte_t _dst_pte; 6421 spinlock_t *ptl; 6422 int ret = -ENOMEM; 6423 struct folio *folio; 6424 bool folio_in_pagecache = false; 6425 pte_t dst_ptep; 6426 6427 if (uffd_flags_mode_is(flags, MFILL_ATOMIC_POISON)) { 6428 ptl = huge_pte_lock(h, dst_mm, dst_pte); 6429 6430 /* Don't overwrite any existing PTEs (even markers) */ 6431 if (!huge_pte_none(huge_ptep_get(dst_mm, dst_addr, dst_pte))) { 6432 spin_unlock(ptl); 6433 return -EEXIST; 6434 } 6435 6436 VM_WARN_ON_ONCE(size == PMD_SIZE && hugetlb_pmd_shared(dst_pte)); 6437 _dst_pte = make_pte_marker(PTE_MARKER_POISONED); 6438 set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte, size); 6439 6440 /* No need to invalidate - it was non-present before */ 6441 update_mmu_cache(dst_vma, dst_addr, dst_pte); 6442 6443 spin_unlock(ptl); 6444 return 0; 6445 } 6446 6447 if (is_continue) { 6448 ret = -EFAULT; 6449 folio = filemap_lock_hugetlb_folio(h, mapping, idx); 6450 if (IS_ERR(folio)) 6451 goto out; 6452 folio_in_pagecache = true; 6453 } else if (!*foliop) { 6454 /* If a folio already exists, then it's UFFDIO_COPY for 6455 * a non-missing case. Return -EEXIST. 6456 */ 6457 if (vm_shared && 6458 hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) { 6459 ret = -EEXIST; 6460 goto out; 6461 } 6462 6463 folio = alloc_hugetlb_folio(dst_vma, dst_addr, false); 6464 if (IS_ERR(folio)) { 6465 pte_t *actual_pte = hugetlb_walk(dst_vma, dst_addr, PMD_SIZE); 6466 if (actual_pte) { 6467 ret = -EEXIST; 6468 goto out; 6469 } 6470 ret = -ENOMEM; 6471 goto out; 6472 } 6473 6474 ret = copy_folio_from_user(folio, (const void __user *) src_addr, 6475 false); 6476 6477 /* fallback to copy_from_user outside mmap_lock */ 6478 if (unlikely(ret)) { 6479 ret = -ENOENT; 6480 /* Free the allocated folio which may have 6481 * consumed a reservation. 6482 */ 6483 restore_reserve_on_error(h, dst_vma, dst_addr, folio); 6484 folio_put(folio); 6485 6486 /* Allocate a temporary folio to hold the copied 6487 * contents. 6488 */ 6489 folio = alloc_hugetlb_folio_vma(h, dst_vma, dst_addr); 6490 if (!folio) { 6491 ret = -ENOMEM; 6492 goto out; 6493 } 6494 *foliop = folio; 6495 /* Set the outparam foliop and return to the caller to 6496 * copy the contents outside the lock. Don't free the 6497 * folio. 6498 */ 6499 goto out; 6500 } 6501 } else { 6502 if (vm_shared && 6503 hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) { 6504 folio_put(*foliop); 6505 ret = -EEXIST; 6506 *foliop = NULL; 6507 goto out; 6508 } 6509 6510 folio = alloc_hugetlb_folio(dst_vma, dst_addr, false); 6511 if (IS_ERR(folio)) { 6512 folio_put(*foliop); 6513 ret = -ENOMEM; 6514 *foliop = NULL; 6515 goto out; 6516 } 6517 ret = copy_user_large_folio(folio, *foliop, dst_addr, dst_vma); 6518 folio_put(*foliop); 6519 *foliop = NULL; 6520 if (ret) { 6521 restore_reserve_on_error(h, dst_vma, dst_addr, folio); 6522 folio_put(folio); 6523 goto out; 6524 } 6525 } 6526 6527 /* 6528 * If we just allocated a new page, we need a memory barrier to ensure 6529 * that preceding stores to the page become visible before the 6530 * set_pte_at() write. The memory barrier inside __folio_mark_uptodate 6531 * is what we need. 6532 * 6533 * In the case where we have not allocated a new page (is_continue), 6534 * the page must already be uptodate. UFFDIO_CONTINUE already includes 6535 * an earlier smp_wmb() to ensure that prior stores will be visible 6536 * before the set_pte_at() write. 6537 */ 6538 if (!is_continue) 6539 __folio_mark_uptodate(folio); 6540 else 6541 WARN_ON_ONCE(!folio_test_uptodate(folio)); 6542 6543 /* Add shared, newly allocated pages to the page cache. */ 6544 if (vm_shared && !is_continue) { 6545 ret = -EFAULT; 6546 if (idx >= (i_size_read(mapping->host) >> huge_page_shift(h))) 6547 goto out_release_nounlock; 6548 6549 /* 6550 * Serialization between remove_inode_hugepages() and 6551 * hugetlb_add_to_page_cache() below happens through the 6552 * hugetlb_fault_mutex_table that here must be hold by 6553 * the caller. 6554 */ 6555 ret = hugetlb_add_to_page_cache(folio, mapping, idx); 6556 if (ret) 6557 goto out_release_nounlock; 6558 folio_in_pagecache = true; 6559 } 6560 6561 ptl = huge_pte_lock(h, dst_mm, dst_pte); 6562 6563 ret = -EIO; 6564 if (folio_test_hwpoison(folio)) 6565 goto out_release_unlock; 6566 6567 ret = -EEXIST; 6568 6569 dst_ptep = huge_ptep_get(dst_mm, dst_addr, dst_pte); 6570 /* 6571 * See comment about UFFD marker overwriting in 6572 * mfill_atomic_install_pte(). 6573 */ 6574 if (!huge_pte_none(dst_ptep) && !pte_is_uffd_marker(dst_ptep)) 6575 goto out_release_unlock; 6576 6577 if (folio_in_pagecache) 6578 hugetlb_add_file_rmap(folio); 6579 else 6580 hugetlb_add_new_anon_rmap(folio, dst_vma, dst_addr); 6581 6582 /* 6583 * For either: (1) CONTINUE on a non-shared VMA, or (2) UFFDIO_COPY 6584 * with wp flag set, don't set pte write bit. 6585 */ 6586 _dst_pte = make_huge_pte(dst_vma, folio, 6587 !wp_enabled && !(is_continue && !vm_shared)); 6588 /* 6589 * Always mark UFFDIO_COPY page dirty; note that this may not be 6590 * extremely important for hugetlbfs for now since swapping is not 6591 * supported, but we should still be clear in that this page cannot be 6592 * thrown away at will, even if write bit not set. 6593 */ 6594 _dst_pte = huge_pte_mkdirty(_dst_pte); 6595 _dst_pte = pte_mkyoung(_dst_pte); 6596 6597 if (wp_enabled) 6598 _dst_pte = huge_pte_mkuffd(_dst_pte); 6599 6600 set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte, size); 6601 6602 hugetlb_count_add(pages_per_huge_page(h), dst_mm); 6603 6604 /* No need to invalidate - it was non-present before */ 6605 update_mmu_cache(dst_vma, dst_addr, dst_pte); 6606 6607 if (!is_continue) 6608 folio_set_hugetlb_migratable(folio); 6609 if (vm_shared || is_continue) 6610 folio_unlock(folio); 6611 6612 /* 6613 * Hold the PTL until we're done with the folio: the page table owns the 6614 * folio reference now. 6615 */ 6616 spin_unlock(ptl); 6617 ret = 0; 6618 out: 6619 return ret; 6620 out_release_unlock: 6621 spin_unlock(ptl); 6622 if (vm_shared || is_continue) 6623 folio_unlock(folio); 6624 out_release_nounlock: 6625 if (!folio_in_pagecache) 6626 restore_reserve_on_error(h, dst_vma, dst_addr, folio); 6627 folio_put(folio); 6628 goto out; 6629 } 6630 #endif /* CONFIG_USERFAULTFD */ 6631 6632 long hugetlb_change_protection(struct vm_area_struct *vma, 6633 unsigned long address, unsigned long end, 6634 pgprot_t newprot, unsigned long cp_flags) 6635 { 6636 struct mm_struct *mm = vma->vm_mm; 6637 unsigned long start = address; 6638 pte_t *ptep; 6639 pte_t pte; 6640 struct hstate *h = hstate_vma(vma); 6641 long pages = 0, psize = huge_page_size(h); 6642 struct mmu_notifier_range range; 6643 unsigned long last_addr_mask; 6644 bool uffd_wp = cp_flags & MM_CP_UFFD_WP; 6645 bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE; 6646 bool uffd_rwp = cp_flags & MM_CP_UFFD_RWP; 6647 bool uffd_rwp_resolve = cp_flags & MM_CP_UFFD_RWP_RESOLVE; 6648 struct mmu_gather tlb; 6649 6650 /* 6651 * In the case of shared PMDs, the area to flush could be beyond 6652 * start/end. Set range.start/range.end to cover the maximum possible 6653 * range if PMD sharing is possible. 6654 */ 6655 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_VMA, 6656 0, mm, start, end); 6657 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end); 6658 6659 BUG_ON(address >= end); 6660 flush_cache_range(vma, range.start, range.end); 6661 tlb_gather_mmu_vma(&tlb, vma); 6662 6663 mmu_notifier_invalidate_range_start(&range); 6664 hugetlb_vma_lock_write(vma); 6665 i_mmap_lock_write(vma->vm_file->f_mapping); 6666 last_addr_mask = hugetlb_mask_last_page(h); 6667 for (; address < end; address += psize) { 6668 softleaf_t entry; 6669 spinlock_t *ptl; 6670 6671 ptep = hugetlb_walk(vma, address, psize); 6672 if (!ptep) { 6673 /* 6674 * uffd_wp installs a pte marker on the unpopulated 6675 * entry; uffd_rwp does not install markers so the 6676 * allocation is unnecessary for it. 6677 */ 6678 if (!uffd_wp) { 6679 address |= last_addr_mask; 6680 continue; 6681 } 6682 /* 6683 * Userfaultfd wr-protect requires pgtable 6684 * pre-allocations to install pte markers. 6685 */ 6686 ptep = huge_pte_alloc(mm, vma, address, psize); 6687 if (!ptep) { 6688 pages = -ENOMEM; 6689 break; 6690 } 6691 } 6692 ptl = huge_pte_lock(h, mm, ptep); 6693 if (huge_pmd_unshare(&tlb, vma, address, ptep)) { 6694 /* 6695 * When uffd-wp is enabled on the vma, unshare 6696 * shouldn't happen at all. Warn about it if it 6697 * happened due to some reason. 6698 */ 6699 WARN_ON_ONCE(uffd_wp || uffd_wp_resolve || 6700 uffd_rwp || uffd_rwp_resolve); 6701 pages++; 6702 spin_unlock(ptl); 6703 address |= last_addr_mask; 6704 continue; 6705 } 6706 pte = huge_ptep_get(mm, address, ptep); 6707 if (huge_pte_none(pte)) { 6708 if (unlikely(uffd_wp)) 6709 /* Safe to modify directly (none->non-present). */ 6710 set_huge_pte_at(mm, address, ptep, 6711 make_pte_marker(PTE_MARKER_UFFD_WP), 6712 psize); 6713 goto next; 6714 } 6715 6716 entry = softleaf_from_pte(pte); 6717 if (unlikely(softleaf_is_hwpoison(entry))) { 6718 /* Nothing to do. */ 6719 } else if (unlikely(softleaf_is_migration(entry))) { 6720 struct folio *folio = softleaf_to_folio(entry); 6721 pte_t newpte = pte; 6722 6723 if (softleaf_is_migration_write(entry)) { 6724 if (folio_test_anon(folio)) 6725 entry = make_readable_exclusive_migration_entry( 6726 swp_offset(entry)); 6727 else 6728 entry = make_readable_migration_entry( 6729 swp_offset(entry)); 6730 newpte = swp_entry_to_pte(entry); 6731 pages++; 6732 } 6733 6734 if (uffd_wp || uffd_rwp) 6735 newpte = pte_swp_mkuffd(newpte); 6736 else if (uffd_wp_resolve || uffd_rwp_resolve) 6737 newpte = pte_swp_clear_uffd(newpte); 6738 if (!pte_same(pte, newpte)) 6739 set_huge_pte_at(mm, address, ptep, newpte, psize); 6740 } else if (unlikely(pte_is_marker(pte))) { 6741 /* 6742 * Do nothing on a poison marker; page is 6743 * corrupted, permissions do not apply. Here 6744 * pte_marker_uffd_wp()==true implies !poison 6745 * because they're mutual exclusive. 6746 */ 6747 if (pte_is_uffd_wp_marker(pte) && 6748 (uffd_wp_resolve || uffd_rwp_resolve)) 6749 /* Safe to modify directly (non-present->none). */ 6750 huge_pte_clear(mm, address, ptep, psize); 6751 } else { 6752 pte_t old_pte; 6753 unsigned int shift = huge_page_shift(hstate_vma(vma)); 6754 6755 /* Already protnone with uffd bit set? Nothing to do. */ 6756 if (uffd_rwp && pte_protnone(pte) && huge_pte_uffd(pte)) 6757 goto next; 6758 6759 old_pte = huge_ptep_modify_prot_start(vma, address, ptep); 6760 pte = huge_pte_modify(old_pte, newprot); 6761 pte = arch_make_huge_pte(pte, shift, vma->vm_flags); 6762 if (uffd_wp || uffd_rwp) 6763 pte = huge_pte_mkuffd(pte); 6764 else if (uffd_wp_resolve || uffd_rwp_resolve) 6765 pte = huge_pte_clear_uffd(pte); 6766 6767 /* Preserve RWP protection across mprotect() */ 6768 if (userfaultfd_rwp(vma) && huge_pte_uffd(pte)) { 6769 pte = huge_pte_modify(pte, PAGE_NONE); 6770 pte = arch_make_huge_pte(pte, shift, vma->vm_flags); 6771 } 6772 6773 huge_ptep_modify_prot_commit(vma, address, ptep, old_pte, pte); 6774 pages++; 6775 tlb_remove_huge_tlb_entry(h, &tlb, ptep, address); 6776 } 6777 6778 next: 6779 spin_unlock(ptl); 6780 cond_resched(); 6781 } 6782 6783 tlb_flush_mmu_tlbonly(&tlb); 6784 huge_pmd_unshare_flush(&tlb, vma); 6785 /* 6786 * No need to call mmu_notifier_arch_invalidate_secondary_tlbs() we are 6787 * downgrading page table protection not changing it to point to a new 6788 * page. 6789 * 6790 * See Documentation/mm/mmu_notifier.rst 6791 */ 6792 i_mmap_unlock_write(vma->vm_file->f_mapping); 6793 hugetlb_vma_unlock_write(vma); 6794 mmu_notifier_invalidate_range_end(&range); 6795 tlb_finish_mmu(&tlb); 6796 6797 return pages > 0 ? (pages << h->order) : pages; 6798 } 6799 6800 /* 6801 * Update the reservation map for the range [from, to]. 6802 * 6803 * Returns the number of entries that would be added to the reservation map 6804 * associated with the range [from, to]. This number is greater or equal to 6805 * zero. -EINVAL or -ENOMEM is returned in case of any errors. 6806 */ 6807 6808 long hugetlb_reserve_pages(struct inode *inode, 6809 long from, long to, 6810 struct vm_area_struct *vma, 6811 vma_flags_t vma_flags) 6812 { 6813 long chg = -1, add = -1, spool_resv, gbl_resv; 6814 struct hstate *h = hstate_inode(inode); 6815 struct hugepage_subpool *spool = subpool_inode(inode); 6816 struct resv_map *resv_map; 6817 struct hugetlb_cgroup *h_cg = NULL; 6818 long gbl_reserve, regions_needed = 0; 6819 int err; 6820 6821 /* This should never happen */ 6822 if (from > to) { 6823 VM_WARN(1, "%s called with a negative range\n", __func__); 6824 return -EINVAL; 6825 } 6826 6827 /* 6828 * vma specific semaphore used for pmd sharing and fault/truncation 6829 * synchronization 6830 */ 6831 hugetlb_vma_lock_alloc(vma); 6832 6833 /* 6834 * Only apply hugepage reservation if asked. At fault time, an 6835 * attempt will be made for VM_NORESERVE to allocate a page 6836 * without using reserves 6837 */ 6838 if (vma_flags_test(&vma_flags, VMA_NORESERVE_BIT)) 6839 return 0; 6840 6841 /* 6842 * Shared mappings base their reservation on the number of pages that 6843 * are already allocated on behalf of the file. Private mappings need 6844 * to reserve the full area even if read-only as mprotect() may be 6845 * called to make the mapping read-write. Assume !vma is a shm mapping 6846 */ 6847 if (!vma || vma_test(vma, VMA_MAYSHARE_BIT)) { 6848 /* 6849 * resv_map can not be NULL as hugetlb_reserve_pages is only 6850 * called for inodes for which resv_maps were created (see 6851 * hugetlbfs_get_inode). 6852 */ 6853 resv_map = inode_resv_map(inode); 6854 6855 chg = region_chg(resv_map, from, to, ®ions_needed); 6856 } else { 6857 /* Private mapping. */ 6858 resv_map = resv_map_alloc(); 6859 if (!resv_map) { 6860 err = -ENOMEM; 6861 goto out_err; 6862 } 6863 6864 chg = to - from; 6865 6866 set_vma_resv_map(vma, resv_map); 6867 set_vma_resv_flags(vma, HPAGE_RESV_OWNER); 6868 } 6869 6870 if (chg < 0) { 6871 /* region_chg() above can return -ENOMEM */ 6872 err = (chg == -ENOMEM) ? -ENOMEM : -EINVAL; 6873 goto out_err; 6874 } 6875 6876 err = hugetlb_cgroup_charge_cgroup_rsvd(hstate_index(h), 6877 chg * pages_per_huge_page(h), &h_cg); 6878 if (err < 0) 6879 goto out_err; 6880 6881 if (vma && !vma_test(vma, VMA_MAYSHARE_BIT) && h_cg) { 6882 /* For private mappings, the hugetlb_cgroup uncharge info hangs 6883 * of the resv_map. 6884 */ 6885 resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, h_cg, h); 6886 } 6887 6888 /* 6889 * There must be enough pages in the subpool for the mapping. If 6890 * the subpool has a minimum size, there may be some global 6891 * reservations already in place (gbl_reserve). 6892 */ 6893 gbl_reserve = hugepage_subpool_get_pages(spool, chg); 6894 if (gbl_reserve < 0) { 6895 err = gbl_reserve; 6896 goto out_uncharge_cgroup; 6897 } 6898 6899 /* 6900 * Check enough hugepages are available for the reservation. 6901 * Hand the pages back to the subpool if there are not 6902 */ 6903 err = hugetlb_acct_memory(h, gbl_reserve); 6904 if (err < 0) 6905 goto out_put_pages; 6906 6907 /* 6908 * Account for the reservations made. Shared mappings record regions 6909 * that have reservations as they are shared by multiple VMAs. 6910 * When the last VMA disappears, the region map says how much 6911 * the reservation was and the page cache tells how much of 6912 * the reservation was consumed. Private mappings are per-VMA and 6913 * only the consumed reservations are tracked. When the VMA 6914 * disappears, the original reservation is the VMA size and the 6915 * consumed reservations are stored in the map. Hence, nothing 6916 * else has to be done for private mappings here 6917 */ 6918 if (!vma || vma_test(vma, VMA_MAYSHARE_BIT)) { 6919 add = region_add(resv_map, from, to, regions_needed, h, h_cg); 6920 6921 if (unlikely(add < 0)) { 6922 hugetlb_acct_memory(h, -gbl_reserve); 6923 err = add; 6924 goto out_put_pages; 6925 } else if (unlikely(chg > add)) { 6926 /* 6927 * pages in this range were added to the reserve 6928 * map between region_chg and region_add. This 6929 * indicates a race with alloc_hugetlb_folio. Adjust 6930 * the subpool and reserve counts modified above 6931 * based on the difference. 6932 */ 6933 long rsv_adjust; 6934 6935 /* 6936 * hugetlb_cgroup_uncharge_cgroup_rsvd() will put the 6937 * reference to h_cg->css. See comment below for detail. 6938 */ 6939 hugetlb_cgroup_uncharge_cgroup_rsvd( 6940 hstate_index(h), 6941 (chg - add) * pages_per_huge_page(h), h_cg); 6942 6943 rsv_adjust = hugepage_subpool_put_pages(spool, 6944 chg - add); 6945 hugetlb_acct_memory(h, -rsv_adjust); 6946 } else if (h_cg) { 6947 /* 6948 * The file_regions will hold their own reference to 6949 * h_cg->css. So we should release the reference held 6950 * via hugetlb_cgroup_charge_cgroup_rsvd() when we are 6951 * done. 6952 */ 6953 hugetlb_cgroup_put_rsvd_cgroup(h_cg); 6954 } 6955 } 6956 return chg; 6957 6958 out_put_pages: 6959 spool_resv = chg - gbl_reserve; 6960 /* Restore used_hpages for pages that failed global reservation */ 6961 if (gbl_reserve && spool) { 6962 unsigned long flags; 6963 6964 spin_lock_irqsave(&spool->lock, flags); 6965 if (spool->max_hpages != -1) 6966 spool->used_hpages -= gbl_reserve; 6967 unlock_or_release_subpool(spool, flags); 6968 } 6969 if (spool_resv) { 6970 /* put sub pool's reservation back, chg - gbl_reserve */ 6971 gbl_resv = hugepage_subpool_put_pages(spool, spool_resv); 6972 /* 6973 * subpool's reserved pages can not be put back due to race, 6974 * return to hstate. 6975 */ 6976 hugetlb_acct_memory(h, -gbl_resv); 6977 } 6978 out_uncharge_cgroup: 6979 hugetlb_cgroup_uncharge_cgroup_rsvd(hstate_index(h), 6980 chg * pages_per_huge_page(h), h_cg); 6981 out_err: 6982 hugetlb_vma_lock_free(vma); 6983 if (!vma || vma_test(vma, VMA_MAYSHARE_BIT)) 6984 /* Only call region_abort if the region_chg succeeded but the 6985 * region_add failed or didn't run. 6986 */ 6987 if (chg >= 0 && add < 0) 6988 region_abort(resv_map, from, to, regions_needed); 6989 if (vma && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) { 6990 kref_put(&resv_map->refs, resv_map_release); 6991 set_vma_resv_map(vma, NULL); 6992 } 6993 return err; 6994 } 6995 6996 long hugetlb_unreserve_pages(struct inode *inode, long start, long end, 6997 long freed) 6998 { 6999 struct hstate *h = hstate_inode(inode); 7000 struct resv_map *resv_map = inode_resv_map(inode); 7001 long chg = 0; 7002 struct hugepage_subpool *spool = subpool_inode(inode); 7003 long gbl_reserve; 7004 7005 /* 7006 * Since this routine can be called in the evict inode path for all 7007 * hugetlbfs inodes, resv_map could be NULL. 7008 */ 7009 if (resv_map) { 7010 chg = region_del(resv_map, start, end); 7011 /* 7012 * region_del() can fail in the rare case where a region 7013 * must be split and another region descriptor can not be 7014 * allocated. If end == LONG_MAX, it will not fail. 7015 */ 7016 if (chg < 0) 7017 return chg; 7018 } 7019 7020 spin_lock(&inode->i_lock); 7021 inode->i_blocks -= (blocks_per_huge_page(h) * freed); 7022 spin_unlock(&inode->i_lock); 7023 7024 /* 7025 * If the subpool has a minimum size, the number of global 7026 * reservations to be released may be adjusted. 7027 * 7028 * Note that !resv_map implies freed == 0. So (chg - freed) 7029 * won't go negative. 7030 */ 7031 gbl_reserve = hugepage_subpool_put_pages(spool, (chg - freed)); 7032 hugetlb_acct_memory(h, -gbl_reserve); 7033 7034 return 0; 7035 } 7036 7037 #ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING 7038 static unsigned long page_table_shareable(struct vm_area_struct *svma, 7039 struct vm_area_struct *vma, 7040 unsigned long addr, pgoff_t idx) 7041 { 7042 unsigned long saddr = ((idx - vma_start_pgoff(svma)) << PAGE_SHIFT) + 7043 svma->vm_start; 7044 unsigned long sbase = saddr & PUD_MASK; 7045 unsigned long s_end = sbase + PUD_SIZE; 7046 7047 /* Allow segments to share if only one is marked locked */ 7048 vm_flags_t vm_flags = vma->vm_flags & ~VM_LOCKED_MASK; 7049 vm_flags_t svm_flags = svma->vm_flags & ~VM_LOCKED_MASK; 7050 7051 /* 7052 * match the virtual addresses, permission and the alignment of the 7053 * page table page. 7054 * 7055 * Also, vma_lock (vm_private_data) is required for sharing. 7056 */ 7057 if (pmd_index(addr) != pmd_index(saddr) || 7058 vm_flags != svm_flags || 7059 !range_in_vma(svma, sbase, s_end) || 7060 !svma->vm_private_data) 7061 return 0; 7062 7063 return saddr; 7064 } 7065 7066 bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr) 7067 { 7068 unsigned long start = addr & PUD_MASK; 7069 unsigned long end = start + PUD_SIZE; 7070 7071 #ifdef CONFIG_USERFAULTFD 7072 if (uffd_disable_huge_pmd_share(vma)) 7073 return false; 7074 #endif 7075 /* 7076 * check on proper vm_flags and page table alignment 7077 */ 7078 if (!(vma->vm_flags & VM_MAYSHARE)) 7079 return false; 7080 if (!vma->vm_private_data) /* vma lock required for sharing */ 7081 return false; 7082 if (!range_in_vma(vma, start, end)) 7083 return false; 7084 return true; 7085 } 7086 7087 /* 7088 * Determine if start,end range within vma could be mapped by shared pmd. 7089 * If yes, adjust start and end to cover range associated with possible 7090 * shared pmd mappings. 7091 */ 7092 void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma, 7093 unsigned long *start, unsigned long *end) 7094 { 7095 unsigned long v_start = ALIGN(vma->vm_start, PUD_SIZE), 7096 v_end = ALIGN_DOWN(vma->vm_end, PUD_SIZE); 7097 7098 /* 7099 * vma needs to span at least one aligned PUD size, and the range 7100 * must be at least partially within in. 7101 */ 7102 if (!(vma->vm_flags & VM_MAYSHARE) || !(v_end > v_start) || 7103 (*end <= v_start) || (*start >= v_end)) 7104 return; 7105 7106 /* Extend the range to be PUD aligned for a worst case scenario */ 7107 if (*start > v_start) 7108 *start = ALIGN_DOWN(*start, PUD_SIZE); 7109 7110 if (*end < v_end) 7111 *end = ALIGN(*end, PUD_SIZE); 7112 } 7113 7114 /* 7115 * Search for a shareable pmd page for hugetlb. In any case calls pmd_alloc() 7116 * and returns the corresponding pte. While this is not necessary for the 7117 * !shared pmd case because we can allocate the pmd later as well, it makes the 7118 * code much cleaner. pmd allocation is essential for the shared case because 7119 * pud has to be populated inside the same i_mmap_rwsem section - otherwise 7120 * racing tasks could either miss the sharing (see huge_pte_offset) or select a 7121 * bad pmd for sharing. 7122 */ 7123 pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma, 7124 unsigned long addr, pud_t *pud) 7125 { 7126 struct address_space *mapping = vma->vm_file->f_mapping; 7127 const pgoff_t idx = linear_page_index(vma, addr); 7128 struct vm_area_struct *svma; 7129 unsigned long saddr; 7130 pte_t *spte = NULL; 7131 pte_t *pte; 7132 7133 i_mmap_lock_read(mapping); 7134 mapping_rmap_tree_foreach(svma, mapping, idx, idx) { 7135 if (svma == vma) 7136 continue; 7137 7138 saddr = page_table_shareable(svma, vma, addr, idx); 7139 if (saddr) { 7140 spte = hugetlb_walk(svma, saddr, 7141 vma_mmu_pagesize(svma)); 7142 if (spte) { 7143 ptdesc_pmd_pts_inc(virt_to_ptdesc(spte)); 7144 break; 7145 } 7146 } 7147 } 7148 7149 if (!spte) 7150 goto out; 7151 7152 spin_lock(&mm->page_table_lock); 7153 if (pud_none(*pud)) { 7154 pud_populate(mm, pud, 7155 (pmd_t *)((unsigned long)spte & PAGE_MASK)); 7156 hugetlbfs_pmd_sharing_inc(file_inode(vma->vm_file)); 7157 mm_inc_nr_pmds(mm); 7158 } else { 7159 ptdesc_pmd_pts_dec(virt_to_ptdesc(spte)); 7160 } 7161 spin_unlock(&mm->page_table_lock); 7162 out: 7163 pte = (pte_t *)pmd_alloc(mm, pud, addr); 7164 i_mmap_unlock_read(mapping); 7165 return pte; 7166 } 7167 7168 static int __huge_pmd_unshare(struct mmu_gather *tlb, 7169 struct vm_area_struct *vma, unsigned long addr, pte_t *ptep, 7170 bool check_locks) 7171 { 7172 unsigned long sz = huge_page_size(hstate_vma(vma)); 7173 struct mm_struct *mm = vma->vm_mm; 7174 pgd_t *pgd = pgd_offset(mm, addr); 7175 p4d_t *p4d = p4d_offset(pgd, addr); 7176 pud_t *pud = pud_offset(p4d, addr); 7177 7178 if (sz != PMD_SIZE) 7179 return 0; 7180 if (!ptdesc_pmd_is_shared(virt_to_ptdesc(ptep))) 7181 return 0; 7182 i_mmap_assert_write_locked(vma->vm_file->f_mapping); 7183 if (check_locks) 7184 hugetlb_vma_assert_locked(vma); 7185 pud_clear(pud); 7186 7187 tlb_unshare_pmd_ptdesc(tlb, virt_to_ptdesc(ptep), addr); 7188 hugetlbfs_pmd_sharing_dec(file_inode(vma->vm_file)); 7189 7190 mm_dec_nr_pmds(mm); 7191 return 1; 7192 } 7193 7194 /** 7195 * huge_pmd_unshare - Unmap a pmd table if it is shared by multiple users 7196 * @tlb: the current mmu_gather. 7197 * @vma: the vma covering the pmd table. 7198 * @addr: the address we are trying to unshare. 7199 * @ptep: pointer into the (pmd) page table. 7200 * 7201 * Called with the page table lock held, the i_mmap_rwsem held in write mode 7202 * and the hugetlb vma lock held in write mode. 7203 * 7204 * Note: The caller must call huge_pmd_unshare_flush() before dropping the 7205 * i_mmap_rwsem. 7206 * 7207 * Returns: 1 if it was a shared PMD table and it got unmapped, or 0 if it 7208 * was not a shared PMD table. 7209 */ 7210 int huge_pmd_unshare(struct mmu_gather *tlb, struct vm_area_struct *vma, 7211 unsigned long addr, pte_t *ptep) 7212 { 7213 return __huge_pmd_unshare(tlb, vma, addr, ptep, /*check_locks=*/true); 7214 } 7215 7216 /* 7217 * huge_pmd_unshare_flush - Complete a sequence of huge_pmd_unshare() calls 7218 * @tlb: the current mmu_gather. 7219 * @vma: the vma covering the pmd table. 7220 * 7221 * Perform necessary TLB flushes or IPI broadcasts to synchronize PMD table 7222 * unsharing with concurrent page table walkers. 7223 * 7224 * This function must be called after a sequence of huge_pmd_unshare() 7225 * calls while still holding the i_mmap_rwsem. 7226 */ 7227 void huge_pmd_unshare_flush(struct mmu_gather *tlb, struct vm_area_struct *vma) 7228 { 7229 /* 7230 * We must synchronize page table unsharing such that nobody will 7231 * try reusing a previously-shared page table while it might still 7232 * be in use by previous sharers (TLB, GUP_fast). 7233 */ 7234 i_mmap_assert_write_locked(vma->vm_file->f_mapping); 7235 7236 tlb_flush_unshared_tables(tlb); 7237 } 7238 7239 #else /* !CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING */ 7240 7241 pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma, 7242 unsigned long addr, pud_t *pud) 7243 { 7244 return NULL; 7245 } 7246 7247 static int __huge_pmd_unshare(struct mmu_gather *tlb, 7248 struct vm_area_struct *vma, unsigned long addr, pte_t *ptep, 7249 bool check_locks) 7250 { 7251 return 0; 7252 } 7253 7254 int huge_pmd_unshare(struct mmu_gather *tlb, struct vm_area_struct *vma, 7255 unsigned long addr, pte_t *ptep) 7256 { 7257 return 0; 7258 } 7259 7260 void huge_pmd_unshare_flush(struct mmu_gather *tlb, struct vm_area_struct *vma) 7261 { 7262 } 7263 7264 void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma, 7265 unsigned long *start, unsigned long *end) 7266 { 7267 } 7268 7269 bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr) 7270 { 7271 return false; 7272 } 7273 #endif /* CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING */ 7274 7275 #ifdef CONFIG_ARCH_WANT_GENERAL_HUGETLB 7276 pte_t *huge_pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma, 7277 unsigned long addr, unsigned long sz) 7278 { 7279 pgd_t *pgd; 7280 p4d_t *p4d; 7281 pud_t *pud; 7282 pte_t *pte = NULL; 7283 7284 pgd = pgd_offset(mm, addr); 7285 p4d = p4d_alloc(mm, pgd, addr); 7286 if (!p4d) 7287 return NULL; 7288 pud = pud_alloc(mm, p4d, addr); 7289 if (pud) { 7290 if (sz == PUD_SIZE) { 7291 pte = (pte_t *)pud; 7292 } else { 7293 BUG_ON(sz != PMD_SIZE); 7294 if (want_pmd_share(vma, addr) && pud_none(*pud)) 7295 pte = huge_pmd_share(mm, vma, addr, pud); 7296 else 7297 pte = (pte_t *)pmd_alloc(mm, pud, addr); 7298 } 7299 } 7300 7301 if (pte) { 7302 pte_t pteval = ptep_get_lockless(pte); 7303 7304 BUG_ON(pte_present(pteval) && !pte_huge(pteval)); 7305 } 7306 7307 return pte; 7308 } 7309 7310 /* 7311 * huge_pte_offset() - Walk the page table to resolve the hugepage 7312 * entry at address @addr 7313 * 7314 * Return: Pointer to page table entry (PUD or PMD) for 7315 * address @addr, or NULL if a !p*d_present() entry is encountered and the 7316 * size @sz doesn't match the hugepage size at this level of the page 7317 * table. 7318 */ 7319 pte_t *huge_pte_offset(struct mm_struct *mm, 7320 unsigned long addr, unsigned long sz) 7321 { 7322 pgd_t *pgd; 7323 p4d_t *p4d; 7324 pud_t *pud; 7325 pmd_t *pmd; 7326 7327 pgd = pgd_offset(mm, addr); 7328 if (!pgd_present(*pgd)) 7329 return NULL; 7330 p4d = p4d_offset(pgd, addr); 7331 if (!p4d_present(*p4d)) 7332 return NULL; 7333 7334 pud = pud_offset(p4d, addr); 7335 if (sz == PUD_SIZE) 7336 /* must be pud huge, non-present or none */ 7337 return (pte_t *)pud; 7338 if (!pud_present(*pud)) 7339 return NULL; 7340 /* must have a valid entry and size to go further */ 7341 7342 pmd = pmd_offset(pud, addr); 7343 /* must be pmd huge, non-present or none */ 7344 return (pte_t *)pmd; 7345 } 7346 7347 /* 7348 * Return a mask that can be used to update an address to the last huge 7349 * page in a page table page mapping size. Used to skip non-present 7350 * page table entries when linearly scanning address ranges. Architectures 7351 * with unique huge page to page table relationships can define their own 7352 * version of this routine. 7353 */ 7354 unsigned long hugetlb_mask_last_page(struct hstate *h) 7355 { 7356 unsigned long hp_size = huge_page_size(h); 7357 7358 if (hp_size == PUD_SIZE) 7359 return P4D_SIZE - PUD_SIZE; 7360 else if (hp_size == PMD_SIZE) 7361 return PUD_SIZE - PMD_SIZE; 7362 else 7363 return 0UL; 7364 } 7365 7366 #else 7367 7368 /* See description above. Architectures can provide their own version. */ 7369 __weak unsigned long hugetlb_mask_last_page(struct hstate *h) 7370 { 7371 #ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING 7372 if (huge_page_size(h) == PMD_SIZE) 7373 return PUD_SIZE - PMD_SIZE; 7374 #endif 7375 return 0UL; 7376 } 7377 7378 #endif /* CONFIG_ARCH_WANT_GENERAL_HUGETLB */ 7379 7380 /** 7381 * folio_isolate_hugetlb - try to isolate an allocated hugetlb folio 7382 * @folio: the folio to isolate 7383 * @list: the list to add the folio to on success 7384 * 7385 * Isolate an allocated (refcount > 0) hugetlb folio, marking it as 7386 * isolated/non-migratable, and moving it from the active list to the 7387 * given list. 7388 * 7389 * Isolation will fail if @folio is not an allocated hugetlb folio, or if 7390 * it is already isolated/non-migratable. 7391 * 7392 * On success, an additional folio reference is taken that must be dropped 7393 * using folio_putback_hugetlb() to undo the isolation. 7394 * 7395 * Return: True if isolation worked, otherwise False. 7396 */ 7397 bool folio_isolate_hugetlb(struct folio *folio, struct list_head *list) 7398 { 7399 bool ret = true; 7400 7401 spin_lock_irq(&hugetlb_lock); 7402 if (!folio_test_hugetlb(folio) || 7403 !folio_test_hugetlb_migratable(folio) || 7404 !folio_try_get(folio)) { 7405 ret = false; 7406 goto unlock; 7407 } 7408 folio_clear_hugetlb_migratable(folio); 7409 list_move_tail(&folio->lru, list); 7410 unlock: 7411 spin_unlock_irq(&hugetlb_lock); 7412 return ret; 7413 } 7414 7415 int get_hwpoison_hugetlb_folio(struct folio *folio, bool *hugetlb, bool unpoison) 7416 { 7417 int ret = 0; 7418 7419 *hugetlb = false; 7420 spin_lock_irq(&hugetlb_lock); 7421 if (folio_test_hugetlb(folio)) { 7422 *hugetlb = true; 7423 if (folio_test_hugetlb_freed(folio)) 7424 ret = 0; 7425 else if (folio_test_hugetlb_migratable(folio) || unpoison) 7426 ret = folio_try_get(folio); 7427 else 7428 ret = -EBUSY; 7429 } 7430 spin_unlock_irq(&hugetlb_lock); 7431 return ret; 7432 } 7433 7434 /** 7435 * folio_putback_hugetlb - unisolate a hugetlb folio 7436 * @folio: the isolated hugetlb folio 7437 * 7438 * Putback/un-isolate the hugetlb folio that was previous isolated using 7439 * folio_isolate_hugetlb(): marking it non-isolated/migratable and putting it 7440 * back onto the active list. 7441 * 7442 * Will drop the additional folio reference obtained through 7443 * folio_isolate_hugetlb(). 7444 */ 7445 void folio_putback_hugetlb(struct folio *folio) 7446 { 7447 spin_lock_irq(&hugetlb_lock); 7448 folio_set_hugetlb_migratable(folio); 7449 list_move_tail(&folio->lru, &(folio_hstate(folio))->hugepage_activelist); 7450 spin_unlock_irq(&hugetlb_lock); 7451 folio_put(folio); 7452 } 7453 7454 static void move_hugetlb_lruvec_stat(struct folio *old_folio, 7455 struct folio *new_folio) 7456 { 7457 struct mem_cgroup *memcg; 7458 long nr_pages = folio_nr_pages(old_folio); 7459 int old_nid = folio_nid(old_folio); 7460 int new_nid = folio_nid(new_folio); 7461 7462 if (old_nid == new_nid) 7463 return; 7464 7465 guard(rcu)(); 7466 7467 memcg = folio_memcg(new_folio); 7468 if (!memcg) 7469 return; 7470 7471 mod_memcg_lruvec_state(mem_cgroup_lruvec(memcg, NODE_DATA(old_nid)), 7472 NR_HUGETLB, -nr_pages); 7473 mod_memcg_lruvec_state(mem_cgroup_lruvec(memcg, NODE_DATA(new_nid)), 7474 NR_HUGETLB, nr_pages); 7475 } 7476 7477 void move_hugetlb_state(struct folio *old_folio, struct folio *new_folio, 7478 enum migrate_reason reason) 7479 { 7480 struct hstate *h = folio_hstate(old_folio); 7481 7482 hugetlb_cgroup_migrate(old_folio, new_folio); 7483 move_hugetlb_lruvec_stat(old_folio, new_folio); 7484 folio_set_owner_migrate_reason(new_folio, reason); 7485 7486 /* 7487 * transfer temporary state of the new hugetlb folio. This is 7488 * reverse to other transitions because the newpage is going to 7489 * be final while the old one will be freed so it takes over 7490 * the temporary status. 7491 * 7492 * Also note that we have to transfer the per-node surplus state 7493 * here as well otherwise the global surplus count will not match 7494 * the per-node's. 7495 */ 7496 if (folio_test_hugetlb_temporary(new_folio)) { 7497 int old_nid = folio_nid(old_folio); 7498 int new_nid = folio_nid(new_folio); 7499 7500 folio_set_hugetlb_temporary(old_folio); 7501 folio_clear_hugetlb_temporary(new_folio); 7502 7503 7504 /* 7505 * There is no need to transfer the per-node surplus state 7506 * when we do not cross the node. 7507 */ 7508 if (new_nid != old_nid) { 7509 spin_lock_irq(&hugetlb_lock); 7510 if (h->surplus_huge_pages_node[old_nid]) { 7511 h->surplus_huge_pages_node[old_nid]--; 7512 h->surplus_huge_pages_node[new_nid]++; 7513 } 7514 spin_unlock_irq(&hugetlb_lock); 7515 } 7516 } 7517 7518 /* 7519 * Our old folio is isolated and has "migratable" cleared until it 7520 * is putback. As migration succeeded, set the new folio "migratable" 7521 * and add it to the active list. 7522 */ 7523 spin_lock_irq(&hugetlb_lock); 7524 folio_set_hugetlb_migratable(new_folio); 7525 list_move_tail(&new_folio->lru, &(folio_hstate(new_folio))->hugepage_activelist); 7526 spin_unlock_irq(&hugetlb_lock); 7527 } 7528 7529 /* 7530 * If @take_locks is false, the caller must ensure that no concurrent page table 7531 * access can happen (except for gup_fast() and hardware page walks). 7532 * If @take_locks is true, we take the hugetlb VMA lock (to lock out things like 7533 * concurrent page fault handling) and the file rmap lock. 7534 */ 7535 static void hugetlb_unshare_pmds(struct vm_area_struct *vma, 7536 unsigned long start, 7537 unsigned long end, 7538 bool take_locks) 7539 { 7540 struct hstate *h = hstate_vma(vma); 7541 unsigned long sz = huge_page_size(h); 7542 struct mm_struct *mm = vma->vm_mm; 7543 struct mmu_notifier_range range; 7544 struct mmu_gather tlb; 7545 unsigned long address; 7546 spinlock_t *ptl; 7547 pte_t *ptep; 7548 7549 if (!(vma->vm_flags & VM_MAYSHARE)) 7550 return; 7551 7552 if (start >= end) 7553 return; 7554 7555 flush_cache_range(vma, start, end); 7556 tlb_gather_mmu_vma(&tlb, vma); 7557 7558 /* 7559 * No need to call adjust_range_if_pmd_sharing_possible(), because 7560 * we have already done the PUD_SIZE alignment. 7561 */ 7562 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, 7563 start, end); 7564 mmu_notifier_invalidate_range_start(&range); 7565 if (take_locks) { 7566 hugetlb_vma_lock_write(vma); 7567 i_mmap_lock_write(vma->vm_file->f_mapping); 7568 } else { 7569 i_mmap_assert_write_locked(vma->vm_file->f_mapping); 7570 } 7571 for (address = start; address < end; address += PUD_SIZE) { 7572 ptep = hugetlb_walk(vma, address, sz); 7573 if (!ptep) 7574 continue; 7575 ptl = huge_pte_lock(h, mm, ptep); 7576 __huge_pmd_unshare(&tlb, vma, address, ptep, take_locks); 7577 spin_unlock(ptl); 7578 } 7579 huge_pmd_unshare_flush(&tlb, vma); 7580 if (take_locks) { 7581 i_mmap_unlock_write(vma->vm_file->f_mapping); 7582 hugetlb_vma_unlock_write(vma); 7583 } 7584 /* 7585 * No need to call mmu_notifier_arch_invalidate_secondary_tlbs(), see 7586 * Documentation/mm/mmu_notifier.rst. 7587 */ 7588 mmu_notifier_invalidate_range_end(&range); 7589 tlb_finish_mmu(&tlb); 7590 } 7591 7592 /* 7593 * This function will unconditionally remove all the shared pmd pgtable entries 7594 * within the specific vma for a hugetlbfs memory range. 7595 */ 7596 void hugetlb_unshare_all_pmds(struct vm_area_struct *vma) 7597 { 7598 hugetlb_unshare_pmds(vma, ALIGN(vma->vm_start, PUD_SIZE), 7599 ALIGN_DOWN(vma->vm_end, PUD_SIZE), 7600 /* take_locks = */ true); 7601 } 7602 7603 /* 7604 * For hugetlb, mremap() is an odd edge case - while the VMA copying is 7605 * performed, we permit both the old and new VMAs to reference the same 7606 * reservation. 7607 * 7608 * We fix this up after the operation succeeds, or if a newly allocated VMA 7609 * is closed as a result of a failure to allocate memory. 7610 */ 7611 void fixup_hugetlb_reservations(struct vm_area_struct *vma) 7612 { 7613 if (!vma_is_hugetlb(vma)) 7614 return; 7615 7616 /* 7617 * Rmap walks might still find this VMA and take the lock 7618 * inside the reservation map for __vma_private_lock(). Don't clear 7619 * the reservation map while that is possible. 7620 */ 7621 i_mmap_lock_write(vma->vm_file->f_mapping); 7622 clear_vma_resv_huge_pages(vma); 7623 i_mmap_unlock_write(vma->vm_file->f_mapping); 7624 } 7625