1 // SPDX-License-Identifier: GPL-2.0-only
3 * Generic hugetlb support.
4 * (C) Nadia Yvette Chambers, April 2004
6 #include <linux/list.h>
7 #include <linux/init.h>
9 #include <linux/seq_file.h>
10 #include <linux/sysctl.h>
11 #include <linux/highmem.h>
12 #include <linux/mmu_notifier.h>
13 #include <linux/nodemask.h>
14 #include <linux/pagemap.h>
15 #include <linux/mempolicy.h>
16 #include <linux/compiler.h>
17 #include <linux/cpumask.h>
18 #include <linux/cpuset.h>
19 #include <linux/mutex.h>
20 #include <linux/memblock.h>
21 #include <linux/minmax.h>
22 #include <linux/sysfs.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/string_helpers.h>
29 #include <linux/swap.h>
30 #include <linux/swapops.h>
31 #include <linux/jhash.h>
32 #include <linux/numa.h>
33 #include <linux/llist.h>
34 #include <linux/cma.h>
35 #include <linux/migrate.h>
36 #include <linux/nospec.h>
37 #include <linux/delayacct.h>
38 #include <linux/memory.h>
39 #include <linux/mm_inline.h>
40 #include <linux/padata.h>
43 #include <asm/pgalloc.h>
45 #include <asm/setup.h>
48 #include <linux/hugetlb.h>
49 #include <linux/hugetlb_cgroup.h>
50 #include <linux/node.h>
51 #include <linux/page_owner.h>
53 #include "hugetlb_vmemmap.h"
54 #include "hugetlb_cma.h"
55 #include <linux/page-isolation.h>
57 int hugetlb_max_hstate __read_mostly;
58 unsigned int default_hstate_idx;
59 struct hstate hstates[HUGE_MAX_HSTATE];
61 __initdata nodemask_t hugetlb_bootmem_nodes;
62 __initdata struct list_head huge_boot_pages[MAX_NUMNODES];
63 static unsigned long hstate_boot_nrinvalid[HUGE_MAX_HSTATE] __initdata;
66 * Due to ordering constraints across the init code for various
67 * architectures, hugetlb hstate cmdline parameters can't simply
68 * be early_param. early_param might call the setup function
69 * before valid hugetlb page sizes are determined, leading to
70 * incorrect rejection of valid hugepagesz= options.
72 * So, record the parameters early and consume them whenever the
73 * init code is ready for them, by calling hugetlb_parse_params().
76 /* one (hugepagesz=,hugepages=) pair per hstate, one default_hugepagesz */
77 #define HUGE_MAX_CMDLINE_ARGS (2 * HUGE_MAX_HSTATE + 1)
78 struct hugetlb_cmdline {
80 int (*setup)(char *val);
83 /* for command line parsing */
84 static struct hstate * __initdata parsed_hstate;
85 static unsigned long __initdata default_hstate_max_huge_pages;
86 static bool __initdata parsed_valid_hugepagesz = true;
87 static bool __initdata parsed_default_hugepagesz;
88 static unsigned int default_hugepages_in_node[MAX_NUMNODES] __initdata;
89 static unsigned long hugepage_allocation_threads __initdata;
91 static char hstate_cmdline_buf[COMMAND_LINE_SIZE] __initdata;
92 static int hstate_cmdline_index __initdata;
93 static struct hugetlb_cmdline hugetlb_params[HUGE_MAX_CMDLINE_ARGS] __initdata;
94 static int hugetlb_param_index __initdata;
95 static __init int hugetlb_add_param(char *s, int (*setup)(char *val));
96 static __init void hugetlb_parse_params(void);
98 #define hugetlb_early_param(str, func) \
99 static __init int func##args(char *s) \
101 return hugetlb_add_param(s, func); \
103 early_param(str, func##args)
106 * Protects updates to hugepage_freelists, hugepage_activelist, nr_huge_pages,
107 * free_huge_pages, and surplus_huge_pages.
109 __cacheline_aligned_in_smp DEFINE_SPINLOCK(hugetlb_lock);
112 * Serializes faults on the same logical page. This is used to
113 * prevent spurious OOMs when the hugepage pool is fully utilized.
115 static int num_fault_mutexes __ro_after_init;
116 struct mutex *hugetlb_fault_mutex_table __ro_after_init;
118 /* Forward declaration */
119 static int hugetlb_acct_memory(struct hstate *h, long delta);
120 static void hugetlb_vma_lock_free(struct vm_area_struct *vma);
121 static void hugetlb_vma_lock_alloc(struct vm_area_struct *vma);
122 static void __hugetlb_vma_unlock_write_free(struct vm_area_struct *vma);
123 static void hugetlb_unshare_pmds(struct vm_area_struct *vma,
124 unsigned long start, unsigned long end, bool take_locks);
125 static struct resv_map *vma_resv_map(struct vm_area_struct *vma);
127 static void hugetlb_free_folio(struct folio *folio)
129 if (folio_test_hugetlb_cma(folio)) {
130 hugetlb_cma_free_folio(folio);
137 static inline bool subpool_is_free(struct hugepage_subpool *spool)
141 if (spool->max_hpages != -1)
142 return spool->used_hpages == 0;
143 if (spool->min_hpages != -1)
144 return spool->rsv_hpages == spool->min_hpages;
149 static inline void unlock_or_release_subpool(struct hugepage_subpool *spool,
150 unsigned long irq_flags)
152 spin_unlock_irqrestore(&spool->lock, irq_flags);
154 /* If no pages are used, and no other handles to the subpool
155 * remain, give up any reservations based on minimum size and
156 * free the subpool */
157 if (subpool_is_free(spool)) {
158 if (spool->min_hpages != -1)
159 hugetlb_acct_memory(spool->hstate,
165 struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages,
168 struct hugepage_subpool *spool;
170 spool = kzalloc(sizeof(*spool), GFP_KERNEL);
174 spin_lock_init(&spool->lock);
176 spool->max_hpages = max_hpages;
178 spool->min_hpages = min_hpages;
180 if (min_hpages != -1 && hugetlb_acct_memory(h, min_hpages)) {
184 spool->rsv_hpages = min_hpages;
189 void hugepage_put_subpool(struct hugepage_subpool *spool)
193 spin_lock_irqsave(&spool->lock, flags);
194 BUG_ON(!spool->count);
196 unlock_or_release_subpool(spool, flags);
200 * Subpool accounting for allocating and reserving pages.
201 * Return -ENOMEM if there are not enough resources to satisfy the
202 * request. Otherwise, return the number of pages by which the
203 * global pools must be adjusted (upward). The returned value may
204 * only be different than the passed value (delta) in the case where
205 * a subpool minimum size must be maintained.
207 static long hugepage_subpool_get_pages(struct hugepage_subpool *spool,
215 spin_lock_irq(&spool->lock);
217 if (spool->max_hpages != -1) { /* maximum size accounting */
218 if ((spool->used_hpages + delta) <= spool->max_hpages)
219 spool->used_hpages += delta;
226 /* minimum size accounting */
227 if (spool->min_hpages != -1 && spool->rsv_hpages) {
228 if (delta > spool->rsv_hpages) {
230 * Asking for more reserves than those already taken on
231 * behalf of subpool. Return difference.
233 ret = delta - spool->rsv_hpages;
234 spool->rsv_hpages = 0;
236 ret = 0; /* reserves already accounted for */
237 spool->rsv_hpages -= delta;
242 spin_unlock_irq(&spool->lock);
247 * Subpool accounting for freeing and unreserving pages.
248 * Return the number of global page reservations that must be dropped.
249 * The return value may only be different than the passed value (delta)
250 * in the case where a subpool minimum size must be maintained.
252 static long hugepage_subpool_put_pages(struct hugepage_subpool *spool,
261 spin_lock_irqsave(&spool->lock, flags);
263 if (spool->max_hpages != -1) /* maximum size accounting */
264 spool->used_hpages -= delta;
266 /* minimum size accounting */
267 if (spool->min_hpages != -1 && spool->used_hpages < spool->min_hpages) {
268 if (spool->rsv_hpages + delta <= spool->min_hpages)
271 ret = spool->rsv_hpages + delta - spool->min_hpages;
273 spool->rsv_hpages += delta;
274 if (spool->rsv_hpages > spool->min_hpages)
275 spool->rsv_hpages = spool->min_hpages;
279 * If hugetlbfs_put_super couldn't free spool due to an outstanding
280 * quota reference, free it now.
282 unlock_or_release_subpool(spool, flags);
287 static inline struct hugepage_subpool *subpool_inode(struct inode *inode)
289 return HUGETLBFS_SB(inode->i_sb)->spool;
292 static inline struct hugepage_subpool *subpool_vma(struct vm_area_struct *vma)
294 return subpool_inode(file_inode(vma->vm_file));
298 * hugetlb vma_lock helper routines
300 void hugetlb_vma_lock_read(struct vm_area_struct *vma)
302 if (__vma_shareable_lock(vma)) {
303 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
305 down_read(&vma_lock->rw_sema);
306 } else if (__vma_private_lock(vma)) {
307 struct resv_map *resv_map = vma_resv_map(vma);
309 down_read(&resv_map->rw_sema);
313 void hugetlb_vma_unlock_read(struct vm_area_struct *vma)
315 if (__vma_shareable_lock(vma)) {
316 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
318 up_read(&vma_lock->rw_sema);
319 } else if (__vma_private_lock(vma)) {
320 struct resv_map *resv_map = vma_resv_map(vma);
322 up_read(&resv_map->rw_sema);
326 void hugetlb_vma_lock_write(struct vm_area_struct *vma)
328 if (__vma_shareable_lock(vma)) {
329 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
331 down_write(&vma_lock->rw_sema);
332 } else if (__vma_private_lock(vma)) {
333 struct resv_map *resv_map = vma_resv_map(vma);
335 down_write(&resv_map->rw_sema);
339 void hugetlb_vma_unlock_write(struct vm_area_struct *vma)
341 if (__vma_shareable_lock(vma)) {
342 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
344 up_write(&vma_lock->rw_sema);
345 } else if (__vma_private_lock(vma)) {
346 struct resv_map *resv_map = vma_resv_map(vma);
348 up_write(&resv_map->rw_sema);
352 int hugetlb_vma_trylock_write(struct vm_area_struct *vma)
355 if (__vma_shareable_lock(vma)) {
356 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
358 return down_write_trylock(&vma_lock->rw_sema);
359 } else if (__vma_private_lock(vma)) {
360 struct resv_map *resv_map = vma_resv_map(vma);
362 return down_write_trylock(&resv_map->rw_sema);
368 void hugetlb_vma_assert_locked(struct vm_area_struct *vma)
370 if (__vma_shareable_lock(vma)) {
371 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
373 lockdep_assert_held(&vma_lock->rw_sema);
374 } else if (__vma_private_lock(vma)) {
375 struct resv_map *resv_map = vma_resv_map(vma);
377 lockdep_assert_held(&resv_map->rw_sema);
381 void hugetlb_vma_lock_release(struct kref *kref)
383 struct hugetlb_vma_lock *vma_lock = container_of(kref,
384 struct hugetlb_vma_lock, refs);
389 static void __hugetlb_vma_unlock_write_put(struct hugetlb_vma_lock *vma_lock)
391 struct vm_area_struct *vma = vma_lock->vma;
394 * vma_lock structure may or not be released as a result of put,
395 * it certainly will no longer be attached to vma so clear pointer.
396 * Semaphore synchronizes access to vma_lock->vma field.
398 vma_lock->vma = NULL;
399 vma->vm_private_data = NULL;
400 up_write(&vma_lock->rw_sema);
401 kref_put(&vma_lock->refs, hugetlb_vma_lock_release);
404 static void __hugetlb_vma_unlock_write_free(struct vm_area_struct *vma)
406 if (__vma_shareable_lock(vma)) {
407 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
409 __hugetlb_vma_unlock_write_put(vma_lock);
410 } else if (__vma_private_lock(vma)) {
411 struct resv_map *resv_map = vma_resv_map(vma);
413 /* no free for anon vmas, but still need to unlock */
414 up_write(&resv_map->rw_sema);
418 static void hugetlb_vma_lock_free(struct vm_area_struct *vma)
421 * Only present in sharable vmas.
423 if (!vma || !__vma_shareable_lock(vma))
426 if (vma->vm_private_data) {
427 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
429 down_write(&vma_lock->rw_sema);
430 __hugetlb_vma_unlock_write_put(vma_lock);
434 static void hugetlb_vma_lock_alloc(struct vm_area_struct *vma)
436 struct hugetlb_vma_lock *vma_lock;
438 /* Only establish in (flags) sharable vmas */
439 if (!vma || !(vma->vm_flags & VM_MAYSHARE))
442 /* Should never get here with non-NULL vm_private_data */
443 if (vma->vm_private_data)
446 vma_lock = kmalloc(sizeof(*vma_lock), GFP_KERNEL);
449 * If we can not allocate structure, then vma can not
450 * participate in pmd sharing. This is only a possible
451 * performance enhancement and memory saving issue.
452 * However, the lock is also used to synchronize page
453 * faults with truncation. If the lock is not present,
454 * unlikely races could leave pages in a file past i_size
455 * until the file is removed. Warn in the unlikely case of
456 * allocation failure.
458 pr_warn_once("HugeTLB: unable to allocate vma specific lock\n");
462 kref_init(&vma_lock->refs);
463 init_rwsem(&vma_lock->rw_sema);
465 vma->vm_private_data = vma_lock;
468 /* Helper that removes a struct file_region from the resv_map cache and returns
471 static struct file_region *
472 get_file_region_entry_from_cache(struct resv_map *resv, long from, long to)
474 struct file_region *nrg;
476 VM_BUG_ON(resv->region_cache_count <= 0);
478 resv->region_cache_count--;
479 nrg = list_first_entry(&resv->region_cache, struct file_region, link);
480 list_del(&nrg->link);
488 static void copy_hugetlb_cgroup_uncharge_info(struct file_region *nrg,
489 struct file_region *rg)
491 #ifdef CONFIG_CGROUP_HUGETLB
492 nrg->reservation_counter = rg->reservation_counter;
499 /* Helper that records hugetlb_cgroup uncharge info. */
500 static void record_hugetlb_cgroup_uncharge_info(struct hugetlb_cgroup *h_cg,
502 struct resv_map *resv,
503 struct file_region *nrg)
505 #ifdef CONFIG_CGROUP_HUGETLB
507 nrg->reservation_counter =
508 &h_cg->rsvd_hugepage[hstate_index(h)];
509 nrg->css = &h_cg->css;
511 * The caller will hold exactly one h_cg->css reference for the
512 * whole contiguous reservation region. But this area might be
513 * scattered when there are already some file_regions reside in
514 * it. As a result, many file_regions may share only one css
515 * reference. In order to ensure that one file_region must hold
516 * exactly one h_cg->css reference, we should do css_get for
517 * each file_region and leave the reference held by caller
521 if (!resv->pages_per_hpage)
522 resv->pages_per_hpage = pages_per_huge_page(h);
523 /* pages_per_hpage should be the same for all entries in
526 VM_BUG_ON(resv->pages_per_hpage != pages_per_huge_page(h));
528 nrg->reservation_counter = NULL;
534 static void put_uncharge_info(struct file_region *rg)
536 #ifdef CONFIG_CGROUP_HUGETLB
542 static bool has_same_uncharge_info(struct file_region *rg,
543 struct file_region *org)
545 #ifdef CONFIG_CGROUP_HUGETLB
546 return rg->reservation_counter == org->reservation_counter &&
554 static void coalesce_file_region(struct resv_map *resv, struct file_region *rg)
556 struct file_region *nrg, *prg;
558 prg = list_prev_entry(rg, link);
559 if (&prg->link != &resv->regions && prg->to == rg->from &&
560 has_same_uncharge_info(prg, rg)) {
564 put_uncharge_info(rg);
570 nrg = list_next_entry(rg, link);
571 if (&nrg->link != &resv->regions && nrg->from == rg->to &&
572 has_same_uncharge_info(nrg, rg)) {
573 nrg->from = rg->from;
576 put_uncharge_info(rg);
582 hugetlb_resv_map_add(struct resv_map *map, struct list_head *rg, long from,
583 long to, struct hstate *h, struct hugetlb_cgroup *cg,
584 long *regions_needed)
586 struct file_region *nrg;
588 if (!regions_needed) {
589 nrg = get_file_region_entry_from_cache(map, from, to);
590 record_hugetlb_cgroup_uncharge_info(cg, h, map, nrg);
591 list_add(&nrg->link, rg);
592 coalesce_file_region(map, nrg);
594 *regions_needed += 1;
600 * Must be called with resv->lock held.
602 * Calling this with regions_needed != NULL will count the number of pages
603 * to be added but will not modify the linked list. And regions_needed will
604 * indicate the number of file_regions needed in the cache to carry out to add
605 * the regions for this range.
607 static long add_reservation_in_range(struct resv_map *resv, long f, long t,
608 struct hugetlb_cgroup *h_cg,
609 struct hstate *h, long *regions_needed)
612 struct list_head *head = &resv->regions;
613 long last_accounted_offset = f;
614 struct file_region *iter, *trg = NULL;
615 struct list_head *rg = NULL;
620 /* In this loop, we essentially handle an entry for the range
621 * [last_accounted_offset, iter->from), at every iteration, with some
624 list_for_each_entry_safe(iter, trg, head, link) {
625 /* Skip irrelevant regions that start before our range. */
626 if (iter->from < f) {
627 /* If this region ends after the last accounted offset,
628 * then we need to update last_accounted_offset.
630 if (iter->to > last_accounted_offset)
631 last_accounted_offset = iter->to;
635 /* When we find a region that starts beyond our range, we've
638 if (iter->from >= t) {
639 rg = iter->link.prev;
643 /* Add an entry for last_accounted_offset -> iter->from, and
644 * update last_accounted_offset.
646 if (iter->from > last_accounted_offset)
647 add += hugetlb_resv_map_add(resv, iter->link.prev,
648 last_accounted_offset,
652 last_accounted_offset = iter->to;
655 /* Handle the case where our range extends beyond
656 * last_accounted_offset.
660 if (last_accounted_offset < t)
661 add += hugetlb_resv_map_add(resv, rg, last_accounted_offset,
662 t, h, h_cg, regions_needed);
667 /* Must be called with resv->lock acquired. Will drop lock to allocate entries.
669 static int allocate_file_region_entries(struct resv_map *resv,
671 __must_hold(&resv->lock)
673 LIST_HEAD(allocated_regions);
674 int to_allocate = 0, i = 0;
675 struct file_region *trg = NULL, *rg = NULL;
677 VM_BUG_ON(regions_needed < 0);
680 * Check for sufficient descriptors in the cache to accommodate
681 * the number of in progress add operations plus regions_needed.
683 * This is a while loop because when we drop the lock, some other call
684 * to region_add or region_del may have consumed some region_entries,
685 * so we keep looping here until we finally have enough entries for
686 * (adds_in_progress + regions_needed).
688 while (resv->region_cache_count <
689 (resv->adds_in_progress + regions_needed)) {
690 to_allocate = resv->adds_in_progress + regions_needed -
691 resv->region_cache_count;
693 /* At this point, we should have enough entries in the cache
694 * for all the existing adds_in_progress. We should only be
695 * needing to allocate for regions_needed.
697 VM_BUG_ON(resv->region_cache_count < resv->adds_in_progress);
699 spin_unlock(&resv->lock);
700 for (i = 0; i < to_allocate; i++) {
701 trg = kmalloc(sizeof(*trg), GFP_KERNEL);
704 list_add(&trg->link, &allocated_regions);
707 spin_lock(&resv->lock);
709 list_splice(&allocated_regions, &resv->region_cache);
710 resv->region_cache_count += to_allocate;
716 list_for_each_entry_safe(rg, trg, &allocated_regions, link) {
724 * Add the huge page range represented by [f, t) to the reserve
725 * map. Regions will be taken from the cache to fill in this range.
726 * Sufficient regions should exist in the cache due to the previous
727 * call to region_chg with the same range, but in some cases the cache will not
728 * have sufficient entries due to races with other code doing region_add or
729 * region_del. The extra needed entries will be allocated.
731 * regions_needed is the out value provided by a previous call to region_chg.
733 * Return the number of new huge pages added to the map. This number is greater
734 * than or equal to zero. If file_region entries needed to be allocated for
735 * this operation and we were not able to allocate, it returns -ENOMEM.
736 * region_add of regions of length 1 never allocate file_regions and cannot
737 * fail; region_chg will always allocate at least 1 entry and a region_add for
738 * 1 page will only require at most 1 entry.
740 static long region_add(struct resv_map *resv, long f, long t,
741 long in_regions_needed, struct hstate *h,
742 struct hugetlb_cgroup *h_cg)
744 long add = 0, actual_regions_needed = 0;
746 spin_lock(&resv->lock);
749 /* Count how many regions are actually needed to execute this add. */
750 add_reservation_in_range(resv, f, t, NULL, NULL,
751 &actual_regions_needed);
754 * Check for sufficient descriptors in the cache to accommodate
755 * this add operation. Note that actual_regions_needed may be greater
756 * than in_regions_needed, as the resv_map may have been modified since
757 * the region_chg call. In this case, we need to make sure that we
758 * allocate extra entries, such that we have enough for all the
759 * existing adds_in_progress, plus the excess needed for this
762 if (actual_regions_needed > in_regions_needed &&
763 resv->region_cache_count <
764 resv->adds_in_progress +
765 (actual_regions_needed - in_regions_needed)) {
766 /* region_add operation of range 1 should never need to
767 * allocate file_region entries.
769 VM_BUG_ON(t - f <= 1);
771 if (allocate_file_region_entries(
772 resv, actual_regions_needed - in_regions_needed)) {
779 add = add_reservation_in_range(resv, f, t, h_cg, h, NULL);
781 resv->adds_in_progress -= in_regions_needed;
783 spin_unlock(&resv->lock);
788 * Examine the existing reserve map and determine how many
789 * huge pages in the specified range [f, t) are NOT currently
790 * represented. This routine is called before a subsequent
791 * call to region_add that will actually modify the reserve
792 * map to add the specified range [f, t). region_chg does
793 * not change the number of huge pages represented by the
794 * map. A number of new file_region structures is added to the cache as a
795 * placeholder, for the subsequent region_add call to use. At least 1
796 * file_region structure is added.
798 * out_regions_needed is the number of regions added to the
799 * resv->adds_in_progress. This value needs to be provided to a follow up call
800 * to region_add or region_abort for proper accounting.
802 * Returns the number of huge pages that need to be added to the existing
803 * reservation map for the range [f, t). This number is greater or equal to
804 * zero. -ENOMEM is returned if a new file_region structure or cache entry
805 * is needed and can not be allocated.
807 static long region_chg(struct resv_map *resv, long f, long t,
808 long *out_regions_needed)
812 spin_lock(&resv->lock);
814 /* Count how many hugepages in this range are NOT represented. */
815 chg = add_reservation_in_range(resv, f, t, NULL, NULL,
818 if (*out_regions_needed == 0)
819 *out_regions_needed = 1;
821 if (allocate_file_region_entries(resv, *out_regions_needed))
824 resv->adds_in_progress += *out_regions_needed;
826 spin_unlock(&resv->lock);
831 * Abort the in progress add operation. The adds_in_progress field
832 * of the resv_map keeps track of the operations in progress between
833 * calls to region_chg and region_add. Operations are sometimes
834 * aborted after the call to region_chg. In such cases, region_abort
835 * is called to decrement the adds_in_progress counter. regions_needed
836 * is the value returned by the region_chg call, it is used to decrement
837 * the adds_in_progress counter.
839 * NOTE: The range arguments [f, t) are not needed or used in this
840 * routine. They are kept to make reading the calling code easier as
841 * arguments will match the associated region_chg call.
843 static void region_abort(struct resv_map *resv, long f, long t,
846 spin_lock(&resv->lock);
847 VM_BUG_ON(!resv->region_cache_count);
848 resv->adds_in_progress -= regions_needed;
849 spin_unlock(&resv->lock);
853 * Delete the specified range [f, t) from the reserve map. If the
854 * t parameter is LONG_MAX, this indicates that ALL regions after f
855 * should be deleted. Locate the regions which intersect [f, t)
856 * and either trim, delete or split the existing regions.
858 * Returns the number of huge pages deleted from the reserve map.
859 * In the normal case, the return value is zero or more. In the
860 * case where a region must be split, a new region descriptor must
861 * be allocated. If the allocation fails, -ENOMEM will be returned.
862 * NOTE: If the parameter t == LONG_MAX, then we will never split
863 * a region and possibly return -ENOMEM. Callers specifying
864 * t == LONG_MAX do not need to check for -ENOMEM error.
866 static long region_del(struct resv_map *resv, long f, long t)
868 struct list_head *head = &resv->regions;
869 struct file_region *rg, *trg;
870 struct file_region *nrg = NULL;
874 spin_lock(&resv->lock);
875 list_for_each_entry_safe(rg, trg, head, link) {
877 * Skip regions before the range to be deleted. file_region
878 * ranges are normally of the form [from, to). However, there
879 * may be a "placeholder" entry in the map which is of the form
880 * (from, to) with from == to. Check for placeholder entries
881 * at the beginning of the range to be deleted.
883 if (rg->to <= f && (rg->to != rg->from || rg->to != f))
889 if (f > rg->from && t < rg->to) { /* Must split region */
891 * Check for an entry in the cache before dropping
892 * lock and attempting allocation.
895 resv->region_cache_count > resv->adds_in_progress) {
896 nrg = list_first_entry(&resv->region_cache,
899 list_del(&nrg->link);
900 resv->region_cache_count--;
904 spin_unlock(&resv->lock);
905 nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
912 hugetlb_cgroup_uncharge_file_region(
913 resv, rg, t - f, false);
915 /* New entry for end of split region */
919 copy_hugetlb_cgroup_uncharge_info(nrg, rg);
921 INIT_LIST_HEAD(&nrg->link);
923 /* Original entry is trimmed */
926 list_add(&nrg->link, &rg->link);
931 if (f <= rg->from && t >= rg->to) { /* Remove entire region */
932 del += rg->to - rg->from;
933 hugetlb_cgroup_uncharge_file_region(resv, rg,
934 rg->to - rg->from, true);
940 if (f <= rg->from) { /* Trim beginning of region */
941 hugetlb_cgroup_uncharge_file_region(resv, rg,
942 t - rg->from, false);
946 } else { /* Trim end of region */
947 hugetlb_cgroup_uncharge_file_region(resv, rg,
955 spin_unlock(&resv->lock);
961 * A rare out of memory error was encountered which prevented removal of
962 * the reserve map region for a page. The huge page itself was free'ed
963 * and removed from the page cache. This routine will adjust the subpool
964 * usage count, and the global reserve count if needed. By incrementing
965 * these counts, the reserve map entry which could not be deleted will
966 * appear as a "reserved" entry instead of simply dangling with incorrect
969 void hugetlb_fix_reserve_counts(struct inode *inode)
971 struct hugepage_subpool *spool = subpool_inode(inode);
973 bool reserved = false;
975 rsv_adjust = hugepage_subpool_get_pages(spool, 1);
976 if (rsv_adjust > 0) {
977 struct hstate *h = hstate_inode(inode);
979 if (!hugetlb_acct_memory(h, 1))
981 } else if (!rsv_adjust) {
986 pr_warn("hugetlb: Huge Page Reserved count may go negative.\n");
990 * Count and return the number of huge pages in the reserve map
991 * that intersect with the range [f, t).
993 static long region_count(struct resv_map *resv, long f, long t)
995 struct list_head *head = &resv->regions;
996 struct file_region *rg;
999 spin_lock(&resv->lock);
1000 /* Locate each segment we overlap with, and count that overlap. */
1001 list_for_each_entry(rg, head, link) {
1010 seg_from = max(rg->from, f);
1011 seg_to = min(rg->to, t);
1013 chg += seg_to - seg_from;
1015 spin_unlock(&resv->lock);
1021 * Convert the address within this vma to the page offset within
1022 * the mapping, huge page units here.
1024 static pgoff_t vma_hugecache_offset(struct hstate *h,
1025 struct vm_area_struct *vma, unsigned long address)
1027 return ((address - vma->vm_start) >> huge_page_shift(h)) +
1028 (vma->vm_pgoff >> huge_page_order(h));
1032 * vma_kernel_pagesize - Page size granularity for this VMA.
1033 * @vma: The user mapping.
1035 * Folios in this VMA will be aligned to, and at least the size of the
1036 * number of bytes returned by this function.
1038 * Return: The default size of the folios allocated when backing a VMA.
1040 unsigned long vma_kernel_pagesize(struct vm_area_struct *vma)
1042 if (vma->vm_ops && vma->vm_ops->pagesize)
1043 return vma->vm_ops->pagesize(vma);
1046 EXPORT_SYMBOL_GPL(vma_kernel_pagesize);
1049 * Return the page size being used by the MMU to back a VMA. In the majority
1050 * of cases, the page size used by the kernel matches the MMU size. On
1051 * architectures where it differs, an architecture-specific 'strong'
1052 * version of this symbol is required.
1054 __weak unsigned long vma_mmu_pagesize(struct vm_area_struct *vma)
1056 return vma_kernel_pagesize(vma);
1060 * Flags for MAP_PRIVATE reservations. These are stored in the bottom
1061 * bits of the reservation map pointer, which are always clear due to
1064 #define HPAGE_RESV_OWNER (1UL << 0)
1065 #define HPAGE_RESV_UNMAPPED (1UL << 1)
1066 #define HPAGE_RESV_MASK (HPAGE_RESV_OWNER | HPAGE_RESV_UNMAPPED)
1069 * These helpers are used to track how many pages are reserved for
1070 * faults in a MAP_PRIVATE mapping. Only the process that called mmap()
1071 * is guaranteed to have their future faults succeed.
1073 * With the exception of hugetlb_dup_vma_private() which is called at fork(),
1074 * the reserve counters are updated with the hugetlb_lock held. It is safe
1075 * to reset the VMA at fork() time as it is not in use yet and there is no
1076 * chance of the global counters getting corrupted as a result of the values.
1078 * The private mapping reservation is represented in a subtly different
1079 * manner to a shared mapping. A shared mapping has a region map associated
1080 * with the underlying file, this region map represents the backing file
1081 * pages which have ever had a reservation assigned which this persists even
1082 * after the page is instantiated. A private mapping has a region map
1083 * associated with the original mmap which is attached to all VMAs which
1084 * reference it, this region map represents those offsets which have consumed
1085 * reservation ie. where pages have been instantiated.
1087 static unsigned long get_vma_private_data(struct vm_area_struct *vma)
1089 return (unsigned long)vma->vm_private_data;
1092 static void set_vma_private_data(struct vm_area_struct *vma,
1093 unsigned long value)
1095 vma->vm_private_data = (void *)value;
1099 resv_map_set_hugetlb_cgroup_uncharge_info(struct resv_map *resv_map,
1100 struct hugetlb_cgroup *h_cg,
1103 #ifdef CONFIG_CGROUP_HUGETLB
1105 resv_map->reservation_counter = NULL;
1106 resv_map->pages_per_hpage = 0;
1107 resv_map->css = NULL;
1109 resv_map->reservation_counter =
1110 &h_cg->rsvd_hugepage[hstate_index(h)];
1111 resv_map->pages_per_hpage = pages_per_huge_page(h);
1112 resv_map->css = &h_cg->css;
1117 struct resv_map *resv_map_alloc(void)
1119 struct resv_map *resv_map = kmalloc(sizeof(*resv_map), GFP_KERNEL);
1120 struct file_region *rg = kmalloc(sizeof(*rg), GFP_KERNEL);
1122 if (!resv_map || !rg) {
1128 kref_init(&resv_map->refs);
1129 spin_lock_init(&resv_map->lock);
1130 INIT_LIST_HEAD(&resv_map->regions);
1131 init_rwsem(&resv_map->rw_sema);
1133 resv_map->adds_in_progress = 0;
1135 * Initialize these to 0. On shared mappings, 0's here indicate these
1136 * fields don't do cgroup accounting. On private mappings, these will be
1137 * re-initialized to the proper values, to indicate that hugetlb cgroup
1138 * reservations are to be un-charged from here.
1140 resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, NULL, NULL);
1142 INIT_LIST_HEAD(&resv_map->region_cache);
1143 list_add(&rg->link, &resv_map->region_cache);
1144 resv_map->region_cache_count = 1;
1149 void resv_map_release(struct kref *ref)
1151 struct resv_map *resv_map = container_of(ref, struct resv_map, refs);
1152 struct list_head *head = &resv_map->region_cache;
1153 struct file_region *rg, *trg;
1155 /* Clear out any active regions before we release the map. */
1156 region_del(resv_map, 0, LONG_MAX);
1158 /* ... and any entries left in the cache */
1159 list_for_each_entry_safe(rg, trg, head, link) {
1160 list_del(&rg->link);
1164 VM_BUG_ON(resv_map->adds_in_progress);
1169 static inline struct resv_map *inode_resv_map(struct inode *inode)
1172 * At inode evict time, i_mapping may not point to the original
1173 * address space within the inode. This original address space
1174 * contains the pointer to the resv_map. So, always use the
1175 * address space embedded within the inode.
1176 * The VERY common case is inode->mapping == &inode->i_data but,
1177 * this may not be true for device special inodes.
1179 return (struct resv_map *)(&inode->i_data)->i_private_data;
1182 static struct resv_map *vma_resv_map(struct vm_area_struct *vma)
1184 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
1185 if (vma->vm_flags & VM_MAYSHARE) {
1186 struct address_space *mapping = vma->vm_file->f_mapping;
1187 struct inode *inode = mapping->host;
1189 return inode_resv_map(inode);
1192 return (struct resv_map *)(get_vma_private_data(vma) &
1197 static void set_vma_resv_map(struct vm_area_struct *vma, struct resv_map *map)
1199 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
1200 VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
1202 set_vma_private_data(vma, (unsigned long)map);
1205 static void set_vma_resv_flags(struct vm_area_struct *vma, unsigned long flags)
1207 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
1208 VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
1210 set_vma_private_data(vma, get_vma_private_data(vma) | flags);
1213 static int is_vma_resv_set(struct vm_area_struct *vma, unsigned long flag)
1215 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
1217 return (get_vma_private_data(vma) & flag) != 0;
1220 bool __vma_private_lock(struct vm_area_struct *vma)
1222 return !(vma->vm_flags & VM_MAYSHARE) &&
1223 get_vma_private_data(vma) & ~HPAGE_RESV_MASK &&
1224 is_vma_resv_set(vma, HPAGE_RESV_OWNER);
1227 void hugetlb_dup_vma_private(struct vm_area_struct *vma)
1229 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
1231 * Clear vm_private_data
1232 * - For shared mappings this is a per-vma semaphore that may be
1233 * allocated in a subsequent call to hugetlb_vm_op_open.
1234 * Before clearing, make sure pointer is not associated with vma
1235 * as this will leak the structure. This is the case when called
1236 * via clear_vma_resv_huge_pages() and hugetlb_vm_op_open has already
1237 * been called to allocate a new structure.
1238 * - For MAP_PRIVATE mappings, this is the reserve map which does
1239 * not apply to children. Faults generated by the children are
1240 * not guaranteed to succeed, even if read-only.
1242 if (vma->vm_flags & VM_MAYSHARE) {
1243 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
1245 if (vma_lock && vma_lock->vma != vma)
1246 vma->vm_private_data = NULL;
1248 vma->vm_private_data = NULL;
1252 * Reset and decrement one ref on hugepage private reservation.
1253 * Called with mm->mmap_lock writer semaphore held.
1254 * This function should be only used by mremap and operate on
1255 * same sized vma. It should never come here with last ref on the
1258 void clear_vma_resv_huge_pages(struct vm_area_struct *vma)
1261 * Clear the old hugetlb private page reservation.
1262 * It has already been transferred to new_vma.
1264 * During a mremap() operation of a hugetlb vma we call move_vma()
1265 * which copies vma into new_vma and unmaps vma. After the copy
1266 * operation both new_vma and vma share a reference to the resv_map
1267 * struct, and at that point vma is about to be unmapped. We don't
1268 * want to return the reservation to the pool at unmap of vma because
1269 * the reservation still lives on in new_vma, so simply decrement the
1270 * ref here and remove the resv_map reference from this vma.
1272 struct resv_map *reservations = vma_resv_map(vma);
1274 if (reservations && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
1275 resv_map_put_hugetlb_cgroup_uncharge_info(reservations);
1276 kref_put(&reservations->refs, resv_map_release);
1279 hugetlb_dup_vma_private(vma);
1282 static void enqueue_hugetlb_folio(struct hstate *h, struct folio *folio)
1284 int nid = folio_nid(folio);
1286 lockdep_assert_held(&hugetlb_lock);
1287 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
1289 list_move(&folio->lru, &h->hugepage_freelists[nid]);
1290 h->free_huge_pages++;
1291 h->free_huge_pages_node[nid]++;
1292 folio_set_hugetlb_freed(folio);
1295 static struct folio *dequeue_hugetlb_folio_node_exact(struct hstate *h,
1298 struct folio *folio;
1299 bool pin = !!(current->flags & PF_MEMALLOC_PIN);
1301 lockdep_assert_held(&hugetlb_lock);
1302 list_for_each_entry(folio, &h->hugepage_freelists[nid], lru) {
1303 if (pin && !folio_is_longterm_pinnable(folio))
1306 if (folio_test_hwpoison(folio))
1309 if (is_migrate_isolate_page(&folio->page))
1312 list_move(&folio->lru, &h->hugepage_activelist);
1313 folio_ref_unfreeze(folio, 1);
1314 folio_clear_hugetlb_freed(folio);
1315 h->free_huge_pages--;
1316 h->free_huge_pages_node[nid]--;
1323 static struct folio *dequeue_hugetlb_folio_nodemask(struct hstate *h, gfp_t gfp_mask,
1324 int nid, nodemask_t *nmask)
1326 unsigned int cpuset_mems_cookie;
1327 struct zonelist *zonelist;
1330 int node = NUMA_NO_NODE;
1332 /* 'nid' should not be NUMA_NO_NODE. Try to catch any misuse of it and rectifiy. */
1333 if (nid == NUMA_NO_NODE)
1334 nid = numa_node_id();
1336 zonelist = node_zonelist(nid, gfp_mask);
1339 cpuset_mems_cookie = read_mems_allowed_begin();
1340 for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nmask) {
1341 struct folio *folio;
1343 if (!cpuset_zone_allowed(zone, gfp_mask))
1346 * no need to ask again on the same node. Pool is node rather than
1349 if (zone_to_nid(zone) == node)
1351 node = zone_to_nid(zone);
1353 folio = dequeue_hugetlb_folio_node_exact(h, node);
1357 if (unlikely(read_mems_allowed_retry(cpuset_mems_cookie)))
1363 static unsigned long available_huge_pages(struct hstate *h)
1365 return h->free_huge_pages - h->resv_huge_pages;
1368 static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,
1369 struct vm_area_struct *vma,
1370 unsigned long address, long gbl_chg)
1372 struct folio *folio = NULL;
1373 struct mempolicy *mpol;
1375 nodemask_t *nodemask;
1379 * gbl_chg==1 means the allocation requires a new page that was not
1380 * reserved before. Making sure there's at least one free page.
1382 if (gbl_chg && !available_huge_pages(h))
1385 gfp_mask = htlb_alloc_mask(h);
1386 nid = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
1388 if (mpol_is_preferred_many(mpol)) {
1389 folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask,
1392 /* Fallback to all nodes if page==NULL */
1397 folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask,
1400 mpol_cond_put(mpol);
1408 * common helper functions for hstate_next_node_to_{alloc|free}.
1409 * We may have allocated or freed a huge page based on a different
1410 * nodes_allowed previously, so h->next_node_to_{alloc|free} might
1411 * be outside of *nodes_allowed. Ensure that we use an allowed
1412 * node for alloc or free.
1414 static int next_node_allowed(int nid, nodemask_t *nodes_allowed)
1416 nid = next_node_in(nid, *nodes_allowed);
1417 VM_BUG_ON(nid >= MAX_NUMNODES);
1422 static int get_valid_node_allowed(int nid, nodemask_t *nodes_allowed)
1424 if (!node_isset(nid, *nodes_allowed))
1425 nid = next_node_allowed(nid, nodes_allowed);
1430 * returns the previously saved node ["this node"] from which to
1431 * allocate a persistent huge page for the pool and advance the
1432 * next node from which to allocate, handling wrap at end of node
1435 static int hstate_next_node_to_alloc(int *next_node,
1436 nodemask_t *nodes_allowed)
1440 VM_BUG_ON(!nodes_allowed);
1442 nid = get_valid_node_allowed(*next_node, nodes_allowed);
1443 *next_node = next_node_allowed(nid, nodes_allowed);
1449 * helper for remove_pool_hugetlb_folio() - return the previously saved
1450 * node ["this node"] from which to free a huge page. Advance the
1451 * next node id whether or not we find a free huge page to free so
1452 * that the next attempt to free addresses the next node.
1454 static int hstate_next_node_to_free(struct hstate *h, nodemask_t *nodes_allowed)
1458 VM_BUG_ON(!nodes_allowed);
1460 nid = get_valid_node_allowed(h->next_nid_to_free, nodes_allowed);
1461 h->next_nid_to_free = next_node_allowed(nid, nodes_allowed);
1466 #define for_each_node_mask_to_alloc(next_node, nr_nodes, node, mask) \
1467 for (nr_nodes = nodes_weight(*mask); \
1469 ((node = hstate_next_node_to_alloc(next_node, mask)) || 1); \
1472 #define for_each_node_mask_to_free(hs, nr_nodes, node, mask) \
1473 for (nr_nodes = nodes_weight(*mask); \
1475 ((node = hstate_next_node_to_free(hs, mask)) || 1); \
1478 #ifdef CONFIG_ARCH_HAS_GIGANTIC_PAGE
1479 #ifdef CONFIG_CONTIG_ALLOC
1480 static struct folio *alloc_gigantic_folio(struct hstate *h, gfp_t gfp_mask,
1481 int nid, nodemask_t *nodemask)
1483 struct folio *folio;
1484 int order = huge_page_order(h);
1485 bool retried = false;
1487 if (nid == NUMA_NO_NODE)
1488 nid = numa_mem_id();
1490 folio = hugetlb_cma_alloc_folio(h, gfp_mask, nid, nodemask);
1492 if (hugetlb_cma_exclusive_alloc())
1495 folio = folio_alloc_gigantic(order, gfp_mask, nid, nodemask);
1500 if (folio_ref_freeze(folio, 1))
1503 pr_warn("HugeTLB: unexpected refcount on PFN %lu\n", folio_pfn(folio));
1504 hugetlb_free_folio(folio);
1512 #else /* !CONFIG_CONTIG_ALLOC */
1513 static struct folio *alloc_gigantic_folio(struct hstate *h, gfp_t gfp_mask,
1514 int nid, nodemask_t *nodemask)
1518 #endif /* CONFIG_CONTIG_ALLOC */
1520 #else /* !CONFIG_ARCH_HAS_GIGANTIC_PAGE */
1521 static struct folio *alloc_gigantic_folio(struct hstate *h, gfp_t gfp_mask,
1522 int nid, nodemask_t *nodemask)
1529 * Remove hugetlb folio from lists.
1530 * If vmemmap exists for the folio, clear the hugetlb flag so that the
1531 * folio appears as just a compound page. Otherwise, wait until after
1532 * allocating vmemmap to clear the flag.
1534 * Must be called with hugetlb lock held.
1536 static void remove_hugetlb_folio(struct hstate *h, struct folio *folio,
1537 bool adjust_surplus)
1539 int nid = folio_nid(folio);
1541 VM_BUG_ON_FOLIO(hugetlb_cgroup_from_folio(folio), folio);
1542 VM_BUG_ON_FOLIO(hugetlb_cgroup_from_folio_rsvd(folio), folio);
1544 lockdep_assert_held(&hugetlb_lock);
1545 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
1548 list_del(&folio->lru);
1550 if (folio_test_hugetlb_freed(folio)) {
1551 folio_clear_hugetlb_freed(folio);
1552 h->free_huge_pages--;
1553 h->free_huge_pages_node[nid]--;
1555 if (adjust_surplus) {
1556 h->surplus_huge_pages--;
1557 h->surplus_huge_pages_node[nid]--;
1561 * We can only clear the hugetlb flag after allocating vmemmap
1562 * pages. Otherwise, someone (memory error handling) may try to write
1563 * to tail struct pages.
1565 if (!folio_test_hugetlb_vmemmap_optimized(folio))
1566 __folio_clear_hugetlb(folio);
1569 h->nr_huge_pages_node[nid]--;
1572 static void add_hugetlb_folio(struct hstate *h, struct folio *folio,
1573 bool adjust_surplus)
1575 int nid = folio_nid(folio);
1577 VM_BUG_ON_FOLIO(!folio_test_hugetlb_vmemmap_optimized(folio), folio);
1579 lockdep_assert_held(&hugetlb_lock);
1581 INIT_LIST_HEAD(&folio->lru);
1583 h->nr_huge_pages_node[nid]++;
1585 if (adjust_surplus) {
1586 h->surplus_huge_pages++;
1587 h->surplus_huge_pages_node[nid]++;
1590 __folio_set_hugetlb(folio);
1591 folio_change_private(folio, NULL);
1593 * We have to set hugetlb_vmemmap_optimized again as above
1594 * folio_change_private(folio, NULL) cleared it.
1596 folio_set_hugetlb_vmemmap_optimized(folio);
1598 arch_clear_hugetlb_flags(folio);
1599 enqueue_hugetlb_folio(h, folio);
1602 static void __update_and_free_hugetlb_folio(struct hstate *h,
1603 struct folio *folio)
1605 bool clear_flag = folio_test_hugetlb_vmemmap_optimized(folio);
1607 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
1611 * If we don't know which subpages are hwpoisoned, we can't free
1612 * the hugepage, so it's leaked intentionally.
1614 if (folio_test_hugetlb_raw_hwp_unreliable(folio))
1618 * If folio is not vmemmap optimized (!clear_flag), then the folio
1619 * is no longer identified as a hugetlb page. hugetlb_vmemmap_restore_folio
1620 * can only be passed hugetlb pages and will BUG otherwise.
1622 if (clear_flag && hugetlb_vmemmap_restore_folio(h, folio)) {
1623 spin_lock_irq(&hugetlb_lock);
1625 * If we cannot allocate vmemmap pages, just refuse to free the
1626 * page and put the page back on the hugetlb free list and treat
1627 * as a surplus page.
1629 add_hugetlb_folio(h, folio, true);
1630 spin_unlock_irq(&hugetlb_lock);
1635 * If vmemmap pages were allocated above, then we need to clear the
1636 * hugetlb flag under the hugetlb lock.
1638 if (folio_test_hugetlb(folio)) {
1639 spin_lock_irq(&hugetlb_lock);
1640 __folio_clear_hugetlb(folio);
1641 spin_unlock_irq(&hugetlb_lock);
1645 * Move PageHWPoison flag from head page to the raw error pages,
1646 * which makes any healthy subpages reusable.
1648 if (unlikely(folio_test_hwpoison(folio)))
1649 folio_clear_hugetlb_hwpoison(folio);
1651 folio_ref_unfreeze(folio, 1);
1653 hugetlb_free_folio(folio);
1657 * As update_and_free_hugetlb_folio() can be called under any context, so we cannot
1658 * use GFP_KERNEL to allocate vmemmap pages. However, we can defer the
1659 * actual freeing in a workqueue to prevent from using GFP_ATOMIC to allocate
1660 * the vmemmap pages.
1662 * free_hpage_workfn() locklessly retrieves the linked list of pages to be
1663 * freed and frees them one-by-one. As the page->mapping pointer is going
1664 * to be cleared in free_hpage_workfn() anyway, it is reused as the llist_node
1665 * structure of a lockless linked list of huge pages to be freed.
1667 static LLIST_HEAD(hpage_freelist);
1669 static void free_hpage_workfn(struct work_struct *work)
1671 struct llist_node *node;
1673 node = llist_del_all(&hpage_freelist);
1676 struct folio *folio;
1679 folio = container_of((struct address_space **)node,
1680 struct folio, mapping);
1682 folio->mapping = NULL;
1684 * The VM_BUG_ON_FOLIO(!folio_test_hugetlb(folio), folio) in
1685 * folio_hstate() is going to trigger because a previous call to
1686 * remove_hugetlb_folio() will clear the hugetlb bit, so do
1687 * not use folio_hstate() directly.
1689 h = size_to_hstate(folio_size(folio));
1691 __update_and_free_hugetlb_folio(h, folio);
1696 static DECLARE_WORK(free_hpage_work, free_hpage_workfn);
1698 static inline void flush_free_hpage_work(struct hstate *h)
1700 if (hugetlb_vmemmap_optimizable(h))
1701 flush_work(&free_hpage_work);
1704 static void update_and_free_hugetlb_folio(struct hstate *h, struct folio *folio,
1707 if (!folio_test_hugetlb_vmemmap_optimized(folio) || !atomic) {
1708 __update_and_free_hugetlb_folio(h, folio);
1713 * Defer freeing to avoid using GFP_ATOMIC to allocate vmemmap pages.
1715 * Only call schedule_work() if hpage_freelist is previously
1716 * empty. Otherwise, schedule_work() had been called but the workfn
1717 * hasn't retrieved the list yet.
1719 if (llist_add((struct llist_node *)&folio->mapping, &hpage_freelist))
1720 schedule_work(&free_hpage_work);
1723 static void bulk_vmemmap_restore_error(struct hstate *h,
1724 struct list_head *folio_list,
1725 struct list_head *non_hvo_folios)
1727 struct folio *folio, *t_folio;
1729 if (!list_empty(non_hvo_folios)) {
1731 * Free any restored hugetlb pages so that restore of the
1732 * entire list can be retried.
1733 * The idea is that in the common case of ENOMEM errors freeing
1734 * hugetlb pages with vmemmap we will free up memory so that we
1735 * can allocate vmemmap for more hugetlb pages.
1737 list_for_each_entry_safe(folio, t_folio, non_hvo_folios, lru) {
1738 list_del(&folio->lru);
1739 spin_lock_irq(&hugetlb_lock);
1740 __folio_clear_hugetlb(folio);
1741 spin_unlock_irq(&hugetlb_lock);
1742 update_and_free_hugetlb_folio(h, folio, false);
1747 * In the case where there are no folios which can be
1748 * immediately freed, we loop through the list trying to restore
1749 * vmemmap individually in the hope that someone elsewhere may
1750 * have done something to cause success (such as freeing some
1751 * memory). If unable to restore a hugetlb page, the hugetlb
1752 * page is made a surplus page and removed from the list.
1753 * If are able to restore vmemmap and free one hugetlb page, we
1754 * quit processing the list to retry the bulk operation.
1756 list_for_each_entry_safe(folio, t_folio, folio_list, lru)
1757 if (hugetlb_vmemmap_restore_folio(h, folio)) {
1758 list_del(&folio->lru);
1759 spin_lock_irq(&hugetlb_lock);
1760 add_hugetlb_folio(h, folio, true);
1761 spin_unlock_irq(&hugetlb_lock);
1763 list_del(&folio->lru);
1764 spin_lock_irq(&hugetlb_lock);
1765 __folio_clear_hugetlb(folio);
1766 spin_unlock_irq(&hugetlb_lock);
1767 update_and_free_hugetlb_folio(h, folio, false);
1774 static void update_and_free_pages_bulk(struct hstate *h,
1775 struct list_head *folio_list)
1778 struct folio *folio, *t_folio;
1779 LIST_HEAD(non_hvo_folios);
1782 * First allocate required vmemmmap (if necessary) for all folios.
1783 * Carefully handle errors and free up any available hugetlb pages
1784 * in an effort to make forward progress.
1787 ret = hugetlb_vmemmap_restore_folios(h, folio_list, &non_hvo_folios);
1789 bulk_vmemmap_restore_error(h, folio_list, &non_hvo_folios);
1794 * At this point, list should be empty, ret should be >= 0 and there
1795 * should only be pages on the non_hvo_folios list.
1796 * Do note that the non_hvo_folios list could be empty.
1797 * Without HVO enabled, ret will be 0 and there is no need to call
1798 * __folio_clear_hugetlb as this was done previously.
1800 VM_WARN_ON(!list_empty(folio_list));
1801 VM_WARN_ON(ret < 0);
1802 if (!list_empty(&non_hvo_folios) && ret) {
1803 spin_lock_irq(&hugetlb_lock);
1804 list_for_each_entry(folio, &non_hvo_folios, lru)
1805 __folio_clear_hugetlb(folio);
1806 spin_unlock_irq(&hugetlb_lock);
1809 list_for_each_entry_safe(folio, t_folio, &non_hvo_folios, lru) {
1810 update_and_free_hugetlb_folio(h, folio, false);
1815 struct hstate *size_to_hstate(unsigned long size)
1819 for_each_hstate(h) {
1820 if (huge_page_size(h) == size)
1826 void free_huge_folio(struct folio *folio)
1829 * Can't pass hstate in here because it is called from the
1832 struct hstate *h = folio_hstate(folio);
1833 int nid = folio_nid(folio);
1834 struct hugepage_subpool *spool = hugetlb_folio_subpool(folio);
1835 bool restore_reserve;
1836 unsigned long flags;
1838 VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
1839 VM_BUG_ON_FOLIO(folio_mapcount(folio), folio);
1841 hugetlb_set_folio_subpool(folio, NULL);
1842 if (folio_test_anon(folio))
1843 __ClearPageAnonExclusive(&folio->page);
1844 folio->mapping = NULL;
1845 restore_reserve = folio_test_hugetlb_restore_reserve(folio);
1846 folio_clear_hugetlb_restore_reserve(folio);
1849 * If HPageRestoreReserve was set on page, page allocation consumed a
1850 * reservation. If the page was associated with a subpool, there
1851 * would have been a page reserved in the subpool before allocation
1852 * via hugepage_subpool_get_pages(). Since we are 'restoring' the
1853 * reservation, do not call hugepage_subpool_put_pages() as this will
1854 * remove the reserved page from the subpool.
1856 if (!restore_reserve) {
1858 * A return code of zero implies that the subpool will be
1859 * under its minimum size if the reservation is not restored
1860 * after page is free. Therefore, force restore_reserve
1863 if (hugepage_subpool_put_pages(spool, 1) == 0)
1864 restore_reserve = true;
1867 spin_lock_irqsave(&hugetlb_lock, flags);
1868 folio_clear_hugetlb_migratable(folio);
1869 hugetlb_cgroup_uncharge_folio(hstate_index(h),
1870 pages_per_huge_page(h), folio);
1871 hugetlb_cgroup_uncharge_folio_rsvd(hstate_index(h),
1872 pages_per_huge_page(h), folio);
1873 lruvec_stat_mod_folio(folio, NR_HUGETLB, -pages_per_huge_page(h));
1874 mem_cgroup_uncharge(folio);
1875 if (restore_reserve)
1876 h->resv_huge_pages++;
1878 if (folio_test_hugetlb_temporary(folio)) {
1879 remove_hugetlb_folio(h, folio, false);
1880 spin_unlock_irqrestore(&hugetlb_lock, flags);
1881 update_and_free_hugetlb_folio(h, folio, true);
1882 } else if (h->surplus_huge_pages_node[nid]) {
1883 /* remove the page from active list */
1884 remove_hugetlb_folio(h, folio, true);
1885 spin_unlock_irqrestore(&hugetlb_lock, flags);
1886 update_and_free_hugetlb_folio(h, folio, true);
1888 arch_clear_hugetlb_flags(folio);
1889 enqueue_hugetlb_folio(h, folio);
1890 spin_unlock_irqrestore(&hugetlb_lock, flags);
1895 * Must be called with the hugetlb lock held
1897 static void __prep_account_new_huge_page(struct hstate *h, int nid)
1899 lockdep_assert_held(&hugetlb_lock);
1901 h->nr_huge_pages_node[nid]++;
1904 static void init_new_hugetlb_folio(struct hstate *h, struct folio *folio)
1906 __folio_set_hugetlb(folio);
1907 INIT_LIST_HEAD(&folio->lru);
1908 hugetlb_set_folio_subpool(folio, NULL);
1909 set_hugetlb_cgroup(folio, NULL);
1910 set_hugetlb_cgroup_rsvd(folio, NULL);
1913 static void __prep_new_hugetlb_folio(struct hstate *h, struct folio *folio)
1915 init_new_hugetlb_folio(h, folio);
1916 hugetlb_vmemmap_optimize_folio(h, folio);
1919 static void prep_new_hugetlb_folio(struct hstate *h, struct folio *folio, int nid)
1921 __prep_new_hugetlb_folio(h, folio);
1922 spin_lock_irq(&hugetlb_lock);
1923 __prep_account_new_huge_page(h, nid);
1924 spin_unlock_irq(&hugetlb_lock);
1928 * Find and lock address space (mapping) in write mode.
1930 * Upon entry, the folio is locked which means that folio_mapping() is
1931 * stable. Due to locking order, we can only trylock_write. If we can
1932 * not get the lock, simply return NULL to caller.
1934 struct address_space *hugetlb_folio_mapping_lock_write(struct folio *folio)
1936 struct address_space *mapping = folio_mapping(folio);
1941 if (i_mmap_trylock_write(mapping))
1947 static struct folio *alloc_buddy_hugetlb_folio(struct hstate *h,
1948 gfp_t gfp_mask, int nid, nodemask_t *nmask,
1949 nodemask_t *node_alloc_noretry)
1951 int order = huge_page_order(h);
1952 struct folio *folio;
1953 bool alloc_try_hard = true;
1956 * By default we always try hard to allocate the folio with
1957 * __GFP_RETRY_MAYFAIL flag. However, if we are allocating folios in
1958 * a loop (to adjust global huge page counts) and previous allocation
1959 * failed, do not continue to try hard on the same node. Use the
1960 * node_alloc_noretry bitmap to manage this state information.
1962 if (node_alloc_noretry && node_isset(nid, *node_alloc_noretry))
1963 alloc_try_hard = false;
1965 gfp_mask |= __GFP_RETRY_MAYFAIL;
1966 if (nid == NUMA_NO_NODE)
1967 nid = numa_mem_id();
1969 folio = (struct folio *)__alloc_frozen_pages(gfp_mask, order, nid, nmask);
1972 * If we did not specify __GFP_RETRY_MAYFAIL, but still got a
1973 * folio this indicates an overall state change. Clear bit so
1974 * that we resume normal 'try hard' allocations.
1976 if (node_alloc_noretry && folio && !alloc_try_hard)
1977 node_clear(nid, *node_alloc_noretry);
1980 * If we tried hard to get a folio but failed, set bit so that
1981 * subsequent attempts will not try as hard until there is an
1982 * overall state change.
1984 if (node_alloc_noretry && !folio && alloc_try_hard)
1985 node_set(nid, *node_alloc_noretry);
1988 __count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
1992 __count_vm_event(HTLB_BUDDY_PGALLOC);
1996 static struct folio *only_alloc_fresh_hugetlb_folio(struct hstate *h,
1997 gfp_t gfp_mask, int nid, nodemask_t *nmask,
1998 nodemask_t *node_alloc_noretry)
2000 struct folio *folio;
2002 if (hstate_is_gigantic(h))
2003 folio = alloc_gigantic_folio(h, gfp_mask, nid, nmask);
2005 folio = alloc_buddy_hugetlb_folio(h, gfp_mask, nid, nmask, node_alloc_noretry);
2007 init_new_hugetlb_folio(h, folio);
2012 * Common helper to allocate a fresh hugetlb page. All specific allocators
2013 * should use this function to get new hugetlb pages
2015 * Note that returned page is 'frozen': ref count of head page and all tail
2018 static struct folio *alloc_fresh_hugetlb_folio(struct hstate *h,
2019 gfp_t gfp_mask, int nid, nodemask_t *nmask)
2021 struct folio *folio;
2023 if (hstate_is_gigantic(h))
2024 folio = alloc_gigantic_folio(h, gfp_mask, nid, nmask);
2026 folio = alloc_buddy_hugetlb_folio(h, gfp_mask, nid, nmask, NULL);
2030 prep_new_hugetlb_folio(h, folio, folio_nid(folio));
2034 static void prep_and_add_allocated_folios(struct hstate *h,
2035 struct list_head *folio_list)
2037 unsigned long flags;
2038 struct folio *folio, *tmp_f;
2040 /* Send list for bulk vmemmap optimization processing */
2041 hugetlb_vmemmap_optimize_folios(h, folio_list);
2043 /* Add all new pool pages to free lists in one lock cycle */
2044 spin_lock_irqsave(&hugetlb_lock, flags);
2045 list_for_each_entry_safe(folio, tmp_f, folio_list, lru) {
2046 __prep_account_new_huge_page(h, folio_nid(folio));
2047 enqueue_hugetlb_folio(h, folio);
2049 spin_unlock_irqrestore(&hugetlb_lock, flags);
2053 * Allocates a fresh hugetlb page in a node interleaved manner. The page
2054 * will later be added to the appropriate hugetlb pool.
2056 static struct folio *alloc_pool_huge_folio(struct hstate *h,
2057 nodemask_t *nodes_allowed,
2058 nodemask_t *node_alloc_noretry,
2061 gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
2064 for_each_node_mask_to_alloc(next_node, nr_nodes, node, nodes_allowed) {
2065 struct folio *folio;
2067 folio = only_alloc_fresh_hugetlb_folio(h, gfp_mask, node,
2068 nodes_allowed, node_alloc_noretry);
2077 * Remove huge page from pool from next node to free. Attempt to keep
2078 * persistent huge pages more or less balanced over allowed nodes.
2079 * This routine only 'removes' the hugetlb page. The caller must make
2080 * an additional call to free the page to low level allocators.
2081 * Called with hugetlb_lock locked.
2083 static struct folio *remove_pool_hugetlb_folio(struct hstate *h,
2084 nodemask_t *nodes_allowed, bool acct_surplus)
2087 struct folio *folio = NULL;
2089 lockdep_assert_held(&hugetlb_lock);
2090 for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
2092 * If we're returning unused surplus pages, only examine
2093 * nodes with surplus pages.
2095 if ((!acct_surplus || h->surplus_huge_pages_node[node]) &&
2096 !list_empty(&h->hugepage_freelists[node])) {
2097 folio = list_entry(h->hugepage_freelists[node].next,
2099 remove_hugetlb_folio(h, folio, acct_surplus);
2108 * Dissolve a given free hugetlb folio into free buddy pages. This function
2109 * does nothing for in-use hugetlb folios and non-hugetlb folios.
2110 * This function returns values like below:
2112 * -ENOMEM: failed to allocate vmemmap pages to free the freed hugepages
2113 * when the system is under memory pressure and the feature of
2114 * freeing unused vmemmap pages associated with each hugetlb page
2116 * -EBUSY: failed to dissolved free hugepages or the hugepage is in-use
2117 * (allocated or reserved.)
2118 * 0: successfully dissolved free hugepages or the page is not a
2119 * hugepage (considered as already dissolved)
2121 int dissolve_free_hugetlb_folio(struct folio *folio)
2126 /* Not to disrupt normal path by vainly holding hugetlb_lock */
2127 if (!folio_test_hugetlb(folio))
2130 spin_lock_irq(&hugetlb_lock);
2131 if (!folio_test_hugetlb(folio)) {
2136 if (!folio_ref_count(folio)) {
2137 struct hstate *h = folio_hstate(folio);
2138 bool adjust_surplus = false;
2140 if (!available_huge_pages(h))
2144 * We should make sure that the page is already on the free list
2145 * when it is dissolved.
2147 if (unlikely(!folio_test_hugetlb_freed(folio))) {
2148 spin_unlock_irq(&hugetlb_lock);
2152 * Theoretically, we should return -EBUSY when we
2153 * encounter this race. In fact, we have a chance
2154 * to successfully dissolve the page if we do a
2155 * retry. Because the race window is quite small.
2156 * If we seize this opportunity, it is an optimization
2157 * for increasing the success rate of dissolving page.
2162 if (h->surplus_huge_pages_node[folio_nid(folio)])
2163 adjust_surplus = true;
2164 remove_hugetlb_folio(h, folio, adjust_surplus);
2165 h->max_huge_pages--;
2166 spin_unlock_irq(&hugetlb_lock);
2169 * Normally update_and_free_hugtlb_folio will allocate required vmemmmap
2170 * before freeing the page. update_and_free_hugtlb_folio will fail to
2171 * free the page if it can not allocate required vmemmap. We
2172 * need to adjust max_huge_pages if the page is not freed.
2173 * Attempt to allocate vmemmmap here so that we can take
2174 * appropriate action on failure.
2176 * The folio_test_hugetlb check here is because
2177 * remove_hugetlb_folio will clear hugetlb folio flag for
2178 * non-vmemmap optimized hugetlb folios.
2180 if (folio_test_hugetlb(folio)) {
2181 rc = hugetlb_vmemmap_restore_folio(h, folio);
2183 spin_lock_irq(&hugetlb_lock);
2184 add_hugetlb_folio(h, folio, adjust_surplus);
2185 h->max_huge_pages++;
2191 update_and_free_hugetlb_folio(h, folio, false);
2195 spin_unlock_irq(&hugetlb_lock);
2200 * Dissolve free hugepages in a given pfn range. Used by memory hotplug to
2201 * make specified memory blocks removable from the system.
2202 * Note that this will dissolve a free gigantic hugepage completely, if any
2203 * part of it lies within the given range.
2204 * Also note that if dissolve_free_hugetlb_folio() returns with an error, all
2205 * free hugetlb folios that were dissolved before that error are lost.
2207 int dissolve_free_hugetlb_folios(unsigned long start_pfn, unsigned long end_pfn)
2210 struct folio *folio;
2215 if (!hugepages_supported())
2218 order = huge_page_order(&default_hstate);
2220 order = min(order, huge_page_order(h));
2222 for (pfn = start_pfn; pfn < end_pfn; pfn += 1 << order) {
2223 folio = pfn_folio(pfn);
2224 rc = dissolve_free_hugetlb_folio(folio);
2233 * Allocates a fresh surplus page from the page allocator.
2235 static struct folio *alloc_surplus_hugetlb_folio(struct hstate *h,
2236 gfp_t gfp_mask, int nid, nodemask_t *nmask)
2238 struct folio *folio = NULL;
2240 if (hstate_is_gigantic(h))
2243 spin_lock_irq(&hugetlb_lock);
2244 if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages)
2246 spin_unlock_irq(&hugetlb_lock);
2248 folio = only_alloc_fresh_hugetlb_folio(h, gfp_mask, nid, nmask, NULL);
2252 hugetlb_vmemmap_optimize_folio(h, folio);
2254 spin_lock_irq(&hugetlb_lock);
2256 * nr_huge_pages needs to be adjusted within the same lock cycle
2257 * as surplus_pages, otherwise it might confuse
2258 * persistent_huge_pages() momentarily.
2260 __prep_account_new_huge_page(h, folio_nid(folio));
2263 * We could have raced with the pool size change.
2264 * Double check that and simply deallocate the new page
2265 * if we would end up overcommiting the surpluses. Abuse
2266 * temporary page to workaround the nasty free_huge_folio
2269 if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) {
2270 folio_set_hugetlb_temporary(folio);
2271 spin_unlock_irq(&hugetlb_lock);
2272 free_huge_folio(folio);
2276 h->surplus_huge_pages++;
2277 h->surplus_huge_pages_node[folio_nid(folio)]++;
2280 spin_unlock_irq(&hugetlb_lock);
2285 static struct folio *alloc_migrate_hugetlb_folio(struct hstate *h, gfp_t gfp_mask,
2286 int nid, nodemask_t *nmask)
2288 struct folio *folio;
2290 if (hstate_is_gigantic(h))
2293 folio = alloc_fresh_hugetlb_folio(h, gfp_mask, nid, nmask);
2297 /* fresh huge pages are frozen */
2298 folio_ref_unfreeze(folio, 1);
2300 * We do not account these pages as surplus because they are only
2301 * temporary and will be released properly on the last reference
2303 folio_set_hugetlb_temporary(folio);
2309 * Use the VMA's mpolicy to allocate a huge page from the buddy.
2312 struct folio *alloc_buddy_hugetlb_folio_with_mpol(struct hstate *h,
2313 struct vm_area_struct *vma, unsigned long addr)
2315 struct folio *folio = NULL;
2316 struct mempolicy *mpol;
2317 gfp_t gfp_mask = htlb_alloc_mask(h);
2319 nodemask_t *nodemask;
2321 nid = huge_node(vma, addr, gfp_mask, &mpol, &nodemask);
2322 if (mpol_is_preferred_many(mpol)) {
2323 gfp_t gfp = gfp_mask & ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
2325 folio = alloc_surplus_hugetlb_folio(h, gfp, nid, nodemask);
2327 /* Fallback to all nodes if page==NULL */
2332 folio = alloc_surplus_hugetlb_folio(h, gfp_mask, nid, nodemask);
2333 mpol_cond_put(mpol);
2337 struct folio *alloc_hugetlb_folio_reserve(struct hstate *h, int preferred_nid,
2338 nodemask_t *nmask, gfp_t gfp_mask)
2340 struct folio *folio;
2342 spin_lock_irq(&hugetlb_lock);
2343 if (!h->resv_huge_pages) {
2344 spin_unlock_irq(&hugetlb_lock);
2348 folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask, preferred_nid,
2351 h->resv_huge_pages--;
2353 spin_unlock_irq(&hugetlb_lock);
2357 /* folio migration callback function */
2358 struct folio *alloc_hugetlb_folio_nodemask(struct hstate *h, int preferred_nid,
2359 nodemask_t *nmask, gfp_t gfp_mask, bool allow_alloc_fallback)
2361 spin_lock_irq(&hugetlb_lock);
2362 if (available_huge_pages(h)) {
2363 struct folio *folio;
2365 folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask,
2366 preferred_nid, nmask);
2368 spin_unlock_irq(&hugetlb_lock);
2372 spin_unlock_irq(&hugetlb_lock);
2374 /* We cannot fallback to other nodes, as we could break the per-node pool. */
2375 if (!allow_alloc_fallback)
2376 gfp_mask |= __GFP_THISNODE;
2378 return alloc_migrate_hugetlb_folio(h, gfp_mask, preferred_nid, nmask);
2381 static nodemask_t *policy_mbind_nodemask(gfp_t gfp)
2384 struct mempolicy *mpol = get_task_policy(current);
2387 * Only enforce MPOL_BIND policy which overlaps with cpuset policy
2388 * (from policy_nodemask) specifically for hugetlb case
2390 if (mpol->mode == MPOL_BIND &&
2391 (apply_policy_zone(mpol, gfp_zone(gfp)) &&
2392 cpuset_nodemask_valid_mems_allowed(&mpol->nodes)))
2393 return &mpol->nodes;
2399 * Increase the hugetlb pool such that it can accommodate a reservation
2402 static int gather_surplus_pages(struct hstate *h, long delta)
2403 __must_hold(&hugetlb_lock)
2405 LIST_HEAD(surplus_list);
2406 struct folio *folio, *tmp;
2409 long needed, allocated;
2410 bool alloc_ok = true;
2411 nodemask_t *mbind_nodemask, alloc_nodemask;
2413 mbind_nodemask = policy_mbind_nodemask(htlb_alloc_mask(h));
2415 nodes_and(alloc_nodemask, *mbind_nodemask, cpuset_current_mems_allowed);
2417 alloc_nodemask = cpuset_current_mems_allowed;
2419 lockdep_assert_held(&hugetlb_lock);
2420 needed = (h->resv_huge_pages + delta) - h->free_huge_pages;
2422 h->resv_huge_pages += delta;
2430 spin_unlock_irq(&hugetlb_lock);
2431 for (i = 0; i < needed; i++) {
2435 * It is okay to use NUMA_NO_NODE because we use numa_mem_id()
2436 * down the road to pick the current node if that is the case.
2438 folio = alloc_surplus_hugetlb_folio(h, htlb_alloc_mask(h),
2439 NUMA_NO_NODE, &alloc_nodemask);
2444 list_add(&folio->lru, &surplus_list);
2450 * After retaking hugetlb_lock, we need to recalculate 'needed'
2451 * because either resv_huge_pages or free_huge_pages may have changed.
2453 spin_lock_irq(&hugetlb_lock);
2454 needed = (h->resv_huge_pages + delta) -
2455 (h->free_huge_pages + allocated);
2460 * We were not able to allocate enough pages to
2461 * satisfy the entire reservation so we free what
2462 * we've allocated so far.
2467 * The surplus_list now contains _at_least_ the number of extra pages
2468 * needed to accommodate the reservation. Add the appropriate number
2469 * of pages to the hugetlb pool and free the extras back to the buddy
2470 * allocator. Commit the entire reservation here to prevent another
2471 * process from stealing the pages as they are added to the pool but
2472 * before they are reserved.
2474 needed += allocated;
2475 h->resv_huge_pages += delta;
2478 /* Free the needed pages to the hugetlb pool */
2479 list_for_each_entry_safe(folio, tmp, &surplus_list, lru) {
2482 /* Add the page to the hugetlb allocator */
2483 enqueue_hugetlb_folio(h, folio);
2486 spin_unlock_irq(&hugetlb_lock);
2489 * Free unnecessary surplus pages to the buddy allocator.
2490 * Pages have no ref count, call free_huge_folio directly.
2492 list_for_each_entry_safe(folio, tmp, &surplus_list, lru)
2493 free_huge_folio(folio);
2494 spin_lock_irq(&hugetlb_lock);
2500 * This routine has two main purposes:
2501 * 1) Decrement the reservation count (resv_huge_pages) by the value passed
2502 * in unused_resv_pages. This corresponds to the prior adjustments made
2503 * to the associated reservation map.
2504 * 2) Free any unused surplus pages that may have been allocated to satisfy
2505 * the reservation. As many as unused_resv_pages may be freed.
2507 static void return_unused_surplus_pages(struct hstate *h,
2508 unsigned long unused_resv_pages)
2510 unsigned long nr_pages;
2511 LIST_HEAD(page_list);
2513 lockdep_assert_held(&hugetlb_lock);
2514 /* Uncommit the reservation */
2515 h->resv_huge_pages -= unused_resv_pages;
2517 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
2521 * Part (or even all) of the reservation could have been backed
2522 * by pre-allocated pages. Only free surplus pages.
2524 nr_pages = min(unused_resv_pages, h->surplus_huge_pages);
2527 * We want to release as many surplus pages as possible, spread
2528 * evenly across all nodes with memory. Iterate across these nodes
2529 * until we can no longer free unreserved surplus pages. This occurs
2530 * when the nodes with surplus pages have no free pages.
2531 * remove_pool_hugetlb_folio() will balance the freed pages across the
2532 * on-line nodes with memory and will handle the hstate accounting.
2534 while (nr_pages--) {
2535 struct folio *folio;
2537 folio = remove_pool_hugetlb_folio(h, &node_states[N_MEMORY], 1);
2541 list_add(&folio->lru, &page_list);
2545 spin_unlock_irq(&hugetlb_lock);
2546 update_and_free_pages_bulk(h, &page_list);
2547 spin_lock_irq(&hugetlb_lock);
2552 * vma_needs_reservation, vma_commit_reservation and vma_end_reservation
2553 * are used by the huge page allocation routines to manage reservations.
2555 * vma_needs_reservation is called to determine if the huge page at addr
2556 * within the vma has an associated reservation. If a reservation is
2557 * needed, the value 1 is returned. The caller is then responsible for
2558 * managing the global reservation and subpool usage counts. After
2559 * the huge page has been allocated, vma_commit_reservation is called
2560 * to add the page to the reservation map. If the page allocation fails,
2561 * the reservation must be ended instead of committed. vma_end_reservation
2562 * is called in such cases.
2564 * In the normal case, vma_commit_reservation returns the same value
2565 * as the preceding vma_needs_reservation call. The only time this
2566 * is not the case is if a reserve map was changed between calls. It
2567 * is the responsibility of the caller to notice the difference and
2568 * take appropriate action.
2570 * vma_add_reservation is used in error paths where a reservation must
2571 * be restored when a newly allocated huge page must be freed. It is
2572 * to be called after calling vma_needs_reservation to determine if a
2573 * reservation exists.
2575 * vma_del_reservation is used in error paths where an entry in the reserve
2576 * map was created during huge page allocation and must be removed. It is to
2577 * be called after calling vma_needs_reservation to determine if a reservation
2580 enum vma_resv_mode {
2587 static long __vma_reservation_common(struct hstate *h,
2588 struct vm_area_struct *vma, unsigned long addr,
2589 enum vma_resv_mode mode)
2591 struct resv_map *resv;
2594 long dummy_out_regions_needed;
2596 resv = vma_resv_map(vma);
2600 idx = vma_hugecache_offset(h, vma, addr);
2602 case VMA_NEEDS_RESV:
2603 ret = region_chg(resv, idx, idx + 1, &dummy_out_regions_needed);
2604 /* We assume that vma_reservation_* routines always operate on
2605 * 1 page, and that adding to resv map a 1 page entry can only
2606 * ever require 1 region.
2608 VM_BUG_ON(dummy_out_regions_needed != 1);
2610 case VMA_COMMIT_RESV:
2611 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2612 /* region_add calls of range 1 should never fail. */
2616 region_abort(resv, idx, idx + 1, 1);
2620 if (vma->vm_flags & VM_MAYSHARE) {
2621 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2622 /* region_add calls of range 1 should never fail. */
2625 region_abort(resv, idx, idx + 1, 1);
2626 ret = region_del(resv, idx, idx + 1);
2630 if (vma->vm_flags & VM_MAYSHARE) {
2631 region_abort(resv, idx, idx + 1, 1);
2632 ret = region_del(resv, idx, idx + 1);
2634 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2635 /* region_add calls of range 1 should never fail. */
2643 if (vma->vm_flags & VM_MAYSHARE || mode == VMA_DEL_RESV)
2646 * We know private mapping must have HPAGE_RESV_OWNER set.
2648 * In most cases, reserves always exist for private mappings.
2649 * However, a file associated with mapping could have been
2650 * hole punched or truncated after reserves were consumed.
2651 * As subsequent fault on such a range will not use reserves.
2652 * Subtle - The reserve map for private mappings has the
2653 * opposite meaning than that of shared mappings. If NO
2654 * entry is in the reserve map, it means a reservation exists.
2655 * If an entry exists in the reserve map, it means the
2656 * reservation has already been consumed. As a result, the
2657 * return value of this routine is the opposite of the
2658 * value returned from reserve map manipulation routines above.
2667 static long vma_needs_reservation(struct hstate *h,
2668 struct vm_area_struct *vma, unsigned long addr)
2670 return __vma_reservation_common(h, vma, addr, VMA_NEEDS_RESV);
2673 static long vma_commit_reservation(struct hstate *h,
2674 struct vm_area_struct *vma, unsigned long addr)
2676 return __vma_reservation_common(h, vma, addr, VMA_COMMIT_RESV);
2679 static void vma_end_reservation(struct hstate *h,
2680 struct vm_area_struct *vma, unsigned long addr)
2682 (void)__vma_reservation_common(h, vma, addr, VMA_END_RESV);
2685 static long vma_add_reservation(struct hstate *h,
2686 struct vm_area_struct *vma, unsigned long addr)
2688 return __vma_reservation_common(h, vma, addr, VMA_ADD_RESV);
2691 static long vma_del_reservation(struct hstate *h,
2692 struct vm_area_struct *vma, unsigned long addr)
2694 return __vma_reservation_common(h, vma, addr, VMA_DEL_RESV);
2698 * This routine is called to restore reservation information on error paths.
2699 * It should ONLY be called for folios allocated via alloc_hugetlb_folio(),
2700 * and the hugetlb mutex should remain held when calling this routine.
2702 * It handles two specific cases:
2703 * 1) A reservation was in place and the folio consumed the reservation.
2704 * hugetlb_restore_reserve is set in the folio.
2705 * 2) No reservation was in place for the page, so hugetlb_restore_reserve is
2706 * not set. However, alloc_hugetlb_folio always updates the reserve map.
2708 * In case 1, free_huge_folio later in the error path will increment the
2709 * global reserve count. But, free_huge_folio does not have enough context
2710 * to adjust the reservation map. This case deals primarily with private
2711 * mappings. Adjust the reserve map here to be consistent with global
2712 * reserve count adjustments to be made by free_huge_folio. Make sure the
2713 * reserve map indicates there is a reservation present.
2715 * In case 2, simply undo reserve map modifications done by alloc_hugetlb_folio.
2717 void restore_reserve_on_error(struct hstate *h, struct vm_area_struct *vma,
2718 unsigned long address, struct folio *folio)
2720 long rc = vma_needs_reservation(h, vma, address);
2722 if (folio_test_hugetlb_restore_reserve(folio)) {
2723 if (unlikely(rc < 0))
2725 * Rare out of memory condition in reserve map
2726 * manipulation. Clear hugetlb_restore_reserve so
2727 * that global reserve count will not be incremented
2728 * by free_huge_folio. This will make it appear
2729 * as though the reservation for this folio was
2730 * consumed. This may prevent the task from
2731 * faulting in the folio at a later time. This
2732 * is better than inconsistent global huge page
2733 * accounting of reserve counts.
2735 folio_clear_hugetlb_restore_reserve(folio);
2737 (void)vma_add_reservation(h, vma, address);
2739 vma_end_reservation(h, vma, address);
2743 * This indicates there is an entry in the reserve map
2744 * not added by alloc_hugetlb_folio. We know it was added
2745 * before the alloc_hugetlb_folio call, otherwise
2746 * hugetlb_restore_reserve would be set on the folio.
2747 * Remove the entry so that a subsequent allocation
2748 * does not consume a reservation.
2750 rc = vma_del_reservation(h, vma, address);
2753 * VERY rare out of memory condition. Since
2754 * we can not delete the entry, set
2755 * hugetlb_restore_reserve so that the reserve
2756 * count will be incremented when the folio
2757 * is freed. This reserve will be consumed
2758 * on a subsequent allocation.
2760 folio_set_hugetlb_restore_reserve(folio);
2761 } else if (rc < 0) {
2763 * Rare out of memory condition from
2764 * vma_needs_reservation call. Memory allocation is
2765 * only attempted if a new entry is needed. Therefore,
2766 * this implies there is not an entry in the
2769 * For shared mappings, no entry in the map indicates
2770 * no reservation. We are done.
2772 if (!(vma->vm_flags & VM_MAYSHARE))
2774 * For private mappings, no entry indicates
2775 * a reservation is present. Since we can
2776 * not add an entry, set hugetlb_restore_reserve
2777 * on the folio so reserve count will be
2778 * incremented when freed. This reserve will
2779 * be consumed on a subsequent allocation.
2781 folio_set_hugetlb_restore_reserve(folio);
2784 * No reservation present, do nothing
2786 vma_end_reservation(h, vma, address);
2791 * alloc_and_dissolve_hugetlb_folio - Allocate a new folio and dissolve
2793 * @old_folio: Old folio to dissolve
2794 * @list: List to isolate the page in case we need to
2795 * Returns 0 on success, otherwise negated error.
2797 static int alloc_and_dissolve_hugetlb_folio(struct folio *old_folio,
2798 struct list_head *list)
2802 int nid = folio_nid(old_folio);
2803 struct folio *new_folio = NULL;
2808 * The old_folio might have been dissolved from under our feet, so make sure
2809 * to carefully check the state under the lock.
2811 spin_lock_irq(&hugetlb_lock);
2812 if (!folio_test_hugetlb(old_folio)) {
2814 * Freed from under us. Drop new_folio too.
2817 } else if (folio_ref_count(old_folio)) {
2821 * Someone has grabbed the folio, try to isolate it here.
2822 * Fail with -EBUSY if not possible.
2824 spin_unlock_irq(&hugetlb_lock);
2825 isolated = folio_isolate_hugetlb(old_folio, list);
2826 ret = isolated ? 0 : -EBUSY;
2827 spin_lock_irq(&hugetlb_lock);
2829 } else if (!folio_test_hugetlb_freed(old_folio)) {
2831 * Folio's refcount is 0 but it has not been enqueued in the
2832 * freelist yet. Race window is small, so we can succeed here if
2835 spin_unlock_irq(&hugetlb_lock);
2839 h = folio_hstate(old_folio);
2841 spin_unlock_irq(&hugetlb_lock);
2842 gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
2843 new_folio = alloc_buddy_hugetlb_folio(h, gfp_mask, nid,
2847 __prep_new_hugetlb_folio(h, new_folio);
2852 * Ok, old_folio is still a genuine free hugepage. Remove it from
2853 * the freelist and decrease the counters. These will be
2854 * incremented again when calling __prep_account_new_huge_page()
2855 * and enqueue_hugetlb_folio() for new_folio. The counters will
2856 * remain stable since this happens under the lock.
2858 remove_hugetlb_folio(h, old_folio, false);
2861 * Ref count on new_folio is already zero as it was dropped
2862 * earlier. It can be directly added to the pool free list.
2864 __prep_account_new_huge_page(h, nid);
2865 enqueue_hugetlb_folio(h, new_folio);
2868 * Folio has been replaced, we can safely free the old one.
2870 spin_unlock_irq(&hugetlb_lock);
2871 update_and_free_hugetlb_folio(h, old_folio, false);
2877 spin_unlock_irq(&hugetlb_lock);
2879 update_and_free_hugetlb_folio(h, new_folio, false);
2884 int isolate_or_dissolve_huge_folio(struct folio *folio, struct list_head *list)
2888 /* Not to disrupt normal path by vainly holding hugetlb_lock */
2889 if (!folio_test_hugetlb(folio))
2893 * Fence off gigantic pages as there is a cyclic dependency between
2894 * alloc_contig_range and them. Return -ENOMEM as this has the effect
2895 * of bailing out right away without further retrying.
2897 if (folio_order(folio) > MAX_PAGE_ORDER)
2900 if (folio_ref_count(folio) && folio_isolate_hugetlb(folio, list))
2902 else if (!folio_ref_count(folio))
2903 ret = alloc_and_dissolve_hugetlb_folio(folio, list);
2909 * replace_free_hugepage_folios - Replace free hugepage folios in a given pfn
2910 * range with new folios.
2911 * @start_pfn: start pfn of the given pfn range
2912 * @end_pfn: end pfn of the given pfn range
2913 * Returns 0 on success, otherwise negated error.
2915 int replace_free_hugepage_folios(unsigned long start_pfn, unsigned long end_pfn)
2917 struct folio *folio;
2920 LIST_HEAD(isolate_list);
2922 while (start_pfn < end_pfn) {
2923 folio = pfn_folio(start_pfn);
2925 /* Not to disrupt normal path by vainly holding hugetlb_lock */
2926 if (folio_test_hugetlb(folio) && !folio_ref_count(folio)) {
2927 ret = alloc_and_dissolve_hugetlb_folio(folio, &isolate_list);
2931 putback_movable_pages(&isolate_list);
2939 void wait_for_freed_hugetlb_folios(void)
2941 if (llist_empty(&hpage_freelist))
2944 flush_work(&free_hpage_work);
2949 * For either 0/1: we checked the per-vma resv map, and one resv
2950 * count either can be reused (0), or an extra needed (1).
2955 * Cannot use per-vma resv count can be used, hence a new resv
2956 * count is enforced.
2958 * NOTE: This is mostly identical to MAP_CHG_NEEDED, except
2959 * that currently vma_needs_reservation() has an unwanted side
2960 * effect to either use end() or commit() to complete the
2961 * transaction. Hence it needs to differenciate from NEEDED.
2963 MAP_CHG_ENFORCED = 2,
2967 * NOTE! "cow_from_owner" represents a very hacky usage only used in CoW
2968 * faults of hugetlb private mappings on top of a non-page-cache folio (in
2969 * which case even if there's a private vma resv map it won't cover such
2970 * allocation). New call sites should (probably) never set it to true!!
2971 * When it's set, the allocation will bypass all vma level reservations.
2973 struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
2974 unsigned long addr, bool cow_from_owner)
2976 struct hugepage_subpool *spool = subpool_vma(vma);
2977 struct hstate *h = hstate_vma(vma);
2978 struct folio *folio;
2979 long retval, gbl_chg, gbl_reserve;
2980 map_chg_state map_chg;
2982 struct hugetlb_cgroup *h_cg = NULL;
2983 gfp_t gfp = htlb_alloc_mask(h) | __GFP_RETRY_MAYFAIL;
2985 idx = hstate_index(h);
2987 /* Whether we need a separate per-vma reservation? */
2988 if (cow_from_owner) {
2990 * Special case! Since it's a CoW on top of a reserved
2991 * page, the private resv map doesn't count. So it cannot
2992 * consume the per-vma resv map even if it's reserved.
2994 map_chg = MAP_CHG_ENFORCED;
2997 * Examine the region/reserve map to determine if the process
2998 * has a reservation for the page to be allocated. A return
2999 * code of zero indicates a reservation exists (no change).
3001 retval = vma_needs_reservation(h, vma, addr);
3003 return ERR_PTR(-ENOMEM);
3004 map_chg = retval ? MAP_CHG_NEEDED : MAP_CHG_REUSE;
3008 * Whether we need a separate global reservation?
3010 * Processes that did not create the mapping will have no
3011 * reserves as indicated by the region/reserve map. Check
3012 * that the allocation will not exceed the subpool limit.
3013 * Or if it can get one from the pool reservation directly.
3016 gbl_chg = hugepage_subpool_get_pages(spool, 1);
3018 goto out_end_reservation;
3021 * If we have the vma reservation ready, no need for extra
3022 * global reservation.
3028 * If this allocation is not consuming a per-vma reservation,
3029 * charge the hugetlb cgroup now.
3032 ret = hugetlb_cgroup_charge_cgroup_rsvd(
3033 idx, pages_per_huge_page(h), &h_cg);
3035 goto out_subpool_put;
3038 ret = hugetlb_cgroup_charge_cgroup(idx, pages_per_huge_page(h), &h_cg);
3040 goto out_uncharge_cgroup_reservation;
3042 spin_lock_irq(&hugetlb_lock);
3044 * glb_chg is passed to indicate whether or not a page must be taken
3045 * from the global free pool (global change). gbl_chg == 0 indicates
3046 * a reservation exists for the allocation.
3048 folio = dequeue_hugetlb_folio_vma(h, vma, addr, gbl_chg);
3050 spin_unlock_irq(&hugetlb_lock);
3051 folio = alloc_buddy_hugetlb_folio_with_mpol(h, vma, addr);
3053 goto out_uncharge_cgroup;
3054 spin_lock_irq(&hugetlb_lock);
3055 list_add(&folio->lru, &h->hugepage_activelist);
3056 folio_ref_unfreeze(folio, 1);
3061 * Either dequeued or buddy-allocated folio needs to add special
3062 * mark to the folio when it consumes a global reservation.
3065 folio_set_hugetlb_restore_reserve(folio);
3066 h->resv_huge_pages--;
3069 hugetlb_cgroup_commit_charge(idx, pages_per_huge_page(h), h_cg, folio);
3070 /* If allocation is not consuming a reservation, also store the
3071 * hugetlb_cgroup pointer on the page.
3074 hugetlb_cgroup_commit_charge_rsvd(idx, pages_per_huge_page(h),
3078 spin_unlock_irq(&hugetlb_lock);
3080 hugetlb_set_folio_subpool(folio, spool);
3082 if (map_chg != MAP_CHG_ENFORCED) {
3083 /* commit() is only needed if the map_chg is not enforced */
3084 retval = vma_commit_reservation(h, vma, addr);
3086 * Check for possible race conditions. When it happens..
3087 * The page was added to the reservation map between
3088 * vma_needs_reservation and vma_commit_reservation.
3089 * This indicates a race with hugetlb_reserve_pages.
3090 * Adjust for the subpool count incremented above AND
3091 * in hugetlb_reserve_pages for the same page. Also,
3092 * the reservation count added in hugetlb_reserve_pages
3093 * no longer applies.
3095 if (unlikely(map_chg == MAP_CHG_NEEDED && retval == 0)) {
3098 rsv_adjust = hugepage_subpool_put_pages(spool, 1);
3099 hugetlb_acct_memory(h, -rsv_adjust);
3101 spin_lock_irq(&hugetlb_lock);
3102 hugetlb_cgroup_uncharge_folio_rsvd(
3103 hstate_index(h), pages_per_huge_page(h),
3105 spin_unlock_irq(&hugetlb_lock);
3110 ret = mem_cgroup_charge_hugetlb(folio, gfp);
3112 * Unconditionally increment NR_HUGETLB here. If it turns out that
3113 * mem_cgroup_charge_hugetlb failed, then immediately free the page and
3114 * decrement NR_HUGETLB.
3116 lruvec_stat_mod_folio(folio, NR_HUGETLB, pages_per_huge_page(h));
3118 if (ret == -ENOMEM) {
3119 free_huge_folio(folio);
3120 return ERR_PTR(-ENOMEM);
3125 out_uncharge_cgroup:
3126 hugetlb_cgroup_uncharge_cgroup(idx, pages_per_huge_page(h), h_cg);
3127 out_uncharge_cgroup_reservation:
3129 hugetlb_cgroup_uncharge_cgroup_rsvd(idx, pages_per_huge_page(h),
3133 * put page to subpool iff the quota of subpool's rsv_hpages is used
3134 * during hugepage_subpool_get_pages.
3136 if (map_chg && !gbl_chg) {
3137 gbl_reserve = hugepage_subpool_put_pages(spool, 1);
3138 hugetlb_acct_memory(h, -gbl_reserve);
3142 out_end_reservation:
3143 if (map_chg != MAP_CHG_ENFORCED)
3144 vma_end_reservation(h, vma, addr);
3145 return ERR_PTR(-ENOSPC);
3148 static __init void *alloc_bootmem(struct hstate *h, int nid, bool node_exact)
3150 struct huge_bootmem_page *m;
3153 if (hugetlb_early_cma(h))
3154 m = hugetlb_cma_alloc_bootmem(h, &listnode, node_exact);
3157 m = memblock_alloc_exact_nid_raw(huge_page_size(h),
3158 huge_page_size(h), 0,
3159 MEMBLOCK_ALLOC_ACCESSIBLE, nid);
3161 m = memblock_alloc_try_nid_raw(huge_page_size(h),
3162 huge_page_size(h), 0,
3163 MEMBLOCK_ALLOC_ACCESSIBLE, nid);
3165 * For pre-HVO to work correctly, pages need to be on
3166 * the list for the node they were actually allocated
3167 * from. That node may be different in the case of
3168 * fallback by memblock_alloc_try_nid_raw. So,
3169 * extract the actual node first.
3172 listnode = early_pfn_to_nid(PHYS_PFN(virt_to_phys(m)));
3183 * Use the beginning of the huge page to store the
3184 * huge_bootmem_page struct (until gather_bootmem
3185 * puts them into the mem_map).
3187 * Put them into a private list first because mem_map
3190 INIT_LIST_HEAD(&m->list);
3191 list_add(&m->list, &huge_boot_pages[listnode]);
3198 int alloc_bootmem_huge_page(struct hstate *h, int nid)
3199 __attribute__ ((weak, alias("__alloc_bootmem_huge_page")));
3200 int __alloc_bootmem_huge_page(struct hstate *h, int nid)
3202 struct huge_bootmem_page *m = NULL; /* initialize for clang */
3203 int nr_nodes, node = nid;
3205 /* do node specific alloc */
3206 if (nid != NUMA_NO_NODE) {
3207 m = alloc_bootmem(h, node, true);
3213 /* allocate from next node when distributing huge pages */
3214 for_each_node_mask_to_alloc(&h->next_nid_to_alloc, nr_nodes, node,
3215 &hugetlb_bootmem_nodes) {
3216 m = alloc_bootmem(h, node, false);
3225 * Only initialize the head struct page in memmap_init_reserved_pages,
3226 * rest of the struct pages will be initialized by the HugeTLB
3228 * The head struct page is used to get folio information by the HugeTLB
3229 * subsystem like zone id and node id.
3231 memblock_reserved_mark_noinit(virt_to_phys((void *)m + PAGE_SIZE),
3232 huge_page_size(h) - PAGE_SIZE);
3237 /* Initialize [start_page:end_page_number] tail struct pages of a hugepage */
3238 static void __init hugetlb_folio_init_tail_vmemmap(struct folio *folio,
3239 unsigned long start_page_number,
3240 unsigned long end_page_number)
3242 enum zone_type zone = zone_idx(folio_zone(folio));
3243 int nid = folio_nid(folio);
3244 unsigned long head_pfn = folio_pfn(folio);
3245 unsigned long pfn, end_pfn = head_pfn + end_page_number;
3248 for (pfn = head_pfn + start_page_number; pfn < end_pfn; pfn++) {
3249 struct page *page = pfn_to_page(pfn);
3251 __init_single_page(page, pfn, zone, nid);
3252 prep_compound_tail((struct page *)folio, pfn - head_pfn);
3253 ret = page_ref_freeze(page, 1);
3258 static void __init hugetlb_folio_init_vmemmap(struct folio *folio,
3260 unsigned long nr_pages)
3264 /* Prepare folio head */
3265 __folio_clear_reserved(folio);
3266 __folio_set_head(folio);
3267 ret = folio_ref_freeze(folio, 1);
3269 /* Initialize the necessary tail struct pages */
3270 hugetlb_folio_init_tail_vmemmap(folio, 1, nr_pages);
3271 prep_compound_head((struct page *)folio, huge_page_order(h));
3274 static bool __init hugetlb_bootmem_page_prehvo(struct huge_bootmem_page *m)
3276 return m->flags & HUGE_BOOTMEM_HVO;
3279 static bool __init hugetlb_bootmem_page_earlycma(struct huge_bootmem_page *m)
3281 return m->flags & HUGE_BOOTMEM_CMA;
3285 * memblock-allocated pageblocks might not have the migrate type set
3286 * if marked with the 'noinit' flag. Set it to the default (MIGRATE_MOVABLE)
3287 * here, or MIGRATE_CMA if this was a page allocated through an early CMA
3290 * In case of vmemmap optimized folios, the tail vmemmap pages are mapped
3291 * read-only, but that's ok - for sparse vmemmap this does not write to
3292 * the page structure.
3294 static void __init hugetlb_bootmem_init_migratetype(struct folio *folio,
3297 unsigned long nr_pages = pages_per_huge_page(h), i;
3299 WARN_ON_ONCE(!pageblock_aligned(folio_pfn(folio)));
3301 for (i = 0; i < nr_pages; i += pageblock_nr_pages) {
3302 if (folio_test_hugetlb_cma(folio))
3303 init_cma_pageblock(folio_page(folio, i));
3305 set_pageblock_migratetype(folio_page(folio, i),
3310 static void __init prep_and_add_bootmem_folios(struct hstate *h,
3311 struct list_head *folio_list)
3313 unsigned long flags;
3314 struct folio *folio, *tmp_f;
3316 /* Send list for bulk vmemmap optimization processing */
3317 hugetlb_vmemmap_optimize_bootmem_folios(h, folio_list);
3319 list_for_each_entry_safe(folio, tmp_f, folio_list, lru) {
3320 if (!folio_test_hugetlb_vmemmap_optimized(folio)) {
3322 * If HVO fails, initialize all tail struct pages
3323 * We do not worry about potential long lock hold
3324 * time as this is early in boot and there should
3327 hugetlb_folio_init_tail_vmemmap(folio,
3328 HUGETLB_VMEMMAP_RESERVE_PAGES,
3329 pages_per_huge_page(h));
3331 hugetlb_bootmem_init_migratetype(folio, h);
3332 /* Subdivide locks to achieve better parallel performance */
3333 spin_lock_irqsave(&hugetlb_lock, flags);
3334 __prep_account_new_huge_page(h, folio_nid(folio));
3335 enqueue_hugetlb_folio(h, folio);
3336 spin_unlock_irqrestore(&hugetlb_lock, flags);
3340 bool __init hugetlb_bootmem_page_zones_valid(int nid,
3341 struct huge_bootmem_page *m)
3343 unsigned long start_pfn;
3346 if (m->flags & HUGE_BOOTMEM_ZONES_VALID) {
3348 * Already validated, skip check.
3353 if (hugetlb_bootmem_page_earlycma(m)) {
3354 valid = cma_validate_zones(m->cma);
3358 start_pfn = virt_to_phys(m) >> PAGE_SHIFT;
3360 valid = !pfn_range_intersects_zones(nid, start_pfn,
3361 pages_per_huge_page(m->hstate));
3364 hstate_boot_nrinvalid[hstate_index(m->hstate)]++;
3370 * Free a bootmem page that was found to be invalid (intersecting with
3373 * Since it intersects with multiple zones, we can't just do a free
3374 * operation on all pages at once, but instead have to walk all
3375 * pages, freeing them one by one.
3377 static void __init hugetlb_bootmem_free_invalid_page(int nid, struct page *page,
3380 unsigned long npages = pages_per_huge_page(h);
3384 pfn = page_to_pfn(page);
3385 __init_page_from_nid(pfn, nid);
3386 free_reserved_page(page);
3392 * Put bootmem huge pages into the standard lists after mem_map is up.
3393 * Note: This only applies to gigantic (order > MAX_PAGE_ORDER) pages.
3395 static void __init gather_bootmem_prealloc_node(unsigned long nid)
3397 LIST_HEAD(folio_list);
3398 struct huge_bootmem_page *m, *tm;
3399 struct hstate *h = NULL, *prev_h = NULL;
3401 list_for_each_entry_safe(m, tm, &huge_boot_pages[nid], list) {
3402 struct page *page = virt_to_page(m);
3403 struct folio *folio = (void *)page;
3406 if (!hugetlb_bootmem_page_zones_valid(nid, m)) {
3408 * Can't use this page. Initialize the
3409 * page structures if that hasn't already
3410 * been done, and give them to the page
3413 hugetlb_bootmem_free_invalid_page(nid, page, h);
3418 * It is possible to have multiple huge page sizes (hstates)
3419 * in this list. If so, process each size separately.
3421 if (h != prev_h && prev_h != NULL)
3422 prep_and_add_bootmem_folios(prev_h, &folio_list);
3425 VM_BUG_ON(!hstate_is_gigantic(h));
3426 WARN_ON(folio_ref_count(folio) != 1);
3428 hugetlb_folio_init_vmemmap(folio, h,
3429 HUGETLB_VMEMMAP_RESERVE_PAGES);
3430 init_new_hugetlb_folio(h, folio);
3432 if (hugetlb_bootmem_page_prehvo(m))
3434 * If pre-HVO was done, just set the
3435 * flag, the HVO code will then skip
3438 folio_set_hugetlb_vmemmap_optimized(folio);
3440 if (hugetlb_bootmem_page_earlycma(m))
3441 folio_set_hugetlb_cma(folio);
3443 list_add(&folio->lru, &folio_list);
3446 * We need to restore the 'stolen' pages to totalram_pages
3447 * in order to fix confusing memory reports from free(1) and
3448 * other side-effects, like CommitLimit going negative.
3450 * For CMA pages, this is done in init_cma_pageblock
3451 * (via hugetlb_bootmem_init_migratetype), so skip it here.
3453 if (!folio_test_hugetlb_cma(folio))
3454 adjust_managed_page_count(page, pages_per_huge_page(h));
3458 prep_and_add_bootmem_folios(h, &folio_list);
3461 static void __init gather_bootmem_prealloc_parallel(unsigned long start,
3462 unsigned long end, void *arg)
3466 for (nid = start; nid < end; nid++)
3467 gather_bootmem_prealloc_node(nid);
3470 static void __init gather_bootmem_prealloc(void)
3472 struct padata_mt_job job = {
3473 .thread_fn = gather_bootmem_prealloc_parallel,
3476 .size = nr_node_ids,
3479 .max_threads = num_node_state(N_MEMORY),
3483 padata_do_multithreaded(&job);
3486 static void __init hugetlb_hstate_alloc_pages_onenode(struct hstate *h, int nid)
3490 LIST_HEAD(folio_list);
3492 for (i = 0; i < h->max_huge_pages_node[nid]; ++i) {
3493 if (hstate_is_gigantic(h)) {
3494 if (!alloc_bootmem_huge_page(h, nid))
3497 struct folio *folio;
3498 gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
3500 folio = only_alloc_fresh_hugetlb_folio(h, gfp_mask, nid,
3501 &node_states[N_MEMORY], NULL);
3504 list_add(&folio->lru, &folio_list);
3509 if (!list_empty(&folio_list))
3510 prep_and_add_allocated_folios(h, &folio_list);
3512 if (i == h->max_huge_pages_node[nid])
3515 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
3516 pr_warn("HugeTLB: allocating %u of page size %s failed node%d. Only allocated %lu hugepages.\n",
3517 h->max_huge_pages_node[nid], buf, nid, i);
3518 h->max_huge_pages -= (h->max_huge_pages_node[nid] - i);
3519 h->max_huge_pages_node[nid] = i;
3522 static bool __init hugetlb_hstate_alloc_pages_specific_nodes(struct hstate *h)
3525 bool node_specific_alloc = false;
3527 for_each_online_node(i) {
3528 if (h->max_huge_pages_node[i] > 0) {
3529 hugetlb_hstate_alloc_pages_onenode(h, i);
3530 node_specific_alloc = true;
3534 return node_specific_alloc;
3537 static void __init hugetlb_hstate_alloc_pages_errcheck(unsigned long allocated, struct hstate *h)
3539 if (allocated < h->max_huge_pages) {
3542 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
3543 pr_warn("HugeTLB: allocating %lu of page size %s failed. Only allocated %lu hugepages.\n",
3544 h->max_huge_pages, buf, allocated);
3545 h->max_huge_pages = allocated;
3549 static void __init hugetlb_pages_alloc_boot_node(unsigned long start, unsigned long end, void *arg)
3551 struct hstate *h = (struct hstate *)arg;
3552 int i, num = end - start;
3553 nodemask_t node_alloc_noretry;
3554 LIST_HEAD(folio_list);
3555 int next_node = first_online_node;
3557 /* Bit mask controlling how hard we retry per-node allocations.*/
3558 nodes_clear(node_alloc_noretry);
3560 for (i = 0; i < num; ++i) {
3561 struct folio *folio = alloc_pool_huge_folio(h, &node_states[N_MEMORY],
3562 &node_alloc_noretry, &next_node);
3566 list_move(&folio->lru, &folio_list);
3570 prep_and_add_allocated_folios(h, &folio_list);
3573 static unsigned long __init hugetlb_gigantic_pages_alloc_boot(struct hstate *h)
3577 for (i = 0; i < h->max_huge_pages; ++i) {
3578 if (!alloc_bootmem_huge_page(h, NUMA_NO_NODE))
3586 static unsigned long __init hugetlb_pages_alloc_boot(struct hstate *h)
3588 struct padata_mt_job job = {
3594 unsigned long jiffies_start;
3595 unsigned long jiffies_end;
3597 job.thread_fn = hugetlb_pages_alloc_boot_node;
3599 job.size = h->max_huge_pages;
3602 * job.max_threads is 25% of the available cpu threads by default.
3604 * On large servers with terabytes of memory, huge page allocation
3605 * can consume a considerably amount of time.
3607 * Tests below show how long it takes to allocate 1 TiB of memory with 2MiB huge pages.
3608 * 2MiB huge pages. Using more threads can significantly improve allocation time.
3610 * +-----------------------+-------+-------+-------+-------+-------+
3611 * | threads | 8 | 16 | 32 | 64 | 128 |
3612 * +-----------------------+-------+-------+-------+-------+-------+
3613 * | skylake 144 cpus | 44s | 22s | 16s | 19s | 20s |
3614 * | cascade lake 192 cpus | 39s | 20s | 11s | 10s | 9s |
3615 * +-----------------------+-------+-------+-------+-------+-------+
3617 if (hugepage_allocation_threads == 0) {
3618 hugepage_allocation_threads = num_online_cpus() / 4;
3619 hugepage_allocation_threads = max(hugepage_allocation_threads, 1);
3622 job.max_threads = hugepage_allocation_threads;
3623 job.min_chunk = h->max_huge_pages / hugepage_allocation_threads;
3625 jiffies_start = jiffies;
3626 padata_do_multithreaded(&job);
3627 jiffies_end = jiffies;
3629 pr_info("HugeTLB: allocation took %dms with hugepage_allocation_threads=%ld\n",
3630 jiffies_to_msecs(jiffies_end - jiffies_start),
3631 hugepage_allocation_threads);
3633 return h->nr_huge_pages;
3637 * NOTE: this routine is called in different contexts for gigantic and
3638 * non-gigantic pages.
3639 * - For gigantic pages, this is called early in the boot process and
3640 * pages are allocated from memblock allocated or something similar.
3641 * Gigantic pages are actually added to pools later with the routine
3642 * gather_bootmem_prealloc.
3643 * - For non-gigantic pages, this is called later in the boot process after
3644 * all of mm is up and functional. Pages are allocated from buddy and
3645 * then added to hugetlb pools.
3647 static void __init hugetlb_hstate_alloc_pages(struct hstate *h)
3649 unsigned long allocated;
3652 * Skip gigantic hugepages allocation if early CMA
3653 * reservations are not available.
3655 if (hstate_is_gigantic(h) && hugetlb_cma_total_size() &&
3656 !hugetlb_early_cma(h)) {
3657 pr_warn_once("HugeTLB: hugetlb_cma is enabled, skip boot time allocation\n");
3661 /* do node specific alloc */
3662 if (hugetlb_hstate_alloc_pages_specific_nodes(h))
3665 /* below will do all node balanced alloc */
3666 if (hstate_is_gigantic(h))
3667 allocated = hugetlb_gigantic_pages_alloc_boot(h);
3669 allocated = hugetlb_pages_alloc_boot(h);
3671 hugetlb_hstate_alloc_pages_errcheck(allocated, h);
3674 static void __init hugetlb_init_hstates(void)
3676 struct hstate *h, *h2;
3678 for_each_hstate(h) {
3680 * Always reset to first_memory_node here, even if
3681 * next_nid_to_alloc was set before - we can't
3682 * reference hugetlb_bootmem_nodes after init, and
3683 * first_memory_node is right for all further allocations.
3685 h->next_nid_to_alloc = first_memory_node;
3686 h->next_nid_to_free = first_memory_node;
3688 /* oversize hugepages were init'ed in early boot */
3689 if (!hstate_is_gigantic(h))
3690 hugetlb_hstate_alloc_pages(h);
3693 * Set demote order for each hstate. Note that
3694 * h->demote_order is initially 0.
3695 * - We can not demote gigantic pages if runtime freeing
3696 * is not supported, so skip this.
3697 * - If CMA allocation is possible, we can not demote
3698 * HUGETLB_PAGE_ORDER or smaller size pages.
3700 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
3702 if (hugetlb_cma_total_size() && h->order <= HUGETLB_PAGE_ORDER)
3704 for_each_hstate(h2) {
3707 if (h2->order < h->order &&
3708 h2->order > h->demote_order)
3709 h->demote_order = h2->order;
3714 static void __init report_hugepages(void)
3717 unsigned long nrinvalid;
3719 for_each_hstate(h) {
3722 nrinvalid = hstate_boot_nrinvalid[hstate_index(h)];
3723 h->max_huge_pages -= nrinvalid;
3725 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
3726 pr_info("HugeTLB: registered %s page size, pre-allocated %ld pages\n",
3727 buf, h->nr_huge_pages);
3729 pr_info("HugeTLB: %s page size: %lu invalid page%s discarded\n",
3730 buf, nrinvalid, nrinvalid > 1 ? "s" : "");
3731 pr_info("HugeTLB: %d KiB vmemmap can be freed for a %s page\n",
3732 hugetlb_vmemmap_optimizable_size(h) / SZ_1K, buf);
3736 #ifdef CONFIG_HIGHMEM
3737 static void try_to_free_low(struct hstate *h, unsigned long count,
3738 nodemask_t *nodes_allowed)
3741 LIST_HEAD(page_list);
3743 lockdep_assert_held(&hugetlb_lock);
3744 if (hstate_is_gigantic(h))
3748 * Collect pages to be freed on a list, and free after dropping lock
3750 for_each_node_mask(i, *nodes_allowed) {
3751 struct folio *folio, *next;
3752 struct list_head *freel = &h->hugepage_freelists[i];
3753 list_for_each_entry_safe(folio, next, freel, lru) {
3754 if (count >= h->nr_huge_pages)
3756 if (folio_test_highmem(folio))
3758 remove_hugetlb_folio(h, folio, false);
3759 list_add(&folio->lru, &page_list);
3764 spin_unlock_irq(&hugetlb_lock);
3765 update_and_free_pages_bulk(h, &page_list);
3766 spin_lock_irq(&hugetlb_lock);
3769 static inline void try_to_free_low(struct hstate *h, unsigned long count,
3770 nodemask_t *nodes_allowed)
3776 * Increment or decrement surplus_huge_pages. Keep node-specific counters
3777 * balanced by operating on them in a round-robin fashion.
3778 * Returns 1 if an adjustment was made.
3780 static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed,
3785 lockdep_assert_held(&hugetlb_lock);
3786 VM_BUG_ON(delta != -1 && delta != 1);
3789 for_each_node_mask_to_alloc(&h->next_nid_to_alloc, nr_nodes, node, nodes_allowed) {
3790 if (h->surplus_huge_pages_node[node])
3794 for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
3795 if (h->surplus_huge_pages_node[node] <
3796 h->nr_huge_pages_node[node])
3803 h->surplus_huge_pages += delta;
3804 h->surplus_huge_pages_node[node] += delta;
3808 #define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages)
3809 static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,
3810 nodemask_t *nodes_allowed)
3812 unsigned long persistent_free_count;
3813 unsigned long min_count;
3814 unsigned long allocated;
3815 struct folio *folio;
3816 LIST_HEAD(page_list);
3817 NODEMASK_ALLOC(nodemask_t, node_alloc_noretry, GFP_KERNEL);
3820 * Bit mask controlling how hard we retry per-node allocations.
3821 * If we can not allocate the bit mask, do not attempt to allocate
3822 * the requested huge pages.
3824 if (node_alloc_noretry)
3825 nodes_clear(*node_alloc_noretry);
3830 * resize_lock mutex prevents concurrent adjustments to number of
3831 * pages in hstate via the proc/sysfs interfaces.
3833 mutex_lock(&h->resize_lock);
3834 flush_free_hpage_work(h);
3835 spin_lock_irq(&hugetlb_lock);
3838 * Check for a node specific request.
3839 * Changing node specific huge page count may require a corresponding
3840 * change to the global count. In any case, the passed node mask
3841 * (nodes_allowed) will restrict alloc/free to the specified node.
3843 if (nid != NUMA_NO_NODE) {
3844 unsigned long old_count = count;
3846 count += persistent_huge_pages(h) -
3847 (h->nr_huge_pages_node[nid] -
3848 h->surplus_huge_pages_node[nid]);
3850 * User may have specified a large count value which caused the
3851 * above calculation to overflow. In this case, they wanted
3852 * to allocate as many huge pages as possible. Set count to
3853 * largest possible value to align with their intention.
3855 if (count < old_count)
3860 * Gigantic pages runtime allocation depend on the capability for large
3861 * page range allocation.
3862 * If the system does not provide this feature, return an error when
3863 * the user tries to allocate gigantic pages but let the user free the
3864 * boottime allocated gigantic pages.
3866 if (hstate_is_gigantic(h) && !IS_ENABLED(CONFIG_CONTIG_ALLOC)) {
3867 if (count > persistent_huge_pages(h)) {
3868 spin_unlock_irq(&hugetlb_lock);
3869 mutex_unlock(&h->resize_lock);
3870 NODEMASK_FREE(node_alloc_noretry);
3873 /* Fall through to decrease pool */
3877 * Increase the pool size
3878 * First take pages out of surplus state. Then make up the
3879 * remaining difference by allocating fresh huge pages.
3881 * We might race with alloc_surplus_hugetlb_folio() here and be unable
3882 * to convert a surplus huge page to a normal huge page. That is
3883 * not critical, though, it just means the overall size of the
3884 * pool might be one hugepage larger than it needs to be, but
3885 * within all the constraints specified by the sysctls.
3887 while (h->surplus_huge_pages && count > persistent_huge_pages(h)) {
3888 if (!adjust_pool_surplus(h, nodes_allowed, -1))
3893 while (count > (persistent_huge_pages(h) + allocated)) {
3895 * If this allocation races such that we no longer need the
3896 * page, free_huge_folio will handle it by freeing the page
3897 * and reducing the surplus.
3899 spin_unlock_irq(&hugetlb_lock);
3901 /* yield cpu to avoid soft lockup */
3904 folio = alloc_pool_huge_folio(h, nodes_allowed,
3906 &h->next_nid_to_alloc);
3908 prep_and_add_allocated_folios(h, &page_list);
3909 spin_lock_irq(&hugetlb_lock);
3913 list_add(&folio->lru, &page_list);
3916 /* Bail for signals. Probably ctrl-c from user */
3917 if (signal_pending(current)) {
3918 prep_and_add_allocated_folios(h, &page_list);
3919 spin_lock_irq(&hugetlb_lock);
3923 spin_lock_irq(&hugetlb_lock);
3926 /* Add allocated pages to the pool */
3927 if (!list_empty(&page_list)) {
3928 spin_unlock_irq(&hugetlb_lock);
3929 prep_and_add_allocated_folios(h, &page_list);
3930 spin_lock_irq(&hugetlb_lock);
3934 * Decrease the pool size
3935 * First return free pages to the buddy allocator (being careful
3936 * to keep enough around to satisfy reservations). Then place
3937 * pages into surplus state as needed so the pool will shrink
3938 * to the desired size as pages become free.
3940 * By placing pages into the surplus state independent of the
3941 * overcommit value, we are allowing the surplus pool size to
3942 * exceed overcommit. There are few sane options here. Since
3943 * alloc_surplus_hugetlb_folio() is checking the global counter,
3944 * though, we'll note that we're not allowed to exceed surplus
3945 * and won't grow the pool anywhere else. Not until one of the
3946 * sysctls are changed, or the surplus pages go out of use.
3948 * min_count is the expected number of persistent pages, we
3949 * shouldn't calculate min_count by using
3950 * resv_huge_pages + persistent_huge_pages() - free_huge_pages,
3951 * because there may exist free surplus huge pages, and this will
3952 * lead to subtracting twice. Free surplus huge pages come from HVO
3953 * failing to restore vmemmap, see comments in the callers of
3954 * hugetlb_vmemmap_restore_folio(). Thus, we should calculate
3955 * persistent free count first.
3957 persistent_free_count = h->free_huge_pages;
3958 if (h->free_huge_pages > persistent_huge_pages(h)) {
3959 if (h->free_huge_pages > h->surplus_huge_pages)
3960 persistent_free_count -= h->surplus_huge_pages;
3962 persistent_free_count = 0;
3964 min_count = h->resv_huge_pages + persistent_huge_pages(h) - persistent_free_count;
3965 min_count = max(count, min_count);
3966 try_to_free_low(h, min_count, nodes_allowed);
3969 * Collect pages to be removed on list without dropping lock
3971 while (min_count < persistent_huge_pages(h)) {
3972 folio = remove_pool_hugetlb_folio(h, nodes_allowed, 0);
3976 list_add(&folio->lru, &page_list);
3978 /* free the pages after dropping lock */
3979 spin_unlock_irq(&hugetlb_lock);
3980 update_and_free_pages_bulk(h, &page_list);
3981 flush_free_hpage_work(h);
3982 spin_lock_irq(&hugetlb_lock);
3984 while (count < persistent_huge_pages(h)) {
3985 if (!adjust_pool_surplus(h, nodes_allowed, 1))
3989 h->max_huge_pages = persistent_huge_pages(h);
3990 spin_unlock_irq(&hugetlb_lock);
3991 mutex_unlock(&h->resize_lock);
3993 NODEMASK_FREE(node_alloc_noretry);
3998 static long demote_free_hugetlb_folios(struct hstate *src, struct hstate *dst,
3999 struct list_head *src_list)
4002 struct folio *folio, *next;
4003 LIST_HEAD(dst_list);
4004 LIST_HEAD(ret_list);
4006 rc = hugetlb_vmemmap_restore_folios(src, src_list, &ret_list);
4007 list_splice_init(&ret_list, src_list);
4010 * Taking target hstate mutex synchronizes with set_max_huge_pages.
4011 * Without the mutex, pages added to target hstate could be marked
4014 * Note that we already hold src->resize_lock. To prevent deadlock,
4015 * use the convention of always taking larger size hstate mutex first.
4017 mutex_lock(&dst->resize_lock);
4019 list_for_each_entry_safe(folio, next, src_list, lru) {
4023 if (folio_test_hugetlb_vmemmap_optimized(folio))
4026 cma = folio_test_hugetlb_cma(folio);
4028 list_del(&folio->lru);
4030 split_page_owner(&folio->page, huge_page_order(src), huge_page_order(dst));
4031 pgalloc_tag_split(folio, huge_page_order(src), huge_page_order(dst));
4033 for (i = 0; i < pages_per_huge_page(src); i += pages_per_huge_page(dst)) {
4034 struct page *page = folio_page(folio, i);
4035 /* Careful: see __split_huge_page_tail() */
4036 struct folio *new_folio = (struct folio *)page;
4038 clear_compound_head(page);
4039 prep_compound_page(page, dst->order);
4041 new_folio->mapping = NULL;
4042 init_new_hugetlb_folio(dst, new_folio);
4043 /* Copy the CMA flag so that it is freed correctly */
4045 folio_set_hugetlb_cma(new_folio);
4046 list_add(&new_folio->lru, &dst_list);
4050 prep_and_add_allocated_folios(dst, &dst_list);
4052 mutex_unlock(&dst->resize_lock);
4057 static long demote_pool_huge_page(struct hstate *src, nodemask_t *nodes_allowed,
4058 unsigned long nr_to_demote)
4059 __must_hold(&hugetlb_lock)
4064 long nr_demoted = 0;
4066 lockdep_assert_held(&hugetlb_lock);
4068 /* We should never get here if no demote order */
4069 if (!src->demote_order) {
4070 pr_warn("HugeTLB: NULL demote order passed to demote_pool_huge_page.\n");
4071 return -EINVAL; /* internal error */
4073 dst = size_to_hstate(PAGE_SIZE << src->demote_order);
4075 for_each_node_mask_to_free(src, nr_nodes, node, nodes_allowed) {
4077 struct folio *folio, *next;
4079 list_for_each_entry_safe(folio, next, &src->hugepage_freelists[node], lru) {
4080 if (folio_test_hwpoison(folio))
4083 remove_hugetlb_folio(src, folio, false);
4084 list_add(&folio->lru, &list);
4086 if (++nr_demoted == nr_to_demote)
4090 spin_unlock_irq(&hugetlb_lock);
4092 rc = demote_free_hugetlb_folios(src, dst, &list);
4094 spin_lock_irq(&hugetlb_lock);
4096 list_for_each_entry_safe(folio, next, &list, lru) {
4097 list_del(&folio->lru);
4098 add_hugetlb_folio(src, folio, false);
4103 if (rc < 0 || nr_demoted == nr_to_demote)
4108 * Not absolutely necessary, but for consistency update max_huge_pages
4109 * based on pool changes for the demoted page.
4111 src->max_huge_pages -= nr_demoted;
4112 dst->max_huge_pages += nr_demoted << (huge_page_order(src) - huge_page_order(dst));
4120 * Only way to get here is if all pages on free lists are poisoned.
4121 * Return -EBUSY so that caller will not retry.
4126 #define HSTATE_ATTR_RO(_name) \
4127 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
4129 #define HSTATE_ATTR_WO(_name) \
4130 static struct kobj_attribute _name##_attr = __ATTR_WO(_name)
4132 #define HSTATE_ATTR(_name) \
4133 static struct kobj_attribute _name##_attr = __ATTR_RW(_name)
4135 static struct kobject *hugepages_kobj;
4136 static struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
4138 static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp);
4140 static struct hstate *kobj_to_hstate(struct kobject *kobj, int *nidp)
4144 for (i = 0; i < HUGE_MAX_HSTATE; i++)
4145 if (hstate_kobjs[i] == kobj) {
4147 *nidp = NUMA_NO_NODE;
4151 return kobj_to_node_hstate(kobj, nidp);
4154 static ssize_t nr_hugepages_show_common(struct kobject *kobj,
4155 struct kobj_attribute *attr, char *buf)
4158 unsigned long nr_huge_pages;
4161 h = kobj_to_hstate(kobj, &nid);
4162 if (nid == NUMA_NO_NODE)
4163 nr_huge_pages = h->nr_huge_pages;
4165 nr_huge_pages = h->nr_huge_pages_node[nid];
4167 return sysfs_emit(buf, "%lu\n", nr_huge_pages);
4170 static ssize_t __nr_hugepages_store_common(bool obey_mempolicy,
4171 struct hstate *h, int nid,
4172 unsigned long count, size_t len)
4175 nodemask_t nodes_allowed, *n_mask;
4177 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
4180 if (nid == NUMA_NO_NODE) {
4182 * global hstate attribute
4184 if (!(obey_mempolicy &&
4185 init_nodemask_of_mempolicy(&nodes_allowed)))
4186 n_mask = &node_states[N_MEMORY];
4188 n_mask = &nodes_allowed;
4191 * Node specific request. count adjustment happens in
4192 * set_max_huge_pages() after acquiring hugetlb_lock.
4194 init_nodemask_of_node(&nodes_allowed, nid);
4195 n_mask = &nodes_allowed;
4198 err = set_max_huge_pages(h, count, nid, n_mask);
4200 return err ? err : len;
4203 static ssize_t nr_hugepages_store_common(bool obey_mempolicy,
4204 struct kobject *kobj, const char *buf,
4208 unsigned long count;
4212 err = kstrtoul(buf, 10, &count);
4216 h = kobj_to_hstate(kobj, &nid);
4217 return __nr_hugepages_store_common(obey_mempolicy, h, nid, count, len);
4220 static ssize_t nr_hugepages_show(struct kobject *kobj,
4221 struct kobj_attribute *attr, char *buf)
4223 return nr_hugepages_show_common(kobj, attr, buf);
4226 static ssize_t nr_hugepages_store(struct kobject *kobj,
4227 struct kobj_attribute *attr, const char *buf, size_t len)
4229 return nr_hugepages_store_common(false, kobj, buf, len);
4231 HSTATE_ATTR(nr_hugepages);
4236 * hstate attribute for optionally mempolicy-based constraint on persistent
4237 * huge page alloc/free.
4239 static ssize_t nr_hugepages_mempolicy_show(struct kobject *kobj,
4240 struct kobj_attribute *attr,
4243 return nr_hugepages_show_common(kobj, attr, buf);
4246 static ssize_t nr_hugepages_mempolicy_store(struct kobject *kobj,
4247 struct kobj_attribute *attr, const char *buf, size_t len)
4249 return nr_hugepages_store_common(true, kobj, buf, len);
4251 HSTATE_ATTR(nr_hugepages_mempolicy);
4255 static ssize_t nr_overcommit_hugepages_show(struct kobject *kobj,
4256 struct kobj_attribute *attr, char *buf)
4258 struct hstate *h = kobj_to_hstate(kobj, NULL);
4259 return sysfs_emit(buf, "%lu\n", h->nr_overcommit_huge_pages);
4262 static ssize_t nr_overcommit_hugepages_store(struct kobject *kobj,
4263 struct kobj_attribute *attr, const char *buf, size_t count)
4266 unsigned long input;
4267 struct hstate *h = kobj_to_hstate(kobj, NULL);
4269 if (hstate_is_gigantic(h))
4272 err = kstrtoul(buf, 10, &input);
4276 spin_lock_irq(&hugetlb_lock);
4277 h->nr_overcommit_huge_pages = input;
4278 spin_unlock_irq(&hugetlb_lock);
4282 HSTATE_ATTR(nr_overcommit_hugepages);
4284 static ssize_t free_hugepages_show(struct kobject *kobj,
4285 struct kobj_attribute *attr, char *buf)
4288 unsigned long free_huge_pages;
4291 h = kobj_to_hstate(kobj, &nid);
4292 if (nid == NUMA_NO_NODE)
4293 free_huge_pages = h->free_huge_pages;
4295 free_huge_pages = h->free_huge_pages_node[nid];
4297 return sysfs_emit(buf, "%lu\n", free_huge_pages);
4299 HSTATE_ATTR_RO(free_hugepages);
4301 static ssize_t resv_hugepages_show(struct kobject *kobj,
4302 struct kobj_attribute *attr, char *buf)
4304 struct hstate *h = kobj_to_hstate(kobj, NULL);
4305 return sysfs_emit(buf, "%lu\n", h->resv_huge_pages);
4307 HSTATE_ATTR_RO(resv_hugepages);
4309 static ssize_t surplus_hugepages_show(struct kobject *kobj,
4310 struct kobj_attribute *attr, char *buf)
4313 unsigned long surplus_huge_pages;
4316 h = kobj_to_hstate(kobj, &nid);
4317 if (nid == NUMA_NO_NODE)
4318 surplus_huge_pages = h->surplus_huge_pages;
4320 surplus_huge_pages = h->surplus_huge_pages_node[nid];
4322 return sysfs_emit(buf, "%lu\n", surplus_huge_pages);
4324 HSTATE_ATTR_RO(surplus_hugepages);
4326 static ssize_t demote_store(struct kobject *kobj,
4327 struct kobj_attribute *attr, const char *buf, size_t len)
4329 unsigned long nr_demote;
4330 unsigned long nr_available;
4331 nodemask_t nodes_allowed, *n_mask;
4336 err = kstrtoul(buf, 10, &nr_demote);
4339 h = kobj_to_hstate(kobj, &nid);
4341 if (nid != NUMA_NO_NODE) {
4342 init_nodemask_of_node(&nodes_allowed, nid);
4343 n_mask = &nodes_allowed;
4345 n_mask = &node_states[N_MEMORY];
4348 /* Synchronize with other sysfs operations modifying huge pages */
4349 mutex_lock(&h->resize_lock);
4350 spin_lock_irq(&hugetlb_lock);
4356 * Check for available pages to demote each time thorough the
4357 * loop as demote_pool_huge_page will drop hugetlb_lock.
4359 if (nid != NUMA_NO_NODE)
4360 nr_available = h->free_huge_pages_node[nid];
4362 nr_available = h->free_huge_pages;
4363 nr_available -= h->resv_huge_pages;
4367 rc = demote_pool_huge_page(h, n_mask, nr_demote);
4376 spin_unlock_irq(&hugetlb_lock);
4377 mutex_unlock(&h->resize_lock);
4383 HSTATE_ATTR_WO(demote);
4385 static ssize_t demote_size_show(struct kobject *kobj,
4386 struct kobj_attribute *attr, char *buf)
4388 struct hstate *h = kobj_to_hstate(kobj, NULL);
4389 unsigned long demote_size = (PAGE_SIZE << h->demote_order) / SZ_1K;
4391 return sysfs_emit(buf, "%lukB\n", demote_size);
4394 static ssize_t demote_size_store(struct kobject *kobj,
4395 struct kobj_attribute *attr,
4396 const char *buf, size_t count)
4398 struct hstate *h, *demote_hstate;
4399 unsigned long demote_size;
4400 unsigned int demote_order;
4402 demote_size = (unsigned long)memparse(buf, NULL);
4404 demote_hstate = size_to_hstate(demote_size);
4407 demote_order = demote_hstate->order;
4408 if (demote_order < HUGETLB_PAGE_ORDER)
4411 /* demote order must be smaller than hstate order */
4412 h = kobj_to_hstate(kobj, NULL);
4413 if (demote_order >= h->order)
4416 /* resize_lock synchronizes access to demote size and writes */
4417 mutex_lock(&h->resize_lock);
4418 h->demote_order = demote_order;
4419 mutex_unlock(&h->resize_lock);
4423 HSTATE_ATTR(demote_size);
4425 static struct attribute *hstate_attrs[] = {
4426 &nr_hugepages_attr.attr,
4427 &nr_overcommit_hugepages_attr.attr,
4428 &free_hugepages_attr.attr,
4429 &resv_hugepages_attr.attr,
4430 &surplus_hugepages_attr.attr,
4432 &nr_hugepages_mempolicy_attr.attr,
4437 static const struct attribute_group hstate_attr_group = {
4438 .attrs = hstate_attrs,
4441 static struct attribute *hstate_demote_attrs[] = {
4442 &demote_size_attr.attr,
4447 static const struct attribute_group hstate_demote_attr_group = {
4448 .attrs = hstate_demote_attrs,
4451 static int hugetlb_sysfs_add_hstate(struct hstate *h, struct kobject *parent,
4452 struct kobject **hstate_kobjs,
4453 const struct attribute_group *hstate_attr_group)
4456 int hi = hstate_index(h);
4458 hstate_kobjs[hi] = kobject_create_and_add(h->name, parent);
4459 if (!hstate_kobjs[hi])
4462 retval = sysfs_create_group(hstate_kobjs[hi], hstate_attr_group);
4464 kobject_put(hstate_kobjs[hi]);
4465 hstate_kobjs[hi] = NULL;
4469 if (h->demote_order) {
4470 retval = sysfs_create_group(hstate_kobjs[hi],
4471 &hstate_demote_attr_group);
4473 pr_warn("HugeTLB unable to create demote interfaces for %s\n", h->name);
4474 sysfs_remove_group(hstate_kobjs[hi], hstate_attr_group);
4475 kobject_put(hstate_kobjs[hi]);
4476 hstate_kobjs[hi] = NULL;
4485 static bool hugetlb_sysfs_initialized __ro_after_init;
4488 * node_hstate/s - associate per node hstate attributes, via their kobjects,
4489 * with node devices in node_devices[] using a parallel array. The array
4490 * index of a node device or _hstate == node id.
4491 * This is here to avoid any static dependency of the node device driver, in
4492 * the base kernel, on the hugetlb module.
4494 struct node_hstate {
4495 struct kobject *hugepages_kobj;
4496 struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
4498 static struct node_hstate node_hstates[MAX_NUMNODES];
4501 * A subset of global hstate attributes for node devices
4503 static struct attribute *per_node_hstate_attrs[] = {
4504 &nr_hugepages_attr.attr,
4505 &free_hugepages_attr.attr,
4506 &surplus_hugepages_attr.attr,
4510 static const struct attribute_group per_node_hstate_attr_group = {
4511 .attrs = per_node_hstate_attrs,
4515 * kobj_to_node_hstate - lookup global hstate for node device hstate attr kobj.
4516 * Returns node id via non-NULL nidp.
4518 static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
4522 for (nid = 0; nid < nr_node_ids; nid++) {
4523 struct node_hstate *nhs = &node_hstates[nid];
4525 for (i = 0; i < HUGE_MAX_HSTATE; i++)
4526 if (nhs->hstate_kobjs[i] == kobj) {
4538 * Unregister hstate attributes from a single node device.
4539 * No-op if no hstate attributes attached.
4541 void hugetlb_unregister_node(struct node *node)
4544 struct node_hstate *nhs = &node_hstates[node->dev.id];
4546 if (!nhs->hugepages_kobj)
4547 return; /* no hstate attributes */
4549 for_each_hstate(h) {
4550 int idx = hstate_index(h);
4551 struct kobject *hstate_kobj = nhs->hstate_kobjs[idx];
4555 if (h->demote_order)
4556 sysfs_remove_group(hstate_kobj, &hstate_demote_attr_group);
4557 sysfs_remove_group(hstate_kobj, &per_node_hstate_attr_group);
4558 kobject_put(hstate_kobj);
4559 nhs->hstate_kobjs[idx] = NULL;
4562 kobject_put(nhs->hugepages_kobj);
4563 nhs->hugepages_kobj = NULL;
4568 * Register hstate attributes for a single node device.
4569 * No-op if attributes already registered.
4571 void hugetlb_register_node(struct node *node)
4574 struct node_hstate *nhs = &node_hstates[node->dev.id];
4577 if (!hugetlb_sysfs_initialized)
4580 if (nhs->hugepages_kobj)
4581 return; /* already allocated */
4583 nhs->hugepages_kobj = kobject_create_and_add("hugepages",
4585 if (!nhs->hugepages_kobj)
4588 for_each_hstate(h) {
4589 err = hugetlb_sysfs_add_hstate(h, nhs->hugepages_kobj,
4591 &per_node_hstate_attr_group);
4593 pr_err("HugeTLB: Unable to add hstate %s for node %d\n",
4594 h->name, node->dev.id);
4595 hugetlb_unregister_node(node);
4602 * hugetlb init time: register hstate attributes for all registered node
4603 * devices of nodes that have memory. All on-line nodes should have
4604 * registered their associated device by this time.
4606 static void __init hugetlb_register_all_nodes(void)
4610 for_each_online_node(nid)
4611 hugetlb_register_node(node_devices[nid]);
4613 #else /* !CONFIG_NUMA */
4615 static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
4623 static void hugetlb_register_all_nodes(void) { }
4627 static void __init hugetlb_sysfs_init(void)
4632 hugepages_kobj = kobject_create_and_add("hugepages", mm_kobj);
4633 if (!hugepages_kobj)
4636 for_each_hstate(h) {
4637 err = hugetlb_sysfs_add_hstate(h, hugepages_kobj,
4638 hstate_kobjs, &hstate_attr_group);
4640 pr_err("HugeTLB: Unable to add hstate %s\n", h->name);
4644 hugetlb_sysfs_initialized = true;
4646 hugetlb_register_all_nodes();
4649 #ifdef CONFIG_SYSCTL
4650 static void hugetlb_sysctl_init(void);
4652 static inline void hugetlb_sysctl_init(void) { }
4655 static int __init hugetlb_init(void)
4659 BUILD_BUG_ON(sizeof_field(struct page, private) * BITS_PER_BYTE <
4662 if (!hugepages_supported()) {
4663 if (hugetlb_max_hstate || default_hstate_max_huge_pages)
4664 pr_warn("HugeTLB: huge pages not supported, ignoring associated command-line parameters\n");
4669 * Make sure HPAGE_SIZE (HUGETLB_PAGE_ORDER) hstate exists. Some
4670 * architectures depend on setup being done here.
4672 hugetlb_add_hstate(HUGETLB_PAGE_ORDER);
4673 if (!parsed_default_hugepagesz) {
4675 * If we did not parse a default huge page size, set
4676 * default_hstate_idx to HPAGE_SIZE hstate. And, if the
4677 * number of huge pages for this default size was implicitly
4678 * specified, set that here as well.
4679 * Note that the implicit setting will overwrite an explicit
4680 * setting. A warning will be printed in this case.
4682 default_hstate_idx = hstate_index(size_to_hstate(HPAGE_SIZE));
4683 if (default_hstate_max_huge_pages) {
4684 if (default_hstate.max_huge_pages) {
4687 string_get_size(huge_page_size(&default_hstate),
4688 1, STRING_UNITS_2, buf, 32);
4689 pr_warn("HugeTLB: Ignoring hugepages=%lu associated with %s page size\n",
4690 default_hstate.max_huge_pages, buf);
4691 pr_warn("HugeTLB: Using hugepages=%lu for number of default huge pages\n",
4692 default_hstate_max_huge_pages);
4694 default_hstate.max_huge_pages =
4695 default_hstate_max_huge_pages;
4697 for_each_online_node(i)
4698 default_hstate.max_huge_pages_node[i] =
4699 default_hugepages_in_node[i];
4703 hugetlb_cma_check();
4704 hugetlb_init_hstates();
4705 gather_bootmem_prealloc();
4708 hugetlb_sysfs_init();
4709 hugetlb_cgroup_file_init();
4710 hugetlb_sysctl_init();
4713 num_fault_mutexes = roundup_pow_of_two(8 * num_possible_cpus());
4715 num_fault_mutexes = 1;
4717 hugetlb_fault_mutex_table =
4718 kmalloc_array(num_fault_mutexes, sizeof(struct mutex),
4720 BUG_ON(!hugetlb_fault_mutex_table);
4722 for (i = 0; i < num_fault_mutexes; i++)
4723 mutex_init(&hugetlb_fault_mutex_table[i]);
4726 subsys_initcall(hugetlb_init);
4728 /* Overwritten by architectures with more huge page sizes */
4729 bool __init __attribute((weak)) arch_hugetlb_valid_size(unsigned long size)
4731 return size == HPAGE_SIZE;
4734 void __init hugetlb_add_hstate(unsigned int order)
4739 if (size_to_hstate(PAGE_SIZE << order)) {
4742 BUG_ON(hugetlb_max_hstate >= HUGE_MAX_HSTATE);
4743 BUG_ON(order < order_base_2(__NR_USED_SUBPAGE));
4744 h = &hstates[hugetlb_max_hstate++];
4745 __mutex_init(&h->resize_lock, "resize mutex", &h->resize_key);
4747 h->mask = ~(huge_page_size(h) - 1);
4748 for (i = 0; i < MAX_NUMNODES; ++i)
4749 INIT_LIST_HEAD(&h->hugepage_freelists[i]);
4750 INIT_LIST_HEAD(&h->hugepage_activelist);
4751 snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB",
4752 huge_page_size(h)/SZ_1K);
4757 bool __init __weak hugetlb_node_alloc_supported(void)
4762 static void __init hugepages_clear_pages_in_node(void)
4764 if (!hugetlb_max_hstate) {
4765 default_hstate_max_huge_pages = 0;
4766 memset(default_hugepages_in_node, 0,
4767 sizeof(default_hugepages_in_node));
4769 parsed_hstate->max_huge_pages = 0;
4770 memset(parsed_hstate->max_huge_pages_node, 0,
4771 sizeof(parsed_hstate->max_huge_pages_node));
4775 static __init int hugetlb_add_param(char *s, int (*setup)(char *))
4780 if (hugetlb_param_index >= HUGE_MAX_CMDLINE_ARGS)
4783 len = strlen(s) + 1;
4784 if (len + hstate_cmdline_index > sizeof(hstate_cmdline_buf))
4787 p = &hstate_cmdline_buf[hstate_cmdline_index];
4789 hstate_cmdline_index += len;
4791 hugetlb_params[hugetlb_param_index].val = p;
4792 hugetlb_params[hugetlb_param_index].setup = setup;
4794 hugetlb_param_index++;
4799 static __init void hugetlb_parse_params(void)
4802 struct hugetlb_cmdline *hcp;
4804 for (i = 0; i < hugetlb_param_index; i++) {
4805 hcp = &hugetlb_params[i];
4807 hcp->setup(hcp->val);
4810 hugetlb_cma_validate_params();
4814 * hugepages command line processing
4815 * hugepages normally follows a valid hugepagsz or default_hugepagsz
4816 * specification. If not, ignore the hugepages value. hugepages can also
4817 * be the first huge page command line option in which case it implicitly
4818 * specifies the number of huge pages for the default size.
4820 static int __init hugepages_setup(char *s)
4823 static unsigned long *last_mhp;
4824 int node = NUMA_NO_NODE;
4829 if (!parsed_valid_hugepagesz) {
4830 pr_warn("HugeTLB: hugepages=%s does not follow a valid hugepagesz, ignoring\n", s);
4831 parsed_valid_hugepagesz = true;
4836 * !hugetlb_max_hstate means we haven't parsed a hugepagesz= parameter
4837 * yet, so this hugepages= parameter goes to the "default hstate".
4838 * Otherwise, it goes with the previously parsed hugepagesz or
4839 * default_hugepagesz.
4841 else if (!hugetlb_max_hstate)
4842 mhp = &default_hstate_max_huge_pages;
4844 mhp = &parsed_hstate->max_huge_pages;
4846 if (mhp == last_mhp) {
4847 pr_warn("HugeTLB: hugepages= specified twice without interleaving hugepagesz=, ignoring hugepages=%s\n", s);
4853 if (sscanf(p, "%lu%n", &tmp, &count) != 1)
4855 /* Parameter is node format */
4856 if (p[count] == ':') {
4857 if (!hugetlb_node_alloc_supported()) {
4858 pr_warn("HugeTLB: architecture can't support node specific alloc, ignoring!\n");
4861 if (tmp >= MAX_NUMNODES || !node_online(tmp))
4863 node = array_index_nospec(tmp, MAX_NUMNODES);
4865 /* Parse hugepages */
4866 if (sscanf(p, "%lu%n", &tmp, &count) != 1)
4868 if (!hugetlb_max_hstate)
4869 default_hugepages_in_node[node] = tmp;
4871 parsed_hstate->max_huge_pages_node[node] = tmp;
4873 /* Go to parse next node*/
4874 if (p[count] == ',')
4891 pr_warn("HugeTLB: Invalid hugepages parameter %s\n", p);
4892 hugepages_clear_pages_in_node();
4895 hugetlb_early_param("hugepages", hugepages_setup);
4898 * hugepagesz command line processing
4899 * A specific huge page size can only be specified once with hugepagesz.
4900 * hugepagesz is followed by hugepages on the command line. The global
4901 * variable 'parsed_valid_hugepagesz' is used to determine if prior
4902 * hugepagesz argument was valid.
4904 static int __init hugepagesz_setup(char *s)
4909 parsed_valid_hugepagesz = false;
4910 size = (unsigned long)memparse(s, NULL);
4912 if (!arch_hugetlb_valid_size(size)) {
4913 pr_err("HugeTLB: unsupported hugepagesz=%s\n", s);
4917 h = size_to_hstate(size);
4920 * hstate for this size already exists. This is normally
4921 * an error, but is allowed if the existing hstate is the
4922 * default hstate. More specifically, it is only allowed if
4923 * the number of huge pages for the default hstate was not
4924 * previously specified.
4926 if (!parsed_default_hugepagesz || h != &default_hstate ||
4927 default_hstate.max_huge_pages) {
4928 pr_warn("HugeTLB: hugepagesz=%s specified twice, ignoring\n", s);
4933 * No need to call hugetlb_add_hstate() as hstate already
4934 * exists. But, do set parsed_hstate so that a following
4935 * hugepages= parameter will be applied to this hstate.
4938 parsed_valid_hugepagesz = true;
4942 hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
4943 parsed_valid_hugepagesz = true;
4946 hugetlb_early_param("hugepagesz", hugepagesz_setup);
4949 * default_hugepagesz command line input
4950 * Only one instance of default_hugepagesz allowed on command line.
4952 static int __init default_hugepagesz_setup(char *s)
4957 parsed_valid_hugepagesz = false;
4958 if (parsed_default_hugepagesz) {
4959 pr_err("HugeTLB: default_hugepagesz previously specified, ignoring %s\n", s);
4963 size = (unsigned long)memparse(s, NULL);
4965 if (!arch_hugetlb_valid_size(size)) {
4966 pr_err("HugeTLB: unsupported default_hugepagesz=%s\n", s);
4970 hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
4971 parsed_valid_hugepagesz = true;
4972 parsed_default_hugepagesz = true;
4973 default_hstate_idx = hstate_index(size_to_hstate(size));
4976 * The number of default huge pages (for this size) could have been
4977 * specified as the first hugetlb parameter: hugepages=X. If so,
4978 * then default_hstate_max_huge_pages is set. If the default huge
4979 * page size is gigantic (> MAX_PAGE_ORDER), then the pages must be
4980 * allocated here from bootmem allocator.
4982 if (default_hstate_max_huge_pages) {
4983 default_hstate.max_huge_pages = default_hstate_max_huge_pages;
4985 * Since this is an early parameter, we can't check
4986 * NUMA node state yet, so loop through MAX_NUMNODES.
4988 for (i = 0; i < MAX_NUMNODES; i++) {
4989 if (default_hugepages_in_node[i] != 0)
4990 default_hstate.max_huge_pages_node[i] =
4991 default_hugepages_in_node[i];
4993 default_hstate_max_huge_pages = 0;
4998 hugetlb_early_param("default_hugepagesz", default_hugepagesz_setup);
5000 void __init hugetlb_bootmem_set_nodes(void)
5003 unsigned long start_pfn, end_pfn;
5005 if (!nodes_empty(hugetlb_bootmem_nodes))
5008 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
5009 if (end_pfn > start_pfn)
5010 node_set(nid, hugetlb_bootmem_nodes);
5014 static bool __hugetlb_bootmem_allocated __initdata;
5016 bool __init hugetlb_bootmem_allocated(void)
5018 return __hugetlb_bootmem_allocated;
5021 void __init hugetlb_bootmem_alloc(void)
5026 if (__hugetlb_bootmem_allocated)
5029 hugetlb_bootmem_set_nodes();
5031 for (i = 0; i < MAX_NUMNODES; i++)
5032 INIT_LIST_HEAD(&huge_boot_pages[i]);
5034 hugetlb_parse_params();
5036 for_each_hstate(h) {
5037 h->next_nid_to_alloc = first_online_node;
5039 if (hstate_is_gigantic(h))
5040 hugetlb_hstate_alloc_pages(h);
5043 __hugetlb_bootmem_allocated = true;
5047 * hugepage_alloc_threads command line parsing.
5049 * When set, use this specific number of threads for the boot
5050 * allocation of hugepages.
5052 static int __init hugepage_alloc_threads_setup(char *s)
5054 unsigned long allocation_threads;
5056 if (kstrtoul(s, 0, &allocation_threads) != 0)
5059 if (allocation_threads == 0)
5062 hugepage_allocation_threads = allocation_threads;
5066 __setup("hugepage_alloc_threads=", hugepage_alloc_threads_setup);
5068 static unsigned int allowed_mems_nr(struct hstate *h)
5071 unsigned int nr = 0;
5072 nodemask_t *mbind_nodemask;
5073 unsigned int *array = h->free_huge_pages_node;
5074 gfp_t gfp_mask = htlb_alloc_mask(h);
5076 mbind_nodemask = policy_mbind_nodemask(gfp_mask);
5077 for_each_node_mask(node, cpuset_current_mems_allowed) {
5078 if (!mbind_nodemask || node_isset(node, *mbind_nodemask))
5085 #ifdef CONFIG_SYSCTL
5086 static int proc_hugetlb_doulongvec_minmax(const struct ctl_table *table, int write,
5087 void *buffer, size_t *length,
5088 loff_t *ppos, unsigned long *out)
5090 struct ctl_table dup_table;
5093 * In order to avoid races with __do_proc_doulongvec_minmax(), we
5094 * can duplicate the @table and alter the duplicate of it.
5097 dup_table.data = out;
5099 return proc_doulongvec_minmax(&dup_table, write, buffer, length, ppos);
5102 static int hugetlb_sysctl_handler_common(bool obey_mempolicy,
5103 const struct ctl_table *table, int write,
5104 void *buffer, size_t *length, loff_t *ppos)
5106 struct hstate *h = &default_hstate;
5107 unsigned long tmp = h->max_huge_pages;
5110 if (!hugepages_supported())
5113 ret = proc_hugetlb_doulongvec_minmax(table, write, buffer, length, ppos,
5119 ret = __nr_hugepages_store_common(obey_mempolicy, h,
5120 NUMA_NO_NODE, tmp, *length);
5125 static int hugetlb_sysctl_handler(const struct ctl_table *table, int write,
5126 void *buffer, size_t *length, loff_t *ppos)
5129 return hugetlb_sysctl_handler_common(false, table, write,
5130 buffer, length, ppos);
5134 static int hugetlb_mempolicy_sysctl_handler(const struct ctl_table *table, int write,
5135 void *buffer, size_t *length, loff_t *ppos)
5137 return hugetlb_sysctl_handler_common(true, table, write,
5138 buffer, length, ppos);
5140 #endif /* CONFIG_NUMA */
5142 static int hugetlb_overcommit_handler(const struct ctl_table *table, int write,
5143 void *buffer, size_t *length, loff_t *ppos)
5145 struct hstate *h = &default_hstate;
5149 if (!hugepages_supported())
5152 tmp = h->nr_overcommit_huge_pages;
5154 if (write && hstate_is_gigantic(h))
5157 ret = proc_hugetlb_doulongvec_minmax(table, write, buffer, length, ppos,
5163 spin_lock_irq(&hugetlb_lock);
5164 h->nr_overcommit_huge_pages = tmp;
5165 spin_unlock_irq(&hugetlb_lock);
5171 static const struct ctl_table hugetlb_table[] = {
5173 .procname = "nr_hugepages",
5175 .maxlen = sizeof(unsigned long),
5177 .proc_handler = hugetlb_sysctl_handler,
5181 .procname = "nr_hugepages_mempolicy",
5183 .maxlen = sizeof(unsigned long),
5185 .proc_handler = &hugetlb_mempolicy_sysctl_handler,
5189 .procname = "hugetlb_shm_group",
5190 .data = &sysctl_hugetlb_shm_group,
5191 .maxlen = sizeof(gid_t),
5193 .proc_handler = proc_dointvec,
5196 .procname = "nr_overcommit_hugepages",
5198 .maxlen = sizeof(unsigned long),
5200 .proc_handler = hugetlb_overcommit_handler,
5204 static void __init hugetlb_sysctl_init(void)
5206 register_sysctl_init("vm", hugetlb_table);
5208 #endif /* CONFIG_SYSCTL */
5210 void hugetlb_report_meminfo(struct seq_file *m)
5213 unsigned long total = 0;
5215 if (!hugepages_supported())
5218 for_each_hstate(h) {
5219 unsigned long count = h->nr_huge_pages;
5221 total += huge_page_size(h) * count;
5223 if (h == &default_hstate)
5225 "HugePages_Total: %5lu\n"
5226 "HugePages_Free: %5lu\n"
5227 "HugePages_Rsvd: %5lu\n"
5228 "HugePages_Surp: %5lu\n"
5229 "Hugepagesize: %8lu kB\n",
5233 h->surplus_huge_pages,
5234 huge_page_size(h) / SZ_1K);
5237 seq_printf(m, "Hugetlb: %8lu kB\n", total / SZ_1K);
5240 int hugetlb_report_node_meminfo(char *buf, int len, int nid)
5242 struct hstate *h = &default_hstate;
5244 if (!hugepages_supported())
5247 return sysfs_emit_at(buf, len,
5248 "Node %d HugePages_Total: %5u\n"
5249 "Node %d HugePages_Free: %5u\n"
5250 "Node %d HugePages_Surp: %5u\n",
5251 nid, h->nr_huge_pages_node[nid],
5252 nid, h->free_huge_pages_node[nid],
5253 nid, h->surplus_huge_pages_node[nid]);
5256 void hugetlb_show_meminfo_node(int nid)
5260 if (!hugepages_supported())
5264 printk("Node %d hugepages_total=%u hugepages_free=%u hugepages_surp=%u hugepages_size=%lukB\n",
5266 h->nr_huge_pages_node[nid],
5267 h->free_huge_pages_node[nid],
5268 h->surplus_huge_pages_node[nid],
5269 huge_page_size(h) / SZ_1K);
5272 void hugetlb_report_usage(struct seq_file *m, struct mm_struct *mm)
5274 seq_printf(m, "HugetlbPages:\t%8lu kB\n",
5275 K(atomic_long_read(&mm->hugetlb_usage)));
5278 /* Return the number pages of memory we physically have, in PAGE_SIZE units. */
5279 unsigned long hugetlb_total_pages(void)
5282 unsigned long nr_total_pages = 0;
5285 nr_total_pages += h->nr_huge_pages * pages_per_huge_page(h);
5286 return nr_total_pages;
5289 static int hugetlb_acct_memory(struct hstate *h, long delta)
5296 spin_lock_irq(&hugetlb_lock);
5298 * When cpuset is configured, it breaks the strict hugetlb page
5299 * reservation as the accounting is done on a global variable. Such
5300 * reservation is completely rubbish in the presence of cpuset because
5301 * the reservation is not checked against page availability for the
5302 * current cpuset. Application can still potentially OOM'ed by kernel
5303 * with lack of free htlb page in cpuset that the task is in.
5304 * Attempt to enforce strict accounting with cpuset is almost
5305 * impossible (or too ugly) because cpuset is too fluid that
5306 * task or memory node can be dynamically moved between cpusets.
5308 * The change of semantics for shared hugetlb mapping with cpuset is
5309 * undesirable. However, in order to preserve some of the semantics,
5310 * we fall back to check against current free page availability as
5311 * a best attempt and hopefully to minimize the impact of changing
5312 * semantics that cpuset has.
5314 * Apart from cpuset, we also have memory policy mechanism that
5315 * also determines from which node the kernel will allocate memory
5316 * in a NUMA system. So similar to cpuset, we also should consider
5317 * the memory policy of the current task. Similar to the description
5321 if (gather_surplus_pages(h, delta) < 0)
5324 if (delta > allowed_mems_nr(h)) {
5325 return_unused_surplus_pages(h, delta);
5332 return_unused_surplus_pages(h, (unsigned long) -delta);
5335 spin_unlock_irq(&hugetlb_lock);
5339 static void hugetlb_vm_op_open(struct vm_area_struct *vma)
5341 struct resv_map *resv = vma_resv_map(vma);
5344 * HPAGE_RESV_OWNER indicates a private mapping.
5345 * This new VMA should share its siblings reservation map if present.
5346 * The VMA will only ever have a valid reservation map pointer where
5347 * it is being copied for another still existing VMA. As that VMA
5348 * has a reference to the reservation map it cannot disappear until
5349 * after this open call completes. It is therefore safe to take a
5350 * new reference here without additional locking.
5352 if (resv && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
5353 resv_map_dup_hugetlb_cgroup_uncharge_info(resv);
5354 kref_get(&resv->refs);
5358 * vma_lock structure for sharable mappings is vma specific.
5359 * Clear old pointer (if copied via vm_area_dup) and allocate
5360 * new structure. Before clearing, make sure vma_lock is not
5363 if (vma->vm_flags & VM_MAYSHARE) {
5364 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
5367 if (vma_lock->vma != vma) {
5368 vma->vm_private_data = NULL;
5369 hugetlb_vma_lock_alloc(vma);
5371 pr_warn("HugeTLB: vma_lock already exists in %s.\n", __func__);
5373 hugetlb_vma_lock_alloc(vma);
5377 static void hugetlb_vm_op_close(struct vm_area_struct *vma)
5379 struct hstate *h = hstate_vma(vma);
5380 struct resv_map *resv;
5381 struct hugepage_subpool *spool = subpool_vma(vma);
5382 unsigned long reserve, start, end;
5385 hugetlb_vma_lock_free(vma);
5387 resv = vma_resv_map(vma);
5388 if (!resv || !is_vma_resv_set(vma, HPAGE_RESV_OWNER))
5391 start = vma_hugecache_offset(h, vma, vma->vm_start);
5392 end = vma_hugecache_offset(h, vma, vma->vm_end);
5394 reserve = (end - start) - region_count(resv, start, end);
5395 hugetlb_cgroup_uncharge_counter(resv, start, end);
5398 * Decrement reserve counts. The global reserve count may be
5399 * adjusted if the subpool has a minimum size.
5401 gbl_reserve = hugepage_subpool_put_pages(spool, reserve);
5402 hugetlb_acct_memory(h, -gbl_reserve);
5405 kref_put(&resv->refs, resv_map_release);
5408 static int hugetlb_vm_op_split(struct vm_area_struct *vma, unsigned long addr)
5410 if (addr & ~(huge_page_mask(hstate_vma(vma))))
5415 void hugetlb_split(struct vm_area_struct *vma, unsigned long addr)
5418 * PMD sharing is only possible for PUD_SIZE-aligned address ranges
5419 * in HugeTLB VMAs. If we will lose PUD_SIZE alignment due to this
5420 * split, unshare PMDs in the PUD_SIZE interval surrounding addr now.
5421 * This function is called in the middle of a VMA split operation, with
5422 * MM, VMA and rmap all write-locked to prevent concurrent page table
5423 * walks (except hardware and gup_fast()).
5425 vma_assert_write_locked(vma);
5426 i_mmap_assert_write_locked(vma->vm_file->f_mapping);
5428 if (addr & ~PUD_MASK) {
5429 unsigned long floor = addr & PUD_MASK;
5430 unsigned long ceil = floor + PUD_SIZE;
5432 if (floor >= vma->vm_start && ceil <= vma->vm_end) {
5435 * Use take_locks=false here.
5436 * The file rmap lock is already held.
5437 * The hugetlb VMA lock can't be taken when we already
5438 * hold the file rmap lock, and we don't need it because
5439 * its purpose is to synchronize against concurrent page
5440 * table walks, which are not possible thanks to the
5441 * locks held by our caller.
5443 hugetlb_unshare_pmds(vma, floor, ceil, /* take_locks = */ false);
5448 static unsigned long hugetlb_vm_op_pagesize(struct vm_area_struct *vma)
5450 return huge_page_size(hstate_vma(vma));
5454 * We cannot handle pagefaults against hugetlb pages at all. They cause
5455 * handle_mm_fault() to try to instantiate regular-sized pages in the
5456 * hugepage VMA. do_page_fault() is supposed to trap this, so BUG is we get
5459 static vm_fault_t hugetlb_vm_op_fault(struct vm_fault *vmf)
5466 * When a new function is introduced to vm_operations_struct and added
5467 * to hugetlb_vm_ops, please consider adding the function to shm_vm_ops.
5468 * This is because under System V memory model, mappings created via
5469 * shmget/shmat with "huge page" specified are backed by hugetlbfs files,
5470 * their original vm_ops are overwritten with shm_vm_ops.
5472 const struct vm_operations_struct hugetlb_vm_ops = {
5473 .fault = hugetlb_vm_op_fault,
5474 .open = hugetlb_vm_op_open,
5475 .close = hugetlb_vm_op_close,
5476 .may_split = hugetlb_vm_op_split,
5477 .pagesize = hugetlb_vm_op_pagesize,
5480 static pte_t make_huge_pte(struct vm_area_struct *vma, struct folio *folio,
5483 pte_t entry = folio_mk_pte(folio, vma->vm_page_prot);
5484 unsigned int shift = huge_page_shift(hstate_vma(vma));
5486 if (try_mkwrite && (vma->vm_flags & VM_WRITE)) {
5487 entry = pte_mkwrite_novma(pte_mkdirty(entry));
5489 entry = pte_wrprotect(entry);
5491 entry = pte_mkyoung(entry);
5492 entry = arch_make_huge_pte(entry, shift, vma->vm_flags);
5497 static void set_huge_ptep_writable(struct vm_area_struct *vma,
5498 unsigned long address, pte_t *ptep)
5502 entry = huge_pte_mkwrite(huge_pte_mkdirty(huge_ptep_get(vma->vm_mm, address, ptep)));
5503 if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1))
5504 update_mmu_cache(vma, address, ptep);
5507 static void set_huge_ptep_maybe_writable(struct vm_area_struct *vma,
5508 unsigned long address, pte_t *ptep)
5510 if (vma->vm_flags & VM_WRITE)
5511 set_huge_ptep_writable(vma, address, ptep);
5514 bool is_hugetlb_entry_migration(pte_t pte)
5518 if (huge_pte_none(pte) || pte_present(pte))
5520 swp = pte_to_swp_entry(pte);
5521 if (is_migration_entry(swp))
5527 bool is_hugetlb_entry_hwpoisoned(pte_t pte)
5531 if (huge_pte_none(pte) || pte_present(pte))
5533 swp = pte_to_swp_entry(pte);
5534 if (is_hwpoison_entry(swp))
5541 hugetlb_install_folio(struct vm_area_struct *vma, pte_t *ptep, unsigned long addr,
5542 struct folio *new_folio, pte_t old, unsigned long sz)
5544 pte_t newpte = make_huge_pte(vma, new_folio, true);
5546 __folio_mark_uptodate(new_folio);
5547 hugetlb_add_new_anon_rmap(new_folio, vma, addr);
5548 if (userfaultfd_wp(vma) && huge_pte_uffd_wp(old))
5549 newpte = huge_pte_mkuffd_wp(newpte);
5550 set_huge_pte_at(vma->vm_mm, addr, ptep, newpte, sz);
5551 hugetlb_count_add(pages_per_huge_page(hstate_vma(vma)), vma->vm_mm);
5552 folio_set_hugetlb_migratable(new_folio);
5555 int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src,
5556 struct vm_area_struct *dst_vma,
5557 struct vm_area_struct *src_vma)
5559 pte_t *src_pte, *dst_pte, entry;
5560 struct folio *pte_folio;
5562 bool cow = is_cow_mapping(src_vma->vm_flags);
5563 struct hstate *h = hstate_vma(src_vma);
5564 unsigned long sz = huge_page_size(h);
5565 unsigned long npages = pages_per_huge_page(h);
5566 struct mmu_notifier_range range;
5567 unsigned long last_addr_mask;
5571 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, src,
5574 mmu_notifier_invalidate_range_start(&range);
5575 vma_assert_write_locked(src_vma);
5576 raw_write_seqcount_begin(&src->write_protect_seq);
5579 * For shared mappings the vma lock must be held before
5580 * calling hugetlb_walk() in the src vma. Otherwise, the
5581 * returned ptep could go away if part of a shared pmd and
5582 * another thread calls huge_pmd_unshare.
5584 hugetlb_vma_lock_read(src_vma);
5587 last_addr_mask = hugetlb_mask_last_page(h);
5588 for (addr = src_vma->vm_start; addr < src_vma->vm_end; addr += sz) {
5589 spinlock_t *src_ptl, *dst_ptl;
5590 src_pte = hugetlb_walk(src_vma, addr, sz);
5592 addr |= last_addr_mask;
5595 dst_pte = huge_pte_alloc(dst, dst_vma, addr, sz);
5602 * If the pagetables are shared don't copy or take references.
5604 * dst_pte == src_pte is the common case of src/dest sharing.
5605 * However, src could have 'unshared' and dst shares with
5606 * another vma. So page_count of ptep page is checked instead
5607 * to reliably determine whether pte is shared.
5609 if (page_count(virt_to_page(dst_pte)) > 1) {
5610 addr |= last_addr_mask;
5614 dst_ptl = huge_pte_lock(h, dst, dst_pte);
5615 src_ptl = huge_pte_lockptr(h, src, src_pte);
5616 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
5617 entry = huge_ptep_get(src_vma->vm_mm, addr, src_pte);
5619 if (huge_pte_none(entry)) {
5621 * Skip if src entry none.
5624 } else if (unlikely(is_hugetlb_entry_hwpoisoned(entry))) {
5625 if (!userfaultfd_wp(dst_vma))
5626 entry = huge_pte_clear_uffd_wp(entry);
5627 set_huge_pte_at(dst, addr, dst_pte, entry, sz);
5628 } else if (unlikely(is_hugetlb_entry_migration(entry))) {
5629 swp_entry_t swp_entry = pte_to_swp_entry(entry);
5630 bool uffd_wp = pte_swp_uffd_wp(entry);
5632 if (!is_readable_migration_entry(swp_entry) && cow) {
5634 * COW mappings require pages in both
5635 * parent and child to be set to read.
5637 swp_entry = make_readable_migration_entry(
5638 swp_offset(swp_entry));
5639 entry = swp_entry_to_pte(swp_entry);
5640 if (userfaultfd_wp(src_vma) && uffd_wp)
5641 entry = pte_swp_mkuffd_wp(entry);
5642 set_huge_pte_at(src, addr, src_pte, entry, sz);
5644 if (!userfaultfd_wp(dst_vma))
5645 entry = huge_pte_clear_uffd_wp(entry);
5646 set_huge_pte_at(dst, addr, dst_pte, entry, sz);
5647 } else if (unlikely(is_pte_marker(entry))) {
5648 pte_marker marker = copy_pte_marker(
5649 pte_to_swp_entry(entry), dst_vma);
5652 set_huge_pte_at(dst, addr, dst_pte,
5653 make_pte_marker(marker), sz);
5655 entry = huge_ptep_get(src_vma->vm_mm, addr, src_pte);
5656 pte_folio = page_folio(pte_page(entry));
5657 folio_get(pte_folio);
5660 * Failing to duplicate the anon rmap is a rare case
5661 * where we see pinned hugetlb pages while they're
5662 * prone to COW. We need to do the COW earlier during
5665 * When pre-allocating the page or copying data, we
5666 * need to be without the pgtable locks since we could
5667 * sleep during the process.
5669 if (!folio_test_anon(pte_folio)) {
5670 hugetlb_add_file_rmap(pte_folio);
5671 } else if (hugetlb_try_dup_anon_rmap(pte_folio, src_vma)) {
5672 pte_t src_pte_old = entry;
5673 struct folio *new_folio;
5675 spin_unlock(src_ptl);
5676 spin_unlock(dst_ptl);
5677 /* Do not use reserve as it's private owned */
5678 new_folio = alloc_hugetlb_folio(dst_vma, addr, false);
5679 if (IS_ERR(new_folio)) {
5680 folio_put(pte_folio);
5681 ret = PTR_ERR(new_folio);
5684 ret = copy_user_large_folio(new_folio, pte_folio,
5686 folio_put(pte_folio);
5688 folio_put(new_folio);
5692 /* Install the new hugetlb folio if src pte stable */
5693 dst_ptl = huge_pte_lock(h, dst, dst_pte);
5694 src_ptl = huge_pte_lockptr(h, src, src_pte);
5695 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
5696 entry = huge_ptep_get(src_vma->vm_mm, addr, src_pte);
5697 if (!pte_same(src_pte_old, entry)) {
5698 restore_reserve_on_error(h, dst_vma, addr,
5700 folio_put(new_folio);
5701 /* huge_ptep of dst_pte won't change as in child */
5704 hugetlb_install_folio(dst_vma, dst_pte, addr,
5705 new_folio, src_pte_old, sz);
5706 spin_unlock(src_ptl);
5707 spin_unlock(dst_ptl);
5713 * No need to notify as we are downgrading page
5714 * table protection not changing it to point
5717 * See Documentation/mm/mmu_notifier.rst
5719 huge_ptep_set_wrprotect(src, addr, src_pte);
5720 entry = huge_pte_wrprotect(entry);
5723 if (!userfaultfd_wp(dst_vma))
5724 entry = huge_pte_clear_uffd_wp(entry);
5726 set_huge_pte_at(dst, addr, dst_pte, entry, sz);
5727 hugetlb_count_add(npages, dst);
5729 spin_unlock(src_ptl);
5730 spin_unlock(dst_ptl);
5734 raw_write_seqcount_end(&src->write_protect_seq);
5735 mmu_notifier_invalidate_range_end(&range);
5737 hugetlb_vma_unlock_read(src_vma);
5743 static void move_huge_pte(struct vm_area_struct *vma, unsigned long old_addr,
5744 unsigned long new_addr, pte_t *src_pte, pte_t *dst_pte,
5747 bool need_clear_uffd_wp = vma_has_uffd_without_event_remap(vma);
5748 struct hstate *h = hstate_vma(vma);
5749 struct mm_struct *mm = vma->vm_mm;
5750 spinlock_t *src_ptl, *dst_ptl;
5753 dst_ptl = huge_pte_lock(h, mm, dst_pte);
5754 src_ptl = huge_pte_lockptr(h, mm, src_pte);
5757 * We don't have to worry about the ordering of src and dst ptlocks
5758 * because exclusive mmap_lock (or the i_mmap_lock) prevents deadlock.
5760 if (src_ptl != dst_ptl)
5761 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
5763 pte = huge_ptep_get_and_clear(mm, old_addr, src_pte, sz);
5765 if (need_clear_uffd_wp && pte_marker_uffd_wp(pte))
5766 huge_pte_clear(mm, new_addr, dst_pte, sz);
5768 if (need_clear_uffd_wp) {
5769 if (pte_present(pte))
5770 pte = huge_pte_clear_uffd_wp(pte);
5771 else if (is_swap_pte(pte))
5772 pte = pte_swp_clear_uffd_wp(pte);
5774 set_huge_pte_at(mm, new_addr, dst_pte, pte, sz);
5777 if (src_ptl != dst_ptl)
5778 spin_unlock(src_ptl);
5779 spin_unlock(dst_ptl);
5782 int move_hugetlb_page_tables(struct vm_area_struct *vma,
5783 struct vm_area_struct *new_vma,
5784 unsigned long old_addr, unsigned long new_addr,
5787 struct hstate *h = hstate_vma(vma);
5788 struct address_space *mapping = vma->vm_file->f_mapping;
5789 unsigned long sz = huge_page_size(h);
5790 struct mm_struct *mm = vma->vm_mm;
5791 unsigned long old_end = old_addr + len;
5792 unsigned long last_addr_mask;
5793 pte_t *src_pte, *dst_pte;
5794 struct mmu_notifier_range range;
5795 bool shared_pmd = false;
5797 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, old_addr,
5799 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
5801 * In case of shared PMDs, we should cover the maximum possible
5804 flush_cache_range(vma, range.start, range.end);
5806 mmu_notifier_invalidate_range_start(&range);
5807 last_addr_mask = hugetlb_mask_last_page(h);
5808 /* Prevent race with file truncation */
5809 hugetlb_vma_lock_write(vma);
5810 i_mmap_lock_write(mapping);
5811 for (; old_addr < old_end; old_addr += sz, new_addr += sz) {
5812 src_pte = hugetlb_walk(vma, old_addr, sz);
5814 old_addr |= last_addr_mask;
5815 new_addr |= last_addr_mask;
5818 if (huge_pte_none(huge_ptep_get(mm, old_addr, src_pte)))
5821 if (huge_pmd_unshare(mm, vma, old_addr, src_pte)) {
5823 old_addr |= last_addr_mask;
5824 new_addr |= last_addr_mask;
5828 dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz);
5832 move_huge_pte(vma, old_addr, new_addr, src_pte, dst_pte, sz);
5836 flush_hugetlb_tlb_range(vma, range.start, range.end);
5838 flush_hugetlb_tlb_range(vma, old_end - len, old_end);
5839 mmu_notifier_invalidate_range_end(&range);
5840 i_mmap_unlock_write(mapping);
5841 hugetlb_vma_unlock_write(vma);
5843 return len + old_addr - old_end;
5846 void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
5847 unsigned long start, unsigned long end,
5848 struct folio *folio, zap_flags_t zap_flags)
5850 struct mm_struct *mm = vma->vm_mm;
5851 const bool folio_provided = !!folio;
5852 unsigned long address;
5856 struct hstate *h = hstate_vma(vma);
5857 unsigned long sz = huge_page_size(h);
5858 bool adjust_reservation = false;
5859 unsigned long last_addr_mask;
5860 bool force_flush = false;
5862 WARN_ON(!is_vm_hugetlb_page(vma));
5863 BUG_ON(start & ~huge_page_mask(h));
5864 BUG_ON(end & ~huge_page_mask(h));
5867 * This is a hugetlb vma, all the pte entries should point
5870 tlb_change_page_size(tlb, sz);
5871 tlb_start_vma(tlb, vma);
5873 last_addr_mask = hugetlb_mask_last_page(h);
5875 for (; address < end; address += sz) {
5876 ptep = hugetlb_walk(vma, address, sz);
5878 address |= last_addr_mask;
5882 ptl = huge_pte_lock(h, mm, ptep);
5883 if (huge_pmd_unshare(mm, vma, address, ptep)) {
5885 tlb_flush_pmd_range(tlb, address & PUD_MASK, PUD_SIZE);
5887 address |= last_addr_mask;
5891 pte = huge_ptep_get(mm, address, ptep);
5892 if (huge_pte_none(pte)) {
5898 * Migrating hugepage or HWPoisoned hugepage is already
5899 * unmapped and its refcount is dropped, so just clear pte here.
5901 if (unlikely(!pte_present(pte))) {
5903 * If the pte was wr-protected by uffd-wp in any of the
5904 * swap forms, meanwhile the caller does not want to
5905 * drop the uffd-wp bit in this zap, then replace the
5906 * pte with a marker.
5908 if (pte_swp_uffd_wp_any(pte) &&
5909 !(zap_flags & ZAP_FLAG_DROP_MARKER))
5910 set_huge_pte_at(mm, address, ptep,
5911 make_pte_marker(PTE_MARKER_UFFD_WP),
5914 huge_pte_clear(mm, address, ptep, sz);
5920 * If a folio is supplied, it is because a specific
5921 * folio is being unmapped, not a range. Ensure the folio we
5922 * are about to unmap is the actual folio of interest.
5924 if (folio_provided) {
5925 if (folio != page_folio(pte_page(pte))) {
5930 * Mark the VMA as having unmapped its page so that
5931 * future faults in this VMA will fail rather than
5932 * looking like data was lost
5934 set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED);
5936 folio = page_folio(pte_page(pte));
5939 pte = huge_ptep_get_and_clear(mm, address, ptep, sz);
5940 tlb_remove_huge_tlb_entry(h, tlb, ptep, address);
5941 if (huge_pte_dirty(pte))
5942 folio_mark_dirty(folio);
5943 /* Leave a uffd-wp pte marker if needed */
5944 if (huge_pte_uffd_wp(pte) &&
5945 !(zap_flags & ZAP_FLAG_DROP_MARKER))
5946 set_huge_pte_at(mm, address, ptep,
5947 make_pte_marker(PTE_MARKER_UFFD_WP),
5949 hugetlb_count_sub(pages_per_huge_page(h), mm);
5950 hugetlb_remove_rmap(folio);
5953 * Restore the reservation for anonymous page, otherwise the
5954 * backing page could be stolen by someone.
5955 * If there we are freeing a surplus, do not set the restore
5958 if (!h->surplus_huge_pages && __vma_private_lock(vma) &&
5959 folio_test_anon(folio)) {
5960 folio_set_hugetlb_restore_reserve(folio);
5961 /* Reservation to be adjusted after the spin lock */
5962 adjust_reservation = true;
5968 * Adjust the reservation for the region that will have the
5969 * reserve restored. Keep in mind that vma_needs_reservation() changes
5970 * resv->adds_in_progress if it succeeds. If this is not done,
5971 * do_exit() will not see it, and will keep the reservation
5974 if (adjust_reservation) {
5975 int rc = vma_needs_reservation(h, vma, address);
5978 /* Pressumably allocate_file_region_entries failed
5979 * to allocate a file_region struct. Clear
5980 * hugetlb_restore_reserve so that global reserve
5981 * count will not be incremented by free_huge_folio.
5982 * Act as if we consumed the reservation.
5984 folio_clear_hugetlb_restore_reserve(folio);
5986 vma_add_reservation(h, vma, address);
5989 tlb_remove_page_size(tlb, folio_page(folio, 0),
5992 * If we were instructed to unmap a specific folio, we're done.
5997 tlb_end_vma(tlb, vma);
6000 * If we unshared PMDs, the TLB flush was not recorded in mmu_gather. We
6001 * could defer the flush until now, since by holding i_mmap_rwsem we
6002 * guaranteed that the last refernece would not be dropped. But we must
6003 * do the flushing before we return, as otherwise i_mmap_rwsem will be
6004 * dropped and the last reference to the shared PMDs page might be
6007 * In theory we could defer the freeing of the PMD pages as well, but
6008 * huge_pmd_unshare() relies on the exact page_count for the PMD page to
6009 * detect sharing, so we cannot defer the release of the page either.
6010 * Instead, do flush now.
6013 tlb_flush_mmu_tlbonly(tlb);
6016 void __hugetlb_zap_begin(struct vm_area_struct *vma,
6017 unsigned long *start, unsigned long *end)
6019 if (!vma->vm_file) /* hugetlbfs_file_mmap error */
6022 adjust_range_if_pmd_sharing_possible(vma, start, end);
6023 hugetlb_vma_lock_write(vma);
6025 i_mmap_lock_write(vma->vm_file->f_mapping);
6028 void __hugetlb_zap_end(struct vm_area_struct *vma,
6029 struct zap_details *details)
6031 zap_flags_t zap_flags = details ? details->zap_flags : 0;
6033 if (!vma->vm_file) /* hugetlbfs_file_mmap error */
6036 if (zap_flags & ZAP_FLAG_UNMAP) { /* final unmap */
6038 * Unlock and free the vma lock before releasing i_mmap_rwsem.
6039 * When the vma_lock is freed, this makes the vma ineligible
6040 * for pmd sharing. And, i_mmap_rwsem is required to set up
6041 * pmd sharing. This is important as page tables for this
6042 * unmapped range will be asynchrously deleted. If the page
6043 * tables are shared, there will be issues when accessed by
6046 __hugetlb_vma_unlock_write_free(vma);
6048 hugetlb_vma_unlock_write(vma);
6052 i_mmap_unlock_write(vma->vm_file->f_mapping);
6055 void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
6056 unsigned long end, struct folio *folio,
6057 zap_flags_t zap_flags)
6059 struct mmu_notifier_range range;
6060 struct mmu_gather tlb;
6062 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
6064 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
6065 mmu_notifier_invalidate_range_start(&range);
6066 tlb_gather_mmu(&tlb, vma->vm_mm);
6068 __unmap_hugepage_range(&tlb, vma, start, end,
6071 mmu_notifier_invalidate_range_end(&range);
6072 tlb_finish_mmu(&tlb);
6076 * This is called when the original mapper is failing to COW a MAP_PRIVATE
6077 * mapping it owns the reserve page for. The intention is to unmap the page
6078 * from other VMAs and let the children be SIGKILLed if they are faulting the
6081 static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,
6082 struct folio *folio, unsigned long address)
6084 struct hstate *h = hstate_vma(vma);
6085 struct vm_area_struct *iter_vma;
6086 struct address_space *mapping;
6090 * vm_pgoff is in PAGE_SIZE units, hence the different calculation
6091 * from page cache lookup which is in HPAGE_SIZE units.
6093 address = address & huge_page_mask(h);
6094 pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) +
6096 mapping = vma->vm_file->f_mapping;
6099 * Take the mapping lock for the duration of the table walk. As
6100 * this mapping should be shared between all the VMAs,
6101 * __unmap_hugepage_range() is called as the lock is already held
6103 i_mmap_lock_write(mapping);
6104 vma_interval_tree_foreach(iter_vma, &mapping->i_mmap, pgoff, pgoff) {
6105 /* Do not unmap the current VMA */
6106 if (iter_vma == vma)
6110 * Shared VMAs have their own reserves and do not affect
6111 * MAP_PRIVATE accounting but it is possible that a shared
6112 * VMA is using the same page so check and skip such VMAs.
6114 if (iter_vma->vm_flags & VM_MAYSHARE)
6118 * Unmap the page from other VMAs without their own reserves.
6119 * They get marked to be SIGKILLed if they fault in these
6120 * areas. This is because a future no-page fault on this VMA
6121 * could insert a zeroed page instead of the data existing
6122 * from the time of fork. This would look like data corruption
6124 if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER))
6125 unmap_hugepage_range(iter_vma, address,
6126 address + huge_page_size(h),
6129 i_mmap_unlock_write(mapping);
6133 * hugetlb_wp() should be called with page lock of the original hugepage held.
6134 * Called with hugetlb_fault_mutex_table held and pte_page locked so we
6135 * cannot race with other handlers or page migration.
6136 * Keep the pte_same checks anyway to make transition from the mutex easier.
6138 static vm_fault_t hugetlb_wp(struct folio *pagecache_folio,
6139 struct vm_fault *vmf)
6141 struct vm_area_struct *vma = vmf->vma;
6142 struct mm_struct *mm = vma->vm_mm;
6143 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
6144 pte_t pte = huge_ptep_get(mm, vmf->address, vmf->pte);
6145 struct hstate *h = hstate_vma(vma);
6146 struct folio *old_folio;
6147 struct folio *new_folio;
6148 bool cow_from_owner = 0;
6150 struct mmu_notifier_range range;
6153 * Never handle CoW for uffd-wp protected pages. It should be only
6154 * handled when the uffd-wp protection is removed.
6156 * Note that only the CoW optimization path (in hugetlb_no_page())
6157 * can trigger this, because hugetlb_fault() will always resolve
6158 * uffd-wp bit first.
6160 if (!unshare && huge_pte_uffd_wp(pte))
6163 /* Let's take out MAP_SHARED mappings first. */
6164 if (vma->vm_flags & VM_MAYSHARE) {
6165 set_huge_ptep_writable(vma, vmf->address, vmf->pte);
6169 old_folio = page_folio(pte_page(pte));
6171 delayacct_wpcopy_start();
6175 * If no-one else is actually using this page, we're the exclusive
6176 * owner and can reuse this page.
6178 * Note that we don't rely on the (safer) folio refcount here, because
6179 * copying the hugetlb folio when there are unexpected (temporary)
6180 * folio references could harm simple fork()+exit() users when
6181 * we run out of free hugetlb folios: we would have to kill processes
6182 * in scenarios that used to work. As a side effect, there can still
6183 * be leaks between processes, for example, with FOLL_GET users.
6185 if (folio_mapcount(old_folio) == 1 && folio_test_anon(old_folio)) {
6186 if (!PageAnonExclusive(&old_folio->page)) {
6187 folio_move_anon_rmap(old_folio, vma);
6188 SetPageAnonExclusive(&old_folio->page);
6190 if (likely(!unshare))
6191 set_huge_ptep_maybe_writable(vma, vmf->address,
6194 delayacct_wpcopy_end();
6197 VM_BUG_ON_PAGE(folio_test_anon(old_folio) &&
6198 PageAnonExclusive(&old_folio->page), &old_folio->page);
6201 * If the process that created a MAP_PRIVATE mapping is about to
6202 * perform a COW due to a shared page count, attempt to satisfy
6203 * the allocation without using the existing reserves. The pagecache
6204 * page is used to determine if the reserve at this address was
6205 * consumed or not. If reserves were used, a partial faulted mapping
6206 * at the time of fork() could consume its reserves on COW instead
6207 * of the full address range.
6209 if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) &&
6210 old_folio != pagecache_folio)
6211 cow_from_owner = true;
6213 folio_get(old_folio);
6216 * Drop page table lock as buddy allocator may be called. It will
6217 * be acquired again before returning to the caller, as expected.
6219 spin_unlock(vmf->ptl);
6220 new_folio = alloc_hugetlb_folio(vma, vmf->address, cow_from_owner);
6222 if (IS_ERR(new_folio)) {
6224 * If a process owning a MAP_PRIVATE mapping fails to COW,
6225 * it is due to references held by a child and an insufficient
6226 * huge page pool. To guarantee the original mappers
6227 * reliability, unmap the page from child processes. The child
6228 * may get SIGKILLed if it later faults.
6230 if (cow_from_owner) {
6231 struct address_space *mapping = vma->vm_file->f_mapping;
6235 folio_put(old_folio);
6237 * Drop hugetlb_fault_mutex and vma_lock before
6238 * unmapping. unmapping needs to hold vma_lock
6239 * in write mode. Dropping vma_lock in read mode
6240 * here is OK as COW mappings do not interact with
6243 * Reacquire both after unmap operation.
6245 idx = vma_hugecache_offset(h, vma, vmf->address);
6246 hash = hugetlb_fault_mutex_hash(mapping, idx);
6247 hugetlb_vma_unlock_read(vma);
6248 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6250 unmap_ref_private(mm, vma, old_folio, vmf->address);
6252 mutex_lock(&hugetlb_fault_mutex_table[hash]);
6253 hugetlb_vma_lock_read(vma);
6254 spin_lock(vmf->ptl);
6255 vmf->pte = hugetlb_walk(vma, vmf->address,
6257 if (likely(vmf->pte &&
6258 pte_same(huge_ptep_get(mm, vmf->address, vmf->pte), pte)))
6259 goto retry_avoidcopy;
6261 * race occurs while re-acquiring page table
6262 * lock, and our job is done.
6264 delayacct_wpcopy_end();
6268 ret = vmf_error(PTR_ERR(new_folio));
6269 goto out_release_old;
6273 * When the original hugepage is shared one, it does not have
6274 * anon_vma prepared.
6276 ret = __vmf_anon_prepare(vmf);
6278 goto out_release_all;
6280 if (copy_user_large_folio(new_folio, old_folio, vmf->real_address, vma)) {
6281 ret = VM_FAULT_HWPOISON_LARGE | VM_FAULT_SET_HINDEX(hstate_index(h));
6282 goto out_release_all;
6284 __folio_mark_uptodate(new_folio);
6286 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, vmf->address,
6287 vmf->address + huge_page_size(h));
6288 mmu_notifier_invalidate_range_start(&range);
6291 * Retake the page table lock to check for racing updates
6292 * before the page tables are altered
6294 spin_lock(vmf->ptl);
6295 vmf->pte = hugetlb_walk(vma, vmf->address, huge_page_size(h));
6296 if (likely(vmf->pte && pte_same(huge_ptep_get(mm, vmf->address, vmf->pte), pte))) {
6297 pte_t newpte = make_huge_pte(vma, new_folio, !unshare);
6299 /* Break COW or unshare */
6300 huge_ptep_clear_flush(vma, vmf->address, vmf->pte);
6301 hugetlb_remove_rmap(old_folio);
6302 hugetlb_add_new_anon_rmap(new_folio, vma, vmf->address);
6303 if (huge_pte_uffd_wp(pte))
6304 newpte = huge_pte_mkuffd_wp(newpte);
6305 set_huge_pte_at(mm, vmf->address, vmf->pte, newpte,
6307 folio_set_hugetlb_migratable(new_folio);
6308 /* Make the old page be freed below */
6309 new_folio = old_folio;
6311 spin_unlock(vmf->ptl);
6312 mmu_notifier_invalidate_range_end(&range);
6315 * No restore in case of successful pagetable update (Break COW or
6318 if (new_folio != old_folio)
6319 restore_reserve_on_error(h, vma, vmf->address, new_folio);
6320 folio_put(new_folio);
6322 folio_put(old_folio);
6324 spin_lock(vmf->ptl); /* Caller expects lock to be held */
6326 delayacct_wpcopy_end();
6331 * Return whether there is a pagecache page to back given address within VMA.
6333 bool hugetlbfs_pagecache_present(struct hstate *h,
6334 struct vm_area_struct *vma, unsigned long address)
6336 struct address_space *mapping = vma->vm_file->f_mapping;
6337 pgoff_t idx = linear_page_index(vma, address);
6338 struct folio *folio;
6340 folio = filemap_get_folio(mapping, idx);
6347 int hugetlb_add_to_page_cache(struct folio *folio, struct address_space *mapping,
6350 struct inode *inode = mapping->host;
6351 struct hstate *h = hstate_inode(inode);
6354 idx <<= huge_page_order(h);
6355 __folio_set_locked(folio);
6356 err = __filemap_add_folio(mapping, folio, idx, GFP_KERNEL, NULL);
6358 if (unlikely(err)) {
6359 __folio_clear_locked(folio);
6362 folio_clear_hugetlb_restore_reserve(folio);
6365 * mark folio dirty so that it will not be removed from cache/file
6366 * by non-hugetlbfs specific code paths.
6368 folio_mark_dirty(folio);
6370 spin_lock(&inode->i_lock);
6371 inode->i_blocks += blocks_per_huge_page(h);
6372 spin_unlock(&inode->i_lock);
6376 static inline vm_fault_t hugetlb_handle_userfault(struct vm_fault *vmf,
6377 struct address_space *mapping,
6378 unsigned long reason)
6383 * vma_lock and hugetlb_fault_mutex must be dropped before handling
6384 * userfault. Also mmap_lock could be dropped due to handling
6385 * userfault, any vma operation should be careful from here.
6387 hugetlb_vma_unlock_read(vmf->vma);
6388 hash = hugetlb_fault_mutex_hash(mapping, vmf->pgoff);
6389 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6390 return handle_userfault(vmf, reason);
6394 * Recheck pte with pgtable lock. Returns true if pte didn't change, or
6395 * false if pte changed or is changing.
6397 static bool hugetlb_pte_stable(struct hstate *h, struct mm_struct *mm, unsigned long addr,
6398 pte_t *ptep, pte_t old_pte)
6403 ptl = huge_pte_lock(h, mm, ptep);
6404 same = pte_same(huge_ptep_get(mm, addr, ptep), old_pte);
6410 static vm_fault_t hugetlb_no_page(struct address_space *mapping,
6411 struct vm_fault *vmf)
6413 struct vm_area_struct *vma = vmf->vma;
6414 struct mm_struct *mm = vma->vm_mm;
6415 struct hstate *h = hstate_vma(vma);
6416 vm_fault_t ret = VM_FAULT_SIGBUS;
6419 struct folio *folio;
6421 bool new_folio, new_pagecache_folio = false;
6422 u32 hash = hugetlb_fault_mutex_hash(mapping, vmf->pgoff);
6425 * Currently, we are forced to kill the process in the event the
6426 * original mapper has unmapped pages from the child due to a failed
6427 * COW/unsharing. Warn that such a situation has occurred as it may not
6430 if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) {
6431 pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n",
6437 * Use page lock to guard against racing truncation
6438 * before we get page_table_lock.
6441 folio = filemap_lock_hugetlb_folio(h, mapping, vmf->pgoff);
6442 if (IS_ERR(folio)) {
6443 size = i_size_read(mapping->host) >> huge_page_shift(h);
6444 if (vmf->pgoff >= size)
6446 /* Check for page in userfault range */
6447 if (userfaultfd_missing(vma)) {
6449 * Since hugetlb_no_page() was examining pte
6450 * without pgtable lock, we need to re-test under
6451 * lock because the pte may not be stable and could
6452 * have changed from under us. Try to detect
6453 * either changed or during-changing ptes and retry
6454 * properly when needed.
6456 * Note that userfaultfd is actually fine with
6457 * false positives (e.g. caused by pte changed),
6458 * but not wrong logical events (e.g. caused by
6459 * reading a pte during changing). The latter can
6460 * confuse the userspace, so the strictness is very
6461 * much preferred. E.g., MISSING event should
6462 * never happen on the page after UFFDIO_COPY has
6463 * correctly installed the page and returned.
6465 if (!hugetlb_pte_stable(h, mm, vmf->address, vmf->pte, vmf->orig_pte)) {
6470 return hugetlb_handle_userfault(vmf, mapping,
6474 if (!(vma->vm_flags & VM_MAYSHARE)) {
6475 ret = __vmf_anon_prepare(vmf);
6480 folio = alloc_hugetlb_folio(vma, vmf->address, false);
6481 if (IS_ERR(folio)) {
6483 * Returning error will result in faulting task being
6484 * sent SIGBUS. The hugetlb fault mutex prevents two
6485 * tasks from racing to fault in the same page which
6486 * could result in false unable to allocate errors.
6487 * Page migration does not take the fault mutex, but
6488 * does a clear then write of pte's under page table
6489 * lock. Page fault code could race with migration,
6490 * notice the clear pte and try to allocate a page
6491 * here. Before returning error, get ptl and make
6492 * sure there really is no pte entry.
6494 if (hugetlb_pte_stable(h, mm, vmf->address, vmf->pte, vmf->orig_pte))
6495 ret = vmf_error(PTR_ERR(folio));
6500 folio_zero_user(folio, vmf->real_address);
6501 __folio_mark_uptodate(folio);
6504 if (vma->vm_flags & VM_MAYSHARE) {
6505 int err = hugetlb_add_to_page_cache(folio, mapping,
6509 * err can't be -EEXIST which implies someone
6510 * else consumed the reservation since hugetlb
6511 * fault mutex is held when add a hugetlb page
6512 * to the page cache. So it's safe to call
6513 * restore_reserve_on_error() here.
6515 restore_reserve_on_error(h, vma, vmf->address,
6518 ret = VM_FAULT_SIGBUS;
6521 new_pagecache_folio = true;
6528 * If memory error occurs between mmap() and fault, some process
6529 * don't have hwpoisoned swap entry for errored virtual address.
6530 * So we need to block hugepage fault by PG_hwpoison bit check.
6532 if (unlikely(folio_test_hwpoison(folio))) {
6533 ret = VM_FAULT_HWPOISON_LARGE |
6534 VM_FAULT_SET_HINDEX(hstate_index(h));
6535 goto backout_unlocked;
6538 /* Check for page in userfault range. */
6539 if (userfaultfd_minor(vma)) {
6540 folio_unlock(folio);
6542 /* See comment in userfaultfd_missing() block above */
6543 if (!hugetlb_pte_stable(h, mm, vmf->address, vmf->pte, vmf->orig_pte)) {
6547 return hugetlb_handle_userfault(vmf, mapping,
6553 * If we are going to COW a private mapping later, we examine the
6554 * pending reservations for this page now. This will ensure that
6555 * any allocations necessary to record that reservation occur outside
6558 if ((vmf->flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
6559 if (vma_needs_reservation(h, vma, vmf->address) < 0) {
6561 goto backout_unlocked;
6563 /* Just decrements count, does not deallocate */
6564 vma_end_reservation(h, vma, vmf->address);
6567 vmf->ptl = huge_pte_lock(h, mm, vmf->pte);
6569 /* If pte changed from under us, retry */
6570 if (!pte_same(huge_ptep_get(mm, vmf->address, vmf->pte), vmf->orig_pte))
6574 hugetlb_add_new_anon_rmap(folio, vma, vmf->address);
6576 hugetlb_add_file_rmap(folio);
6577 new_pte = make_huge_pte(vma, folio, vma->vm_flags & VM_SHARED);
6579 * If this pte was previously wr-protected, keep it wr-protected even
6582 if (unlikely(pte_marker_uffd_wp(vmf->orig_pte)))
6583 new_pte = huge_pte_mkuffd_wp(new_pte);
6584 set_huge_pte_at(mm, vmf->address, vmf->pte, new_pte, huge_page_size(h));
6586 hugetlb_count_add(pages_per_huge_page(h), mm);
6587 if ((vmf->flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
6588 /* Optimization, do the COW without a second fault */
6589 ret = hugetlb_wp(folio, vmf);
6592 spin_unlock(vmf->ptl);
6595 * Only set hugetlb_migratable in newly allocated pages. Existing pages
6596 * found in the pagecache may not have hugetlb_migratable if they have
6597 * been isolated for migration.
6600 folio_set_hugetlb_migratable(folio);
6602 folio_unlock(folio);
6604 hugetlb_vma_unlock_read(vma);
6607 * We must check to release the per-VMA lock. __vmf_anon_prepare() is
6608 * the only way ret can be set to VM_FAULT_RETRY.
6610 if (unlikely(ret & VM_FAULT_RETRY))
6613 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6617 spin_unlock(vmf->ptl);
6619 if (new_folio && !new_pagecache_folio)
6620 restore_reserve_on_error(h, vma, vmf->address, folio);
6622 folio_unlock(folio);
6628 u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
6630 unsigned long key[2];
6633 key[0] = (unsigned long) mapping;
6636 hash = jhash2((u32 *)&key, sizeof(key)/(sizeof(u32)), 0);
6638 return hash & (num_fault_mutexes - 1);
6642 * For uniprocessor systems we always use a single mutex, so just
6643 * return 0 and avoid the hashing overhead.
6645 u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
6651 vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,
6652 unsigned long address, unsigned int flags)
6656 struct folio *folio = NULL;
6657 struct folio *pagecache_folio = NULL;
6658 struct hstate *h = hstate_vma(vma);
6659 struct address_space *mapping;
6660 int need_wait_lock = 0;
6661 struct vm_fault vmf = {
6663 .address = address & huge_page_mask(h),
6664 .real_address = address,
6666 .pgoff = vma_hugecache_offset(h, vma,
6667 address & huge_page_mask(h)),
6668 /* TODO: Track hugetlb faults using vm_fault */
6671 * Some fields may not be initialized, be careful as it may
6672 * be hard to debug if called functions make assumptions
6677 * Serialize hugepage allocation and instantiation, so that we don't
6678 * get spurious allocation failures if two CPUs race to instantiate
6679 * the same page in the page cache.
6681 mapping = vma->vm_file->f_mapping;
6682 hash = hugetlb_fault_mutex_hash(mapping, vmf.pgoff);
6683 mutex_lock(&hugetlb_fault_mutex_table[hash]);
6686 * Acquire vma lock before calling huge_pte_alloc and hold
6687 * until finished with vmf.pte. This prevents huge_pmd_unshare from
6688 * being called elsewhere and making the vmf.pte no longer valid.
6690 hugetlb_vma_lock_read(vma);
6691 vmf.pte = huge_pte_alloc(mm, vma, vmf.address, huge_page_size(h));
6693 hugetlb_vma_unlock_read(vma);
6694 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6695 return VM_FAULT_OOM;
6698 vmf.orig_pte = huge_ptep_get(mm, vmf.address, vmf.pte);
6699 if (huge_pte_none_mostly(vmf.orig_pte)) {
6700 if (is_pte_marker(vmf.orig_pte)) {
6702 pte_marker_get(pte_to_swp_entry(vmf.orig_pte));
6704 if (marker & PTE_MARKER_POISONED) {
6705 ret = VM_FAULT_HWPOISON_LARGE |
6706 VM_FAULT_SET_HINDEX(hstate_index(h));
6708 } else if (WARN_ON_ONCE(marker & PTE_MARKER_GUARD)) {
6709 /* This isn't supported in hugetlb. */
6710 ret = VM_FAULT_SIGSEGV;
6716 * Other PTE markers should be handled the same way as none PTE.
6718 * hugetlb_no_page will drop vma lock and hugetlb fault
6719 * mutex internally, which make us return immediately.
6721 return hugetlb_no_page(mapping, &vmf);
6727 * vmf.orig_pte could be a migration/hwpoison vmf.orig_pte at this
6728 * point, so this check prevents the kernel from going below assuming
6729 * that we have an active hugepage in pagecache. This goto expects
6730 * the 2nd page fault, and is_hugetlb_entry_(migration|hwpoisoned)
6731 * check will properly handle it.
6733 if (!pte_present(vmf.orig_pte)) {
6734 if (unlikely(is_hugetlb_entry_migration(vmf.orig_pte))) {
6736 * Release the hugetlb fault lock now, but retain
6737 * the vma lock, because it is needed to guard the
6738 * huge_pte_lockptr() later in
6739 * migration_entry_wait_huge(). The vma lock will
6740 * be released there.
6742 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6743 migration_entry_wait_huge(vma, vmf.address, vmf.pte);
6745 } else if (unlikely(is_hugetlb_entry_hwpoisoned(vmf.orig_pte)))
6746 ret = VM_FAULT_HWPOISON_LARGE |
6747 VM_FAULT_SET_HINDEX(hstate_index(h));
6752 * If we are going to COW/unshare the mapping later, we examine the
6753 * pending reservations for this page now. This will ensure that any
6754 * allocations necessary to record that reservation occur outside the
6755 * spinlock. Also lookup the pagecache page now as it is used to
6756 * determine if a reservation has been consumed.
6758 if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) &&
6759 !(vma->vm_flags & VM_MAYSHARE) && !huge_pte_write(vmf.orig_pte)) {
6760 if (vma_needs_reservation(h, vma, vmf.address) < 0) {
6764 /* Just decrements count, does not deallocate */
6765 vma_end_reservation(h, vma, vmf.address);
6767 pagecache_folio = filemap_lock_hugetlb_folio(h, mapping,
6769 if (IS_ERR(pagecache_folio))
6770 pagecache_folio = NULL;
6773 vmf.ptl = huge_pte_lock(h, mm, vmf.pte);
6775 /* Check for a racing update before calling hugetlb_wp() */
6776 if (unlikely(!pte_same(vmf.orig_pte, huge_ptep_get(mm, vmf.address, vmf.pte))))
6779 /* Handle userfault-wp first, before trying to lock more pages */
6780 if (userfaultfd_wp(vma) && huge_pte_uffd_wp(huge_ptep_get(mm, vmf.address, vmf.pte)) &&
6781 (flags & FAULT_FLAG_WRITE) && !huge_pte_write(vmf.orig_pte)) {
6782 if (!userfaultfd_wp_async(vma)) {
6783 spin_unlock(vmf.ptl);
6784 if (pagecache_folio) {
6785 folio_unlock(pagecache_folio);
6786 folio_put(pagecache_folio);
6788 hugetlb_vma_unlock_read(vma);
6789 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6790 return handle_userfault(&vmf, VM_UFFD_WP);
6793 vmf.orig_pte = huge_pte_clear_uffd_wp(vmf.orig_pte);
6794 set_huge_pte_at(mm, vmf.address, vmf.pte, vmf.orig_pte,
6795 huge_page_size(hstate_vma(vma)));
6796 /* Fallthrough to CoW */
6800 * hugetlb_wp() requires page locks of pte_page(vmf.orig_pte) and
6801 * pagecache_folio, so here we need take the former one
6802 * when folio != pagecache_folio or !pagecache_folio.
6804 folio = page_folio(pte_page(vmf.orig_pte));
6805 if (folio != pagecache_folio)
6806 if (!folio_trylock(folio)) {
6813 if (flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) {
6814 if (!huge_pte_write(vmf.orig_pte)) {
6815 ret = hugetlb_wp(pagecache_folio, &vmf);
6817 } else if (likely(flags & FAULT_FLAG_WRITE)) {
6818 vmf.orig_pte = huge_pte_mkdirty(vmf.orig_pte);
6821 vmf.orig_pte = pte_mkyoung(vmf.orig_pte);
6822 if (huge_ptep_set_access_flags(vma, vmf.address, vmf.pte, vmf.orig_pte,
6823 flags & FAULT_FLAG_WRITE))
6824 update_mmu_cache(vma, vmf.address, vmf.pte);
6826 if (folio != pagecache_folio)
6827 folio_unlock(folio);
6830 spin_unlock(vmf.ptl);
6832 if (pagecache_folio) {
6833 folio_unlock(pagecache_folio);
6834 folio_put(pagecache_folio);
6837 hugetlb_vma_unlock_read(vma);
6840 * We must check to release the per-VMA lock. __vmf_anon_prepare() in
6841 * hugetlb_wp() is the only way ret can be set to VM_FAULT_RETRY.
6843 if (unlikely(ret & VM_FAULT_RETRY))
6846 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6848 * Generally it's safe to hold refcount during waiting page lock. But
6849 * here we just wait to defer the next page fault to avoid busy loop and
6850 * the page is not used after unlocked before returning from the current
6851 * page fault. So we are safe from accessing freed page, even if we wait
6852 * here without taking refcount.
6855 folio_wait_locked(folio);
6859 #ifdef CONFIG_USERFAULTFD
6861 * Can probably be eliminated, but still used by hugetlb_mfill_atomic_pte().
6863 static struct folio *alloc_hugetlb_folio_vma(struct hstate *h,
6864 struct vm_area_struct *vma, unsigned long address)
6866 struct mempolicy *mpol;
6867 nodemask_t *nodemask;
6868 struct folio *folio;
6872 gfp_mask = htlb_alloc_mask(h);
6873 node = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
6875 * This is used to allocate a temporary hugetlb to hold the copied
6876 * content, which will then be copied again to the final hugetlb
6877 * consuming a reservation. Set the alloc_fallback to false to indicate
6878 * that breaking the per-node hugetlb pool is not allowed in this case.
6880 folio = alloc_hugetlb_folio_nodemask(h, node, nodemask, gfp_mask, false);
6881 mpol_cond_put(mpol);
6887 * Used by userfaultfd UFFDIO_* ioctls. Based on userfaultfd's mfill_atomic_pte
6888 * with modifications for hugetlb pages.
6890 int hugetlb_mfill_atomic_pte(pte_t *dst_pte,
6891 struct vm_area_struct *dst_vma,
6892 unsigned long dst_addr,
6893 unsigned long src_addr,
6895 struct folio **foliop)
6897 struct mm_struct *dst_mm = dst_vma->vm_mm;
6898 bool is_continue = uffd_flags_mode_is(flags, MFILL_ATOMIC_CONTINUE);
6899 bool wp_enabled = (flags & MFILL_ATOMIC_WP);
6900 struct hstate *h = hstate_vma(dst_vma);
6901 struct address_space *mapping = dst_vma->vm_file->f_mapping;
6902 pgoff_t idx = vma_hugecache_offset(h, dst_vma, dst_addr);
6903 unsigned long size = huge_page_size(h);
6904 int vm_shared = dst_vma->vm_flags & VM_SHARED;
6908 struct folio *folio;
6909 bool folio_in_pagecache = false;
6911 if (uffd_flags_mode_is(flags, MFILL_ATOMIC_POISON)) {
6912 ptl = huge_pte_lock(h, dst_mm, dst_pte);
6914 /* Don't overwrite any existing PTEs (even markers) */
6915 if (!huge_pte_none(huge_ptep_get(dst_mm, dst_addr, dst_pte))) {
6920 _dst_pte = make_pte_marker(PTE_MARKER_POISONED);
6921 set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte, size);
6923 /* No need to invalidate - it was non-present before */
6924 update_mmu_cache(dst_vma, dst_addr, dst_pte);
6932 folio = filemap_lock_hugetlb_folio(h, mapping, idx);
6935 folio_in_pagecache = true;
6936 } else if (!*foliop) {
6937 /* If a folio already exists, then it's UFFDIO_COPY for
6938 * a non-missing case. Return -EEXIST.
6941 hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
6946 folio = alloc_hugetlb_folio(dst_vma, dst_addr, false);
6947 if (IS_ERR(folio)) {
6952 ret = copy_folio_from_user(folio, (const void __user *) src_addr,
6955 /* fallback to copy_from_user outside mmap_lock */
6956 if (unlikely(ret)) {
6958 /* Free the allocated folio which may have
6959 * consumed a reservation.
6961 restore_reserve_on_error(h, dst_vma, dst_addr, folio);
6964 /* Allocate a temporary folio to hold the copied
6967 folio = alloc_hugetlb_folio_vma(h, dst_vma, dst_addr);
6973 /* Set the outparam foliop and return to the caller to
6974 * copy the contents outside the lock. Don't free the
6981 hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
6988 folio = alloc_hugetlb_folio(dst_vma, dst_addr, false);
6989 if (IS_ERR(folio)) {
6995 ret = copy_user_large_folio(folio, *foliop, dst_addr, dst_vma);
7005 * If we just allocated a new page, we need a memory barrier to ensure
7006 * that preceding stores to the page become visible before the
7007 * set_pte_at() write. The memory barrier inside __folio_mark_uptodate
7010 * In the case where we have not allocated a new page (is_continue),
7011 * the page must already be uptodate. UFFDIO_CONTINUE already includes
7012 * an earlier smp_wmb() to ensure that prior stores will be visible
7013 * before the set_pte_at() write.
7016 __folio_mark_uptodate(folio);
7018 WARN_ON_ONCE(!folio_test_uptodate(folio));
7020 /* Add shared, newly allocated pages to the page cache. */
7021 if (vm_shared && !is_continue) {
7023 if (idx >= (i_size_read(mapping->host) >> huge_page_shift(h)))
7024 goto out_release_nounlock;
7027 * Serialization between remove_inode_hugepages() and
7028 * hugetlb_add_to_page_cache() below happens through the
7029 * hugetlb_fault_mutex_table that here must be hold by
7032 ret = hugetlb_add_to_page_cache(folio, mapping, idx);
7034 goto out_release_nounlock;
7035 folio_in_pagecache = true;
7038 ptl = huge_pte_lock(h, dst_mm, dst_pte);
7041 if (folio_test_hwpoison(folio))
7042 goto out_release_unlock;
7045 * We allow to overwrite a pte marker: consider when both MISSING|WP
7046 * registered, we firstly wr-protect a none pte which has no page cache
7047 * page backing it, then access the page.
7050 if (!huge_pte_none_mostly(huge_ptep_get(dst_mm, dst_addr, dst_pte)))
7051 goto out_release_unlock;
7053 if (folio_in_pagecache)
7054 hugetlb_add_file_rmap(folio);
7056 hugetlb_add_new_anon_rmap(folio, dst_vma, dst_addr);
7059 * For either: (1) CONTINUE on a non-shared VMA, or (2) UFFDIO_COPY
7060 * with wp flag set, don't set pte write bit.
7062 _dst_pte = make_huge_pte(dst_vma, folio,
7063 !wp_enabled && !(is_continue && !vm_shared));
7065 * Always mark UFFDIO_COPY page dirty; note that this may not be
7066 * extremely important for hugetlbfs for now since swapping is not
7067 * supported, but we should still be clear in that this page cannot be
7068 * thrown away at will, even if write bit not set.
7070 _dst_pte = huge_pte_mkdirty(_dst_pte);
7071 _dst_pte = pte_mkyoung(_dst_pte);
7074 _dst_pte = huge_pte_mkuffd_wp(_dst_pte);
7076 set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte, size);
7078 hugetlb_count_add(pages_per_huge_page(h), dst_mm);
7080 /* No need to invalidate - it was non-present before */
7081 update_mmu_cache(dst_vma, dst_addr, dst_pte);
7085 folio_set_hugetlb_migratable(folio);
7086 if (vm_shared || is_continue)
7087 folio_unlock(folio);
7093 if (vm_shared || is_continue)
7094 folio_unlock(folio);
7095 out_release_nounlock:
7096 if (!folio_in_pagecache)
7097 restore_reserve_on_error(h, dst_vma, dst_addr, folio);
7101 #endif /* CONFIG_USERFAULTFD */
7103 long hugetlb_change_protection(struct vm_area_struct *vma,
7104 unsigned long address, unsigned long end,
7105 pgprot_t newprot, unsigned long cp_flags)
7107 struct mm_struct *mm = vma->vm_mm;
7108 unsigned long start = address;
7111 struct hstate *h = hstate_vma(vma);
7112 long pages = 0, psize = huge_page_size(h);
7113 bool shared_pmd = false;
7114 struct mmu_notifier_range range;
7115 unsigned long last_addr_mask;
7116 bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
7117 bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
7120 * In the case of shared PMDs, the area to flush could be beyond
7121 * start/end. Set range.start/range.end to cover the maximum possible
7122 * range if PMD sharing is possible.
7124 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_VMA,
7126 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
7128 BUG_ON(address >= end);
7129 flush_cache_range(vma, range.start, range.end);
7131 mmu_notifier_invalidate_range_start(&range);
7132 hugetlb_vma_lock_write(vma);
7133 i_mmap_lock_write(vma->vm_file->f_mapping);
7134 last_addr_mask = hugetlb_mask_last_page(h);
7135 for (; address < end; address += psize) {
7137 ptep = hugetlb_walk(vma, address, psize);
7140 address |= last_addr_mask;
7144 * Userfaultfd wr-protect requires pgtable
7145 * pre-allocations to install pte markers.
7147 ptep = huge_pte_alloc(mm, vma, address, psize);
7153 ptl = huge_pte_lock(h, mm, ptep);
7154 if (huge_pmd_unshare(mm, vma, address, ptep)) {
7156 * When uffd-wp is enabled on the vma, unshare
7157 * shouldn't happen at all. Warn about it if it
7158 * happened due to some reason.
7160 WARN_ON_ONCE(uffd_wp || uffd_wp_resolve);
7164 address |= last_addr_mask;
7167 pte = huge_ptep_get(mm, address, ptep);
7168 if (unlikely(is_hugetlb_entry_hwpoisoned(pte))) {
7169 /* Nothing to do. */
7170 } else if (unlikely(is_hugetlb_entry_migration(pte))) {
7171 swp_entry_t entry = pte_to_swp_entry(pte);
7172 struct page *page = pfn_swap_entry_to_page(entry);
7175 if (is_writable_migration_entry(entry)) {
7177 entry = make_readable_exclusive_migration_entry(
7180 entry = make_readable_migration_entry(
7182 newpte = swp_entry_to_pte(entry);
7187 newpte = pte_swp_mkuffd_wp(newpte);
7188 else if (uffd_wp_resolve)
7189 newpte = pte_swp_clear_uffd_wp(newpte);
7190 if (!pte_same(pte, newpte))
7191 set_huge_pte_at(mm, address, ptep, newpte, psize);
7192 } else if (unlikely(is_pte_marker(pte))) {
7194 * Do nothing on a poison marker; page is
7195 * corrupted, permissons do not apply. Here
7196 * pte_marker_uffd_wp()==true implies !poison
7197 * because they're mutual exclusive.
7199 if (pte_marker_uffd_wp(pte) && uffd_wp_resolve)
7200 /* Safe to modify directly (non-present->none). */
7201 huge_pte_clear(mm, address, ptep, psize);
7202 } else if (!huge_pte_none(pte)) {
7204 unsigned int shift = huge_page_shift(hstate_vma(vma));
7206 old_pte = huge_ptep_modify_prot_start(vma, address, ptep);
7207 pte = huge_pte_modify(old_pte, newprot);
7208 pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
7210 pte = huge_pte_mkuffd_wp(pte);
7211 else if (uffd_wp_resolve)
7212 pte = huge_pte_clear_uffd_wp(pte);
7213 huge_ptep_modify_prot_commit(vma, address, ptep, old_pte, pte);
7217 if (unlikely(uffd_wp))
7218 /* Safe to modify directly (none->non-present). */
7219 set_huge_pte_at(mm, address, ptep,
7220 make_pte_marker(PTE_MARKER_UFFD_WP),
7226 * Must flush TLB before releasing i_mmap_rwsem: x86's huge_pmd_unshare
7227 * may have cleared our pud entry and done put_page on the page table:
7228 * once we release i_mmap_rwsem, another task can do the final put_page
7229 * and that page table be reused and filled with junk. If we actually
7230 * did unshare a page of pmds, flush the range corresponding to the pud.
7233 flush_hugetlb_tlb_range(vma, range.start, range.end);
7235 flush_hugetlb_tlb_range(vma, start, end);
7237 * No need to call mmu_notifier_arch_invalidate_secondary_tlbs() we are
7238 * downgrading page table protection not changing it to point to a new
7241 * See Documentation/mm/mmu_notifier.rst
7243 i_mmap_unlock_write(vma->vm_file->f_mapping);
7244 hugetlb_vma_unlock_write(vma);
7245 mmu_notifier_invalidate_range_end(&range);
7247 return pages > 0 ? (pages << h->order) : pages;
7250 /* Return true if reservation was successful, false otherwise. */
7251 bool hugetlb_reserve_pages(struct inode *inode,
7253 struct vm_area_struct *vma,
7254 vm_flags_t vm_flags)
7256 long chg = -1, add = -1, spool_resv, gbl_resv;
7257 struct hstate *h = hstate_inode(inode);
7258 struct hugepage_subpool *spool = subpool_inode(inode);
7259 struct resv_map *resv_map;
7260 struct hugetlb_cgroup *h_cg = NULL;
7261 long gbl_reserve, regions_needed = 0;
7263 /* This should never happen */
7265 VM_WARN(1, "%s called with a negative range\n", __func__);
7270 * vma specific semaphore used for pmd sharing and fault/truncation
7273 hugetlb_vma_lock_alloc(vma);
7276 * Only apply hugepage reservation if asked. At fault time, an
7277 * attempt will be made for VM_NORESERVE to allocate a page
7278 * without using reserves
7280 if (vm_flags & VM_NORESERVE)
7284 * Shared mappings base their reservation on the number of pages that
7285 * are already allocated on behalf of the file. Private mappings need
7286 * to reserve the full area even if read-only as mprotect() may be
7287 * called to make the mapping read-write. Assume !vma is a shm mapping
7289 if (!vma || vma->vm_flags & VM_MAYSHARE) {
7291 * resv_map can not be NULL as hugetlb_reserve_pages is only
7292 * called for inodes for which resv_maps were created (see
7293 * hugetlbfs_get_inode).
7295 resv_map = inode_resv_map(inode);
7297 chg = region_chg(resv_map, from, to, ®ions_needed);
7299 /* Private mapping. */
7300 resv_map = resv_map_alloc();
7306 set_vma_resv_map(vma, resv_map);
7307 set_vma_resv_flags(vma, HPAGE_RESV_OWNER);
7313 if (hugetlb_cgroup_charge_cgroup_rsvd(hstate_index(h),
7314 chg * pages_per_huge_page(h), &h_cg) < 0)
7317 if (vma && !(vma->vm_flags & VM_MAYSHARE) && h_cg) {
7318 /* For private mappings, the hugetlb_cgroup uncharge info hangs
7321 resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, h_cg, h);
7325 * There must be enough pages in the subpool for the mapping. If
7326 * the subpool has a minimum size, there may be some global
7327 * reservations already in place (gbl_reserve).
7329 gbl_reserve = hugepage_subpool_get_pages(spool, chg);
7330 if (gbl_reserve < 0)
7331 goto out_uncharge_cgroup;
7334 * Check enough hugepages are available for the reservation.
7335 * Hand the pages back to the subpool if there are not
7337 if (hugetlb_acct_memory(h, gbl_reserve) < 0)
7341 * Account for the reservations made. Shared mappings record regions
7342 * that have reservations as they are shared by multiple VMAs.
7343 * When the last VMA disappears, the region map says how much
7344 * the reservation was and the page cache tells how much of
7345 * the reservation was consumed. Private mappings are per-VMA and
7346 * only the consumed reservations are tracked. When the VMA
7347 * disappears, the original reservation is the VMA size and the
7348 * consumed reservations are stored in the map. Hence, nothing
7349 * else has to be done for private mappings here
7351 if (!vma || vma->vm_flags & VM_MAYSHARE) {
7352 add = region_add(resv_map, from, to, regions_needed, h, h_cg);
7354 if (unlikely(add < 0)) {
7355 hugetlb_acct_memory(h, -gbl_reserve);
7357 } else if (unlikely(chg > add)) {
7359 * pages in this range were added to the reserve
7360 * map between region_chg and region_add. This
7361 * indicates a race with alloc_hugetlb_folio. Adjust
7362 * the subpool and reserve counts modified above
7363 * based on the difference.
7368 * hugetlb_cgroup_uncharge_cgroup_rsvd() will put the
7369 * reference to h_cg->css. See comment below for detail.
7371 hugetlb_cgroup_uncharge_cgroup_rsvd(
7373 (chg - add) * pages_per_huge_page(h), h_cg);
7375 rsv_adjust = hugepage_subpool_put_pages(spool,
7377 hugetlb_acct_memory(h, -rsv_adjust);
7380 * The file_regions will hold their own reference to
7381 * h_cg->css. So we should release the reference held
7382 * via hugetlb_cgroup_charge_cgroup_rsvd() when we are
7385 hugetlb_cgroup_put_rsvd_cgroup(h_cg);
7391 spool_resv = chg - gbl_reserve;
7393 /* put sub pool's reservation back, chg - gbl_reserve */
7394 gbl_resv = hugepage_subpool_put_pages(spool, spool_resv);
7396 * subpool's reserved pages can not be put back due to race,
7399 hugetlb_acct_memory(h, -gbl_resv);
7401 out_uncharge_cgroup:
7402 hugetlb_cgroup_uncharge_cgroup_rsvd(hstate_index(h),
7403 chg * pages_per_huge_page(h), h_cg);
7405 hugetlb_vma_lock_free(vma);
7406 if (!vma || vma->vm_flags & VM_MAYSHARE)
7407 /* Only call region_abort if the region_chg succeeded but the
7408 * region_add failed or didn't run.
7410 if (chg >= 0 && add < 0)
7411 region_abort(resv_map, from, to, regions_needed);
7412 if (vma && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
7413 kref_put(&resv_map->refs, resv_map_release);
7414 set_vma_resv_map(vma, NULL);
7419 long hugetlb_unreserve_pages(struct inode *inode, long start, long end,
7422 struct hstate *h = hstate_inode(inode);
7423 struct resv_map *resv_map = inode_resv_map(inode);
7425 struct hugepage_subpool *spool = subpool_inode(inode);
7429 * Since this routine can be called in the evict inode path for all
7430 * hugetlbfs inodes, resv_map could be NULL.
7433 chg = region_del(resv_map, start, end);
7435 * region_del() can fail in the rare case where a region
7436 * must be split and another region descriptor can not be
7437 * allocated. If end == LONG_MAX, it will not fail.
7443 spin_lock(&inode->i_lock);
7444 inode->i_blocks -= (blocks_per_huge_page(h) * freed);
7445 spin_unlock(&inode->i_lock);
7448 * If the subpool has a minimum size, the number of global
7449 * reservations to be released may be adjusted.
7451 * Note that !resv_map implies freed == 0. So (chg - freed)
7452 * won't go negative.
7454 gbl_reserve = hugepage_subpool_put_pages(spool, (chg - freed));
7455 hugetlb_acct_memory(h, -gbl_reserve);
7460 #ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING
7461 static unsigned long page_table_shareable(struct vm_area_struct *svma,
7462 struct vm_area_struct *vma,
7463 unsigned long addr, pgoff_t idx)
7465 unsigned long saddr = ((idx - svma->vm_pgoff) << PAGE_SHIFT) +
7467 unsigned long sbase = saddr & PUD_MASK;
7468 unsigned long s_end = sbase + PUD_SIZE;
7470 /* Allow segments to share if only one is marked locked */
7471 unsigned long vm_flags = vma->vm_flags & ~VM_LOCKED_MASK;
7472 unsigned long svm_flags = svma->vm_flags & ~VM_LOCKED_MASK;
7475 * match the virtual addresses, permission and the alignment of the
7478 * Also, vma_lock (vm_private_data) is required for sharing.
7480 if (pmd_index(addr) != pmd_index(saddr) ||
7481 vm_flags != svm_flags ||
7482 !range_in_vma(svma, sbase, s_end) ||
7483 !svma->vm_private_data)
7489 bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
7491 unsigned long start = addr & PUD_MASK;
7492 unsigned long end = start + PUD_SIZE;
7494 #ifdef CONFIG_USERFAULTFD
7495 if (uffd_disable_huge_pmd_share(vma))
7499 * check on proper vm_flags and page table alignment
7501 if (!(vma->vm_flags & VM_MAYSHARE))
7503 if (!vma->vm_private_data) /* vma lock required for sharing */
7505 if (!range_in_vma(vma, start, end))
7511 * Determine if start,end range within vma could be mapped by shared pmd.
7512 * If yes, adjust start and end to cover range associated with possible
7513 * shared pmd mappings.
7515 void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
7516 unsigned long *start, unsigned long *end)
7518 unsigned long v_start = ALIGN(vma->vm_start, PUD_SIZE),
7519 v_end = ALIGN_DOWN(vma->vm_end, PUD_SIZE);
7522 * vma needs to span at least one aligned PUD size, and the range
7523 * must be at least partially within in.
7525 if (!(vma->vm_flags & VM_MAYSHARE) || !(v_end > v_start) ||
7526 (*end <= v_start) || (*start >= v_end))
7529 /* Extend the range to be PUD aligned for a worst case scenario */
7530 if (*start > v_start)
7531 *start = ALIGN_DOWN(*start, PUD_SIZE);
7534 *end = ALIGN(*end, PUD_SIZE);
7538 * Search for a shareable pmd page for hugetlb. In any case calls pmd_alloc()
7539 * and returns the corresponding pte. While this is not necessary for the
7540 * !shared pmd case because we can allocate the pmd later as well, it makes the
7541 * code much cleaner. pmd allocation is essential for the shared case because
7542 * pud has to be populated inside the same i_mmap_rwsem section - otherwise
7543 * racing tasks could either miss the sharing (see huge_pte_offset) or select a
7544 * bad pmd for sharing.
7546 pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
7547 unsigned long addr, pud_t *pud)
7549 struct address_space *mapping = vma->vm_file->f_mapping;
7550 pgoff_t idx = ((addr - vma->vm_start) >> PAGE_SHIFT) +
7552 struct vm_area_struct *svma;
7553 unsigned long saddr;
7557 i_mmap_lock_read(mapping);
7558 vma_interval_tree_foreach(svma, &mapping->i_mmap, idx, idx) {
7562 saddr = page_table_shareable(svma, vma, addr, idx);
7564 spte = hugetlb_walk(svma, saddr,
7565 vma_mmu_pagesize(svma));
7567 ptdesc_pmd_pts_inc(virt_to_ptdesc(spte));
7576 spin_lock(&mm->page_table_lock);
7577 if (pud_none(*pud)) {
7578 pud_populate(mm, pud,
7579 (pmd_t *)((unsigned long)spte & PAGE_MASK));
7582 ptdesc_pmd_pts_dec(virt_to_ptdesc(spte));
7584 spin_unlock(&mm->page_table_lock);
7586 pte = (pte_t *)pmd_alloc(mm, pud, addr);
7587 i_mmap_unlock_read(mapping);
7592 * unmap huge page backed by shared pte.
7594 * Called with page table lock held.
7596 * returns: 1 successfully unmapped a shared pte page
7597 * 0 the underlying pte page is not shared, or it is the last user
7599 int huge_pmd_unshare(struct mm_struct *mm, struct vm_area_struct *vma,
7600 unsigned long addr, pte_t *ptep)
7602 unsigned long sz = huge_page_size(hstate_vma(vma));
7603 pgd_t *pgd = pgd_offset(mm, addr);
7604 p4d_t *p4d = p4d_offset(pgd, addr);
7605 pud_t *pud = pud_offset(p4d, addr);
7607 i_mmap_assert_write_locked(vma->vm_file->f_mapping);
7608 hugetlb_vma_assert_locked(vma);
7611 if (!ptdesc_pmd_pts_count(virt_to_ptdesc(ptep)))
7616 * Once our caller drops the rmap lock, some other process might be
7617 * using this page table as a normal, non-hugetlb page table.
7618 * Wait for pending gup_fast() in other threads to finish before letting
7621 tlb_remove_table_sync_one();
7622 ptdesc_pmd_pts_dec(virt_to_ptdesc(ptep));
7627 #else /* !CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING */
7629 pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
7630 unsigned long addr, pud_t *pud)
7635 int huge_pmd_unshare(struct mm_struct *mm, struct vm_area_struct *vma,
7636 unsigned long addr, pte_t *ptep)
7641 void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
7642 unsigned long *start, unsigned long *end)
7646 bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
7650 #endif /* CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING */
7652 #ifdef CONFIG_ARCH_WANT_GENERAL_HUGETLB
7653 pte_t *huge_pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma,
7654 unsigned long addr, unsigned long sz)
7661 pgd = pgd_offset(mm, addr);
7662 p4d = p4d_alloc(mm, pgd, addr);
7665 pud = pud_alloc(mm, p4d, addr);
7667 if (sz == PUD_SIZE) {
7670 BUG_ON(sz != PMD_SIZE);
7671 if (want_pmd_share(vma, addr) && pud_none(*pud))
7672 pte = huge_pmd_share(mm, vma, addr, pud);
7674 pte = (pte_t *)pmd_alloc(mm, pud, addr);
7679 pte_t pteval = ptep_get_lockless(pte);
7681 BUG_ON(pte_present(pteval) && !pte_huge(pteval));
7688 * huge_pte_offset() - Walk the page table to resolve the hugepage
7689 * entry at address @addr
7691 * Return: Pointer to page table entry (PUD or PMD) for
7692 * address @addr, or NULL if a !p*d_present() entry is encountered and the
7693 * size @sz doesn't match the hugepage size at this level of the page
7696 pte_t *huge_pte_offset(struct mm_struct *mm,
7697 unsigned long addr, unsigned long sz)
7704 pgd = pgd_offset(mm, addr);
7705 if (!pgd_present(*pgd))
7707 p4d = p4d_offset(pgd, addr);
7708 if (!p4d_present(*p4d))
7711 pud = pud_offset(p4d, addr);
7713 /* must be pud huge, non-present or none */
7714 return (pte_t *)pud;
7715 if (!pud_present(*pud))
7717 /* must have a valid entry and size to go further */
7719 pmd = pmd_offset(pud, addr);
7720 /* must be pmd huge, non-present or none */
7721 return (pte_t *)pmd;
7725 * Return a mask that can be used to update an address to the last huge
7726 * page in a page table page mapping size. Used to skip non-present
7727 * page table entries when linearly scanning address ranges. Architectures
7728 * with unique huge page to page table relationships can define their own
7729 * version of this routine.
7731 unsigned long hugetlb_mask_last_page(struct hstate *h)
7733 unsigned long hp_size = huge_page_size(h);
7735 if (hp_size == PUD_SIZE)
7736 return P4D_SIZE - PUD_SIZE;
7737 else if (hp_size == PMD_SIZE)
7738 return PUD_SIZE - PMD_SIZE;
7745 /* See description above. Architectures can provide their own version. */
7746 __weak unsigned long hugetlb_mask_last_page(struct hstate *h)
7748 #ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING
7749 if (huge_page_size(h) == PMD_SIZE)
7750 return PUD_SIZE - PMD_SIZE;
7755 #endif /* CONFIG_ARCH_WANT_GENERAL_HUGETLB */
7758 * folio_isolate_hugetlb - try to isolate an allocated hugetlb folio
7759 * @folio: the folio to isolate
7760 * @list: the list to add the folio to on success
7762 * Isolate an allocated (refcount > 0) hugetlb folio, marking it as
7763 * isolated/non-migratable, and moving it from the active list to the
7766 * Isolation will fail if @folio is not an allocated hugetlb folio, or if
7767 * it is already isolated/non-migratable.
7769 * On success, an additional folio reference is taken that must be dropped
7770 * using folio_putback_hugetlb() to undo the isolation.
7772 * Return: True if isolation worked, otherwise False.
7774 bool folio_isolate_hugetlb(struct folio *folio, struct list_head *list)
7778 spin_lock_irq(&hugetlb_lock);
7779 if (!folio_test_hugetlb(folio) ||
7780 !folio_test_hugetlb_migratable(folio) ||
7781 !folio_try_get(folio)) {
7785 folio_clear_hugetlb_migratable(folio);
7786 list_move_tail(&folio->lru, list);
7788 spin_unlock_irq(&hugetlb_lock);
7792 int get_hwpoison_hugetlb_folio(struct folio *folio, bool *hugetlb, bool unpoison)
7797 spin_lock_irq(&hugetlb_lock);
7798 if (folio_test_hugetlb(folio)) {
7800 if (folio_test_hugetlb_freed(folio))
7802 else if (folio_test_hugetlb_migratable(folio) || unpoison)
7803 ret = folio_try_get(folio);
7807 spin_unlock_irq(&hugetlb_lock);
7811 int get_huge_page_for_hwpoison(unsigned long pfn, int flags,
7812 bool *migratable_cleared)
7816 spin_lock_irq(&hugetlb_lock);
7817 ret = __get_huge_page_for_hwpoison(pfn, flags, migratable_cleared);
7818 spin_unlock_irq(&hugetlb_lock);
7823 * folio_putback_hugetlb - unisolate a hugetlb folio
7824 * @folio: the isolated hugetlb folio
7826 * Putback/un-isolate the hugetlb folio that was previous isolated using
7827 * folio_isolate_hugetlb(): marking it non-isolated/migratable and putting it
7828 * back onto the active list.
7830 * Will drop the additional folio reference obtained through
7831 * folio_isolate_hugetlb().
7833 void folio_putback_hugetlb(struct folio *folio)
7835 spin_lock_irq(&hugetlb_lock);
7836 folio_set_hugetlb_migratable(folio);
7837 list_move_tail(&folio->lru, &(folio_hstate(folio))->hugepage_activelist);
7838 spin_unlock_irq(&hugetlb_lock);
7842 void move_hugetlb_state(struct folio *old_folio, struct folio *new_folio, int reason)
7844 struct hstate *h = folio_hstate(old_folio);
7846 hugetlb_cgroup_migrate(old_folio, new_folio);
7847 set_page_owner_migrate_reason(&new_folio->page, reason);
7850 * transfer temporary state of the new hugetlb folio. This is
7851 * reverse to other transitions because the newpage is going to
7852 * be final while the old one will be freed so it takes over
7853 * the temporary status.
7855 * Also note that we have to transfer the per-node surplus state
7856 * here as well otherwise the global surplus count will not match
7859 if (folio_test_hugetlb_temporary(new_folio)) {
7860 int old_nid = folio_nid(old_folio);
7861 int new_nid = folio_nid(new_folio);
7863 folio_set_hugetlb_temporary(old_folio);
7864 folio_clear_hugetlb_temporary(new_folio);
7868 * There is no need to transfer the per-node surplus state
7869 * when we do not cross the node.
7871 if (new_nid == old_nid)
7873 spin_lock_irq(&hugetlb_lock);
7874 if (h->surplus_huge_pages_node[old_nid]) {
7875 h->surplus_huge_pages_node[old_nid]--;
7876 h->surplus_huge_pages_node[new_nid]++;
7878 spin_unlock_irq(&hugetlb_lock);
7882 * Our old folio is isolated and has "migratable" cleared until it
7883 * is putback. As migration succeeded, set the new folio "migratable"
7884 * and add it to the active list.
7886 spin_lock_irq(&hugetlb_lock);
7887 folio_set_hugetlb_migratable(new_folio);
7888 list_move_tail(&new_folio->lru, &(folio_hstate(new_folio))->hugepage_activelist);
7889 spin_unlock_irq(&hugetlb_lock);
7893 * If @take_locks is false, the caller must ensure that no concurrent page table
7894 * access can happen (except for gup_fast() and hardware page walks).
7895 * If @take_locks is true, we take the hugetlb VMA lock (to lock out things like
7896 * concurrent page fault handling) and the file rmap lock.
7898 static void hugetlb_unshare_pmds(struct vm_area_struct *vma,
7899 unsigned long start,
7903 struct hstate *h = hstate_vma(vma);
7904 unsigned long sz = huge_page_size(h);
7905 struct mm_struct *mm = vma->vm_mm;
7906 struct mmu_notifier_range range;
7907 unsigned long address;
7911 if (!(vma->vm_flags & VM_MAYSHARE))
7917 flush_cache_range(vma, start, end);
7919 * No need to call adjust_range_if_pmd_sharing_possible(), because
7920 * we have already done the PUD_SIZE alignment.
7922 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
7924 mmu_notifier_invalidate_range_start(&range);
7926 hugetlb_vma_lock_write(vma);
7927 i_mmap_lock_write(vma->vm_file->f_mapping);
7929 i_mmap_assert_write_locked(vma->vm_file->f_mapping);
7931 for (address = start; address < end; address += PUD_SIZE) {
7932 ptep = hugetlb_walk(vma, address, sz);
7935 ptl = huge_pte_lock(h, mm, ptep);
7936 huge_pmd_unshare(mm, vma, address, ptep);
7939 flush_hugetlb_tlb_range(vma, start, end);
7941 i_mmap_unlock_write(vma->vm_file->f_mapping);
7942 hugetlb_vma_unlock_write(vma);
7945 * No need to call mmu_notifier_arch_invalidate_secondary_tlbs(), see
7946 * Documentation/mm/mmu_notifier.rst.
7948 mmu_notifier_invalidate_range_end(&range);
7952 * This function will unconditionally remove all the shared pmd pgtable entries
7953 * within the specific vma for a hugetlbfs memory range.
7955 void hugetlb_unshare_all_pmds(struct vm_area_struct *vma)
7957 hugetlb_unshare_pmds(vma, ALIGN(vma->vm_start, PUD_SIZE),
7958 ALIGN_DOWN(vma->vm_end, PUD_SIZE),
7959 /* take_locks = */ true);
7963 * For hugetlb, mremap() is an odd edge case - while the VMA copying is
7964 * performed, we permit both the old and new VMAs to reference the same
7967 * We fix this up after the operation succeeds, or if a newly allocated VMA
7968 * is closed as a result of a failure to allocate memory.
7970 void fixup_hugetlb_reservations(struct vm_area_struct *vma)
7972 if (is_vm_hugetlb_page(vma))
7973 clear_vma_resv_huge_pages(vma);