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/cpuset.h>
18 #include <linux/mutex.h>
19 #include <linux/memblock.h>
20 #include <linux/sysfs.h>
21 #include <linux/slab.h>
22 #include <linux/sched/mm.h>
23 #include <linux/mmdebug.h>
24 #include <linux/sched/signal.h>
25 #include <linux/rmap.h>
26 #include <linux/string_helpers.h>
27 #include <linux/swap.h>
28 #include <linux/swapops.h>
29 #include <linux/jhash.h>
30 #include <linux/numa.h>
31 #include <linux/llist.h>
32 #include <linux/cma.h>
33 #include <linux/migrate.h>
34 #include <linux/nospec.h>
35 #include <linux/delayacct.h>
36 #include <linux/memory.h>
39 #include <asm/pgalloc.h>
43 #include <linux/hugetlb.h>
44 #include <linux/hugetlb_cgroup.h>
45 #include <linux/node.h>
46 #include <linux/page_owner.h>
48 #include "hugetlb_vmemmap.h"
50 int hugetlb_max_hstate __read_mostly;
51 unsigned int default_hstate_idx;
52 struct hstate hstates[HUGE_MAX_HSTATE];
55 static struct cma *hugetlb_cma[MAX_NUMNODES];
56 static unsigned long hugetlb_cma_size_in_node[MAX_NUMNODES] __initdata;
57 static bool hugetlb_cma_page(struct page *page, unsigned int order)
59 return cma_pages_valid(hugetlb_cma[page_to_nid(page)], page,
63 static bool hugetlb_cma_page(struct page *page, unsigned int order)
68 static unsigned long hugetlb_cma_size __initdata;
70 __initdata LIST_HEAD(huge_boot_pages);
72 /* for command line parsing */
73 static struct hstate * __initdata parsed_hstate;
74 static unsigned long __initdata default_hstate_max_huge_pages;
75 static bool __initdata parsed_valid_hugepagesz = true;
76 static bool __initdata parsed_default_hugepagesz;
77 static unsigned int default_hugepages_in_node[MAX_NUMNODES] __initdata;
80 * Protects updates to hugepage_freelists, hugepage_activelist, nr_huge_pages,
81 * free_huge_pages, and surplus_huge_pages.
83 DEFINE_SPINLOCK(hugetlb_lock);
86 * Serializes faults on the same logical page. This is used to
87 * prevent spurious OOMs when the hugepage pool is fully utilized.
89 static int num_fault_mutexes;
90 struct mutex *hugetlb_fault_mutex_table ____cacheline_aligned_in_smp;
92 /* Forward declaration */
93 static int hugetlb_acct_memory(struct hstate *h, long delta);
94 static void hugetlb_vma_lock_free(struct vm_area_struct *vma);
95 static void hugetlb_vma_lock_alloc(struct vm_area_struct *vma);
96 static void __hugetlb_vma_unlock_write_free(struct vm_area_struct *vma);
97 static void hugetlb_unshare_pmds(struct vm_area_struct *vma,
98 unsigned long start, unsigned long end);
99 static struct resv_map *vma_resv_map(struct vm_area_struct *vma);
101 static inline bool subpool_is_free(struct hugepage_subpool *spool)
105 if (spool->max_hpages != -1)
106 return spool->used_hpages == 0;
107 if (spool->min_hpages != -1)
108 return spool->rsv_hpages == spool->min_hpages;
113 static inline void unlock_or_release_subpool(struct hugepage_subpool *spool,
114 unsigned long irq_flags)
116 spin_unlock_irqrestore(&spool->lock, irq_flags);
118 /* If no pages are used, and no other handles to the subpool
119 * remain, give up any reservations based on minimum size and
120 * free the subpool */
121 if (subpool_is_free(spool)) {
122 if (spool->min_hpages != -1)
123 hugetlb_acct_memory(spool->hstate,
129 struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages,
132 struct hugepage_subpool *spool;
134 spool = kzalloc(sizeof(*spool), GFP_KERNEL);
138 spin_lock_init(&spool->lock);
140 spool->max_hpages = max_hpages;
142 spool->min_hpages = min_hpages;
144 if (min_hpages != -1 && hugetlb_acct_memory(h, min_hpages)) {
148 spool->rsv_hpages = min_hpages;
153 void hugepage_put_subpool(struct hugepage_subpool *spool)
157 spin_lock_irqsave(&spool->lock, flags);
158 BUG_ON(!spool->count);
160 unlock_or_release_subpool(spool, flags);
164 * Subpool accounting for allocating and reserving pages.
165 * Return -ENOMEM if there are not enough resources to satisfy the
166 * request. Otherwise, return the number of pages by which the
167 * global pools must be adjusted (upward). The returned value may
168 * only be different than the passed value (delta) in the case where
169 * a subpool minimum size must be maintained.
171 static long hugepage_subpool_get_pages(struct hugepage_subpool *spool,
179 spin_lock_irq(&spool->lock);
181 if (spool->max_hpages != -1) { /* maximum size accounting */
182 if ((spool->used_hpages + delta) <= spool->max_hpages)
183 spool->used_hpages += delta;
190 /* minimum size accounting */
191 if (spool->min_hpages != -1 && spool->rsv_hpages) {
192 if (delta > spool->rsv_hpages) {
194 * Asking for more reserves than those already taken on
195 * behalf of subpool. Return difference.
197 ret = delta - spool->rsv_hpages;
198 spool->rsv_hpages = 0;
200 ret = 0; /* reserves already accounted for */
201 spool->rsv_hpages -= delta;
206 spin_unlock_irq(&spool->lock);
211 * Subpool accounting for freeing and unreserving pages.
212 * Return the number of global page reservations that must be dropped.
213 * The return value may only be different than the passed value (delta)
214 * in the case where a subpool minimum size must be maintained.
216 static long hugepage_subpool_put_pages(struct hugepage_subpool *spool,
225 spin_lock_irqsave(&spool->lock, flags);
227 if (spool->max_hpages != -1) /* maximum size accounting */
228 spool->used_hpages -= delta;
230 /* minimum size accounting */
231 if (spool->min_hpages != -1 && spool->used_hpages < spool->min_hpages) {
232 if (spool->rsv_hpages + delta <= spool->min_hpages)
235 ret = spool->rsv_hpages + delta - spool->min_hpages;
237 spool->rsv_hpages += delta;
238 if (spool->rsv_hpages > spool->min_hpages)
239 spool->rsv_hpages = spool->min_hpages;
243 * If hugetlbfs_put_super couldn't free spool due to an outstanding
244 * quota reference, free it now.
246 unlock_or_release_subpool(spool, flags);
251 static inline struct hugepage_subpool *subpool_inode(struct inode *inode)
253 return HUGETLBFS_SB(inode->i_sb)->spool;
256 static inline struct hugepage_subpool *subpool_vma(struct vm_area_struct *vma)
258 return subpool_inode(file_inode(vma->vm_file));
262 * hugetlb vma_lock helper routines
264 static bool __vma_shareable_lock(struct vm_area_struct *vma)
266 return vma->vm_flags & (VM_MAYSHARE | VM_SHARED) &&
267 vma->vm_private_data;
270 void hugetlb_vma_lock_read(struct vm_area_struct *vma)
272 if (__vma_shareable_lock(vma)) {
273 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
275 down_read(&vma_lock->rw_sema);
276 } else if (__vma_private_lock(vma)) {
277 struct resv_map *resv_map = vma_resv_map(vma);
279 down_read(&resv_map->rw_sema);
283 void hugetlb_vma_unlock_read(struct vm_area_struct *vma)
285 if (__vma_shareable_lock(vma)) {
286 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
288 up_read(&vma_lock->rw_sema);
289 } else if (__vma_private_lock(vma)) {
290 struct resv_map *resv_map = vma_resv_map(vma);
292 up_read(&resv_map->rw_sema);
296 void hugetlb_vma_lock_write(struct vm_area_struct *vma)
298 if (__vma_shareable_lock(vma)) {
299 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
301 down_write(&vma_lock->rw_sema);
302 } else if (__vma_private_lock(vma)) {
303 struct resv_map *resv_map = vma_resv_map(vma);
305 down_write(&resv_map->rw_sema);
309 void hugetlb_vma_unlock_write(struct vm_area_struct *vma)
311 if (__vma_shareable_lock(vma)) {
312 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
314 up_write(&vma_lock->rw_sema);
315 } else if (__vma_private_lock(vma)) {
316 struct resv_map *resv_map = vma_resv_map(vma);
318 up_write(&resv_map->rw_sema);
322 int hugetlb_vma_trylock_write(struct vm_area_struct *vma)
325 if (__vma_shareable_lock(vma)) {
326 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
328 return down_write_trylock(&vma_lock->rw_sema);
329 } else if (__vma_private_lock(vma)) {
330 struct resv_map *resv_map = vma_resv_map(vma);
332 return down_write_trylock(&resv_map->rw_sema);
338 void hugetlb_vma_assert_locked(struct vm_area_struct *vma)
340 if (__vma_shareable_lock(vma)) {
341 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
343 lockdep_assert_held(&vma_lock->rw_sema);
344 } else if (__vma_private_lock(vma)) {
345 struct resv_map *resv_map = vma_resv_map(vma);
347 lockdep_assert_held(&resv_map->rw_sema);
351 void hugetlb_vma_lock_release(struct kref *kref)
353 struct hugetlb_vma_lock *vma_lock = container_of(kref,
354 struct hugetlb_vma_lock, refs);
359 static void __hugetlb_vma_unlock_write_put(struct hugetlb_vma_lock *vma_lock)
361 struct vm_area_struct *vma = vma_lock->vma;
364 * vma_lock structure may or not be released as a result of put,
365 * it certainly will no longer be attached to vma so clear pointer.
366 * Semaphore synchronizes access to vma_lock->vma field.
368 vma_lock->vma = NULL;
369 vma->vm_private_data = NULL;
370 up_write(&vma_lock->rw_sema);
371 kref_put(&vma_lock->refs, hugetlb_vma_lock_release);
374 static void __hugetlb_vma_unlock_write_free(struct vm_area_struct *vma)
376 if (__vma_shareable_lock(vma)) {
377 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
379 __hugetlb_vma_unlock_write_put(vma_lock);
380 } else if (__vma_private_lock(vma)) {
381 struct resv_map *resv_map = vma_resv_map(vma);
383 /* no free for anon vmas, but still need to unlock */
384 up_write(&resv_map->rw_sema);
388 static void hugetlb_vma_lock_free(struct vm_area_struct *vma)
391 * Only present in sharable vmas.
393 if (!vma || !__vma_shareable_lock(vma))
396 if (vma->vm_private_data) {
397 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
399 down_write(&vma_lock->rw_sema);
400 __hugetlb_vma_unlock_write_put(vma_lock);
404 static void hugetlb_vma_lock_alloc(struct vm_area_struct *vma)
406 struct hugetlb_vma_lock *vma_lock;
408 /* Only establish in (flags) sharable vmas */
409 if (!vma || !(vma->vm_flags & VM_MAYSHARE))
412 /* Should never get here with non-NULL vm_private_data */
413 if (vma->vm_private_data)
416 vma_lock = kmalloc(sizeof(*vma_lock), GFP_KERNEL);
419 * If we can not allocate structure, then vma can not
420 * participate in pmd sharing. This is only a possible
421 * performance enhancement and memory saving issue.
422 * However, the lock is also used to synchronize page
423 * faults with truncation. If the lock is not present,
424 * unlikely races could leave pages in a file past i_size
425 * until the file is removed. Warn in the unlikely case of
426 * allocation failure.
428 pr_warn_once("HugeTLB: unable to allocate vma specific lock\n");
432 kref_init(&vma_lock->refs);
433 init_rwsem(&vma_lock->rw_sema);
435 vma->vm_private_data = vma_lock;
438 /* Helper that removes a struct file_region from the resv_map cache and returns
441 static struct file_region *
442 get_file_region_entry_from_cache(struct resv_map *resv, long from, long to)
444 struct file_region *nrg;
446 VM_BUG_ON(resv->region_cache_count <= 0);
448 resv->region_cache_count--;
449 nrg = list_first_entry(&resv->region_cache, struct file_region, link);
450 list_del(&nrg->link);
458 static void copy_hugetlb_cgroup_uncharge_info(struct file_region *nrg,
459 struct file_region *rg)
461 #ifdef CONFIG_CGROUP_HUGETLB
462 nrg->reservation_counter = rg->reservation_counter;
469 /* Helper that records hugetlb_cgroup uncharge info. */
470 static void record_hugetlb_cgroup_uncharge_info(struct hugetlb_cgroup *h_cg,
472 struct resv_map *resv,
473 struct file_region *nrg)
475 #ifdef CONFIG_CGROUP_HUGETLB
477 nrg->reservation_counter =
478 &h_cg->rsvd_hugepage[hstate_index(h)];
479 nrg->css = &h_cg->css;
481 * The caller will hold exactly one h_cg->css reference for the
482 * whole contiguous reservation region. But this area might be
483 * scattered when there are already some file_regions reside in
484 * it. As a result, many file_regions may share only one css
485 * reference. In order to ensure that one file_region must hold
486 * exactly one h_cg->css reference, we should do css_get for
487 * each file_region and leave the reference held by caller
491 if (!resv->pages_per_hpage)
492 resv->pages_per_hpage = pages_per_huge_page(h);
493 /* pages_per_hpage should be the same for all entries in
496 VM_BUG_ON(resv->pages_per_hpage != pages_per_huge_page(h));
498 nrg->reservation_counter = NULL;
504 static void put_uncharge_info(struct file_region *rg)
506 #ifdef CONFIG_CGROUP_HUGETLB
512 static bool has_same_uncharge_info(struct file_region *rg,
513 struct file_region *org)
515 #ifdef CONFIG_CGROUP_HUGETLB
516 return rg->reservation_counter == org->reservation_counter &&
524 static void coalesce_file_region(struct resv_map *resv, struct file_region *rg)
526 struct file_region *nrg, *prg;
528 prg = list_prev_entry(rg, link);
529 if (&prg->link != &resv->regions && prg->to == rg->from &&
530 has_same_uncharge_info(prg, rg)) {
534 put_uncharge_info(rg);
540 nrg = list_next_entry(rg, link);
541 if (&nrg->link != &resv->regions && nrg->from == rg->to &&
542 has_same_uncharge_info(nrg, rg)) {
543 nrg->from = rg->from;
546 put_uncharge_info(rg);
552 hugetlb_resv_map_add(struct resv_map *map, struct list_head *rg, long from,
553 long to, struct hstate *h, struct hugetlb_cgroup *cg,
554 long *regions_needed)
556 struct file_region *nrg;
558 if (!regions_needed) {
559 nrg = get_file_region_entry_from_cache(map, from, to);
560 record_hugetlb_cgroup_uncharge_info(cg, h, map, nrg);
561 list_add(&nrg->link, rg);
562 coalesce_file_region(map, nrg);
564 *regions_needed += 1;
570 * Must be called with resv->lock held.
572 * Calling this with regions_needed != NULL will count the number of pages
573 * to be added but will not modify the linked list. And regions_needed will
574 * indicate the number of file_regions needed in the cache to carry out to add
575 * the regions for this range.
577 static long add_reservation_in_range(struct resv_map *resv, long f, long t,
578 struct hugetlb_cgroup *h_cg,
579 struct hstate *h, long *regions_needed)
582 struct list_head *head = &resv->regions;
583 long last_accounted_offset = f;
584 struct file_region *iter, *trg = NULL;
585 struct list_head *rg = NULL;
590 /* In this loop, we essentially handle an entry for the range
591 * [last_accounted_offset, iter->from), at every iteration, with some
594 list_for_each_entry_safe(iter, trg, head, link) {
595 /* Skip irrelevant regions that start before our range. */
596 if (iter->from < f) {
597 /* If this region ends after the last accounted offset,
598 * then we need to update last_accounted_offset.
600 if (iter->to > last_accounted_offset)
601 last_accounted_offset = iter->to;
605 /* When we find a region that starts beyond our range, we've
608 if (iter->from >= t) {
609 rg = iter->link.prev;
613 /* Add an entry for last_accounted_offset -> iter->from, and
614 * update last_accounted_offset.
616 if (iter->from > last_accounted_offset)
617 add += hugetlb_resv_map_add(resv, iter->link.prev,
618 last_accounted_offset,
622 last_accounted_offset = iter->to;
625 /* Handle the case where our range extends beyond
626 * last_accounted_offset.
630 if (last_accounted_offset < t)
631 add += hugetlb_resv_map_add(resv, rg, last_accounted_offset,
632 t, h, h_cg, regions_needed);
637 /* Must be called with resv->lock acquired. Will drop lock to allocate entries.
639 static int allocate_file_region_entries(struct resv_map *resv,
641 __must_hold(&resv->lock)
643 LIST_HEAD(allocated_regions);
644 int to_allocate = 0, i = 0;
645 struct file_region *trg = NULL, *rg = NULL;
647 VM_BUG_ON(regions_needed < 0);
650 * Check for sufficient descriptors in the cache to accommodate
651 * the number of in progress add operations plus regions_needed.
653 * This is a while loop because when we drop the lock, some other call
654 * to region_add or region_del may have consumed some region_entries,
655 * so we keep looping here until we finally have enough entries for
656 * (adds_in_progress + regions_needed).
658 while (resv->region_cache_count <
659 (resv->adds_in_progress + regions_needed)) {
660 to_allocate = resv->adds_in_progress + regions_needed -
661 resv->region_cache_count;
663 /* At this point, we should have enough entries in the cache
664 * for all the existing adds_in_progress. We should only be
665 * needing to allocate for regions_needed.
667 VM_BUG_ON(resv->region_cache_count < resv->adds_in_progress);
669 spin_unlock(&resv->lock);
670 for (i = 0; i < to_allocate; i++) {
671 trg = kmalloc(sizeof(*trg), GFP_KERNEL);
674 list_add(&trg->link, &allocated_regions);
677 spin_lock(&resv->lock);
679 list_splice(&allocated_regions, &resv->region_cache);
680 resv->region_cache_count += to_allocate;
686 list_for_each_entry_safe(rg, trg, &allocated_regions, link) {
694 * Add the huge page range represented by [f, t) to the reserve
695 * map. Regions will be taken from the cache to fill in this range.
696 * Sufficient regions should exist in the cache due to the previous
697 * call to region_chg with the same range, but in some cases the cache will not
698 * have sufficient entries due to races with other code doing region_add or
699 * region_del. The extra needed entries will be allocated.
701 * regions_needed is the out value provided by a previous call to region_chg.
703 * Return the number of new huge pages added to the map. This number is greater
704 * than or equal to zero. If file_region entries needed to be allocated for
705 * this operation and we were not able to allocate, it returns -ENOMEM.
706 * region_add of regions of length 1 never allocate file_regions and cannot
707 * fail; region_chg will always allocate at least 1 entry and a region_add for
708 * 1 page will only require at most 1 entry.
710 static long region_add(struct resv_map *resv, long f, long t,
711 long in_regions_needed, struct hstate *h,
712 struct hugetlb_cgroup *h_cg)
714 long add = 0, actual_regions_needed = 0;
716 spin_lock(&resv->lock);
719 /* Count how many regions are actually needed to execute this add. */
720 add_reservation_in_range(resv, f, t, NULL, NULL,
721 &actual_regions_needed);
724 * Check for sufficient descriptors in the cache to accommodate
725 * this add operation. Note that actual_regions_needed may be greater
726 * than in_regions_needed, as the resv_map may have been modified since
727 * the region_chg call. In this case, we need to make sure that we
728 * allocate extra entries, such that we have enough for all the
729 * existing adds_in_progress, plus the excess needed for this
732 if (actual_regions_needed > in_regions_needed &&
733 resv->region_cache_count <
734 resv->adds_in_progress +
735 (actual_regions_needed - in_regions_needed)) {
736 /* region_add operation of range 1 should never need to
737 * allocate file_region entries.
739 VM_BUG_ON(t - f <= 1);
741 if (allocate_file_region_entries(
742 resv, actual_regions_needed - in_regions_needed)) {
749 add = add_reservation_in_range(resv, f, t, h_cg, h, NULL);
751 resv->adds_in_progress -= in_regions_needed;
753 spin_unlock(&resv->lock);
758 * Examine the existing reserve map and determine how many
759 * huge pages in the specified range [f, t) are NOT currently
760 * represented. This routine is called before a subsequent
761 * call to region_add that will actually modify the reserve
762 * map to add the specified range [f, t). region_chg does
763 * not change the number of huge pages represented by the
764 * map. A number of new file_region structures is added to the cache as a
765 * placeholder, for the subsequent region_add call to use. At least 1
766 * file_region structure is added.
768 * out_regions_needed is the number of regions added to the
769 * resv->adds_in_progress. This value needs to be provided to a follow up call
770 * to region_add or region_abort for proper accounting.
772 * Returns the number of huge pages that need to be added to the existing
773 * reservation map for the range [f, t). This number is greater or equal to
774 * zero. -ENOMEM is returned if a new file_region structure or cache entry
775 * is needed and can not be allocated.
777 static long region_chg(struct resv_map *resv, long f, long t,
778 long *out_regions_needed)
782 spin_lock(&resv->lock);
784 /* Count how many hugepages in this range are NOT represented. */
785 chg = add_reservation_in_range(resv, f, t, NULL, NULL,
788 if (*out_regions_needed == 0)
789 *out_regions_needed = 1;
791 if (allocate_file_region_entries(resv, *out_regions_needed))
794 resv->adds_in_progress += *out_regions_needed;
796 spin_unlock(&resv->lock);
801 * Abort the in progress add operation. The adds_in_progress field
802 * of the resv_map keeps track of the operations in progress between
803 * calls to region_chg and region_add. Operations are sometimes
804 * aborted after the call to region_chg. In such cases, region_abort
805 * is called to decrement the adds_in_progress counter. regions_needed
806 * is the value returned by the region_chg call, it is used to decrement
807 * the adds_in_progress counter.
809 * NOTE: The range arguments [f, t) are not needed or used in this
810 * routine. They are kept to make reading the calling code easier as
811 * arguments will match the associated region_chg call.
813 static void region_abort(struct resv_map *resv, long f, long t,
816 spin_lock(&resv->lock);
817 VM_BUG_ON(!resv->region_cache_count);
818 resv->adds_in_progress -= regions_needed;
819 spin_unlock(&resv->lock);
823 * Delete the specified range [f, t) from the reserve map. If the
824 * t parameter is LONG_MAX, this indicates that ALL regions after f
825 * should be deleted. Locate the regions which intersect [f, t)
826 * and either trim, delete or split the existing regions.
828 * Returns the number of huge pages deleted from the reserve map.
829 * In the normal case, the return value is zero or more. In the
830 * case where a region must be split, a new region descriptor must
831 * be allocated. If the allocation fails, -ENOMEM will be returned.
832 * NOTE: If the parameter t == LONG_MAX, then we will never split
833 * a region and possibly return -ENOMEM. Callers specifying
834 * t == LONG_MAX do not need to check for -ENOMEM error.
836 static long region_del(struct resv_map *resv, long f, long t)
838 struct list_head *head = &resv->regions;
839 struct file_region *rg, *trg;
840 struct file_region *nrg = NULL;
844 spin_lock(&resv->lock);
845 list_for_each_entry_safe(rg, trg, head, link) {
847 * Skip regions before the range to be deleted. file_region
848 * ranges are normally of the form [from, to). However, there
849 * may be a "placeholder" entry in the map which is of the form
850 * (from, to) with from == to. Check for placeholder entries
851 * at the beginning of the range to be deleted.
853 if (rg->to <= f && (rg->to != rg->from || rg->to != f))
859 if (f > rg->from && t < rg->to) { /* Must split region */
861 * Check for an entry in the cache before dropping
862 * lock and attempting allocation.
865 resv->region_cache_count > resv->adds_in_progress) {
866 nrg = list_first_entry(&resv->region_cache,
869 list_del(&nrg->link);
870 resv->region_cache_count--;
874 spin_unlock(&resv->lock);
875 nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
882 hugetlb_cgroup_uncharge_file_region(
883 resv, rg, t - f, false);
885 /* New entry for end of split region */
889 copy_hugetlb_cgroup_uncharge_info(nrg, rg);
891 INIT_LIST_HEAD(&nrg->link);
893 /* Original entry is trimmed */
896 list_add(&nrg->link, &rg->link);
901 if (f <= rg->from && t >= rg->to) { /* Remove entire region */
902 del += rg->to - rg->from;
903 hugetlb_cgroup_uncharge_file_region(resv, rg,
904 rg->to - rg->from, true);
910 if (f <= rg->from) { /* Trim beginning of region */
911 hugetlb_cgroup_uncharge_file_region(resv, rg,
912 t - rg->from, false);
916 } else { /* Trim end of region */
917 hugetlb_cgroup_uncharge_file_region(resv, rg,
925 spin_unlock(&resv->lock);
931 * A rare out of memory error was encountered which prevented removal of
932 * the reserve map region for a page. The huge page itself was free'ed
933 * and removed from the page cache. This routine will adjust the subpool
934 * usage count, and the global reserve count if needed. By incrementing
935 * these counts, the reserve map entry which could not be deleted will
936 * appear as a "reserved" entry instead of simply dangling with incorrect
939 void hugetlb_fix_reserve_counts(struct inode *inode)
941 struct hugepage_subpool *spool = subpool_inode(inode);
943 bool reserved = false;
945 rsv_adjust = hugepage_subpool_get_pages(spool, 1);
946 if (rsv_adjust > 0) {
947 struct hstate *h = hstate_inode(inode);
949 if (!hugetlb_acct_memory(h, 1))
951 } else if (!rsv_adjust) {
956 pr_warn("hugetlb: Huge Page Reserved count may go negative.\n");
960 * Count and return the number of huge pages in the reserve map
961 * that intersect with the range [f, t).
963 static long region_count(struct resv_map *resv, long f, long t)
965 struct list_head *head = &resv->regions;
966 struct file_region *rg;
969 spin_lock(&resv->lock);
970 /* Locate each segment we overlap with, and count that overlap. */
971 list_for_each_entry(rg, head, link) {
980 seg_from = max(rg->from, f);
981 seg_to = min(rg->to, t);
983 chg += seg_to - seg_from;
985 spin_unlock(&resv->lock);
991 * Convert the address within this vma to the page offset within
992 * the mapping, in pagecache page units; huge pages here.
994 static pgoff_t vma_hugecache_offset(struct hstate *h,
995 struct vm_area_struct *vma, unsigned long address)
997 return ((address - vma->vm_start) >> huge_page_shift(h)) +
998 (vma->vm_pgoff >> huge_page_order(h));
1001 pgoff_t linear_hugepage_index(struct vm_area_struct *vma,
1002 unsigned long address)
1004 return vma_hugecache_offset(hstate_vma(vma), vma, address);
1006 EXPORT_SYMBOL_GPL(linear_hugepage_index);
1009 * Return the size of the pages allocated when backing a VMA. In the majority
1010 * cases this will be same size as used by the page table entries.
1012 unsigned long vma_kernel_pagesize(struct vm_area_struct *vma)
1014 if (vma->vm_ops && vma->vm_ops->pagesize)
1015 return vma->vm_ops->pagesize(vma);
1018 EXPORT_SYMBOL_GPL(vma_kernel_pagesize);
1021 * Return the page size being used by the MMU to back a VMA. In the majority
1022 * of cases, the page size used by the kernel matches the MMU size. On
1023 * architectures where it differs, an architecture-specific 'strong'
1024 * version of this symbol is required.
1026 __weak unsigned long vma_mmu_pagesize(struct vm_area_struct *vma)
1028 return vma_kernel_pagesize(vma);
1032 * Flags for MAP_PRIVATE reservations. These are stored in the bottom
1033 * bits of the reservation map pointer, which are always clear due to
1036 #define HPAGE_RESV_OWNER (1UL << 0)
1037 #define HPAGE_RESV_UNMAPPED (1UL << 1)
1038 #define HPAGE_RESV_MASK (HPAGE_RESV_OWNER | HPAGE_RESV_UNMAPPED)
1041 * These helpers are used to track how many pages are reserved for
1042 * faults in a MAP_PRIVATE mapping. Only the process that called mmap()
1043 * is guaranteed to have their future faults succeed.
1045 * With the exception of hugetlb_dup_vma_private() which is called at fork(),
1046 * the reserve counters are updated with the hugetlb_lock held. It is safe
1047 * to reset the VMA at fork() time as it is not in use yet and there is no
1048 * chance of the global counters getting corrupted as a result of the values.
1050 * The private mapping reservation is represented in a subtly different
1051 * manner to a shared mapping. A shared mapping has a region map associated
1052 * with the underlying file, this region map represents the backing file
1053 * pages which have ever had a reservation assigned which this persists even
1054 * after the page is instantiated. A private mapping has a region map
1055 * associated with the original mmap which is attached to all VMAs which
1056 * reference it, this region map represents those offsets which have consumed
1057 * reservation ie. where pages have been instantiated.
1059 static unsigned long get_vma_private_data(struct vm_area_struct *vma)
1061 return (unsigned long)vma->vm_private_data;
1064 static void set_vma_private_data(struct vm_area_struct *vma,
1065 unsigned long value)
1067 vma->vm_private_data = (void *)value;
1071 resv_map_set_hugetlb_cgroup_uncharge_info(struct resv_map *resv_map,
1072 struct hugetlb_cgroup *h_cg,
1075 #ifdef CONFIG_CGROUP_HUGETLB
1077 resv_map->reservation_counter = NULL;
1078 resv_map->pages_per_hpage = 0;
1079 resv_map->css = NULL;
1081 resv_map->reservation_counter =
1082 &h_cg->rsvd_hugepage[hstate_index(h)];
1083 resv_map->pages_per_hpage = pages_per_huge_page(h);
1084 resv_map->css = &h_cg->css;
1089 struct resv_map *resv_map_alloc(void)
1091 struct resv_map *resv_map = kmalloc(sizeof(*resv_map), GFP_KERNEL);
1092 struct file_region *rg = kmalloc(sizeof(*rg), GFP_KERNEL);
1094 if (!resv_map || !rg) {
1100 kref_init(&resv_map->refs);
1101 spin_lock_init(&resv_map->lock);
1102 INIT_LIST_HEAD(&resv_map->regions);
1103 init_rwsem(&resv_map->rw_sema);
1105 resv_map->adds_in_progress = 0;
1107 * Initialize these to 0. On shared mappings, 0's here indicate these
1108 * fields don't do cgroup accounting. On private mappings, these will be
1109 * re-initialized to the proper values, to indicate that hugetlb cgroup
1110 * reservations are to be un-charged from here.
1112 resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, NULL, NULL);
1114 INIT_LIST_HEAD(&resv_map->region_cache);
1115 list_add(&rg->link, &resv_map->region_cache);
1116 resv_map->region_cache_count = 1;
1121 void resv_map_release(struct kref *ref)
1123 struct resv_map *resv_map = container_of(ref, struct resv_map, refs);
1124 struct list_head *head = &resv_map->region_cache;
1125 struct file_region *rg, *trg;
1127 /* Clear out any active regions before we release the map. */
1128 region_del(resv_map, 0, LONG_MAX);
1130 /* ... and any entries left in the cache */
1131 list_for_each_entry_safe(rg, trg, head, link) {
1132 list_del(&rg->link);
1136 VM_BUG_ON(resv_map->adds_in_progress);
1141 static inline struct resv_map *inode_resv_map(struct inode *inode)
1144 * At inode evict time, i_mapping may not point to the original
1145 * address space within the inode. This original address space
1146 * contains the pointer to the resv_map. So, always use the
1147 * address space embedded within the inode.
1148 * The VERY common case is inode->mapping == &inode->i_data but,
1149 * this may not be true for device special inodes.
1151 return (struct resv_map *)(&inode->i_data)->private_data;
1154 static struct resv_map *vma_resv_map(struct vm_area_struct *vma)
1156 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
1157 if (vma->vm_flags & VM_MAYSHARE) {
1158 struct address_space *mapping = vma->vm_file->f_mapping;
1159 struct inode *inode = mapping->host;
1161 return inode_resv_map(inode);
1164 return (struct resv_map *)(get_vma_private_data(vma) &
1169 static void set_vma_resv_map(struct vm_area_struct *vma, struct resv_map *map)
1171 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
1172 VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
1174 set_vma_private_data(vma, (unsigned long)map);
1177 static void set_vma_resv_flags(struct vm_area_struct *vma, unsigned long flags)
1179 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
1180 VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
1182 set_vma_private_data(vma, get_vma_private_data(vma) | flags);
1185 static int is_vma_resv_set(struct vm_area_struct *vma, unsigned long flag)
1187 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
1189 return (get_vma_private_data(vma) & flag) != 0;
1192 void hugetlb_dup_vma_private(struct vm_area_struct *vma)
1194 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
1196 * Clear vm_private_data
1197 * - For shared mappings this is a per-vma semaphore that may be
1198 * allocated in a subsequent call to hugetlb_vm_op_open.
1199 * Before clearing, make sure pointer is not associated with vma
1200 * as this will leak the structure. This is the case when called
1201 * via clear_vma_resv_huge_pages() and hugetlb_vm_op_open has already
1202 * been called to allocate a new structure.
1203 * - For MAP_PRIVATE mappings, this is the reserve map which does
1204 * not apply to children. Faults generated by the children are
1205 * not guaranteed to succeed, even if read-only.
1207 if (vma->vm_flags & VM_MAYSHARE) {
1208 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
1210 if (vma_lock && vma_lock->vma != vma)
1211 vma->vm_private_data = NULL;
1213 vma->vm_private_data = NULL;
1217 * Reset and decrement one ref on hugepage private reservation.
1218 * Called with mm->mmap_sem writer semaphore held.
1219 * This function should be only used by move_vma() and operate on
1220 * same sized vma. It should never come here with last ref on the
1223 void clear_vma_resv_huge_pages(struct vm_area_struct *vma)
1226 * Clear the old hugetlb private page reservation.
1227 * It has already been transferred to new_vma.
1229 * During a mremap() operation of a hugetlb vma we call move_vma()
1230 * which copies vma into new_vma and unmaps vma. After the copy
1231 * operation both new_vma and vma share a reference to the resv_map
1232 * struct, and at that point vma is about to be unmapped. We don't
1233 * want to return the reservation to the pool at unmap of vma because
1234 * the reservation still lives on in new_vma, so simply decrement the
1235 * ref here and remove the resv_map reference from this vma.
1237 struct resv_map *reservations = vma_resv_map(vma);
1239 if (reservations && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
1240 resv_map_put_hugetlb_cgroup_uncharge_info(reservations);
1241 kref_put(&reservations->refs, resv_map_release);
1244 hugetlb_dup_vma_private(vma);
1247 /* Returns true if the VMA has associated reserve pages */
1248 static bool vma_has_reserves(struct vm_area_struct *vma, long chg)
1250 if (vma->vm_flags & VM_NORESERVE) {
1252 * This address is already reserved by other process(chg == 0),
1253 * so, we should decrement reserved count. Without decrementing,
1254 * reserve count remains after releasing inode, because this
1255 * allocated page will go into page cache and is regarded as
1256 * coming from reserved pool in releasing step. Currently, we
1257 * don't have any other solution to deal with this situation
1258 * properly, so add work-around here.
1260 if (vma->vm_flags & VM_MAYSHARE && chg == 0)
1266 /* Shared mappings always use reserves */
1267 if (vma->vm_flags & VM_MAYSHARE) {
1269 * We know VM_NORESERVE is not set. Therefore, there SHOULD
1270 * be a region map for all pages. The only situation where
1271 * there is no region map is if a hole was punched via
1272 * fallocate. In this case, there really are no reserves to
1273 * use. This situation is indicated if chg != 0.
1282 * Only the process that called mmap() has reserves for
1285 if (is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
1287 * Like the shared case above, a hole punch or truncate
1288 * could have been performed on the private mapping.
1289 * Examine the value of chg to determine if reserves
1290 * actually exist or were previously consumed.
1291 * Very Subtle - The value of chg comes from a previous
1292 * call to vma_needs_reserves(). The reserve map for
1293 * private mappings has different (opposite) semantics
1294 * than that of shared mappings. vma_needs_reserves()
1295 * has already taken this difference in semantics into
1296 * account. Therefore, the meaning of chg is the same
1297 * as in the shared case above. Code could easily be
1298 * combined, but keeping it separate draws attention to
1299 * subtle differences.
1310 static void enqueue_huge_page(struct hstate *h, struct page *page)
1312 int nid = page_to_nid(page);
1314 lockdep_assert_held(&hugetlb_lock);
1315 VM_BUG_ON_PAGE(page_count(page), page);
1317 list_move(&page->lru, &h->hugepage_freelists[nid]);
1318 h->free_huge_pages++;
1319 h->free_huge_pages_node[nid]++;
1320 SetHPageFreed(page);
1323 static struct page *dequeue_huge_page_node_exact(struct hstate *h, int nid)
1326 bool pin = !!(current->flags & PF_MEMALLOC_PIN);
1328 lockdep_assert_held(&hugetlb_lock);
1329 list_for_each_entry(page, &h->hugepage_freelists[nid], lru) {
1330 if (pin && !is_longterm_pinnable_page(page))
1333 if (PageHWPoison(page))
1336 list_move(&page->lru, &h->hugepage_activelist);
1337 set_page_refcounted(page);
1338 ClearHPageFreed(page);
1339 h->free_huge_pages--;
1340 h->free_huge_pages_node[nid]--;
1347 static struct page *dequeue_huge_page_nodemask(struct hstate *h, gfp_t gfp_mask, int nid,
1350 unsigned int cpuset_mems_cookie;
1351 struct zonelist *zonelist;
1354 int node = NUMA_NO_NODE;
1356 zonelist = node_zonelist(nid, gfp_mask);
1359 cpuset_mems_cookie = read_mems_allowed_begin();
1360 for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nmask) {
1363 if (!cpuset_zone_allowed(zone, gfp_mask))
1366 * no need to ask again on the same node. Pool is node rather than
1369 if (zone_to_nid(zone) == node)
1371 node = zone_to_nid(zone);
1373 page = dequeue_huge_page_node_exact(h, node);
1377 if (unlikely(read_mems_allowed_retry(cpuset_mems_cookie)))
1383 static unsigned long available_huge_pages(struct hstate *h)
1385 return h->free_huge_pages - h->resv_huge_pages;
1388 static struct page *dequeue_huge_page_vma(struct hstate *h,
1389 struct vm_area_struct *vma,
1390 unsigned long address, int avoid_reserve,
1393 struct page *page = NULL;
1394 struct mempolicy *mpol;
1396 nodemask_t *nodemask;
1400 * A child process with MAP_PRIVATE mappings created by their parent
1401 * have no page reserves. This check ensures that reservations are
1402 * not "stolen". The child may still get SIGKILLed
1404 if (!vma_has_reserves(vma, chg) && !available_huge_pages(h))
1407 /* If reserves cannot be used, ensure enough pages are in the pool */
1408 if (avoid_reserve && !available_huge_pages(h))
1411 gfp_mask = htlb_alloc_mask(h);
1412 nid = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
1414 if (mpol_is_preferred_many(mpol)) {
1415 page = dequeue_huge_page_nodemask(h, gfp_mask, nid, nodemask);
1417 /* Fallback to all nodes if page==NULL */
1422 page = dequeue_huge_page_nodemask(h, gfp_mask, nid, nodemask);
1424 if (page && !avoid_reserve && vma_has_reserves(vma, chg)) {
1425 SetHPageRestoreReserve(page);
1426 h->resv_huge_pages--;
1429 mpol_cond_put(mpol);
1437 * common helper functions for hstate_next_node_to_{alloc|free}.
1438 * We may have allocated or freed a huge page based on a different
1439 * nodes_allowed previously, so h->next_node_to_{alloc|free} might
1440 * be outside of *nodes_allowed. Ensure that we use an allowed
1441 * node for alloc or free.
1443 static int next_node_allowed(int nid, nodemask_t *nodes_allowed)
1445 nid = next_node_in(nid, *nodes_allowed);
1446 VM_BUG_ON(nid >= MAX_NUMNODES);
1451 static int get_valid_node_allowed(int nid, nodemask_t *nodes_allowed)
1453 if (!node_isset(nid, *nodes_allowed))
1454 nid = next_node_allowed(nid, nodes_allowed);
1459 * returns the previously saved node ["this node"] from which to
1460 * allocate a persistent huge page for the pool and advance the
1461 * next node from which to allocate, handling wrap at end of node
1464 static int hstate_next_node_to_alloc(struct hstate *h,
1465 nodemask_t *nodes_allowed)
1469 VM_BUG_ON(!nodes_allowed);
1471 nid = get_valid_node_allowed(h->next_nid_to_alloc, nodes_allowed);
1472 h->next_nid_to_alloc = next_node_allowed(nid, nodes_allowed);
1478 * helper for remove_pool_huge_page() - return the previously saved
1479 * node ["this node"] from which to free a huge page. Advance the
1480 * next node id whether or not we find a free huge page to free so
1481 * that the next attempt to free addresses the next node.
1483 static int hstate_next_node_to_free(struct hstate *h, nodemask_t *nodes_allowed)
1487 VM_BUG_ON(!nodes_allowed);
1489 nid = get_valid_node_allowed(h->next_nid_to_free, nodes_allowed);
1490 h->next_nid_to_free = next_node_allowed(nid, nodes_allowed);
1495 #define for_each_node_mask_to_alloc(hs, nr_nodes, node, mask) \
1496 for (nr_nodes = nodes_weight(*mask); \
1498 ((node = hstate_next_node_to_alloc(hs, mask)) || 1); \
1501 #define for_each_node_mask_to_free(hs, nr_nodes, node, mask) \
1502 for (nr_nodes = nodes_weight(*mask); \
1504 ((node = hstate_next_node_to_free(hs, mask)) || 1); \
1507 /* used to demote non-gigantic_huge pages as well */
1508 static void __destroy_compound_gigantic_page(struct page *page,
1509 unsigned int order, bool demote)
1512 int nr_pages = 1 << order;
1515 atomic_set(compound_mapcount_ptr(page), 0);
1516 atomic_set(compound_pincount_ptr(page), 0);
1518 for (i = 1; i < nr_pages; i++) {
1519 p = nth_page(page, i);
1521 clear_compound_head(p);
1523 set_page_refcounted(p);
1526 set_compound_order(page, 0);
1528 page[1].compound_nr = 0;
1530 __ClearPageHead(page);
1533 static void destroy_compound_hugetlb_page_for_demote(struct page *page,
1536 __destroy_compound_gigantic_page(page, order, true);
1539 #ifdef CONFIG_ARCH_HAS_GIGANTIC_PAGE
1540 static void destroy_compound_gigantic_page(struct page *page,
1543 __destroy_compound_gigantic_page(page, order, false);
1546 static void free_gigantic_page(struct page *page, unsigned int order)
1549 * If the page isn't allocated using the cma allocator,
1550 * cma_release() returns false.
1553 if (cma_release(hugetlb_cma[page_to_nid(page)], page, 1 << order))
1557 free_contig_range(page_to_pfn(page), 1 << order);
1560 #ifdef CONFIG_CONTIG_ALLOC
1561 static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
1562 int nid, nodemask_t *nodemask)
1564 unsigned long nr_pages = pages_per_huge_page(h);
1565 if (nid == NUMA_NO_NODE)
1566 nid = numa_mem_id();
1573 if (hugetlb_cma[nid]) {
1574 page = cma_alloc(hugetlb_cma[nid], nr_pages,
1575 huge_page_order(h), true);
1580 if (!(gfp_mask & __GFP_THISNODE)) {
1581 for_each_node_mask(node, *nodemask) {
1582 if (node == nid || !hugetlb_cma[node])
1585 page = cma_alloc(hugetlb_cma[node], nr_pages,
1586 huge_page_order(h), true);
1594 return alloc_contig_pages(nr_pages, gfp_mask, nid, nodemask);
1597 #else /* !CONFIG_CONTIG_ALLOC */
1598 static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
1599 int nid, nodemask_t *nodemask)
1603 #endif /* CONFIG_CONTIG_ALLOC */
1605 #else /* !CONFIG_ARCH_HAS_GIGANTIC_PAGE */
1606 static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
1607 int nid, nodemask_t *nodemask)
1611 static inline void free_gigantic_page(struct page *page, unsigned int order) { }
1612 static inline void destroy_compound_gigantic_page(struct page *page,
1613 unsigned int order) { }
1616 static inline void __clear_hugetlb_destructor(struct hstate *h,
1619 lockdep_assert_held(&hugetlb_lock);
1624 * For non-gigantic pages set the destructor to the normal compound
1625 * page dtor. This is needed in case someone takes an additional
1626 * temporary ref to the page, and freeing is delayed until they drop
1629 * For gigantic pages set the destructor to the null dtor. This
1630 * destructor will never be called. Before freeing the gigantic
1631 * page destroy_compound_gigantic_folio will turn the folio into a
1632 * simple group of pages. After this the destructor does not
1636 if (hstate_is_gigantic(h))
1637 set_compound_page_dtor(page, NULL_COMPOUND_DTOR);
1639 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
1643 * Remove hugetlb page from lists.
1644 * If vmemmap exists for the page, update dtor so that the page appears
1645 * as just a compound page. Otherwise, wait until after allocating vmemmap
1648 * A reference is held on the page, except in the case of demote.
1650 * Must be called with hugetlb lock held.
1652 static void __remove_hugetlb_page(struct hstate *h, struct page *page,
1653 bool adjust_surplus,
1656 int nid = page_to_nid(page);
1658 VM_BUG_ON_PAGE(hugetlb_cgroup_from_page(page), page);
1659 VM_BUG_ON_PAGE(hugetlb_cgroup_from_page_rsvd(page), page);
1661 lockdep_assert_held(&hugetlb_lock);
1662 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
1665 list_del(&page->lru);
1667 if (HPageFreed(page)) {
1668 h->free_huge_pages--;
1669 h->free_huge_pages_node[nid]--;
1671 if (adjust_surplus) {
1672 h->surplus_huge_pages--;
1673 h->surplus_huge_pages_node[nid]--;
1677 * We can only clear the hugetlb destructor after allocating vmemmap
1678 * pages. Otherwise, someone (memory error handling) may try to write
1679 * to tail struct pages.
1681 if (!HPageVmemmapOptimized(page))
1682 __clear_hugetlb_destructor(h, page);
1685 * In the case of demote we do not ref count the page as it will soon
1686 * be turned into a page of smaller size.
1689 set_page_refcounted(page);
1692 h->nr_huge_pages_node[nid]--;
1695 static void remove_hugetlb_page(struct hstate *h, struct page *page,
1696 bool adjust_surplus)
1698 __remove_hugetlb_page(h, page, adjust_surplus, false);
1701 static void remove_hugetlb_page_for_demote(struct hstate *h, struct page *page,
1702 bool adjust_surplus)
1704 __remove_hugetlb_page(h, page, adjust_surplus, true);
1707 static void add_hugetlb_page(struct hstate *h, struct page *page,
1708 bool adjust_surplus)
1711 int nid = page_to_nid(page);
1713 VM_BUG_ON_PAGE(!HPageVmemmapOptimized(page), page);
1715 lockdep_assert_held(&hugetlb_lock);
1717 INIT_LIST_HEAD(&page->lru);
1719 h->nr_huge_pages_node[nid]++;
1721 if (adjust_surplus) {
1722 h->surplus_huge_pages++;
1723 h->surplus_huge_pages_node[nid]++;
1726 set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
1727 set_page_private(page, 0);
1729 * We have to set HPageVmemmapOptimized again as above
1730 * set_page_private(page, 0) cleared it.
1732 SetHPageVmemmapOptimized(page);
1735 * This page is about to be managed by the hugetlb allocator and
1736 * should have no users. Drop our reference, and check for others
1739 zeroed = put_page_testzero(page);
1742 * It is VERY unlikely soneone else has taken a ref on
1743 * the page. In this case, we simply return as the
1744 * hugetlb destructor (free_huge_page) will be called
1745 * when this other ref is dropped.
1749 arch_clear_hugepage_flags(page);
1750 enqueue_huge_page(h, page);
1753 static void __update_and_free_page(struct hstate *h, struct page *page)
1756 struct page *subpage;
1757 bool clear_dtor = HPageVmemmapOptimized(page);
1759 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
1763 * If we don't know which subpages are hwpoisoned, we can't free
1764 * the hugepage, so it's leaked intentionally.
1766 if (HPageRawHwpUnreliable(page))
1769 if (hugetlb_vmemmap_restore(h, page)) {
1770 spin_lock_irq(&hugetlb_lock);
1772 * If we cannot allocate vmemmap pages, just refuse to free the
1773 * page and put the page back on the hugetlb free list and treat
1774 * as a surplus page.
1776 add_hugetlb_page(h, page, true);
1777 spin_unlock_irq(&hugetlb_lock);
1782 * Move PageHWPoison flag from head page to the raw error pages,
1783 * which makes any healthy subpages reusable.
1785 if (unlikely(PageHWPoison(page)))
1786 hugetlb_clear_page_hwpoison(page);
1789 * If vmemmap pages were allocated above, then we need to clear the
1790 * hugetlb destructor under the hugetlb lock.
1793 spin_lock_irq(&hugetlb_lock);
1794 __clear_hugetlb_destructor(h, page);
1795 spin_unlock_irq(&hugetlb_lock);
1798 for (i = 0; i < pages_per_huge_page(h); i++) {
1799 subpage = nth_page(page, i);
1800 subpage->flags &= ~(1 << PG_locked | 1 << PG_error |
1801 1 << PG_referenced | 1 << PG_dirty |
1802 1 << PG_active | 1 << PG_private |
1807 * Non-gigantic pages demoted from CMA allocated gigantic pages
1808 * need to be given back to CMA in free_gigantic_page.
1810 if (hstate_is_gigantic(h) ||
1811 hugetlb_cma_page(page, huge_page_order(h))) {
1812 destroy_compound_gigantic_page(page, huge_page_order(h));
1813 free_gigantic_page(page, huge_page_order(h));
1815 __free_pages(page, huge_page_order(h));
1820 * As update_and_free_page() can be called under any context, so we cannot
1821 * use GFP_KERNEL to allocate vmemmap pages. However, we can defer the
1822 * actual freeing in a workqueue to prevent from using GFP_ATOMIC to allocate
1823 * the vmemmap pages.
1825 * free_hpage_workfn() locklessly retrieves the linked list of pages to be
1826 * freed and frees them one-by-one. As the page->mapping pointer is going
1827 * to be cleared in free_hpage_workfn() anyway, it is reused as the llist_node
1828 * structure of a lockless linked list of huge pages to be freed.
1830 static LLIST_HEAD(hpage_freelist);
1832 static void free_hpage_workfn(struct work_struct *work)
1834 struct llist_node *node;
1836 node = llist_del_all(&hpage_freelist);
1842 page = container_of((struct address_space **)node,
1843 struct page, mapping);
1845 page->mapping = NULL;
1847 * The VM_BUG_ON_PAGE(!PageHuge(page), page) in page_hstate()
1848 * is going to trigger because a previous call to
1849 * remove_hugetlb_page() will set_compound_page_dtor(page,
1850 * NULL_COMPOUND_DTOR), so do not use page_hstate() directly.
1852 h = size_to_hstate(page_size(page));
1854 __update_and_free_page(h, page);
1859 static DECLARE_WORK(free_hpage_work, free_hpage_workfn);
1861 static inline void flush_free_hpage_work(struct hstate *h)
1863 if (hugetlb_vmemmap_optimizable(h))
1864 flush_work(&free_hpage_work);
1867 static void update_and_free_page(struct hstate *h, struct page *page,
1870 if (!HPageVmemmapOptimized(page) || !atomic) {
1871 __update_and_free_page(h, page);
1876 * Defer freeing to avoid using GFP_ATOMIC to allocate vmemmap pages.
1878 * Only call schedule_work() if hpage_freelist is previously
1879 * empty. Otherwise, schedule_work() had been called but the workfn
1880 * hasn't retrieved the list yet.
1882 if (llist_add((struct llist_node *)&page->mapping, &hpage_freelist))
1883 schedule_work(&free_hpage_work);
1886 static void update_and_free_pages_bulk(struct hstate *h, struct list_head *list)
1888 struct page *page, *t_page;
1890 list_for_each_entry_safe(page, t_page, list, lru) {
1891 update_and_free_page(h, page, false);
1896 struct hstate *size_to_hstate(unsigned long size)
1900 for_each_hstate(h) {
1901 if (huge_page_size(h) == size)
1907 void free_huge_page(struct page *page)
1910 * Can't pass hstate in here because it is called from the
1911 * compound page destructor.
1913 struct hstate *h = page_hstate(page);
1914 int nid = page_to_nid(page);
1915 struct hugepage_subpool *spool = hugetlb_page_subpool(page);
1916 bool restore_reserve;
1917 unsigned long flags;
1919 VM_BUG_ON_PAGE(page_count(page), page);
1920 VM_BUG_ON_PAGE(page_mapcount(page), page);
1922 hugetlb_set_page_subpool(page, NULL);
1924 __ClearPageAnonExclusive(page);
1925 page->mapping = NULL;
1926 restore_reserve = HPageRestoreReserve(page);
1927 ClearHPageRestoreReserve(page);
1930 * If HPageRestoreReserve was set on page, page allocation consumed a
1931 * reservation. If the page was associated with a subpool, there
1932 * would have been a page reserved in the subpool before allocation
1933 * via hugepage_subpool_get_pages(). Since we are 'restoring' the
1934 * reservation, do not call hugepage_subpool_put_pages() as this will
1935 * remove the reserved page from the subpool.
1937 if (!restore_reserve) {
1939 * A return code of zero implies that the subpool will be
1940 * under its minimum size if the reservation is not restored
1941 * after page is free. Therefore, force restore_reserve
1944 if (hugepage_subpool_put_pages(spool, 1) == 0)
1945 restore_reserve = true;
1948 spin_lock_irqsave(&hugetlb_lock, flags);
1949 ClearHPageMigratable(page);
1950 hugetlb_cgroup_uncharge_page(hstate_index(h),
1951 pages_per_huge_page(h), page);
1952 hugetlb_cgroup_uncharge_page_rsvd(hstate_index(h),
1953 pages_per_huge_page(h), page);
1954 if (restore_reserve)
1955 h->resv_huge_pages++;
1957 if (HPageTemporary(page)) {
1958 remove_hugetlb_page(h, page, false);
1959 spin_unlock_irqrestore(&hugetlb_lock, flags);
1960 update_and_free_page(h, page, true);
1961 } else if (h->surplus_huge_pages_node[nid]) {
1962 /* remove the page from active list */
1963 remove_hugetlb_page(h, page, true);
1964 spin_unlock_irqrestore(&hugetlb_lock, flags);
1965 update_and_free_page(h, page, true);
1967 arch_clear_hugepage_flags(page);
1968 enqueue_huge_page(h, page);
1969 spin_unlock_irqrestore(&hugetlb_lock, flags);
1974 * Must be called with the hugetlb lock held
1976 static void __prep_account_new_huge_page(struct hstate *h, int nid)
1978 lockdep_assert_held(&hugetlb_lock);
1980 h->nr_huge_pages_node[nid]++;
1983 static void __prep_new_huge_page(struct hstate *h, struct page *page)
1985 hugetlb_vmemmap_optimize(h, page);
1986 INIT_LIST_HEAD(&page->lru);
1987 set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
1988 hugetlb_set_page_subpool(page, NULL);
1989 set_hugetlb_cgroup(page, NULL);
1990 set_hugetlb_cgroup_rsvd(page, NULL);
1993 static void prep_new_huge_page(struct hstate *h, struct page *page, int nid)
1995 __prep_new_huge_page(h, page);
1996 spin_lock_irq(&hugetlb_lock);
1997 __prep_account_new_huge_page(h, nid);
1998 spin_unlock_irq(&hugetlb_lock);
2001 static bool __prep_compound_gigantic_page(struct page *page, unsigned int order,
2005 int nr_pages = 1 << order;
2008 /* we rely on prep_new_huge_page to set the destructor */
2009 set_compound_order(page, order);
2010 __ClearPageReserved(page);
2011 __SetPageHead(page);
2012 for (i = 0; i < nr_pages; i++) {
2013 p = nth_page(page, i);
2016 * For gigantic hugepages allocated through bootmem at
2017 * boot, it's safer to be consistent with the not-gigantic
2018 * hugepages and clear the PG_reserved bit from all tail pages
2019 * too. Otherwise drivers using get_user_pages() to access tail
2020 * pages may get the reference counting wrong if they see
2021 * PG_reserved set on a tail page (despite the head page not
2022 * having PG_reserved set). Enforcing this consistency between
2023 * head and tail pages allows drivers to optimize away a check
2024 * on the head page when they need know if put_page() is needed
2025 * after get_user_pages().
2027 if (i != 0) /* head page cleared above */
2028 __ClearPageReserved(p);
2030 * Subtle and very unlikely
2032 * Gigantic 'page allocators' such as memblock or cma will
2033 * return a set of pages with each page ref counted. We need
2034 * to turn this set of pages into a compound page with tail
2035 * page ref counts set to zero. Code such as speculative page
2036 * cache adding could take a ref on a 'to be' tail page.
2037 * We need to respect any increased ref count, and only set
2038 * the ref count to zero if count is currently 1. If count
2039 * is not 1, we return an error. An error return indicates
2040 * the set of pages can not be converted to a gigantic page.
2041 * The caller who allocated the pages should then discard the
2042 * pages using the appropriate free interface.
2044 * In the case of demote, the ref count will be zero.
2047 if (!page_ref_freeze(p, 1)) {
2048 pr_warn("HugeTLB page can not be used due to unexpected inflated ref count\n");
2052 VM_BUG_ON_PAGE(page_count(p), p);
2055 set_compound_head(p, page);
2057 atomic_set(compound_mapcount_ptr(page), -1);
2058 atomic_set(compound_pincount_ptr(page), 0);
2062 /* undo page modifications made above */
2063 for (j = 0; j < i; j++) {
2064 p = nth_page(page, j);
2066 clear_compound_head(p);
2067 set_page_refcounted(p);
2069 /* need to clear PG_reserved on remaining tail pages */
2070 for (; j < nr_pages; j++) {
2071 p = nth_page(page, j);
2072 __ClearPageReserved(p);
2074 set_compound_order(page, 0);
2076 page[1].compound_nr = 0;
2078 __ClearPageHead(page);
2082 static bool prep_compound_gigantic_page(struct page *page, unsigned int order)
2084 return __prep_compound_gigantic_page(page, order, false);
2087 static bool prep_compound_gigantic_page_for_demote(struct page *page,
2090 return __prep_compound_gigantic_page(page, order, true);
2094 * PageHuge() only returns true for hugetlbfs pages, but not for normal or
2095 * transparent huge pages. See the PageTransHuge() documentation for more
2098 int PageHuge(struct page *page)
2100 if (!PageCompound(page))
2103 page = compound_head(page);
2104 return page[1].compound_dtor == HUGETLB_PAGE_DTOR;
2106 EXPORT_SYMBOL_GPL(PageHuge);
2109 * PageHeadHuge() only returns true for hugetlbfs head page, but not for
2110 * normal or transparent huge pages.
2112 int PageHeadHuge(struct page *page_head)
2114 if (!PageHead(page_head))
2117 return page_head[1].compound_dtor == HUGETLB_PAGE_DTOR;
2119 EXPORT_SYMBOL_GPL(PageHeadHuge);
2122 * Find and lock address space (mapping) in write mode.
2124 * Upon entry, the page is locked which means that page_mapping() is
2125 * stable. Due to locking order, we can only trylock_write. If we can
2126 * not get the lock, simply return NULL to caller.
2128 struct address_space *hugetlb_page_mapping_lock_write(struct page *hpage)
2130 struct address_space *mapping = page_mapping(hpage);
2135 if (i_mmap_trylock_write(mapping))
2141 pgoff_t hugetlb_basepage_index(struct page *page)
2143 struct page *page_head = compound_head(page);
2144 pgoff_t index = page_index(page_head);
2145 unsigned long compound_idx;
2147 if (compound_order(page_head) >= MAX_ORDER)
2148 compound_idx = page_to_pfn(page) - page_to_pfn(page_head);
2150 compound_idx = page - page_head;
2152 return (index << compound_order(page_head)) + compound_idx;
2155 static struct page *alloc_buddy_huge_page(struct hstate *h,
2156 gfp_t gfp_mask, int nid, nodemask_t *nmask,
2157 nodemask_t *node_alloc_noretry)
2159 int order = huge_page_order(h);
2161 bool alloc_try_hard = true;
2165 * By default we always try hard to allocate the page with
2166 * __GFP_RETRY_MAYFAIL flag. However, if we are allocating pages in
2167 * a loop (to adjust global huge page counts) and previous allocation
2168 * failed, do not continue to try hard on the same node. Use the
2169 * node_alloc_noretry bitmap to manage this state information.
2171 if (node_alloc_noretry && node_isset(nid, *node_alloc_noretry))
2172 alloc_try_hard = false;
2173 gfp_mask |= __GFP_COMP|__GFP_NOWARN;
2175 gfp_mask |= __GFP_RETRY_MAYFAIL;
2176 if (nid == NUMA_NO_NODE)
2177 nid = numa_mem_id();
2179 page = __alloc_pages(gfp_mask, order, nid, nmask);
2181 /* Freeze head page */
2182 if (page && !page_ref_freeze(page, 1)) {
2183 __free_pages(page, order);
2184 if (retry) { /* retry once */
2188 /* WOW! twice in a row. */
2189 pr_warn("HugeTLB head page unexpected inflated ref count\n");
2194 __count_vm_event(HTLB_BUDDY_PGALLOC);
2196 __count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
2199 * If we did not specify __GFP_RETRY_MAYFAIL, but still got a page this
2200 * indicates an overall state change. Clear bit so that we resume
2201 * normal 'try hard' allocations.
2203 if (node_alloc_noretry && page && !alloc_try_hard)
2204 node_clear(nid, *node_alloc_noretry);
2207 * If we tried hard to get a page but failed, set bit so that
2208 * subsequent attempts will not try as hard until there is an
2209 * overall state change.
2211 if (node_alloc_noretry && !page && alloc_try_hard)
2212 node_set(nid, *node_alloc_noretry);
2218 * Common helper to allocate a fresh hugetlb page. All specific allocators
2219 * should use this function to get new hugetlb pages
2221 * Note that returned page is 'frozen': ref count of head page and all tail
2224 static struct page *alloc_fresh_huge_page(struct hstate *h,
2225 gfp_t gfp_mask, int nid, nodemask_t *nmask,
2226 nodemask_t *node_alloc_noretry)
2232 if (hstate_is_gigantic(h))
2233 page = alloc_gigantic_page(h, gfp_mask, nid, nmask);
2235 page = alloc_buddy_huge_page(h, gfp_mask,
2236 nid, nmask, node_alloc_noretry);
2240 if (hstate_is_gigantic(h)) {
2241 if (!prep_compound_gigantic_page(page, huge_page_order(h))) {
2243 * Rare failure to convert pages to compound page.
2244 * Free pages and try again - ONCE!
2246 free_gigantic_page(page, huge_page_order(h));
2254 prep_new_huge_page(h, page, page_to_nid(page));
2260 * Allocates a fresh page to the hugetlb allocator pool in the node interleaved
2263 static int alloc_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed,
2264 nodemask_t *node_alloc_noretry)
2268 gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
2270 for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
2271 page = alloc_fresh_huge_page(h, gfp_mask, node, nodes_allowed,
2272 node_alloc_noretry);
2280 free_huge_page(page); /* free it into the hugepage allocator */
2286 * Remove huge page from pool from next node to free. Attempt to keep
2287 * persistent huge pages more or less balanced over allowed nodes.
2288 * This routine only 'removes' the hugetlb page. The caller must make
2289 * an additional call to free the page to low level allocators.
2290 * Called with hugetlb_lock locked.
2292 static struct page *remove_pool_huge_page(struct hstate *h,
2293 nodemask_t *nodes_allowed,
2297 struct page *page = NULL;
2299 lockdep_assert_held(&hugetlb_lock);
2300 for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
2302 * If we're returning unused surplus pages, only examine
2303 * nodes with surplus pages.
2305 if ((!acct_surplus || h->surplus_huge_pages_node[node]) &&
2306 !list_empty(&h->hugepage_freelists[node])) {
2307 page = list_entry(h->hugepage_freelists[node].next,
2309 remove_hugetlb_page(h, page, acct_surplus);
2318 * Dissolve a given free hugepage into free buddy pages. This function does
2319 * nothing for in-use hugepages and non-hugepages.
2320 * This function returns values like below:
2322 * -ENOMEM: failed to allocate vmemmap pages to free the freed hugepages
2323 * when the system is under memory pressure and the feature of
2324 * freeing unused vmemmap pages associated with each hugetlb page
2326 * -EBUSY: failed to dissolved free hugepages or the hugepage is in-use
2327 * (allocated or reserved.)
2328 * 0: successfully dissolved free hugepages or the page is not a
2329 * hugepage (considered as already dissolved)
2331 int dissolve_free_huge_page(struct page *page)
2336 /* Not to disrupt normal path by vainly holding hugetlb_lock */
2337 if (!PageHuge(page))
2340 spin_lock_irq(&hugetlb_lock);
2341 if (!PageHuge(page)) {
2346 if (!page_count(page)) {
2347 struct page *head = compound_head(page);
2348 struct hstate *h = page_hstate(head);
2349 if (!available_huge_pages(h))
2353 * We should make sure that the page is already on the free list
2354 * when it is dissolved.
2356 if (unlikely(!HPageFreed(head))) {
2357 spin_unlock_irq(&hugetlb_lock);
2361 * Theoretically, we should return -EBUSY when we
2362 * encounter this race. In fact, we have a chance
2363 * to successfully dissolve the page if we do a
2364 * retry. Because the race window is quite small.
2365 * If we seize this opportunity, it is an optimization
2366 * for increasing the success rate of dissolving page.
2371 remove_hugetlb_page(h, head, false);
2372 h->max_huge_pages--;
2373 spin_unlock_irq(&hugetlb_lock);
2376 * Normally update_and_free_page will allocate required vmemmmap
2377 * before freeing the page. update_and_free_page will fail to
2378 * free the page if it can not allocate required vmemmap. We
2379 * need to adjust max_huge_pages if the page is not freed.
2380 * Attempt to allocate vmemmmap here so that we can take
2381 * appropriate action on failure.
2383 rc = hugetlb_vmemmap_restore(h, head);
2385 update_and_free_page(h, head, false);
2387 spin_lock_irq(&hugetlb_lock);
2388 add_hugetlb_page(h, head, false);
2389 h->max_huge_pages++;
2390 spin_unlock_irq(&hugetlb_lock);
2396 spin_unlock_irq(&hugetlb_lock);
2401 * Dissolve free hugepages in a given pfn range. Used by memory hotplug to
2402 * make specified memory blocks removable from the system.
2403 * Note that this will dissolve a free gigantic hugepage completely, if any
2404 * part of it lies within the given range.
2405 * Also note that if dissolve_free_huge_page() returns with an error, all
2406 * free hugepages that were dissolved before that error are lost.
2408 int dissolve_free_huge_pages(unsigned long start_pfn, unsigned long end_pfn)
2416 if (!hugepages_supported())
2419 order = huge_page_order(&default_hstate);
2421 order = min(order, huge_page_order(h));
2423 for (pfn = start_pfn; pfn < end_pfn; pfn += 1 << order) {
2424 page = pfn_to_page(pfn);
2425 rc = dissolve_free_huge_page(page);
2434 * Allocates a fresh surplus page from the page allocator.
2436 static struct page *alloc_surplus_huge_page(struct hstate *h, gfp_t gfp_mask,
2437 int nid, nodemask_t *nmask)
2439 struct page *page = NULL;
2441 if (hstate_is_gigantic(h))
2444 spin_lock_irq(&hugetlb_lock);
2445 if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages)
2447 spin_unlock_irq(&hugetlb_lock);
2449 page = alloc_fresh_huge_page(h, gfp_mask, nid, nmask, NULL);
2453 spin_lock_irq(&hugetlb_lock);
2455 * We could have raced with the pool size change.
2456 * Double check that and simply deallocate the new page
2457 * if we would end up overcommiting the surpluses. Abuse
2458 * temporary page to workaround the nasty free_huge_page
2461 if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) {
2462 SetHPageTemporary(page);
2463 spin_unlock_irq(&hugetlb_lock);
2464 free_huge_page(page);
2468 h->surplus_huge_pages++;
2469 h->surplus_huge_pages_node[page_to_nid(page)]++;
2472 spin_unlock_irq(&hugetlb_lock);
2477 static struct page *alloc_migrate_huge_page(struct hstate *h, gfp_t gfp_mask,
2478 int nid, nodemask_t *nmask)
2482 if (hstate_is_gigantic(h))
2485 page = alloc_fresh_huge_page(h, gfp_mask, nid, nmask, NULL);
2489 /* fresh huge pages are frozen */
2490 set_page_refcounted(page);
2493 * We do not account these pages as surplus because they are only
2494 * temporary and will be released properly on the last reference
2496 SetHPageTemporary(page);
2502 * Use the VMA's mpolicy to allocate a huge page from the buddy.
2505 struct page *alloc_buddy_huge_page_with_mpol(struct hstate *h,
2506 struct vm_area_struct *vma, unsigned long addr)
2508 struct page *page = NULL;
2509 struct mempolicy *mpol;
2510 gfp_t gfp_mask = htlb_alloc_mask(h);
2512 nodemask_t *nodemask;
2514 nid = huge_node(vma, addr, gfp_mask, &mpol, &nodemask);
2515 if (mpol_is_preferred_many(mpol)) {
2516 gfp_t gfp = gfp_mask | __GFP_NOWARN;
2518 gfp &= ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
2519 page = alloc_surplus_huge_page(h, gfp, nid, nodemask);
2521 /* Fallback to all nodes if page==NULL */
2526 page = alloc_surplus_huge_page(h, gfp_mask, nid, nodemask);
2527 mpol_cond_put(mpol);
2531 /* page migration callback function */
2532 struct page *alloc_huge_page_nodemask(struct hstate *h, int preferred_nid,
2533 nodemask_t *nmask, gfp_t gfp_mask)
2535 spin_lock_irq(&hugetlb_lock);
2536 if (available_huge_pages(h)) {
2539 page = dequeue_huge_page_nodemask(h, gfp_mask, preferred_nid, nmask);
2541 spin_unlock_irq(&hugetlb_lock);
2545 spin_unlock_irq(&hugetlb_lock);
2547 return alloc_migrate_huge_page(h, gfp_mask, preferred_nid, nmask);
2550 /* mempolicy aware migration callback */
2551 struct page *alloc_huge_page_vma(struct hstate *h, struct vm_area_struct *vma,
2552 unsigned long address)
2554 struct mempolicy *mpol;
2555 nodemask_t *nodemask;
2560 gfp_mask = htlb_alloc_mask(h);
2561 node = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
2562 page = alloc_huge_page_nodemask(h, node, nodemask, gfp_mask);
2563 mpol_cond_put(mpol);
2569 * Increase the hugetlb pool such that it can accommodate a reservation
2572 static int gather_surplus_pages(struct hstate *h, long delta)
2573 __must_hold(&hugetlb_lock)
2575 LIST_HEAD(surplus_list);
2576 struct page *page, *tmp;
2579 long needed, allocated;
2580 bool alloc_ok = true;
2582 lockdep_assert_held(&hugetlb_lock);
2583 needed = (h->resv_huge_pages + delta) - h->free_huge_pages;
2585 h->resv_huge_pages += delta;
2593 spin_unlock_irq(&hugetlb_lock);
2594 for (i = 0; i < needed; i++) {
2595 page = alloc_surplus_huge_page(h, htlb_alloc_mask(h),
2596 NUMA_NO_NODE, NULL);
2601 list_add(&page->lru, &surplus_list);
2607 * After retaking hugetlb_lock, we need to recalculate 'needed'
2608 * because either resv_huge_pages or free_huge_pages may have changed.
2610 spin_lock_irq(&hugetlb_lock);
2611 needed = (h->resv_huge_pages + delta) -
2612 (h->free_huge_pages + allocated);
2617 * We were not able to allocate enough pages to
2618 * satisfy the entire reservation so we free what
2619 * we've allocated so far.
2624 * The surplus_list now contains _at_least_ the number of extra pages
2625 * needed to accommodate the reservation. Add the appropriate number
2626 * of pages to the hugetlb pool and free the extras back to the buddy
2627 * allocator. Commit the entire reservation here to prevent another
2628 * process from stealing the pages as they are added to the pool but
2629 * before they are reserved.
2631 needed += allocated;
2632 h->resv_huge_pages += delta;
2635 /* Free the needed pages to the hugetlb pool */
2636 list_for_each_entry_safe(page, tmp, &surplus_list, lru) {
2639 /* Add the page to the hugetlb allocator */
2640 enqueue_huge_page(h, page);
2643 spin_unlock_irq(&hugetlb_lock);
2646 * Free unnecessary surplus pages to the buddy allocator.
2647 * Pages have no ref count, call free_huge_page directly.
2649 list_for_each_entry_safe(page, tmp, &surplus_list, lru)
2650 free_huge_page(page);
2651 spin_lock_irq(&hugetlb_lock);
2657 * This routine has two main purposes:
2658 * 1) Decrement the reservation count (resv_huge_pages) by the value passed
2659 * in unused_resv_pages. This corresponds to the prior adjustments made
2660 * to the associated reservation map.
2661 * 2) Free any unused surplus pages that may have been allocated to satisfy
2662 * the reservation. As many as unused_resv_pages may be freed.
2664 static void return_unused_surplus_pages(struct hstate *h,
2665 unsigned long unused_resv_pages)
2667 unsigned long nr_pages;
2669 LIST_HEAD(page_list);
2671 lockdep_assert_held(&hugetlb_lock);
2672 /* Uncommit the reservation */
2673 h->resv_huge_pages -= unused_resv_pages;
2675 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
2679 * Part (or even all) of the reservation could have been backed
2680 * by pre-allocated pages. Only free surplus pages.
2682 nr_pages = min(unused_resv_pages, h->surplus_huge_pages);
2685 * We want to release as many surplus pages as possible, spread
2686 * evenly across all nodes with memory. Iterate across these nodes
2687 * until we can no longer free unreserved surplus pages. This occurs
2688 * when the nodes with surplus pages have no free pages.
2689 * remove_pool_huge_page() will balance the freed pages across the
2690 * on-line nodes with memory and will handle the hstate accounting.
2692 while (nr_pages--) {
2693 page = remove_pool_huge_page(h, &node_states[N_MEMORY], 1);
2697 list_add(&page->lru, &page_list);
2701 spin_unlock_irq(&hugetlb_lock);
2702 update_and_free_pages_bulk(h, &page_list);
2703 spin_lock_irq(&hugetlb_lock);
2708 * vma_needs_reservation, vma_commit_reservation and vma_end_reservation
2709 * are used by the huge page allocation routines to manage reservations.
2711 * vma_needs_reservation is called to determine if the huge page at addr
2712 * within the vma has an associated reservation. If a reservation is
2713 * needed, the value 1 is returned. The caller is then responsible for
2714 * managing the global reservation and subpool usage counts. After
2715 * the huge page has been allocated, vma_commit_reservation is called
2716 * to add the page to the reservation map. If the page allocation fails,
2717 * the reservation must be ended instead of committed. vma_end_reservation
2718 * is called in such cases.
2720 * In the normal case, vma_commit_reservation returns the same value
2721 * as the preceding vma_needs_reservation call. The only time this
2722 * is not the case is if a reserve map was changed between calls. It
2723 * is the responsibility of the caller to notice the difference and
2724 * take appropriate action.
2726 * vma_add_reservation is used in error paths where a reservation must
2727 * be restored when a newly allocated huge page must be freed. It is
2728 * to be called after calling vma_needs_reservation to determine if a
2729 * reservation exists.
2731 * vma_del_reservation is used in error paths where an entry in the reserve
2732 * map was created during huge page allocation and must be removed. It is to
2733 * be called after calling vma_needs_reservation to determine if a reservation
2736 enum vma_resv_mode {
2743 static long __vma_reservation_common(struct hstate *h,
2744 struct vm_area_struct *vma, unsigned long addr,
2745 enum vma_resv_mode mode)
2747 struct resv_map *resv;
2750 long dummy_out_regions_needed;
2752 resv = vma_resv_map(vma);
2756 idx = vma_hugecache_offset(h, vma, addr);
2758 case VMA_NEEDS_RESV:
2759 ret = region_chg(resv, idx, idx + 1, &dummy_out_regions_needed);
2760 /* We assume that vma_reservation_* routines always operate on
2761 * 1 page, and that adding to resv map a 1 page entry can only
2762 * ever require 1 region.
2764 VM_BUG_ON(dummy_out_regions_needed != 1);
2766 case VMA_COMMIT_RESV:
2767 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2768 /* region_add calls of range 1 should never fail. */
2772 region_abort(resv, idx, idx + 1, 1);
2776 if (vma->vm_flags & VM_MAYSHARE) {
2777 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2778 /* region_add calls of range 1 should never fail. */
2781 region_abort(resv, idx, idx + 1, 1);
2782 ret = region_del(resv, idx, idx + 1);
2786 if (vma->vm_flags & VM_MAYSHARE) {
2787 region_abort(resv, idx, idx + 1, 1);
2788 ret = region_del(resv, idx, idx + 1);
2790 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2791 /* region_add calls of range 1 should never fail. */
2799 if (vma->vm_flags & VM_MAYSHARE || mode == VMA_DEL_RESV)
2802 * We know private mapping must have HPAGE_RESV_OWNER set.
2804 * In most cases, reserves always exist for private mappings.
2805 * However, a file associated with mapping could have been
2806 * hole punched or truncated after reserves were consumed.
2807 * As subsequent fault on such a range will not use reserves.
2808 * Subtle - The reserve map for private mappings has the
2809 * opposite meaning than that of shared mappings. If NO
2810 * entry is in the reserve map, it means a reservation exists.
2811 * If an entry exists in the reserve map, it means the
2812 * reservation has already been consumed. As a result, the
2813 * return value of this routine is the opposite of the
2814 * value returned from reserve map manipulation routines above.
2823 static long vma_needs_reservation(struct hstate *h,
2824 struct vm_area_struct *vma, unsigned long addr)
2826 return __vma_reservation_common(h, vma, addr, VMA_NEEDS_RESV);
2829 static long vma_commit_reservation(struct hstate *h,
2830 struct vm_area_struct *vma, unsigned long addr)
2832 return __vma_reservation_common(h, vma, addr, VMA_COMMIT_RESV);
2835 static void vma_end_reservation(struct hstate *h,
2836 struct vm_area_struct *vma, unsigned long addr)
2838 (void)__vma_reservation_common(h, vma, addr, VMA_END_RESV);
2841 static long vma_add_reservation(struct hstate *h,
2842 struct vm_area_struct *vma, unsigned long addr)
2844 return __vma_reservation_common(h, vma, addr, VMA_ADD_RESV);
2847 static long vma_del_reservation(struct hstate *h,
2848 struct vm_area_struct *vma, unsigned long addr)
2850 return __vma_reservation_common(h, vma, addr, VMA_DEL_RESV);
2854 * This routine is called to restore reservation information on error paths.
2855 * It should ONLY be called for pages allocated via alloc_huge_page(), and
2856 * the hugetlb mutex should remain held when calling this routine.
2858 * It handles two specific cases:
2859 * 1) A reservation was in place and the page consumed the reservation.
2860 * HPageRestoreReserve is set in the page.
2861 * 2) No reservation was in place for the page, so HPageRestoreReserve is
2862 * not set. However, alloc_huge_page always updates the reserve map.
2864 * In case 1, free_huge_page later in the error path will increment the
2865 * global reserve count. But, free_huge_page does not have enough context
2866 * to adjust the reservation map. This case deals primarily with private
2867 * mappings. Adjust the reserve map here to be consistent with global
2868 * reserve count adjustments to be made by free_huge_page. Make sure the
2869 * reserve map indicates there is a reservation present.
2871 * In case 2, simply undo reserve map modifications done by alloc_huge_page.
2873 void restore_reserve_on_error(struct hstate *h, struct vm_area_struct *vma,
2874 unsigned long address, struct page *page)
2876 long rc = vma_needs_reservation(h, vma, address);
2878 if (HPageRestoreReserve(page)) {
2879 if (unlikely(rc < 0))
2881 * Rare out of memory condition in reserve map
2882 * manipulation. Clear HPageRestoreReserve so that
2883 * global reserve count will not be incremented
2884 * by free_huge_page. This will make it appear
2885 * as though the reservation for this page was
2886 * consumed. This may prevent the task from
2887 * faulting in the page at a later time. This
2888 * is better than inconsistent global huge page
2889 * accounting of reserve counts.
2891 ClearHPageRestoreReserve(page);
2893 (void)vma_add_reservation(h, vma, address);
2895 vma_end_reservation(h, vma, address);
2899 * This indicates there is an entry in the reserve map
2900 * not added by alloc_huge_page. We know it was added
2901 * before the alloc_huge_page call, otherwise
2902 * HPageRestoreReserve would be set on the page.
2903 * Remove the entry so that a subsequent allocation
2904 * does not consume a reservation.
2906 rc = vma_del_reservation(h, vma, address);
2909 * VERY rare out of memory condition. Since
2910 * we can not delete the entry, set
2911 * HPageRestoreReserve so that the reserve
2912 * count will be incremented when the page
2913 * is freed. This reserve will be consumed
2914 * on a subsequent allocation.
2916 SetHPageRestoreReserve(page);
2917 } else if (rc < 0) {
2919 * Rare out of memory condition from
2920 * vma_needs_reservation call. Memory allocation is
2921 * only attempted if a new entry is needed. Therefore,
2922 * this implies there is not an entry in the
2925 * For shared mappings, no entry in the map indicates
2926 * no reservation. We are done.
2928 if (!(vma->vm_flags & VM_MAYSHARE))
2930 * For private mappings, no entry indicates
2931 * a reservation is present. Since we can
2932 * not add an entry, set SetHPageRestoreReserve
2933 * on the page so reserve count will be
2934 * incremented when freed. This reserve will
2935 * be consumed on a subsequent allocation.
2937 SetHPageRestoreReserve(page);
2940 * No reservation present, do nothing
2942 vma_end_reservation(h, vma, address);
2947 * alloc_and_dissolve_huge_page - Allocate a new page and dissolve the old one
2948 * @h: struct hstate old page belongs to
2949 * @old_page: Old page to dissolve
2950 * @list: List to isolate the page in case we need to
2951 * Returns 0 on success, otherwise negated error.
2953 static int alloc_and_dissolve_huge_page(struct hstate *h, struct page *old_page,
2954 struct list_head *list)
2956 gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
2957 int nid = page_to_nid(old_page);
2958 struct page *new_page;
2962 * Before dissolving the page, we need to allocate a new one for the
2963 * pool to remain stable. Here, we allocate the page and 'prep' it
2964 * by doing everything but actually updating counters and adding to
2965 * the pool. This simplifies and let us do most of the processing
2968 new_page = alloc_buddy_huge_page(h, gfp_mask, nid, NULL, NULL);
2971 __prep_new_huge_page(h, new_page);
2974 spin_lock_irq(&hugetlb_lock);
2975 if (!PageHuge(old_page)) {
2977 * Freed from under us. Drop new_page too.
2980 } else if (page_count(old_page)) {
2982 * Someone has grabbed the page, try to isolate it here.
2983 * Fail with -EBUSY if not possible.
2985 spin_unlock_irq(&hugetlb_lock);
2986 ret = isolate_hugetlb(old_page, list);
2987 spin_lock_irq(&hugetlb_lock);
2989 } else if (!HPageFreed(old_page)) {
2991 * Page's refcount is 0 but it has not been enqueued in the
2992 * freelist yet. Race window is small, so we can succeed here if
2995 spin_unlock_irq(&hugetlb_lock);
3000 * Ok, old_page is still a genuine free hugepage. Remove it from
3001 * the freelist and decrease the counters. These will be
3002 * incremented again when calling __prep_account_new_huge_page()
3003 * and enqueue_huge_page() for new_page. The counters will remain
3004 * stable since this happens under the lock.
3006 remove_hugetlb_page(h, old_page, false);
3009 * Ref count on new page is already zero as it was dropped
3010 * earlier. It can be directly added to the pool free list.
3012 __prep_account_new_huge_page(h, nid);
3013 enqueue_huge_page(h, new_page);
3016 * Pages have been replaced, we can safely free the old one.
3018 spin_unlock_irq(&hugetlb_lock);
3019 update_and_free_page(h, old_page, false);
3025 spin_unlock_irq(&hugetlb_lock);
3026 /* Page has a zero ref count, but needs a ref to be freed */
3027 set_page_refcounted(new_page);
3028 update_and_free_page(h, new_page, false);
3033 int isolate_or_dissolve_huge_page(struct page *page, struct list_head *list)
3040 * The page might have been dissolved from under our feet, so make sure
3041 * to carefully check the state under the lock.
3042 * Return success when racing as if we dissolved the page ourselves.
3044 spin_lock_irq(&hugetlb_lock);
3045 if (PageHuge(page)) {
3046 head = compound_head(page);
3047 h = page_hstate(head);
3049 spin_unlock_irq(&hugetlb_lock);
3052 spin_unlock_irq(&hugetlb_lock);
3055 * Fence off gigantic pages as there is a cyclic dependency between
3056 * alloc_contig_range and them. Return -ENOMEM as this has the effect
3057 * of bailing out right away without further retrying.
3059 if (hstate_is_gigantic(h))
3062 if (page_count(head) && !isolate_hugetlb(head, list))
3064 else if (!page_count(head))
3065 ret = alloc_and_dissolve_huge_page(h, head, list);
3070 struct page *alloc_huge_page(struct vm_area_struct *vma,
3071 unsigned long addr, int avoid_reserve)
3073 struct hugepage_subpool *spool = subpool_vma(vma);
3074 struct hstate *h = hstate_vma(vma);
3076 long map_chg, map_commit;
3079 struct hugetlb_cgroup *h_cg;
3080 bool deferred_reserve;
3082 idx = hstate_index(h);
3084 * Examine the region/reserve map to determine if the process
3085 * has a reservation for the page to be allocated. A return
3086 * code of zero indicates a reservation exists (no change).
3088 map_chg = gbl_chg = vma_needs_reservation(h, vma, addr);
3090 return ERR_PTR(-ENOMEM);
3093 * Processes that did not create the mapping will have no
3094 * reserves as indicated by the region/reserve map. Check
3095 * that the allocation will not exceed the subpool limit.
3096 * Allocations for MAP_NORESERVE mappings also need to be
3097 * checked against any subpool limit.
3099 if (map_chg || avoid_reserve) {
3100 gbl_chg = hugepage_subpool_get_pages(spool, 1);
3102 vma_end_reservation(h, vma, addr);
3103 return ERR_PTR(-ENOSPC);
3107 * Even though there was no reservation in the region/reserve
3108 * map, there could be reservations associated with the
3109 * subpool that can be used. This would be indicated if the
3110 * return value of hugepage_subpool_get_pages() is zero.
3111 * However, if avoid_reserve is specified we still avoid even
3112 * the subpool reservations.
3118 /* If this allocation is not consuming a reservation, charge it now.
3120 deferred_reserve = map_chg || avoid_reserve;
3121 if (deferred_reserve) {
3122 ret = hugetlb_cgroup_charge_cgroup_rsvd(
3123 idx, pages_per_huge_page(h), &h_cg);
3125 goto out_subpool_put;
3128 ret = hugetlb_cgroup_charge_cgroup(idx, pages_per_huge_page(h), &h_cg);
3130 goto out_uncharge_cgroup_reservation;
3132 spin_lock_irq(&hugetlb_lock);
3134 * glb_chg is passed to indicate whether or not a page must be taken
3135 * from the global free pool (global change). gbl_chg == 0 indicates
3136 * a reservation exists for the allocation.
3138 page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve, gbl_chg);
3140 spin_unlock_irq(&hugetlb_lock);
3141 page = alloc_buddy_huge_page_with_mpol(h, vma, addr);
3143 goto out_uncharge_cgroup;
3144 spin_lock_irq(&hugetlb_lock);
3145 if (!avoid_reserve && vma_has_reserves(vma, gbl_chg)) {
3146 SetHPageRestoreReserve(page);
3147 h->resv_huge_pages--;
3149 list_add(&page->lru, &h->hugepage_activelist);
3150 set_page_refcounted(page);
3153 hugetlb_cgroup_commit_charge(idx, pages_per_huge_page(h), h_cg, page);
3154 /* If allocation is not consuming a reservation, also store the
3155 * hugetlb_cgroup pointer on the page.
3157 if (deferred_reserve) {
3158 hugetlb_cgroup_commit_charge_rsvd(idx, pages_per_huge_page(h),
3162 spin_unlock_irq(&hugetlb_lock);
3164 hugetlb_set_page_subpool(page, spool);
3166 map_commit = vma_commit_reservation(h, vma, addr);
3167 if (unlikely(map_chg > map_commit)) {
3169 * The page was added to the reservation map between
3170 * vma_needs_reservation and vma_commit_reservation.
3171 * This indicates a race with hugetlb_reserve_pages.
3172 * Adjust for the subpool count incremented above AND
3173 * in hugetlb_reserve_pages for the same page. Also,
3174 * the reservation count added in hugetlb_reserve_pages
3175 * no longer applies.
3179 rsv_adjust = hugepage_subpool_put_pages(spool, 1);
3180 hugetlb_acct_memory(h, -rsv_adjust);
3181 if (deferred_reserve)
3182 hugetlb_cgroup_uncharge_page_rsvd(hstate_index(h),
3183 pages_per_huge_page(h), page);
3187 out_uncharge_cgroup:
3188 hugetlb_cgroup_uncharge_cgroup(idx, pages_per_huge_page(h), h_cg);
3189 out_uncharge_cgroup_reservation:
3190 if (deferred_reserve)
3191 hugetlb_cgroup_uncharge_cgroup_rsvd(idx, pages_per_huge_page(h),
3194 if (map_chg || avoid_reserve)
3195 hugepage_subpool_put_pages(spool, 1);
3196 vma_end_reservation(h, vma, addr);
3197 return ERR_PTR(-ENOSPC);
3200 int alloc_bootmem_huge_page(struct hstate *h, int nid)
3201 __attribute__ ((weak, alias("__alloc_bootmem_huge_page")));
3202 int __alloc_bootmem_huge_page(struct hstate *h, int nid)
3204 struct huge_bootmem_page *m = NULL; /* initialize for clang */
3207 /* do node specific alloc */
3208 if (nid != NUMA_NO_NODE) {
3209 m = memblock_alloc_try_nid_raw(huge_page_size(h), huge_page_size(h),
3210 0, MEMBLOCK_ALLOC_ACCESSIBLE, nid);
3215 /* allocate from next node when distributing huge pages */
3216 for_each_node_mask_to_alloc(h, nr_nodes, node, &node_states[N_MEMORY]) {
3217 m = memblock_alloc_try_nid_raw(
3218 huge_page_size(h), huge_page_size(h),
3219 0, MEMBLOCK_ALLOC_ACCESSIBLE, node);
3221 * Use the beginning of the huge page to store the
3222 * huge_bootmem_page struct (until gather_bootmem
3223 * puts them into the mem_map).
3231 /* Put them into a private list first because mem_map is not up yet */
3232 INIT_LIST_HEAD(&m->list);
3233 list_add(&m->list, &huge_boot_pages);
3239 * Put bootmem huge pages into the standard lists after mem_map is up.
3240 * Note: This only applies to gigantic (order > MAX_ORDER) pages.
3242 static void __init gather_bootmem_prealloc(void)
3244 struct huge_bootmem_page *m;
3246 list_for_each_entry(m, &huge_boot_pages, list) {
3247 struct page *page = virt_to_page(m);
3248 struct hstate *h = m->hstate;
3250 VM_BUG_ON(!hstate_is_gigantic(h));
3251 WARN_ON(page_count(page) != 1);
3252 if (prep_compound_gigantic_page(page, huge_page_order(h))) {
3253 WARN_ON(PageReserved(page));
3254 prep_new_huge_page(h, page, page_to_nid(page));
3255 free_huge_page(page); /* add to the hugepage allocator */
3257 /* VERY unlikely inflated ref count on a tail page */
3258 free_gigantic_page(page, huge_page_order(h));
3262 * We need to restore the 'stolen' pages to totalram_pages
3263 * in order to fix confusing memory reports from free(1) and
3264 * other side-effects, like CommitLimit going negative.
3266 adjust_managed_page_count(page, pages_per_huge_page(h));
3270 static void __init hugetlb_hstate_alloc_pages_onenode(struct hstate *h, int nid)
3275 for (i = 0; i < h->max_huge_pages_node[nid]; ++i) {
3276 if (hstate_is_gigantic(h)) {
3277 if (!alloc_bootmem_huge_page(h, nid))
3281 gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
3283 page = alloc_fresh_huge_page(h, gfp_mask, nid,
3284 &node_states[N_MEMORY], NULL);
3287 free_huge_page(page); /* free it into the hugepage allocator */
3291 if (i == h->max_huge_pages_node[nid])
3294 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
3295 pr_warn("HugeTLB: allocating %u of page size %s failed node%d. Only allocated %lu hugepages.\n",
3296 h->max_huge_pages_node[nid], buf, nid, i);
3297 h->max_huge_pages -= (h->max_huge_pages_node[nid] - i);
3298 h->max_huge_pages_node[nid] = i;
3301 static void __init hugetlb_hstate_alloc_pages(struct hstate *h)
3304 nodemask_t *node_alloc_noretry;
3305 bool node_specific_alloc = false;
3307 /* skip gigantic hugepages allocation if hugetlb_cma enabled */
3308 if (hstate_is_gigantic(h) && hugetlb_cma_size) {
3309 pr_warn_once("HugeTLB: hugetlb_cma is enabled, skip boot time allocation\n");
3313 /* do node specific alloc */
3314 for_each_online_node(i) {
3315 if (h->max_huge_pages_node[i] > 0) {
3316 hugetlb_hstate_alloc_pages_onenode(h, i);
3317 node_specific_alloc = true;
3321 if (node_specific_alloc)
3324 /* below will do all node balanced alloc */
3325 if (!hstate_is_gigantic(h)) {
3327 * Bit mask controlling how hard we retry per-node allocations.
3328 * Ignore errors as lower level routines can deal with
3329 * node_alloc_noretry == NULL. If this kmalloc fails at boot
3330 * time, we are likely in bigger trouble.
3332 node_alloc_noretry = kmalloc(sizeof(*node_alloc_noretry),
3335 /* allocations done at boot time */
3336 node_alloc_noretry = NULL;
3339 /* bit mask controlling how hard we retry per-node allocations */
3340 if (node_alloc_noretry)
3341 nodes_clear(*node_alloc_noretry);
3343 for (i = 0; i < h->max_huge_pages; ++i) {
3344 if (hstate_is_gigantic(h)) {
3345 if (!alloc_bootmem_huge_page(h, NUMA_NO_NODE))
3347 } else if (!alloc_pool_huge_page(h,
3348 &node_states[N_MEMORY],
3349 node_alloc_noretry))
3353 if (i < h->max_huge_pages) {
3356 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
3357 pr_warn("HugeTLB: allocating %lu of page size %s failed. Only allocated %lu hugepages.\n",
3358 h->max_huge_pages, buf, i);
3359 h->max_huge_pages = i;
3361 kfree(node_alloc_noretry);
3364 static void __init hugetlb_init_hstates(void)
3366 struct hstate *h, *h2;
3368 for_each_hstate(h) {
3369 /* oversize hugepages were init'ed in early boot */
3370 if (!hstate_is_gigantic(h))
3371 hugetlb_hstate_alloc_pages(h);
3374 * Set demote order for each hstate. Note that
3375 * h->demote_order is initially 0.
3376 * - We can not demote gigantic pages if runtime freeing
3377 * is not supported, so skip this.
3378 * - If CMA allocation is possible, we can not demote
3379 * HUGETLB_PAGE_ORDER or smaller size pages.
3381 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
3383 if (hugetlb_cma_size && h->order <= HUGETLB_PAGE_ORDER)
3385 for_each_hstate(h2) {
3388 if (h2->order < h->order &&
3389 h2->order > h->demote_order)
3390 h->demote_order = h2->order;
3395 static void __init report_hugepages(void)
3399 for_each_hstate(h) {
3402 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
3403 pr_info("HugeTLB: registered %s page size, pre-allocated %ld pages\n",
3404 buf, h->free_huge_pages);
3405 pr_info("HugeTLB: %d KiB vmemmap can be freed for a %s page\n",
3406 hugetlb_vmemmap_optimizable_size(h) / SZ_1K, buf);
3410 #ifdef CONFIG_HIGHMEM
3411 static void try_to_free_low(struct hstate *h, unsigned long count,
3412 nodemask_t *nodes_allowed)
3415 LIST_HEAD(page_list);
3417 lockdep_assert_held(&hugetlb_lock);
3418 if (hstate_is_gigantic(h))
3422 * Collect pages to be freed on a list, and free after dropping lock
3424 for_each_node_mask(i, *nodes_allowed) {
3425 struct page *page, *next;
3426 struct list_head *freel = &h->hugepage_freelists[i];
3427 list_for_each_entry_safe(page, next, freel, lru) {
3428 if (count >= h->nr_huge_pages)
3430 if (PageHighMem(page))
3432 remove_hugetlb_page(h, page, false);
3433 list_add(&page->lru, &page_list);
3438 spin_unlock_irq(&hugetlb_lock);
3439 update_and_free_pages_bulk(h, &page_list);
3440 spin_lock_irq(&hugetlb_lock);
3443 static inline void try_to_free_low(struct hstate *h, unsigned long count,
3444 nodemask_t *nodes_allowed)
3450 * Increment or decrement surplus_huge_pages. Keep node-specific counters
3451 * balanced by operating on them in a round-robin fashion.
3452 * Returns 1 if an adjustment was made.
3454 static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed,
3459 lockdep_assert_held(&hugetlb_lock);
3460 VM_BUG_ON(delta != -1 && delta != 1);
3463 for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
3464 if (h->surplus_huge_pages_node[node])
3468 for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
3469 if (h->surplus_huge_pages_node[node] <
3470 h->nr_huge_pages_node[node])
3477 h->surplus_huge_pages += delta;
3478 h->surplus_huge_pages_node[node] += delta;
3482 #define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages)
3483 static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,
3484 nodemask_t *nodes_allowed)
3486 unsigned long min_count, ret;
3488 LIST_HEAD(page_list);
3489 NODEMASK_ALLOC(nodemask_t, node_alloc_noretry, GFP_KERNEL);
3492 * Bit mask controlling how hard we retry per-node allocations.
3493 * If we can not allocate the bit mask, do not attempt to allocate
3494 * the requested huge pages.
3496 if (node_alloc_noretry)
3497 nodes_clear(*node_alloc_noretry);
3502 * resize_lock mutex prevents concurrent adjustments to number of
3503 * pages in hstate via the proc/sysfs interfaces.
3505 mutex_lock(&h->resize_lock);
3506 flush_free_hpage_work(h);
3507 spin_lock_irq(&hugetlb_lock);
3510 * Check for a node specific request.
3511 * Changing node specific huge page count may require a corresponding
3512 * change to the global count. In any case, the passed node mask
3513 * (nodes_allowed) will restrict alloc/free to the specified node.
3515 if (nid != NUMA_NO_NODE) {
3516 unsigned long old_count = count;
3518 count += h->nr_huge_pages - h->nr_huge_pages_node[nid];
3520 * User may have specified a large count value which caused the
3521 * above calculation to overflow. In this case, they wanted
3522 * to allocate as many huge pages as possible. Set count to
3523 * largest possible value to align with their intention.
3525 if (count < old_count)
3530 * Gigantic pages runtime allocation depend on the capability for large
3531 * page range allocation.
3532 * If the system does not provide this feature, return an error when
3533 * the user tries to allocate gigantic pages but let the user free the
3534 * boottime allocated gigantic pages.
3536 if (hstate_is_gigantic(h) && !IS_ENABLED(CONFIG_CONTIG_ALLOC)) {
3537 if (count > persistent_huge_pages(h)) {
3538 spin_unlock_irq(&hugetlb_lock);
3539 mutex_unlock(&h->resize_lock);
3540 NODEMASK_FREE(node_alloc_noretry);
3543 /* Fall through to decrease pool */
3547 * Increase the pool size
3548 * First take pages out of surplus state. Then make up the
3549 * remaining difference by allocating fresh huge pages.
3551 * We might race with alloc_surplus_huge_page() here and be unable
3552 * to convert a surplus huge page to a normal huge page. That is
3553 * not critical, though, it just means the overall size of the
3554 * pool might be one hugepage larger than it needs to be, but
3555 * within all the constraints specified by the sysctls.
3557 while (h->surplus_huge_pages && count > persistent_huge_pages(h)) {
3558 if (!adjust_pool_surplus(h, nodes_allowed, -1))
3562 while (count > persistent_huge_pages(h)) {
3564 * If this allocation races such that we no longer need the
3565 * page, free_huge_page will handle it by freeing the page
3566 * and reducing the surplus.
3568 spin_unlock_irq(&hugetlb_lock);
3570 /* yield cpu to avoid soft lockup */
3573 ret = alloc_pool_huge_page(h, nodes_allowed,
3574 node_alloc_noretry);
3575 spin_lock_irq(&hugetlb_lock);
3579 /* Bail for signals. Probably ctrl-c from user */
3580 if (signal_pending(current))
3585 * Decrease the pool size
3586 * First return free pages to the buddy allocator (being careful
3587 * to keep enough around to satisfy reservations). Then place
3588 * pages into surplus state as needed so the pool will shrink
3589 * to the desired size as pages become free.
3591 * By placing pages into the surplus state independent of the
3592 * overcommit value, we are allowing the surplus pool size to
3593 * exceed overcommit. There are few sane options here. Since
3594 * alloc_surplus_huge_page() is checking the global counter,
3595 * though, we'll note that we're not allowed to exceed surplus
3596 * and won't grow the pool anywhere else. Not until one of the
3597 * sysctls are changed, or the surplus pages go out of use.
3599 min_count = h->resv_huge_pages + h->nr_huge_pages - h->free_huge_pages;
3600 min_count = max(count, min_count);
3601 try_to_free_low(h, min_count, nodes_allowed);
3604 * Collect pages to be removed on list without dropping lock
3606 while (min_count < persistent_huge_pages(h)) {
3607 page = remove_pool_huge_page(h, nodes_allowed, 0);
3611 list_add(&page->lru, &page_list);
3613 /* free the pages after dropping lock */
3614 spin_unlock_irq(&hugetlb_lock);
3615 update_and_free_pages_bulk(h, &page_list);
3616 flush_free_hpage_work(h);
3617 spin_lock_irq(&hugetlb_lock);
3619 while (count < persistent_huge_pages(h)) {
3620 if (!adjust_pool_surplus(h, nodes_allowed, 1))
3624 h->max_huge_pages = persistent_huge_pages(h);
3625 spin_unlock_irq(&hugetlb_lock);
3626 mutex_unlock(&h->resize_lock);
3628 NODEMASK_FREE(node_alloc_noretry);
3633 static int demote_free_huge_page(struct hstate *h, struct page *page)
3635 int i, nid = page_to_nid(page);
3636 struct hstate *target_hstate;
3637 struct page *subpage;
3640 target_hstate = size_to_hstate(PAGE_SIZE << h->demote_order);
3642 remove_hugetlb_page_for_demote(h, page, false);
3643 spin_unlock_irq(&hugetlb_lock);
3645 rc = hugetlb_vmemmap_restore(h, page);
3647 /* Allocation of vmemmmap failed, we can not demote page */
3648 spin_lock_irq(&hugetlb_lock);
3649 set_page_refcounted(page);
3650 add_hugetlb_page(h, page, false);
3655 * Use destroy_compound_hugetlb_page_for_demote for all huge page
3656 * sizes as it will not ref count pages.
3658 destroy_compound_hugetlb_page_for_demote(page, huge_page_order(h));
3661 * Taking target hstate mutex synchronizes with set_max_huge_pages.
3662 * Without the mutex, pages added to target hstate could be marked
3665 * Note that we already hold h->resize_lock. To prevent deadlock,
3666 * use the convention of always taking larger size hstate mutex first.
3668 mutex_lock(&target_hstate->resize_lock);
3669 for (i = 0; i < pages_per_huge_page(h);
3670 i += pages_per_huge_page(target_hstate)) {
3671 subpage = nth_page(page, i);
3672 if (hstate_is_gigantic(target_hstate))
3673 prep_compound_gigantic_page_for_demote(subpage,
3674 target_hstate->order);
3676 prep_compound_page(subpage, target_hstate->order);
3677 set_page_private(subpage, 0);
3678 prep_new_huge_page(target_hstate, subpage, nid);
3679 free_huge_page(subpage);
3681 mutex_unlock(&target_hstate->resize_lock);
3683 spin_lock_irq(&hugetlb_lock);
3686 * Not absolutely necessary, but for consistency update max_huge_pages
3687 * based on pool changes for the demoted page.
3689 h->max_huge_pages--;
3690 target_hstate->max_huge_pages +=
3691 pages_per_huge_page(h) / pages_per_huge_page(target_hstate);
3696 static int demote_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed)
3697 __must_hold(&hugetlb_lock)
3702 lockdep_assert_held(&hugetlb_lock);
3704 /* We should never get here if no demote order */
3705 if (!h->demote_order) {
3706 pr_warn("HugeTLB: NULL demote order passed to demote_pool_huge_page.\n");
3707 return -EINVAL; /* internal error */
3710 for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
3711 list_for_each_entry(page, &h->hugepage_freelists[node], lru) {
3712 if (PageHWPoison(page))
3715 return demote_free_huge_page(h, page);
3720 * Only way to get here is if all pages on free lists are poisoned.
3721 * Return -EBUSY so that caller will not retry.
3726 #define HSTATE_ATTR_RO(_name) \
3727 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
3729 #define HSTATE_ATTR_WO(_name) \
3730 static struct kobj_attribute _name##_attr = __ATTR_WO(_name)
3732 #define HSTATE_ATTR(_name) \
3733 static struct kobj_attribute _name##_attr = __ATTR_RW(_name)
3735 static struct kobject *hugepages_kobj;
3736 static struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
3738 static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp);
3740 static struct hstate *kobj_to_hstate(struct kobject *kobj, int *nidp)
3744 for (i = 0; i < HUGE_MAX_HSTATE; i++)
3745 if (hstate_kobjs[i] == kobj) {
3747 *nidp = NUMA_NO_NODE;
3751 return kobj_to_node_hstate(kobj, nidp);
3754 static ssize_t nr_hugepages_show_common(struct kobject *kobj,
3755 struct kobj_attribute *attr, char *buf)
3758 unsigned long nr_huge_pages;
3761 h = kobj_to_hstate(kobj, &nid);
3762 if (nid == NUMA_NO_NODE)
3763 nr_huge_pages = h->nr_huge_pages;
3765 nr_huge_pages = h->nr_huge_pages_node[nid];
3767 return sysfs_emit(buf, "%lu\n", nr_huge_pages);
3770 static ssize_t __nr_hugepages_store_common(bool obey_mempolicy,
3771 struct hstate *h, int nid,
3772 unsigned long count, size_t len)
3775 nodemask_t nodes_allowed, *n_mask;
3777 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
3780 if (nid == NUMA_NO_NODE) {
3782 * global hstate attribute
3784 if (!(obey_mempolicy &&
3785 init_nodemask_of_mempolicy(&nodes_allowed)))
3786 n_mask = &node_states[N_MEMORY];
3788 n_mask = &nodes_allowed;
3791 * Node specific request. count adjustment happens in
3792 * set_max_huge_pages() after acquiring hugetlb_lock.
3794 init_nodemask_of_node(&nodes_allowed, nid);
3795 n_mask = &nodes_allowed;
3798 err = set_max_huge_pages(h, count, nid, n_mask);
3800 return err ? err : len;
3803 static ssize_t nr_hugepages_store_common(bool obey_mempolicy,
3804 struct kobject *kobj, const char *buf,
3808 unsigned long count;
3812 err = kstrtoul(buf, 10, &count);
3816 h = kobj_to_hstate(kobj, &nid);
3817 return __nr_hugepages_store_common(obey_mempolicy, h, nid, count, len);
3820 static ssize_t nr_hugepages_show(struct kobject *kobj,
3821 struct kobj_attribute *attr, char *buf)
3823 return nr_hugepages_show_common(kobj, attr, buf);
3826 static ssize_t nr_hugepages_store(struct kobject *kobj,
3827 struct kobj_attribute *attr, const char *buf, size_t len)
3829 return nr_hugepages_store_common(false, kobj, buf, len);
3831 HSTATE_ATTR(nr_hugepages);
3836 * hstate attribute for optionally mempolicy-based constraint on persistent
3837 * huge page alloc/free.
3839 static ssize_t nr_hugepages_mempolicy_show(struct kobject *kobj,
3840 struct kobj_attribute *attr,
3843 return nr_hugepages_show_common(kobj, attr, buf);
3846 static ssize_t nr_hugepages_mempolicy_store(struct kobject *kobj,
3847 struct kobj_attribute *attr, const char *buf, size_t len)
3849 return nr_hugepages_store_common(true, kobj, buf, len);
3851 HSTATE_ATTR(nr_hugepages_mempolicy);
3855 static ssize_t nr_overcommit_hugepages_show(struct kobject *kobj,
3856 struct kobj_attribute *attr, char *buf)
3858 struct hstate *h = kobj_to_hstate(kobj, NULL);
3859 return sysfs_emit(buf, "%lu\n", h->nr_overcommit_huge_pages);
3862 static ssize_t nr_overcommit_hugepages_store(struct kobject *kobj,
3863 struct kobj_attribute *attr, const char *buf, size_t count)
3866 unsigned long input;
3867 struct hstate *h = kobj_to_hstate(kobj, NULL);
3869 if (hstate_is_gigantic(h))
3872 err = kstrtoul(buf, 10, &input);
3876 spin_lock_irq(&hugetlb_lock);
3877 h->nr_overcommit_huge_pages = input;
3878 spin_unlock_irq(&hugetlb_lock);
3882 HSTATE_ATTR(nr_overcommit_hugepages);
3884 static ssize_t free_hugepages_show(struct kobject *kobj,
3885 struct kobj_attribute *attr, char *buf)
3888 unsigned long free_huge_pages;
3891 h = kobj_to_hstate(kobj, &nid);
3892 if (nid == NUMA_NO_NODE)
3893 free_huge_pages = h->free_huge_pages;
3895 free_huge_pages = h->free_huge_pages_node[nid];
3897 return sysfs_emit(buf, "%lu\n", free_huge_pages);
3899 HSTATE_ATTR_RO(free_hugepages);
3901 static ssize_t resv_hugepages_show(struct kobject *kobj,
3902 struct kobj_attribute *attr, char *buf)
3904 struct hstate *h = kobj_to_hstate(kobj, NULL);
3905 return sysfs_emit(buf, "%lu\n", h->resv_huge_pages);
3907 HSTATE_ATTR_RO(resv_hugepages);
3909 static ssize_t surplus_hugepages_show(struct kobject *kobj,
3910 struct kobj_attribute *attr, char *buf)
3913 unsigned long surplus_huge_pages;
3916 h = kobj_to_hstate(kobj, &nid);
3917 if (nid == NUMA_NO_NODE)
3918 surplus_huge_pages = h->surplus_huge_pages;
3920 surplus_huge_pages = h->surplus_huge_pages_node[nid];
3922 return sysfs_emit(buf, "%lu\n", surplus_huge_pages);
3924 HSTATE_ATTR_RO(surplus_hugepages);
3926 static ssize_t demote_store(struct kobject *kobj,
3927 struct kobj_attribute *attr, const char *buf, size_t len)
3929 unsigned long nr_demote;
3930 unsigned long nr_available;
3931 nodemask_t nodes_allowed, *n_mask;
3936 err = kstrtoul(buf, 10, &nr_demote);
3939 h = kobj_to_hstate(kobj, &nid);
3941 if (nid != NUMA_NO_NODE) {
3942 init_nodemask_of_node(&nodes_allowed, nid);
3943 n_mask = &nodes_allowed;
3945 n_mask = &node_states[N_MEMORY];
3948 /* Synchronize with other sysfs operations modifying huge pages */
3949 mutex_lock(&h->resize_lock);
3950 spin_lock_irq(&hugetlb_lock);
3954 * Check for available pages to demote each time thorough the
3955 * loop as demote_pool_huge_page will drop hugetlb_lock.
3957 if (nid != NUMA_NO_NODE)
3958 nr_available = h->free_huge_pages_node[nid];
3960 nr_available = h->free_huge_pages;
3961 nr_available -= h->resv_huge_pages;
3965 err = demote_pool_huge_page(h, n_mask);
3972 spin_unlock_irq(&hugetlb_lock);
3973 mutex_unlock(&h->resize_lock);
3979 HSTATE_ATTR_WO(demote);
3981 static ssize_t demote_size_show(struct kobject *kobj,
3982 struct kobj_attribute *attr, char *buf)
3984 struct hstate *h = kobj_to_hstate(kobj, NULL);
3985 unsigned long demote_size = (PAGE_SIZE << h->demote_order) / SZ_1K;
3987 return sysfs_emit(buf, "%lukB\n", demote_size);
3990 static ssize_t demote_size_store(struct kobject *kobj,
3991 struct kobj_attribute *attr,
3992 const char *buf, size_t count)
3994 struct hstate *h, *demote_hstate;
3995 unsigned long demote_size;
3996 unsigned int demote_order;
3998 demote_size = (unsigned long)memparse(buf, NULL);
4000 demote_hstate = size_to_hstate(demote_size);
4003 demote_order = demote_hstate->order;
4004 if (demote_order < HUGETLB_PAGE_ORDER)
4007 /* demote order must be smaller than hstate order */
4008 h = kobj_to_hstate(kobj, NULL);
4009 if (demote_order >= h->order)
4012 /* resize_lock synchronizes access to demote size and writes */
4013 mutex_lock(&h->resize_lock);
4014 h->demote_order = demote_order;
4015 mutex_unlock(&h->resize_lock);
4019 HSTATE_ATTR(demote_size);
4021 static struct attribute *hstate_attrs[] = {
4022 &nr_hugepages_attr.attr,
4023 &nr_overcommit_hugepages_attr.attr,
4024 &free_hugepages_attr.attr,
4025 &resv_hugepages_attr.attr,
4026 &surplus_hugepages_attr.attr,
4028 &nr_hugepages_mempolicy_attr.attr,
4033 static const struct attribute_group hstate_attr_group = {
4034 .attrs = hstate_attrs,
4037 static struct attribute *hstate_demote_attrs[] = {
4038 &demote_size_attr.attr,
4043 static const struct attribute_group hstate_demote_attr_group = {
4044 .attrs = hstate_demote_attrs,
4047 static int hugetlb_sysfs_add_hstate(struct hstate *h, struct kobject *parent,
4048 struct kobject **hstate_kobjs,
4049 const struct attribute_group *hstate_attr_group)
4052 int hi = hstate_index(h);
4054 hstate_kobjs[hi] = kobject_create_and_add(h->name, parent);
4055 if (!hstate_kobjs[hi])
4058 retval = sysfs_create_group(hstate_kobjs[hi], hstate_attr_group);
4060 kobject_put(hstate_kobjs[hi]);
4061 hstate_kobjs[hi] = NULL;
4065 if (h->demote_order) {
4066 retval = sysfs_create_group(hstate_kobjs[hi],
4067 &hstate_demote_attr_group);
4069 pr_warn("HugeTLB unable to create demote interfaces for %s\n", h->name);
4070 sysfs_remove_group(hstate_kobjs[hi], hstate_attr_group);
4071 kobject_put(hstate_kobjs[hi]);
4072 hstate_kobjs[hi] = NULL;
4081 static bool hugetlb_sysfs_initialized __ro_after_init;
4084 * node_hstate/s - associate per node hstate attributes, via their kobjects,
4085 * with node devices in node_devices[] using a parallel array. The array
4086 * index of a node device or _hstate == node id.
4087 * This is here to avoid any static dependency of the node device driver, in
4088 * the base kernel, on the hugetlb module.
4090 struct node_hstate {
4091 struct kobject *hugepages_kobj;
4092 struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
4094 static struct node_hstate node_hstates[MAX_NUMNODES];
4097 * A subset of global hstate attributes for node devices
4099 static struct attribute *per_node_hstate_attrs[] = {
4100 &nr_hugepages_attr.attr,
4101 &free_hugepages_attr.attr,
4102 &surplus_hugepages_attr.attr,
4106 static const struct attribute_group per_node_hstate_attr_group = {
4107 .attrs = per_node_hstate_attrs,
4111 * kobj_to_node_hstate - lookup global hstate for node device hstate attr kobj.
4112 * Returns node id via non-NULL nidp.
4114 static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
4118 for (nid = 0; nid < nr_node_ids; nid++) {
4119 struct node_hstate *nhs = &node_hstates[nid];
4121 for (i = 0; i < HUGE_MAX_HSTATE; i++)
4122 if (nhs->hstate_kobjs[i] == kobj) {
4134 * Unregister hstate attributes from a single node device.
4135 * No-op if no hstate attributes attached.
4137 void hugetlb_unregister_node(struct node *node)
4140 struct node_hstate *nhs = &node_hstates[node->dev.id];
4142 if (!nhs->hugepages_kobj)
4143 return; /* no hstate attributes */
4145 for_each_hstate(h) {
4146 int idx = hstate_index(h);
4147 struct kobject *hstate_kobj = nhs->hstate_kobjs[idx];
4151 if (h->demote_order)
4152 sysfs_remove_group(hstate_kobj, &hstate_demote_attr_group);
4153 sysfs_remove_group(hstate_kobj, &per_node_hstate_attr_group);
4154 kobject_put(hstate_kobj);
4155 nhs->hstate_kobjs[idx] = NULL;
4158 kobject_put(nhs->hugepages_kobj);
4159 nhs->hugepages_kobj = NULL;
4164 * Register hstate attributes for a single node device.
4165 * No-op if attributes already registered.
4167 void hugetlb_register_node(struct node *node)
4170 struct node_hstate *nhs = &node_hstates[node->dev.id];
4173 if (!hugetlb_sysfs_initialized)
4176 if (nhs->hugepages_kobj)
4177 return; /* already allocated */
4179 nhs->hugepages_kobj = kobject_create_and_add("hugepages",
4181 if (!nhs->hugepages_kobj)
4184 for_each_hstate(h) {
4185 err = hugetlb_sysfs_add_hstate(h, nhs->hugepages_kobj,
4187 &per_node_hstate_attr_group);
4189 pr_err("HugeTLB: Unable to add hstate %s for node %d\n",
4190 h->name, node->dev.id);
4191 hugetlb_unregister_node(node);
4198 * hugetlb init time: register hstate attributes for all registered node
4199 * devices of nodes that have memory. All on-line nodes should have
4200 * registered their associated device by this time.
4202 static void __init hugetlb_register_all_nodes(void)
4206 for_each_online_node(nid)
4207 hugetlb_register_node(node_devices[nid]);
4209 #else /* !CONFIG_NUMA */
4211 static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
4219 static void hugetlb_register_all_nodes(void) { }
4224 static void __init hugetlb_cma_check(void);
4226 static inline __init void hugetlb_cma_check(void)
4231 static void __init hugetlb_sysfs_init(void)
4236 hugepages_kobj = kobject_create_and_add("hugepages", mm_kobj);
4237 if (!hugepages_kobj)
4240 for_each_hstate(h) {
4241 err = hugetlb_sysfs_add_hstate(h, hugepages_kobj,
4242 hstate_kobjs, &hstate_attr_group);
4244 pr_err("HugeTLB: Unable to add hstate %s", h->name);
4248 hugetlb_sysfs_initialized = true;
4250 hugetlb_register_all_nodes();
4253 static int __init hugetlb_init(void)
4257 BUILD_BUG_ON(sizeof_field(struct page, private) * BITS_PER_BYTE <
4260 if (!hugepages_supported()) {
4261 if (hugetlb_max_hstate || default_hstate_max_huge_pages)
4262 pr_warn("HugeTLB: huge pages not supported, ignoring associated command-line parameters\n");
4267 * Make sure HPAGE_SIZE (HUGETLB_PAGE_ORDER) hstate exists. Some
4268 * architectures depend on setup being done here.
4270 hugetlb_add_hstate(HUGETLB_PAGE_ORDER);
4271 if (!parsed_default_hugepagesz) {
4273 * If we did not parse a default huge page size, set
4274 * default_hstate_idx to HPAGE_SIZE hstate. And, if the
4275 * number of huge pages for this default size was implicitly
4276 * specified, set that here as well.
4277 * Note that the implicit setting will overwrite an explicit
4278 * setting. A warning will be printed in this case.
4280 default_hstate_idx = hstate_index(size_to_hstate(HPAGE_SIZE));
4281 if (default_hstate_max_huge_pages) {
4282 if (default_hstate.max_huge_pages) {
4285 string_get_size(huge_page_size(&default_hstate),
4286 1, STRING_UNITS_2, buf, 32);
4287 pr_warn("HugeTLB: Ignoring hugepages=%lu associated with %s page size\n",
4288 default_hstate.max_huge_pages, buf);
4289 pr_warn("HugeTLB: Using hugepages=%lu for number of default huge pages\n",
4290 default_hstate_max_huge_pages);
4292 default_hstate.max_huge_pages =
4293 default_hstate_max_huge_pages;
4295 for_each_online_node(i)
4296 default_hstate.max_huge_pages_node[i] =
4297 default_hugepages_in_node[i];
4301 hugetlb_cma_check();
4302 hugetlb_init_hstates();
4303 gather_bootmem_prealloc();
4306 hugetlb_sysfs_init();
4307 hugetlb_cgroup_file_init();
4310 num_fault_mutexes = roundup_pow_of_two(8 * num_possible_cpus());
4312 num_fault_mutexes = 1;
4314 hugetlb_fault_mutex_table =
4315 kmalloc_array(num_fault_mutexes, sizeof(struct mutex),
4317 BUG_ON(!hugetlb_fault_mutex_table);
4319 for (i = 0; i < num_fault_mutexes; i++)
4320 mutex_init(&hugetlb_fault_mutex_table[i]);
4323 subsys_initcall(hugetlb_init);
4325 /* Overwritten by architectures with more huge page sizes */
4326 bool __init __attribute((weak)) arch_hugetlb_valid_size(unsigned long size)
4328 return size == HPAGE_SIZE;
4331 void __init hugetlb_add_hstate(unsigned int order)
4336 if (size_to_hstate(PAGE_SIZE << order)) {
4339 BUG_ON(hugetlb_max_hstate >= HUGE_MAX_HSTATE);
4341 h = &hstates[hugetlb_max_hstate++];
4342 mutex_init(&h->resize_lock);
4344 h->mask = ~(huge_page_size(h) - 1);
4345 for (i = 0; i < MAX_NUMNODES; ++i)
4346 INIT_LIST_HEAD(&h->hugepage_freelists[i]);
4347 INIT_LIST_HEAD(&h->hugepage_activelist);
4348 h->next_nid_to_alloc = first_memory_node;
4349 h->next_nid_to_free = first_memory_node;
4350 snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB",
4351 huge_page_size(h)/SZ_1K);
4356 bool __init __weak hugetlb_node_alloc_supported(void)
4361 static void __init hugepages_clear_pages_in_node(void)
4363 if (!hugetlb_max_hstate) {
4364 default_hstate_max_huge_pages = 0;
4365 memset(default_hugepages_in_node, 0,
4366 sizeof(default_hugepages_in_node));
4368 parsed_hstate->max_huge_pages = 0;
4369 memset(parsed_hstate->max_huge_pages_node, 0,
4370 sizeof(parsed_hstate->max_huge_pages_node));
4375 * hugepages command line processing
4376 * hugepages normally follows a valid hugepagsz or default_hugepagsz
4377 * specification. If not, ignore the hugepages value. hugepages can also
4378 * be the first huge page command line option in which case it implicitly
4379 * specifies the number of huge pages for the default size.
4381 static int __init hugepages_setup(char *s)
4384 static unsigned long *last_mhp;
4385 int node = NUMA_NO_NODE;
4390 if (!parsed_valid_hugepagesz) {
4391 pr_warn("HugeTLB: hugepages=%s does not follow a valid hugepagesz, ignoring\n", s);
4392 parsed_valid_hugepagesz = true;
4397 * !hugetlb_max_hstate means we haven't parsed a hugepagesz= parameter
4398 * yet, so this hugepages= parameter goes to the "default hstate".
4399 * Otherwise, it goes with the previously parsed hugepagesz or
4400 * default_hugepagesz.
4402 else if (!hugetlb_max_hstate)
4403 mhp = &default_hstate_max_huge_pages;
4405 mhp = &parsed_hstate->max_huge_pages;
4407 if (mhp == last_mhp) {
4408 pr_warn("HugeTLB: hugepages= specified twice without interleaving hugepagesz=, ignoring hugepages=%s\n", s);
4414 if (sscanf(p, "%lu%n", &tmp, &count) != 1)
4416 /* Parameter is node format */
4417 if (p[count] == ':') {
4418 if (!hugetlb_node_alloc_supported()) {
4419 pr_warn("HugeTLB: architecture can't support node specific alloc, ignoring!\n");
4422 if (tmp >= MAX_NUMNODES || !node_online(tmp))
4424 node = array_index_nospec(tmp, MAX_NUMNODES);
4426 /* Parse hugepages */
4427 if (sscanf(p, "%lu%n", &tmp, &count) != 1)
4429 if (!hugetlb_max_hstate)
4430 default_hugepages_in_node[node] = tmp;
4432 parsed_hstate->max_huge_pages_node[node] = tmp;
4434 /* Go to parse next node*/
4435 if (p[count] == ',')
4448 * Global state is always initialized later in hugetlb_init.
4449 * But we need to allocate gigantic hstates here early to still
4450 * use the bootmem allocator.
4452 if (hugetlb_max_hstate && hstate_is_gigantic(parsed_hstate))
4453 hugetlb_hstate_alloc_pages(parsed_hstate);
4460 pr_warn("HugeTLB: Invalid hugepages parameter %s\n", p);
4461 hugepages_clear_pages_in_node();
4464 __setup("hugepages=", hugepages_setup);
4467 * hugepagesz command line processing
4468 * A specific huge page size can only be specified once with hugepagesz.
4469 * hugepagesz is followed by hugepages on the command line. The global
4470 * variable 'parsed_valid_hugepagesz' is used to determine if prior
4471 * hugepagesz argument was valid.
4473 static int __init hugepagesz_setup(char *s)
4478 parsed_valid_hugepagesz = false;
4479 size = (unsigned long)memparse(s, NULL);
4481 if (!arch_hugetlb_valid_size(size)) {
4482 pr_err("HugeTLB: unsupported hugepagesz=%s\n", s);
4486 h = size_to_hstate(size);
4489 * hstate for this size already exists. This is normally
4490 * an error, but is allowed if the existing hstate is the
4491 * default hstate. More specifically, it is only allowed if
4492 * the number of huge pages for the default hstate was not
4493 * previously specified.
4495 if (!parsed_default_hugepagesz || h != &default_hstate ||
4496 default_hstate.max_huge_pages) {
4497 pr_warn("HugeTLB: hugepagesz=%s specified twice, ignoring\n", s);
4502 * No need to call hugetlb_add_hstate() as hstate already
4503 * exists. But, do set parsed_hstate so that a following
4504 * hugepages= parameter will be applied to this hstate.
4507 parsed_valid_hugepagesz = true;
4511 hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
4512 parsed_valid_hugepagesz = true;
4515 __setup("hugepagesz=", hugepagesz_setup);
4518 * default_hugepagesz command line input
4519 * Only one instance of default_hugepagesz allowed on command line.
4521 static int __init default_hugepagesz_setup(char *s)
4526 parsed_valid_hugepagesz = false;
4527 if (parsed_default_hugepagesz) {
4528 pr_err("HugeTLB: default_hugepagesz previously specified, ignoring %s\n", s);
4532 size = (unsigned long)memparse(s, NULL);
4534 if (!arch_hugetlb_valid_size(size)) {
4535 pr_err("HugeTLB: unsupported default_hugepagesz=%s\n", s);
4539 hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
4540 parsed_valid_hugepagesz = true;
4541 parsed_default_hugepagesz = true;
4542 default_hstate_idx = hstate_index(size_to_hstate(size));
4545 * The number of default huge pages (for this size) could have been
4546 * specified as the first hugetlb parameter: hugepages=X. If so,
4547 * then default_hstate_max_huge_pages is set. If the default huge
4548 * page size is gigantic (>= MAX_ORDER), then the pages must be
4549 * allocated here from bootmem allocator.
4551 if (default_hstate_max_huge_pages) {
4552 default_hstate.max_huge_pages = default_hstate_max_huge_pages;
4553 for_each_online_node(i)
4554 default_hstate.max_huge_pages_node[i] =
4555 default_hugepages_in_node[i];
4556 if (hstate_is_gigantic(&default_hstate))
4557 hugetlb_hstate_alloc_pages(&default_hstate);
4558 default_hstate_max_huge_pages = 0;
4563 __setup("default_hugepagesz=", default_hugepagesz_setup);
4565 static nodemask_t *policy_mbind_nodemask(gfp_t gfp)
4568 struct mempolicy *mpol = get_task_policy(current);
4571 * Only enforce MPOL_BIND policy which overlaps with cpuset policy
4572 * (from policy_nodemask) specifically for hugetlb case
4574 if (mpol->mode == MPOL_BIND &&
4575 (apply_policy_zone(mpol, gfp_zone(gfp)) &&
4576 cpuset_nodemask_valid_mems_allowed(&mpol->nodes)))
4577 return &mpol->nodes;
4582 static unsigned int allowed_mems_nr(struct hstate *h)
4585 unsigned int nr = 0;
4586 nodemask_t *mbind_nodemask;
4587 unsigned int *array = h->free_huge_pages_node;
4588 gfp_t gfp_mask = htlb_alloc_mask(h);
4590 mbind_nodemask = policy_mbind_nodemask(gfp_mask);
4591 for_each_node_mask(node, cpuset_current_mems_allowed) {
4592 if (!mbind_nodemask || node_isset(node, *mbind_nodemask))
4599 #ifdef CONFIG_SYSCTL
4600 static int proc_hugetlb_doulongvec_minmax(struct ctl_table *table, int write,
4601 void *buffer, size_t *length,
4602 loff_t *ppos, unsigned long *out)
4604 struct ctl_table dup_table;
4607 * In order to avoid races with __do_proc_doulongvec_minmax(), we
4608 * can duplicate the @table and alter the duplicate of it.
4611 dup_table.data = out;
4613 return proc_doulongvec_minmax(&dup_table, write, buffer, length, ppos);
4616 static int hugetlb_sysctl_handler_common(bool obey_mempolicy,
4617 struct ctl_table *table, int write,
4618 void *buffer, size_t *length, loff_t *ppos)
4620 struct hstate *h = &default_hstate;
4621 unsigned long tmp = h->max_huge_pages;
4624 if (!hugepages_supported())
4627 ret = proc_hugetlb_doulongvec_minmax(table, write, buffer, length, ppos,
4633 ret = __nr_hugepages_store_common(obey_mempolicy, h,
4634 NUMA_NO_NODE, tmp, *length);
4639 int hugetlb_sysctl_handler(struct ctl_table *table, int write,
4640 void *buffer, size_t *length, loff_t *ppos)
4643 return hugetlb_sysctl_handler_common(false, table, write,
4644 buffer, length, ppos);
4648 int hugetlb_mempolicy_sysctl_handler(struct ctl_table *table, int write,
4649 void *buffer, size_t *length, loff_t *ppos)
4651 return hugetlb_sysctl_handler_common(true, table, write,
4652 buffer, length, ppos);
4654 #endif /* CONFIG_NUMA */
4656 int hugetlb_overcommit_handler(struct ctl_table *table, int write,
4657 void *buffer, size_t *length, loff_t *ppos)
4659 struct hstate *h = &default_hstate;
4663 if (!hugepages_supported())
4666 tmp = h->nr_overcommit_huge_pages;
4668 if (write && hstate_is_gigantic(h))
4671 ret = proc_hugetlb_doulongvec_minmax(table, write, buffer, length, ppos,
4677 spin_lock_irq(&hugetlb_lock);
4678 h->nr_overcommit_huge_pages = tmp;
4679 spin_unlock_irq(&hugetlb_lock);
4685 #endif /* CONFIG_SYSCTL */
4687 void hugetlb_report_meminfo(struct seq_file *m)
4690 unsigned long total = 0;
4692 if (!hugepages_supported())
4695 for_each_hstate(h) {
4696 unsigned long count = h->nr_huge_pages;
4698 total += huge_page_size(h) * count;
4700 if (h == &default_hstate)
4702 "HugePages_Total: %5lu\n"
4703 "HugePages_Free: %5lu\n"
4704 "HugePages_Rsvd: %5lu\n"
4705 "HugePages_Surp: %5lu\n"
4706 "Hugepagesize: %8lu kB\n",
4710 h->surplus_huge_pages,
4711 huge_page_size(h) / SZ_1K);
4714 seq_printf(m, "Hugetlb: %8lu kB\n", total / SZ_1K);
4717 int hugetlb_report_node_meminfo(char *buf, int len, int nid)
4719 struct hstate *h = &default_hstate;
4721 if (!hugepages_supported())
4724 return sysfs_emit_at(buf, len,
4725 "Node %d HugePages_Total: %5u\n"
4726 "Node %d HugePages_Free: %5u\n"
4727 "Node %d HugePages_Surp: %5u\n",
4728 nid, h->nr_huge_pages_node[nid],
4729 nid, h->free_huge_pages_node[nid],
4730 nid, h->surplus_huge_pages_node[nid]);
4733 void hugetlb_show_meminfo_node(int nid)
4737 if (!hugepages_supported())
4741 printk("Node %d hugepages_total=%u hugepages_free=%u hugepages_surp=%u hugepages_size=%lukB\n",
4743 h->nr_huge_pages_node[nid],
4744 h->free_huge_pages_node[nid],
4745 h->surplus_huge_pages_node[nid],
4746 huge_page_size(h) / SZ_1K);
4749 void hugetlb_report_usage(struct seq_file *m, struct mm_struct *mm)
4751 seq_printf(m, "HugetlbPages:\t%8lu kB\n",
4752 atomic_long_read(&mm->hugetlb_usage) << (PAGE_SHIFT - 10));
4755 /* Return the number pages of memory we physically have, in PAGE_SIZE units. */
4756 unsigned long hugetlb_total_pages(void)
4759 unsigned long nr_total_pages = 0;
4762 nr_total_pages += h->nr_huge_pages * pages_per_huge_page(h);
4763 return nr_total_pages;
4766 static int hugetlb_acct_memory(struct hstate *h, long delta)
4773 spin_lock_irq(&hugetlb_lock);
4775 * When cpuset is configured, it breaks the strict hugetlb page
4776 * reservation as the accounting is done on a global variable. Such
4777 * reservation is completely rubbish in the presence of cpuset because
4778 * the reservation is not checked against page availability for the
4779 * current cpuset. Application can still potentially OOM'ed by kernel
4780 * with lack of free htlb page in cpuset that the task is in.
4781 * Attempt to enforce strict accounting with cpuset is almost
4782 * impossible (or too ugly) because cpuset is too fluid that
4783 * task or memory node can be dynamically moved between cpusets.
4785 * The change of semantics for shared hugetlb mapping with cpuset is
4786 * undesirable. However, in order to preserve some of the semantics,
4787 * we fall back to check against current free page availability as
4788 * a best attempt and hopefully to minimize the impact of changing
4789 * semantics that cpuset has.
4791 * Apart from cpuset, we also have memory policy mechanism that
4792 * also determines from which node the kernel will allocate memory
4793 * in a NUMA system. So similar to cpuset, we also should consider
4794 * the memory policy of the current task. Similar to the description
4798 if (gather_surplus_pages(h, delta) < 0)
4801 if (delta > allowed_mems_nr(h)) {
4802 return_unused_surplus_pages(h, delta);
4809 return_unused_surplus_pages(h, (unsigned long) -delta);
4812 spin_unlock_irq(&hugetlb_lock);
4816 static void hugetlb_vm_op_open(struct vm_area_struct *vma)
4818 struct resv_map *resv = vma_resv_map(vma);
4821 * HPAGE_RESV_OWNER indicates a private mapping.
4822 * This new VMA should share its siblings reservation map if present.
4823 * The VMA will only ever have a valid reservation map pointer where
4824 * it is being copied for another still existing VMA. As that VMA
4825 * has a reference to the reservation map it cannot disappear until
4826 * after this open call completes. It is therefore safe to take a
4827 * new reference here without additional locking.
4829 if (resv && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
4830 resv_map_dup_hugetlb_cgroup_uncharge_info(resv);
4831 kref_get(&resv->refs);
4835 * vma_lock structure for sharable mappings is vma specific.
4836 * Clear old pointer (if copied via vm_area_dup) and allocate
4837 * new structure. Before clearing, make sure vma_lock is not
4840 if (vma->vm_flags & VM_MAYSHARE) {
4841 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
4844 if (vma_lock->vma != vma) {
4845 vma->vm_private_data = NULL;
4846 hugetlb_vma_lock_alloc(vma);
4848 pr_warn("HugeTLB: vma_lock already exists in %s.\n", __func__);
4850 hugetlb_vma_lock_alloc(vma);
4854 static void hugetlb_vm_op_close(struct vm_area_struct *vma)
4856 struct hstate *h = hstate_vma(vma);
4857 struct resv_map *resv;
4858 struct hugepage_subpool *spool = subpool_vma(vma);
4859 unsigned long reserve, start, end;
4862 hugetlb_vma_lock_free(vma);
4864 resv = vma_resv_map(vma);
4865 if (!resv || !is_vma_resv_set(vma, HPAGE_RESV_OWNER))
4868 start = vma_hugecache_offset(h, vma, vma->vm_start);
4869 end = vma_hugecache_offset(h, vma, vma->vm_end);
4871 reserve = (end - start) - region_count(resv, start, end);
4872 hugetlb_cgroup_uncharge_counter(resv, start, end);
4875 * Decrement reserve counts. The global reserve count may be
4876 * adjusted if the subpool has a minimum size.
4878 gbl_reserve = hugepage_subpool_put_pages(spool, reserve);
4879 hugetlb_acct_memory(h, -gbl_reserve);
4882 kref_put(&resv->refs, resv_map_release);
4885 static int hugetlb_vm_op_split(struct vm_area_struct *vma, unsigned long addr)
4887 if (addr & ~(huge_page_mask(hstate_vma(vma))))
4891 * PMD sharing is only possible for PUD_SIZE-aligned address ranges
4892 * in HugeTLB VMAs. If we will lose PUD_SIZE alignment due to this
4893 * split, unshare PMDs in the PUD_SIZE interval surrounding addr now.
4895 if (addr & ~PUD_MASK) {
4897 * hugetlb_vm_op_split is called right before we attempt to
4898 * split the VMA. We will need to unshare PMDs in the old and
4899 * new VMAs, so let's unshare before we split.
4901 unsigned long floor = addr & PUD_MASK;
4902 unsigned long ceil = floor + PUD_SIZE;
4904 if (floor >= vma->vm_start && ceil <= vma->vm_end)
4905 hugetlb_unshare_pmds(vma, floor, ceil);
4911 static unsigned long hugetlb_vm_op_pagesize(struct vm_area_struct *vma)
4913 return huge_page_size(hstate_vma(vma));
4917 * We cannot handle pagefaults against hugetlb pages at all. They cause
4918 * handle_mm_fault() to try to instantiate regular-sized pages in the
4919 * hugepage VMA. do_page_fault() is supposed to trap this, so BUG is we get
4922 static vm_fault_t hugetlb_vm_op_fault(struct vm_fault *vmf)
4929 * When a new function is introduced to vm_operations_struct and added
4930 * to hugetlb_vm_ops, please consider adding the function to shm_vm_ops.
4931 * This is because under System V memory model, mappings created via
4932 * shmget/shmat with "huge page" specified are backed by hugetlbfs files,
4933 * their original vm_ops are overwritten with shm_vm_ops.
4935 const struct vm_operations_struct hugetlb_vm_ops = {
4936 .fault = hugetlb_vm_op_fault,
4937 .open = hugetlb_vm_op_open,
4938 .close = hugetlb_vm_op_close,
4939 .may_split = hugetlb_vm_op_split,
4940 .pagesize = hugetlb_vm_op_pagesize,
4943 static pte_t make_huge_pte(struct vm_area_struct *vma, struct page *page,
4947 unsigned int shift = huge_page_shift(hstate_vma(vma));
4950 entry = huge_pte_mkwrite(huge_pte_mkdirty(mk_huge_pte(page,
4951 vma->vm_page_prot)));
4953 entry = huge_pte_wrprotect(mk_huge_pte(page,
4954 vma->vm_page_prot));
4956 entry = pte_mkyoung(entry);
4957 entry = arch_make_huge_pte(entry, shift, vma->vm_flags);
4962 static void set_huge_ptep_writable(struct vm_area_struct *vma,
4963 unsigned long address, pte_t *ptep)
4967 entry = huge_pte_mkwrite(huge_pte_mkdirty(huge_ptep_get(ptep)));
4968 if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1))
4969 update_mmu_cache(vma, address, ptep);
4972 bool is_hugetlb_entry_migration(pte_t pte)
4976 if (huge_pte_none(pte) || pte_present(pte))
4978 swp = pte_to_swp_entry(pte);
4979 if (is_migration_entry(swp))
4985 static bool is_hugetlb_entry_hwpoisoned(pte_t pte)
4989 if (huge_pte_none(pte) || pte_present(pte))
4991 swp = pte_to_swp_entry(pte);
4992 if (is_hwpoison_entry(swp))
4999 hugetlb_install_page(struct vm_area_struct *vma, pte_t *ptep, unsigned long addr,
5000 struct page *new_page)
5002 __SetPageUptodate(new_page);
5003 hugepage_add_new_anon_rmap(new_page, vma, addr);
5004 set_huge_pte_at(vma->vm_mm, addr, ptep, make_huge_pte(vma, new_page, 1));
5005 hugetlb_count_add(pages_per_huge_page(hstate_vma(vma)), vma->vm_mm);
5006 ClearHPageRestoreReserve(new_page);
5007 SetHPageMigratable(new_page);
5010 int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src,
5011 struct vm_area_struct *dst_vma,
5012 struct vm_area_struct *src_vma)
5014 pte_t *src_pte, *dst_pte, entry;
5015 struct page *ptepage;
5017 bool cow = is_cow_mapping(src_vma->vm_flags);
5018 struct hstate *h = hstate_vma(src_vma);
5019 unsigned long sz = huge_page_size(h);
5020 unsigned long npages = pages_per_huge_page(h);
5021 struct mmu_notifier_range range;
5022 unsigned long last_addr_mask;
5026 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, src_vma, src,
5029 mmu_notifier_invalidate_range_start(&range);
5030 mmap_assert_write_locked(src);
5031 raw_write_seqcount_begin(&src->write_protect_seq);
5034 * For shared mappings the vma lock must be held before
5035 * calling huge_pte_offset in the src vma. Otherwise, the
5036 * returned ptep could go away if part of a shared pmd and
5037 * another thread calls huge_pmd_unshare.
5039 hugetlb_vma_lock_read(src_vma);
5042 last_addr_mask = hugetlb_mask_last_page(h);
5043 for (addr = src_vma->vm_start; addr < src_vma->vm_end; addr += sz) {
5044 spinlock_t *src_ptl, *dst_ptl;
5045 src_pte = huge_pte_offset(src, addr, sz);
5047 addr |= last_addr_mask;
5050 dst_pte = huge_pte_alloc(dst, dst_vma, addr, sz);
5057 * If the pagetables are shared don't copy or take references.
5059 * dst_pte == src_pte is the common case of src/dest sharing.
5060 * However, src could have 'unshared' and dst shares with
5061 * another vma. So page_count of ptep page is checked instead
5062 * to reliably determine whether pte is shared.
5064 if (page_count(virt_to_page(dst_pte)) > 1) {
5065 addr |= last_addr_mask;
5069 dst_ptl = huge_pte_lock(h, dst, dst_pte);
5070 src_ptl = huge_pte_lockptr(h, src, src_pte);
5071 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
5072 entry = huge_ptep_get(src_pte);
5074 if (huge_pte_none(entry)) {
5076 * Skip if src entry none.
5079 } else if (unlikely(is_hugetlb_entry_hwpoisoned(entry))) {
5080 bool uffd_wp = huge_pte_uffd_wp(entry);
5082 if (!userfaultfd_wp(dst_vma) && uffd_wp)
5083 entry = huge_pte_clear_uffd_wp(entry);
5084 set_huge_pte_at(dst, addr, dst_pte, entry);
5085 } else if (unlikely(is_hugetlb_entry_migration(entry))) {
5086 swp_entry_t swp_entry = pte_to_swp_entry(entry);
5087 bool uffd_wp = huge_pte_uffd_wp(entry);
5089 if (!is_readable_migration_entry(swp_entry) && cow) {
5091 * COW mappings require pages in both
5092 * parent and child to be set to read.
5094 swp_entry = make_readable_migration_entry(
5095 swp_offset(swp_entry));
5096 entry = swp_entry_to_pte(swp_entry);
5097 if (userfaultfd_wp(src_vma) && uffd_wp)
5098 entry = huge_pte_mkuffd_wp(entry);
5099 set_huge_pte_at(src, addr, src_pte, entry);
5101 if (!userfaultfd_wp(dst_vma) && uffd_wp)
5102 entry = huge_pte_clear_uffd_wp(entry);
5103 set_huge_pte_at(dst, addr, dst_pte, entry);
5104 } else if (unlikely(is_pte_marker(entry))) {
5106 * We copy the pte marker only if the dst vma has
5109 if (userfaultfd_wp(dst_vma))
5110 set_huge_pte_at(dst, addr, dst_pte, entry);
5112 entry = huge_ptep_get(src_pte);
5113 ptepage = pte_page(entry);
5117 * Failing to duplicate the anon rmap is a rare case
5118 * where we see pinned hugetlb pages while they're
5119 * prone to COW. We need to do the COW earlier during
5122 * When pre-allocating the page or copying data, we
5123 * need to be without the pgtable locks since we could
5124 * sleep during the process.
5126 if (!PageAnon(ptepage)) {
5127 page_dup_file_rmap(ptepage, true);
5128 } else if (page_try_dup_anon_rmap(ptepage, true,
5130 pte_t src_pte_old = entry;
5133 spin_unlock(src_ptl);
5134 spin_unlock(dst_ptl);
5135 /* Do not use reserve as it's private owned */
5136 new = alloc_huge_page(dst_vma, addr, 1);
5142 copy_user_huge_page(new, ptepage, addr, dst_vma,
5146 /* Install the new huge page if src pte stable */
5147 dst_ptl = huge_pte_lock(h, dst, dst_pte);
5148 src_ptl = huge_pte_lockptr(h, src, src_pte);
5149 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
5150 entry = huge_ptep_get(src_pte);
5151 if (!pte_same(src_pte_old, entry)) {
5152 restore_reserve_on_error(h, dst_vma, addr,
5155 /* huge_ptep of dst_pte won't change as in child */
5158 hugetlb_install_page(dst_vma, dst_pte, addr, new);
5159 spin_unlock(src_ptl);
5160 spin_unlock(dst_ptl);
5166 * No need to notify as we are downgrading page
5167 * table protection not changing it to point
5170 * See Documentation/mm/mmu_notifier.rst
5172 huge_ptep_set_wrprotect(src, addr, src_pte);
5173 entry = huge_pte_wrprotect(entry);
5176 set_huge_pte_at(dst, addr, dst_pte, entry);
5177 hugetlb_count_add(npages, dst);
5179 spin_unlock(src_ptl);
5180 spin_unlock(dst_ptl);
5184 raw_write_seqcount_end(&src->write_protect_seq);
5185 mmu_notifier_invalidate_range_end(&range);
5187 hugetlb_vma_unlock_read(src_vma);
5193 static void move_huge_pte(struct vm_area_struct *vma, unsigned long old_addr,
5194 unsigned long new_addr, pte_t *src_pte, pte_t *dst_pte)
5196 struct hstate *h = hstate_vma(vma);
5197 struct mm_struct *mm = vma->vm_mm;
5198 spinlock_t *src_ptl, *dst_ptl;
5201 dst_ptl = huge_pte_lock(h, mm, dst_pte);
5202 src_ptl = huge_pte_lockptr(h, mm, src_pte);
5205 * We don't have to worry about the ordering of src and dst ptlocks
5206 * because exclusive mmap_sem (or the i_mmap_lock) prevents deadlock.
5208 if (src_ptl != dst_ptl)
5209 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
5211 pte = huge_ptep_get_and_clear(mm, old_addr, src_pte);
5212 set_huge_pte_at(mm, new_addr, dst_pte, pte);
5214 if (src_ptl != dst_ptl)
5215 spin_unlock(src_ptl);
5216 spin_unlock(dst_ptl);
5219 int move_hugetlb_page_tables(struct vm_area_struct *vma,
5220 struct vm_area_struct *new_vma,
5221 unsigned long old_addr, unsigned long new_addr,
5224 struct hstate *h = hstate_vma(vma);
5225 struct address_space *mapping = vma->vm_file->f_mapping;
5226 unsigned long sz = huge_page_size(h);
5227 struct mm_struct *mm = vma->vm_mm;
5228 unsigned long old_end = old_addr + len;
5229 unsigned long last_addr_mask;
5230 pte_t *src_pte, *dst_pte;
5231 struct mmu_notifier_range range;
5232 bool shared_pmd = false;
5234 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm, old_addr,
5236 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
5238 * In case of shared PMDs, we should cover the maximum possible
5241 flush_cache_range(vma, range.start, range.end);
5243 mmu_notifier_invalidate_range_start(&range);
5244 last_addr_mask = hugetlb_mask_last_page(h);
5245 /* Prevent race with file truncation */
5246 hugetlb_vma_lock_write(vma);
5247 i_mmap_lock_write(mapping);
5248 for (; old_addr < old_end; old_addr += sz, new_addr += sz) {
5249 src_pte = huge_pte_offset(mm, old_addr, sz);
5251 old_addr |= last_addr_mask;
5252 new_addr |= last_addr_mask;
5255 if (huge_pte_none(huge_ptep_get(src_pte)))
5258 if (huge_pmd_unshare(mm, vma, old_addr, src_pte)) {
5260 old_addr |= last_addr_mask;
5261 new_addr |= last_addr_mask;
5265 dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz);
5269 move_huge_pte(vma, old_addr, new_addr, src_pte, dst_pte);
5273 flush_tlb_range(vma, range.start, range.end);
5275 flush_tlb_range(vma, old_end - len, old_end);
5276 mmu_notifier_invalidate_range_end(&range);
5277 i_mmap_unlock_write(mapping);
5278 hugetlb_vma_unlock_write(vma);
5280 return len + old_addr - old_end;
5283 static void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
5284 unsigned long start, unsigned long end,
5285 struct page *ref_page, zap_flags_t zap_flags)
5287 struct mm_struct *mm = vma->vm_mm;
5288 unsigned long address;
5293 struct hstate *h = hstate_vma(vma);
5294 unsigned long sz = huge_page_size(h);
5295 struct mmu_notifier_range range;
5296 unsigned long last_addr_mask;
5297 bool force_flush = false;
5299 WARN_ON(!is_vm_hugetlb_page(vma));
5300 BUG_ON(start & ~huge_page_mask(h));
5301 BUG_ON(end & ~huge_page_mask(h));
5304 * This is a hugetlb vma, all the pte entries should point
5307 tlb_change_page_size(tlb, sz);
5308 tlb_start_vma(tlb, vma);
5311 * If sharing possible, alert mmu notifiers of worst case.
5313 mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, mm, start,
5315 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
5316 mmu_notifier_invalidate_range_start(&range);
5317 last_addr_mask = hugetlb_mask_last_page(h);
5319 for (; address < end; address += sz) {
5320 ptep = huge_pte_offset(mm, address, sz);
5322 address |= last_addr_mask;
5326 ptl = huge_pte_lock(h, mm, ptep);
5327 if (huge_pmd_unshare(mm, vma, address, ptep)) {
5329 tlb_flush_pmd_range(tlb, address & PUD_MASK, PUD_SIZE);
5331 address |= last_addr_mask;
5335 pte = huge_ptep_get(ptep);
5336 if (huge_pte_none(pte)) {
5342 * Migrating hugepage or HWPoisoned hugepage is already
5343 * unmapped and its refcount is dropped, so just clear pte here.
5345 if (unlikely(!pte_present(pte))) {
5346 #ifdef CONFIG_PTE_MARKER_UFFD_WP
5348 * If the pte was wr-protected by uffd-wp in any of the
5349 * swap forms, meanwhile the caller does not want to
5350 * drop the uffd-wp bit in this zap, then replace the
5351 * pte with a marker.
5353 if (pte_swp_uffd_wp_any(pte) &&
5354 !(zap_flags & ZAP_FLAG_DROP_MARKER))
5355 set_huge_pte_at(mm, address, ptep,
5356 make_pte_marker(PTE_MARKER_UFFD_WP));
5359 huge_pte_clear(mm, address, ptep, sz);
5364 page = pte_page(pte);
5366 * If a reference page is supplied, it is because a specific
5367 * page is being unmapped, not a range. Ensure the page we
5368 * are about to unmap is the actual page of interest.
5371 if (page != ref_page) {
5376 * Mark the VMA as having unmapped its page so that
5377 * future faults in this VMA will fail rather than
5378 * looking like data was lost
5380 set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED);
5383 pte = huge_ptep_get_and_clear(mm, address, ptep);
5384 tlb_remove_huge_tlb_entry(h, tlb, ptep, address);
5385 if (huge_pte_dirty(pte))
5386 set_page_dirty(page);
5387 #ifdef CONFIG_PTE_MARKER_UFFD_WP
5388 /* Leave a uffd-wp pte marker if needed */
5389 if (huge_pte_uffd_wp(pte) &&
5390 !(zap_flags & ZAP_FLAG_DROP_MARKER))
5391 set_huge_pte_at(mm, address, ptep,
5392 make_pte_marker(PTE_MARKER_UFFD_WP));
5394 hugetlb_count_sub(pages_per_huge_page(h), mm);
5395 page_remove_rmap(page, vma, true);
5398 tlb_remove_page_size(tlb, page, huge_page_size(h));
5400 * Bail out after unmapping reference page if supplied
5405 mmu_notifier_invalidate_range_end(&range);
5406 tlb_end_vma(tlb, vma);
5409 * If we unshared PMDs, the TLB flush was not recorded in mmu_gather. We
5410 * could defer the flush until now, since by holding i_mmap_rwsem we
5411 * guaranteed that the last refernece would not be dropped. But we must
5412 * do the flushing before we return, as otherwise i_mmap_rwsem will be
5413 * dropped and the last reference to the shared PMDs page might be
5416 * In theory we could defer the freeing of the PMD pages as well, but
5417 * huge_pmd_unshare() relies on the exact page_count for the PMD page to
5418 * detect sharing, so we cannot defer the release of the page either.
5419 * Instead, do flush now.
5422 tlb_flush_mmu_tlbonly(tlb);
5425 void __unmap_hugepage_range_final(struct mmu_gather *tlb,
5426 struct vm_area_struct *vma, unsigned long start,
5427 unsigned long end, struct page *ref_page,
5428 zap_flags_t zap_flags)
5430 hugetlb_vma_lock_write(vma);
5431 i_mmap_lock_write(vma->vm_file->f_mapping);
5433 __unmap_hugepage_range(tlb, vma, start, end, ref_page, zap_flags);
5435 if (zap_flags & ZAP_FLAG_UNMAP) { /* final unmap */
5437 * Unlock and free the vma lock before releasing i_mmap_rwsem.
5438 * When the vma_lock is freed, this makes the vma ineligible
5439 * for pmd sharing. And, i_mmap_rwsem is required to set up
5440 * pmd sharing. This is important as page tables for this
5441 * unmapped range will be asynchrously deleted. If the page
5442 * tables are shared, there will be issues when accessed by
5445 __hugetlb_vma_unlock_write_free(vma);
5446 i_mmap_unlock_write(vma->vm_file->f_mapping);
5448 i_mmap_unlock_write(vma->vm_file->f_mapping);
5449 hugetlb_vma_unlock_write(vma);
5453 void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
5454 unsigned long end, struct page *ref_page,
5455 zap_flags_t zap_flags)
5457 struct mmu_gather tlb;
5459 tlb_gather_mmu(&tlb, vma->vm_mm);
5460 __unmap_hugepage_range(&tlb, vma, start, end, ref_page, zap_flags);
5461 tlb_finish_mmu(&tlb);
5465 * This is called when the original mapper is failing to COW a MAP_PRIVATE
5466 * mapping it owns the reserve page for. The intention is to unmap the page
5467 * from other VMAs and let the children be SIGKILLed if they are faulting the
5470 static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,
5471 struct page *page, unsigned long address)
5473 struct hstate *h = hstate_vma(vma);
5474 struct vm_area_struct *iter_vma;
5475 struct address_space *mapping;
5479 * vm_pgoff is in PAGE_SIZE units, hence the different calculation
5480 * from page cache lookup which is in HPAGE_SIZE units.
5482 address = address & huge_page_mask(h);
5483 pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) +
5485 mapping = vma->vm_file->f_mapping;
5488 * Take the mapping lock for the duration of the table walk. As
5489 * this mapping should be shared between all the VMAs,
5490 * __unmap_hugepage_range() is called as the lock is already held
5492 i_mmap_lock_write(mapping);
5493 vma_interval_tree_foreach(iter_vma, &mapping->i_mmap, pgoff, pgoff) {
5494 /* Do not unmap the current VMA */
5495 if (iter_vma == vma)
5499 * Shared VMAs have their own reserves and do not affect
5500 * MAP_PRIVATE accounting but it is possible that a shared
5501 * VMA is using the same page so check and skip such VMAs.
5503 if (iter_vma->vm_flags & VM_MAYSHARE)
5507 * Unmap the page from other VMAs without their own reserves.
5508 * They get marked to be SIGKILLed if they fault in these
5509 * areas. This is because a future no-page fault on this VMA
5510 * could insert a zeroed page instead of the data existing
5511 * from the time of fork. This would look like data corruption
5513 if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER))
5514 unmap_hugepage_range(iter_vma, address,
5515 address + huge_page_size(h), page, 0);
5517 i_mmap_unlock_write(mapping);
5521 * hugetlb_wp() should be called with page lock of the original hugepage held.
5522 * Called with hugetlb_fault_mutex_table held and pte_page locked so we
5523 * cannot race with other handlers or page migration.
5524 * Keep the pte_same checks anyway to make transition from the mutex easier.
5526 static vm_fault_t hugetlb_wp(struct mm_struct *mm, struct vm_area_struct *vma,
5527 unsigned long address, pte_t *ptep, unsigned int flags,
5528 struct page *pagecache_page, spinlock_t *ptl)
5530 const bool unshare = flags & FAULT_FLAG_UNSHARE;
5531 pte_t pte = huge_ptep_get(ptep);
5532 struct hstate *h = hstate_vma(vma);
5533 struct page *old_page, *new_page;
5534 int outside_reserve = 0;
5536 unsigned long haddr = address & huge_page_mask(h);
5537 struct mmu_notifier_range range;
5539 VM_BUG_ON(unshare && (flags & FOLL_WRITE));
5540 VM_BUG_ON(!unshare && !(flags & FOLL_WRITE));
5543 * Never handle CoW for uffd-wp protected pages. It should be only
5544 * handled when the uffd-wp protection is removed.
5546 * Note that only the CoW optimization path (in hugetlb_no_page())
5547 * can trigger this, because hugetlb_fault() will always resolve
5548 * uffd-wp bit first.
5550 if (!unshare && huge_pte_uffd_wp(pte))
5554 * hugetlb does not support FOLL_FORCE-style write faults that keep the
5555 * PTE mapped R/O such as maybe_mkwrite() would do.
5557 if (WARN_ON_ONCE(!unshare && !(vma->vm_flags & VM_WRITE)))
5558 return VM_FAULT_SIGSEGV;
5560 /* Let's take out MAP_SHARED mappings first. */
5561 if (vma->vm_flags & VM_MAYSHARE) {
5562 if (unlikely(unshare))
5564 set_huge_ptep_writable(vma, haddr, ptep);
5568 old_page = pte_page(pte);
5570 delayacct_wpcopy_start();
5574 * If no-one else is actually using this page, we're the exclusive
5575 * owner and can reuse this page.
5577 if (page_mapcount(old_page) == 1 && PageAnon(old_page)) {
5578 if (!PageAnonExclusive(old_page))
5579 page_move_anon_rmap(old_page, vma);
5580 if (likely(!unshare))
5581 set_huge_ptep_writable(vma, haddr, ptep);
5583 delayacct_wpcopy_end();
5586 VM_BUG_ON_PAGE(PageAnon(old_page) && PageAnonExclusive(old_page),
5590 * If the process that created a MAP_PRIVATE mapping is about to
5591 * perform a COW due to a shared page count, attempt to satisfy
5592 * the allocation without using the existing reserves. The pagecache
5593 * page is used to determine if the reserve at this address was
5594 * consumed or not. If reserves were used, a partial faulted mapping
5595 * at the time of fork() could consume its reserves on COW instead
5596 * of the full address range.
5598 if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) &&
5599 old_page != pagecache_page)
5600 outside_reserve = 1;
5605 * Drop page table lock as buddy allocator may be called. It will
5606 * be acquired again before returning to the caller, as expected.
5609 new_page = alloc_huge_page(vma, haddr, outside_reserve);
5611 if (IS_ERR(new_page)) {
5613 * If a process owning a MAP_PRIVATE mapping fails to COW,
5614 * it is due to references held by a child and an insufficient
5615 * huge page pool. To guarantee the original mappers
5616 * reliability, unmap the page from child processes. The child
5617 * may get SIGKILLed if it later faults.
5619 if (outside_reserve) {
5620 struct address_space *mapping = vma->vm_file->f_mapping;
5626 * Drop hugetlb_fault_mutex and vma_lock before
5627 * unmapping. unmapping needs to hold vma_lock
5628 * in write mode. Dropping vma_lock in read mode
5629 * here is OK as COW mappings do not interact with
5632 * Reacquire both after unmap operation.
5634 idx = vma_hugecache_offset(h, vma, haddr);
5635 hash = hugetlb_fault_mutex_hash(mapping, idx);
5636 hugetlb_vma_unlock_read(vma);
5637 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
5639 unmap_ref_private(mm, vma, old_page, haddr);
5641 mutex_lock(&hugetlb_fault_mutex_table[hash]);
5642 hugetlb_vma_lock_read(vma);
5644 ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
5646 pte_same(huge_ptep_get(ptep), pte)))
5647 goto retry_avoidcopy;
5649 * race occurs while re-acquiring page table
5650 * lock, and our job is done.
5652 delayacct_wpcopy_end();
5656 ret = vmf_error(PTR_ERR(new_page));
5657 goto out_release_old;
5661 * When the original hugepage is shared one, it does not have
5662 * anon_vma prepared.
5664 if (unlikely(anon_vma_prepare(vma))) {
5666 goto out_release_all;
5669 copy_user_huge_page(new_page, old_page, address, vma,
5670 pages_per_huge_page(h));
5671 __SetPageUptodate(new_page);
5673 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm, haddr,
5674 haddr + huge_page_size(h));
5675 mmu_notifier_invalidate_range_start(&range);
5678 * Retake the page table lock to check for racing updates
5679 * before the page tables are altered
5682 ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
5683 if (likely(ptep && pte_same(huge_ptep_get(ptep), pte))) {
5684 ClearHPageRestoreReserve(new_page);
5686 /* Break COW or unshare */
5687 huge_ptep_clear_flush(vma, haddr, ptep);
5688 mmu_notifier_invalidate_range(mm, range.start, range.end);
5689 page_remove_rmap(old_page, vma, true);
5690 hugepage_add_new_anon_rmap(new_page, vma, haddr);
5691 set_huge_pte_at(mm, haddr, ptep,
5692 make_huge_pte(vma, new_page, !unshare));
5693 SetHPageMigratable(new_page);
5694 /* Make the old page be freed below */
5695 new_page = old_page;
5698 mmu_notifier_invalidate_range_end(&range);
5701 * No restore in case of successful pagetable update (Break COW or
5704 if (new_page != old_page)
5705 restore_reserve_on_error(h, vma, haddr, new_page);
5710 spin_lock(ptl); /* Caller expects lock to be held */
5712 delayacct_wpcopy_end();
5717 * Return whether there is a pagecache page to back given address within VMA.
5718 * Caller follow_hugetlb_page() holds page_table_lock so we cannot lock_page.
5720 static bool hugetlbfs_pagecache_present(struct hstate *h,
5721 struct vm_area_struct *vma, unsigned long address)
5723 struct address_space *mapping;
5727 mapping = vma->vm_file->f_mapping;
5728 idx = vma_hugecache_offset(h, vma, address);
5730 page = find_get_page(mapping, idx);
5733 return page != NULL;
5736 int hugetlb_add_to_page_cache(struct page *page, struct address_space *mapping,
5739 struct folio *folio = page_folio(page);
5740 struct inode *inode = mapping->host;
5741 struct hstate *h = hstate_inode(inode);
5744 __folio_set_locked(folio);
5745 err = __filemap_add_folio(mapping, folio, idx, GFP_KERNEL, NULL);
5747 if (unlikely(err)) {
5748 __folio_clear_locked(folio);
5751 ClearHPageRestoreReserve(page);
5754 * mark folio dirty so that it will not be removed from cache/file
5755 * by non-hugetlbfs specific code paths.
5757 folio_mark_dirty(folio);
5759 spin_lock(&inode->i_lock);
5760 inode->i_blocks += blocks_per_huge_page(h);
5761 spin_unlock(&inode->i_lock);
5765 static inline vm_fault_t hugetlb_handle_userfault(struct vm_area_struct *vma,
5766 struct address_space *mapping,
5769 unsigned long haddr,
5771 unsigned long reason)
5774 struct vm_fault vmf = {
5777 .real_address = addr,
5781 * Hard to debug if it ends up being
5782 * used by a callee that assumes
5783 * something about the other
5784 * uninitialized fields... same as in
5790 * vma_lock and hugetlb_fault_mutex must be dropped before handling
5791 * userfault. Also mmap_lock could be dropped due to handling
5792 * userfault, any vma operation should be careful from here.
5794 hugetlb_vma_unlock_read(vma);
5795 hash = hugetlb_fault_mutex_hash(mapping, idx);
5796 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
5797 return handle_userfault(&vmf, reason);
5801 * Recheck pte with pgtable lock. Returns true if pte didn't change, or
5802 * false if pte changed or is changing.
5804 static bool hugetlb_pte_stable(struct hstate *h, struct mm_struct *mm,
5805 pte_t *ptep, pte_t old_pte)
5810 ptl = huge_pte_lock(h, mm, ptep);
5811 same = pte_same(huge_ptep_get(ptep), old_pte);
5817 static vm_fault_t hugetlb_no_page(struct mm_struct *mm,
5818 struct vm_area_struct *vma,
5819 struct address_space *mapping, pgoff_t idx,
5820 unsigned long address, pte_t *ptep,
5821 pte_t old_pte, unsigned int flags)
5823 struct hstate *h = hstate_vma(vma);
5824 vm_fault_t ret = VM_FAULT_SIGBUS;
5830 unsigned long haddr = address & huge_page_mask(h);
5831 bool new_page, new_pagecache_page = false;
5832 u32 hash = hugetlb_fault_mutex_hash(mapping, idx);
5835 * Currently, we are forced to kill the process in the event the
5836 * original mapper has unmapped pages from the child due to a failed
5837 * COW/unsharing. Warn that such a situation has occurred as it may not
5840 if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) {
5841 pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n",
5847 * Use page lock to guard against racing truncation
5848 * before we get page_table_lock.
5851 page = find_lock_page(mapping, idx);
5853 size = i_size_read(mapping->host) >> huge_page_shift(h);
5856 /* Check for page in userfault range */
5857 if (userfaultfd_missing(vma)) {
5859 * Since hugetlb_no_page() was examining pte
5860 * without pgtable lock, we need to re-test under
5861 * lock because the pte may not be stable and could
5862 * have changed from under us. Try to detect
5863 * either changed or during-changing ptes and retry
5864 * properly when needed.
5866 * Note that userfaultfd is actually fine with
5867 * false positives (e.g. caused by pte changed),
5868 * but not wrong logical events (e.g. caused by
5869 * reading a pte during changing). The latter can
5870 * confuse the userspace, so the strictness is very
5871 * much preferred. E.g., MISSING event should
5872 * never happen on the page after UFFDIO_COPY has
5873 * correctly installed the page and returned.
5875 if (!hugetlb_pte_stable(h, mm, ptep, old_pte)) {
5880 return hugetlb_handle_userfault(vma, mapping, idx, flags,
5885 page = alloc_huge_page(vma, haddr, 0);
5888 * Returning error will result in faulting task being
5889 * sent SIGBUS. The hugetlb fault mutex prevents two
5890 * tasks from racing to fault in the same page which
5891 * could result in false unable to allocate errors.
5892 * Page migration does not take the fault mutex, but
5893 * does a clear then write of pte's under page table
5894 * lock. Page fault code could race with migration,
5895 * notice the clear pte and try to allocate a page
5896 * here. Before returning error, get ptl and make
5897 * sure there really is no pte entry.
5899 if (hugetlb_pte_stable(h, mm, ptep, old_pte))
5900 ret = vmf_error(PTR_ERR(page));
5905 clear_huge_page(page, address, pages_per_huge_page(h));
5906 __SetPageUptodate(page);
5909 if (vma->vm_flags & VM_MAYSHARE) {
5910 int err = hugetlb_add_to_page_cache(page, mapping, idx);
5913 * err can't be -EEXIST which implies someone
5914 * else consumed the reservation since hugetlb
5915 * fault mutex is held when add a hugetlb page
5916 * to the page cache. So it's safe to call
5917 * restore_reserve_on_error() here.
5919 restore_reserve_on_error(h, vma, haddr, page);
5923 new_pagecache_page = true;
5926 if (unlikely(anon_vma_prepare(vma))) {
5928 goto backout_unlocked;
5934 * If memory error occurs between mmap() and fault, some process
5935 * don't have hwpoisoned swap entry for errored virtual address.
5936 * So we need to block hugepage fault by PG_hwpoison bit check.
5938 if (unlikely(PageHWPoison(page))) {
5939 ret = VM_FAULT_HWPOISON_LARGE |
5940 VM_FAULT_SET_HINDEX(hstate_index(h));
5941 goto backout_unlocked;
5944 /* Check for page in userfault range. */
5945 if (userfaultfd_minor(vma)) {
5948 /* See comment in userfaultfd_missing() block above */
5949 if (!hugetlb_pte_stable(h, mm, ptep, old_pte)) {
5953 return hugetlb_handle_userfault(vma, mapping, idx, flags,
5960 * If we are going to COW a private mapping later, we examine the
5961 * pending reservations for this page now. This will ensure that
5962 * any allocations necessary to record that reservation occur outside
5965 if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
5966 if (vma_needs_reservation(h, vma, haddr) < 0) {
5968 goto backout_unlocked;
5970 /* Just decrements count, does not deallocate */
5971 vma_end_reservation(h, vma, haddr);
5974 ptl = huge_pte_lock(h, mm, ptep);
5976 /* If pte changed from under us, retry */
5977 if (!pte_same(huge_ptep_get(ptep), old_pte))
5981 ClearHPageRestoreReserve(page);
5982 hugepage_add_new_anon_rmap(page, vma, haddr);
5984 page_dup_file_rmap(page, true);
5985 new_pte = make_huge_pte(vma, page, ((vma->vm_flags & VM_WRITE)
5986 && (vma->vm_flags & VM_SHARED)));
5988 * If this pte was previously wr-protected, keep it wr-protected even
5991 if (unlikely(pte_marker_uffd_wp(old_pte)))
5992 new_pte = huge_pte_wrprotect(huge_pte_mkuffd_wp(new_pte));
5993 set_huge_pte_at(mm, haddr, ptep, new_pte);
5995 hugetlb_count_add(pages_per_huge_page(h), mm);
5996 if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
5997 /* Optimization, do the COW without a second fault */
5998 ret = hugetlb_wp(mm, vma, address, ptep, flags, page, ptl);
6004 * Only set HPageMigratable in newly allocated pages. Existing pages
6005 * found in the pagecache may not have HPageMigratableset if they have
6006 * been isolated for migration.
6009 SetHPageMigratable(page);
6013 hugetlb_vma_unlock_read(vma);
6014 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6020 if (new_page && !new_pagecache_page)
6021 restore_reserve_on_error(h, vma, haddr, page);
6029 u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
6031 unsigned long key[2];
6034 key[0] = (unsigned long) mapping;
6037 hash = jhash2((u32 *)&key, sizeof(key)/(sizeof(u32)), 0);
6039 return hash & (num_fault_mutexes - 1);
6043 * For uniprocessor systems we always use a single mutex, so just
6044 * return 0 and avoid the hashing overhead.
6046 u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
6052 vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,
6053 unsigned long address, unsigned int flags)
6060 struct page *page = NULL;
6061 struct page *pagecache_page = NULL;
6062 struct hstate *h = hstate_vma(vma);
6063 struct address_space *mapping;
6064 int need_wait_lock = 0;
6065 unsigned long haddr = address & huge_page_mask(h);
6067 ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
6070 * Since we hold no locks, ptep could be stale. That is
6071 * OK as we are only making decisions based on content and
6072 * not actually modifying content here.
6074 entry = huge_ptep_get(ptep);
6075 if (unlikely(is_hugetlb_entry_migration(entry))) {
6076 migration_entry_wait_huge(vma, ptep);
6078 } else if (unlikely(is_hugetlb_entry_hwpoisoned(entry)))
6079 return VM_FAULT_HWPOISON_LARGE |
6080 VM_FAULT_SET_HINDEX(hstate_index(h));
6084 * Serialize hugepage allocation and instantiation, so that we don't
6085 * get spurious allocation failures if two CPUs race to instantiate
6086 * the same page in the page cache.
6088 mapping = vma->vm_file->f_mapping;
6089 idx = vma_hugecache_offset(h, vma, haddr);
6090 hash = hugetlb_fault_mutex_hash(mapping, idx);
6091 mutex_lock(&hugetlb_fault_mutex_table[hash]);
6094 * Acquire vma lock before calling huge_pte_alloc and hold
6095 * until finished with ptep. This prevents huge_pmd_unshare from
6096 * being called elsewhere and making the ptep no longer valid.
6098 * ptep could have already be assigned via huge_pte_offset. That
6099 * is OK, as huge_pte_alloc will return the same value unless
6100 * something has changed.
6102 hugetlb_vma_lock_read(vma);
6103 ptep = huge_pte_alloc(mm, vma, haddr, huge_page_size(h));
6105 hugetlb_vma_unlock_read(vma);
6106 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6107 return VM_FAULT_OOM;
6110 entry = huge_ptep_get(ptep);
6111 /* PTE markers should be handled the same way as none pte */
6112 if (huge_pte_none_mostly(entry))
6114 * hugetlb_no_page will drop vma lock and hugetlb fault
6115 * mutex internally, which make us return immediately.
6117 return hugetlb_no_page(mm, vma, mapping, idx, address, ptep,
6123 * entry could be a migration/hwpoison entry at this point, so this
6124 * check prevents the kernel from going below assuming that we have
6125 * an active hugepage in pagecache. This goto expects the 2nd page
6126 * fault, and is_hugetlb_entry_(migration|hwpoisoned) check will
6127 * properly handle it.
6129 if (!pte_present(entry))
6133 * If we are going to COW/unshare the mapping later, we examine the
6134 * pending reservations for this page now. This will ensure that any
6135 * allocations necessary to record that reservation occur outside the
6136 * spinlock. Also lookup the pagecache page now as it is used to
6137 * determine if a reservation has been consumed.
6139 if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) &&
6140 !(vma->vm_flags & VM_MAYSHARE) && !huge_pte_write(entry)) {
6141 if (vma_needs_reservation(h, vma, haddr) < 0) {
6145 /* Just decrements count, does not deallocate */
6146 vma_end_reservation(h, vma, haddr);
6148 pagecache_page = find_lock_page(mapping, idx);
6151 ptl = huge_pte_lock(h, mm, ptep);
6153 /* Check for a racing update before calling hugetlb_wp() */
6154 if (unlikely(!pte_same(entry, huge_ptep_get(ptep))))
6157 /* Handle userfault-wp first, before trying to lock more pages */
6158 if (userfaultfd_wp(vma) && huge_pte_uffd_wp(huge_ptep_get(ptep)) &&
6159 (flags & FAULT_FLAG_WRITE) && !huge_pte_write(entry)) {
6160 struct vm_fault vmf = {
6163 .real_address = address,
6168 if (pagecache_page) {
6169 unlock_page(pagecache_page);
6170 put_page(pagecache_page);
6172 hugetlb_vma_unlock_read(vma);
6173 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6174 return handle_userfault(&vmf, VM_UFFD_WP);
6178 * hugetlb_wp() requires page locks of pte_page(entry) and
6179 * pagecache_page, so here we need take the former one
6180 * when page != pagecache_page or !pagecache_page.
6182 page = pte_page(entry);
6183 if (page != pagecache_page)
6184 if (!trylock_page(page)) {
6191 if (flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) {
6192 if (!huge_pte_write(entry)) {
6193 ret = hugetlb_wp(mm, vma, address, ptep, flags,
6194 pagecache_page, ptl);
6196 } else if (likely(flags & FAULT_FLAG_WRITE)) {
6197 entry = huge_pte_mkdirty(entry);
6200 entry = pte_mkyoung(entry);
6201 if (huge_ptep_set_access_flags(vma, haddr, ptep, entry,
6202 flags & FAULT_FLAG_WRITE))
6203 update_mmu_cache(vma, haddr, ptep);
6205 if (page != pagecache_page)
6211 if (pagecache_page) {
6212 unlock_page(pagecache_page);
6213 put_page(pagecache_page);
6216 hugetlb_vma_unlock_read(vma);
6217 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6219 * Generally it's safe to hold refcount during waiting page lock. But
6220 * here we just wait to defer the next page fault to avoid busy loop and
6221 * the page is not used after unlocked before returning from the current
6222 * page fault. So we are safe from accessing freed page, even if we wait
6223 * here without taking refcount.
6226 wait_on_page_locked(page);
6230 #ifdef CONFIG_USERFAULTFD
6232 * Used by userfaultfd UFFDIO_COPY. Based on mcopy_atomic_pte with
6233 * modifications for huge pages.
6235 int hugetlb_mcopy_atomic_pte(struct mm_struct *dst_mm,
6237 struct vm_area_struct *dst_vma,
6238 unsigned long dst_addr,
6239 unsigned long src_addr,
6240 enum mcopy_atomic_mode mode,
6241 struct page **pagep,
6244 bool is_continue = (mode == MCOPY_ATOMIC_CONTINUE);
6245 struct hstate *h = hstate_vma(dst_vma);
6246 struct address_space *mapping = dst_vma->vm_file->f_mapping;
6247 pgoff_t idx = vma_hugecache_offset(h, dst_vma, dst_addr);
6249 int vm_shared = dst_vma->vm_flags & VM_SHARED;
6255 bool page_in_pagecache = false;
6259 page = find_lock_page(mapping, idx);
6262 page_in_pagecache = true;
6263 } else if (!*pagep) {
6264 /* If a page already exists, then it's UFFDIO_COPY for
6265 * a non-missing case. Return -EEXIST.
6268 hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
6273 page = alloc_huge_page(dst_vma, dst_addr, 0);
6279 ret = copy_huge_page_from_user(page,
6280 (const void __user *) src_addr,
6281 pages_per_huge_page(h), false);
6283 /* fallback to copy_from_user outside mmap_lock */
6284 if (unlikely(ret)) {
6286 /* Free the allocated page which may have
6287 * consumed a reservation.
6289 restore_reserve_on_error(h, dst_vma, dst_addr, page);
6292 /* Allocate a temporary page to hold the copied
6295 page = alloc_huge_page_vma(h, dst_vma, dst_addr);
6301 /* Set the outparam pagep and return to the caller to
6302 * copy the contents outside the lock. Don't free the
6309 hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
6316 page = alloc_huge_page(dst_vma, dst_addr, 0);
6323 copy_user_huge_page(page, *pagep, dst_addr, dst_vma,
6324 pages_per_huge_page(h));
6330 * The memory barrier inside __SetPageUptodate makes sure that
6331 * preceding stores to the page contents become visible before
6332 * the set_pte_at() write.
6334 __SetPageUptodate(page);
6336 /* Add shared, newly allocated pages to the page cache. */
6337 if (vm_shared && !is_continue) {
6338 size = i_size_read(mapping->host) >> huge_page_shift(h);
6341 goto out_release_nounlock;
6344 * Serialization between remove_inode_hugepages() and
6345 * hugetlb_add_to_page_cache() below happens through the
6346 * hugetlb_fault_mutex_table that here must be hold by
6349 ret = hugetlb_add_to_page_cache(page, mapping, idx);
6351 goto out_release_nounlock;
6352 page_in_pagecache = true;
6355 ptl = huge_pte_lock(h, dst_mm, dst_pte);
6358 if (PageHWPoison(page))
6359 goto out_release_unlock;
6362 * We allow to overwrite a pte marker: consider when both MISSING|WP
6363 * registered, we firstly wr-protect a none pte which has no page cache
6364 * page backing it, then access the page.
6367 if (!huge_pte_none_mostly(huge_ptep_get(dst_pte)))
6368 goto out_release_unlock;
6370 if (page_in_pagecache) {
6371 page_dup_file_rmap(page, true);
6373 ClearHPageRestoreReserve(page);
6374 hugepage_add_new_anon_rmap(page, dst_vma, dst_addr);
6378 * For either: (1) CONTINUE on a non-shared VMA, or (2) UFFDIO_COPY
6379 * with wp flag set, don't set pte write bit.
6381 if (wp_copy || (is_continue && !vm_shared))
6384 writable = dst_vma->vm_flags & VM_WRITE;
6386 _dst_pte = make_huge_pte(dst_vma, page, writable);
6388 * Always mark UFFDIO_COPY page dirty; note that this may not be
6389 * extremely important for hugetlbfs for now since swapping is not
6390 * supported, but we should still be clear in that this page cannot be
6391 * thrown away at will, even if write bit not set.
6393 _dst_pte = huge_pte_mkdirty(_dst_pte);
6394 _dst_pte = pte_mkyoung(_dst_pte);
6397 _dst_pte = huge_pte_mkuffd_wp(_dst_pte);
6399 set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
6401 hugetlb_count_add(pages_per_huge_page(h), dst_mm);
6403 /* No need to invalidate - it was non-present before */
6404 update_mmu_cache(dst_vma, dst_addr, dst_pte);
6408 SetHPageMigratable(page);
6409 if (vm_shared || is_continue)
6416 if (vm_shared || is_continue)
6418 out_release_nounlock:
6419 if (!page_in_pagecache)
6420 restore_reserve_on_error(h, dst_vma, dst_addr, page);
6424 #endif /* CONFIG_USERFAULTFD */
6426 static void record_subpages_vmas(struct page *page, struct vm_area_struct *vma,
6427 int refs, struct page **pages,
6428 struct vm_area_struct **vmas)
6432 for (nr = 0; nr < refs; nr++) {
6434 pages[nr] = nth_page(page, nr);
6440 static inline bool __follow_hugetlb_must_fault(unsigned int flags, pte_t *pte,
6443 pte_t pteval = huge_ptep_get(pte);
6446 if (is_swap_pte(pteval))
6448 if (huge_pte_write(pteval))
6450 if (flags & FOLL_WRITE)
6452 if (gup_must_unshare(flags, pte_page(pteval))) {
6459 long follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma,
6460 struct page **pages, struct vm_area_struct **vmas,
6461 unsigned long *position, unsigned long *nr_pages,
6462 long i, unsigned int flags, int *locked)
6464 unsigned long pfn_offset;
6465 unsigned long vaddr = *position;
6466 unsigned long remainder = *nr_pages;
6467 struct hstate *h = hstate_vma(vma);
6468 int err = -EFAULT, refs;
6470 while (vaddr < vma->vm_end && remainder) {
6472 spinlock_t *ptl = NULL;
6473 bool unshare = false;
6478 * If we have a pending SIGKILL, don't keep faulting pages and
6479 * potentially allocating memory.
6481 if (fatal_signal_pending(current)) {
6487 * Some archs (sparc64, sh*) have multiple pte_ts to
6488 * each hugepage. We have to make sure we get the
6489 * first, for the page indexing below to work.
6491 * Note that page table lock is not held when pte is null.
6493 pte = huge_pte_offset(mm, vaddr & huge_page_mask(h),
6496 ptl = huge_pte_lock(h, mm, pte);
6497 absent = !pte || huge_pte_none(huge_ptep_get(pte));
6500 * When coredumping, it suits get_dump_page if we just return
6501 * an error where there's an empty slot with no huge pagecache
6502 * to back it. This way, we avoid allocating a hugepage, and
6503 * the sparse dumpfile avoids allocating disk blocks, but its
6504 * huge holes still show up with zeroes where they need to be.
6506 if (absent && (flags & FOLL_DUMP) &&
6507 !hugetlbfs_pagecache_present(h, vma, vaddr)) {
6515 * We need call hugetlb_fault for both hugepages under migration
6516 * (in which case hugetlb_fault waits for the migration,) and
6517 * hwpoisoned hugepages (in which case we need to prevent the
6518 * caller from accessing to them.) In order to do this, we use
6519 * here is_swap_pte instead of is_hugetlb_entry_migration and
6520 * is_hugetlb_entry_hwpoisoned. This is because it simply covers
6521 * both cases, and because we can't follow correct pages
6522 * directly from any kind of swap entries.
6525 __follow_hugetlb_must_fault(flags, pte, &unshare)) {
6527 unsigned int fault_flags = 0;
6531 if (flags & FOLL_WRITE)
6532 fault_flags |= FAULT_FLAG_WRITE;
6534 fault_flags |= FAULT_FLAG_UNSHARE;
6536 fault_flags |= FAULT_FLAG_ALLOW_RETRY |
6537 FAULT_FLAG_KILLABLE;
6538 if (flags & FOLL_NOWAIT)
6539 fault_flags |= FAULT_FLAG_ALLOW_RETRY |
6540 FAULT_FLAG_RETRY_NOWAIT;
6541 if (flags & FOLL_TRIED) {
6543 * Note: FAULT_FLAG_ALLOW_RETRY and
6544 * FAULT_FLAG_TRIED can co-exist
6546 fault_flags |= FAULT_FLAG_TRIED;
6548 ret = hugetlb_fault(mm, vma, vaddr, fault_flags);
6549 if (ret & VM_FAULT_ERROR) {
6550 err = vm_fault_to_errno(ret, flags);
6554 if (ret & VM_FAULT_RETRY) {
6556 !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
6560 * VM_FAULT_RETRY must not return an
6561 * error, it will return zero
6564 * No need to update "position" as the
6565 * caller will not check it after
6566 * *nr_pages is set to 0.
6573 pfn_offset = (vaddr & ~huge_page_mask(h)) >> PAGE_SHIFT;
6574 page = pte_page(huge_ptep_get(pte));
6576 VM_BUG_ON_PAGE((flags & FOLL_PIN) && PageAnon(page) &&
6577 !PageAnonExclusive(page), page);
6580 * If subpage information not requested, update counters
6581 * and skip the same_page loop below.
6583 if (!pages && !vmas && !pfn_offset &&
6584 (vaddr + huge_page_size(h) < vma->vm_end) &&
6585 (remainder >= pages_per_huge_page(h))) {
6586 vaddr += huge_page_size(h);
6587 remainder -= pages_per_huge_page(h);
6588 i += pages_per_huge_page(h);
6593 /* vaddr may not be aligned to PAGE_SIZE */
6594 refs = min3(pages_per_huge_page(h) - pfn_offset, remainder,
6595 (vma->vm_end - ALIGN_DOWN(vaddr, PAGE_SIZE)) >> PAGE_SHIFT);
6598 record_subpages_vmas(nth_page(page, pfn_offset),
6600 likely(pages) ? pages + i : NULL,
6601 vmas ? vmas + i : NULL);
6605 * try_grab_folio() should always succeed here,
6606 * because: a) we hold the ptl lock, and b) we've just
6607 * checked that the huge page is present in the page
6608 * tables. If the huge page is present, then the tail
6609 * pages must also be present. The ptl prevents the
6610 * head page and tail pages from being rearranged in
6611 * any way. So this page must be available at this
6612 * point, unless the page refcount overflowed:
6614 if (WARN_ON_ONCE(!try_grab_folio(pages[i], refs,
6623 vaddr += (refs << PAGE_SHIFT);
6629 *nr_pages = remainder;
6631 * setting position is actually required only if remainder is
6632 * not zero but it's faster not to add a "if (remainder)"
6640 unsigned long hugetlb_change_protection(struct vm_area_struct *vma,
6641 unsigned long address, unsigned long end,
6642 pgprot_t newprot, unsigned long cp_flags)
6644 struct mm_struct *mm = vma->vm_mm;
6645 unsigned long start = address;
6648 struct hstate *h = hstate_vma(vma);
6649 unsigned long pages = 0, psize = huge_page_size(h);
6650 bool shared_pmd = false;
6651 struct mmu_notifier_range range;
6652 unsigned long last_addr_mask;
6653 bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
6654 bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
6657 * In the case of shared PMDs, the area to flush could be beyond
6658 * start/end. Set range.start/range.end to cover the maximum possible
6659 * range if PMD sharing is possible.
6661 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_VMA,
6662 0, vma, mm, start, end);
6663 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
6665 BUG_ON(address >= end);
6666 flush_cache_range(vma, range.start, range.end);
6668 mmu_notifier_invalidate_range_start(&range);
6669 hugetlb_vma_lock_write(vma);
6670 i_mmap_lock_write(vma->vm_file->f_mapping);
6671 last_addr_mask = hugetlb_mask_last_page(h);
6672 for (; address < end; address += psize) {
6674 ptep = huge_pte_offset(mm, address, psize);
6677 address |= last_addr_mask;
6681 * Userfaultfd wr-protect requires pgtable
6682 * pre-allocations to install pte markers.
6684 ptep = huge_pte_alloc(mm, vma, address, psize);
6688 ptl = huge_pte_lock(h, mm, ptep);
6689 if (huge_pmd_unshare(mm, vma, address, ptep)) {
6691 * When uffd-wp is enabled on the vma, unshare
6692 * shouldn't happen at all. Warn about it if it
6693 * happened due to some reason.
6695 WARN_ON_ONCE(uffd_wp || uffd_wp_resolve);
6699 address |= last_addr_mask;
6702 pte = huge_ptep_get(ptep);
6703 if (unlikely(is_hugetlb_entry_hwpoisoned(pte))) {
6704 /* Nothing to do. */
6705 } else if (unlikely(is_hugetlb_entry_migration(pte))) {
6706 swp_entry_t entry = pte_to_swp_entry(pte);
6707 struct page *page = pfn_swap_entry_to_page(entry);
6710 if (is_writable_migration_entry(entry)) {
6712 entry = make_readable_exclusive_migration_entry(
6715 entry = make_readable_migration_entry(
6717 newpte = swp_entry_to_pte(entry);
6722 newpte = pte_swp_mkuffd_wp(newpte);
6723 else if (uffd_wp_resolve)
6724 newpte = pte_swp_clear_uffd_wp(newpte);
6725 if (!pte_same(pte, newpte))
6726 set_huge_pte_at(mm, address, ptep, newpte);
6727 } else if (unlikely(is_pte_marker(pte))) {
6728 /* No other markers apply for now. */
6729 WARN_ON_ONCE(!pte_marker_uffd_wp(pte));
6730 if (uffd_wp_resolve)
6731 /* Safe to modify directly (non-present->none). */
6732 huge_pte_clear(mm, address, ptep, psize);
6733 } else if (!huge_pte_none(pte)) {
6735 unsigned int shift = huge_page_shift(hstate_vma(vma));
6737 old_pte = huge_ptep_modify_prot_start(vma, address, ptep);
6738 pte = huge_pte_modify(old_pte, newprot);
6739 pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
6741 pte = huge_pte_mkuffd_wp(huge_pte_wrprotect(pte));
6742 else if (uffd_wp_resolve)
6743 pte = huge_pte_clear_uffd_wp(pte);
6744 huge_ptep_modify_prot_commit(vma, address, ptep, old_pte, pte);
6748 if (unlikely(uffd_wp))
6749 /* Safe to modify directly (none->non-present). */
6750 set_huge_pte_at(mm, address, ptep,
6751 make_pte_marker(PTE_MARKER_UFFD_WP));
6756 * Must flush TLB before releasing i_mmap_rwsem: x86's huge_pmd_unshare
6757 * may have cleared our pud entry and done put_page on the page table:
6758 * once we release i_mmap_rwsem, another task can do the final put_page
6759 * and that page table be reused and filled with junk. If we actually
6760 * did unshare a page of pmds, flush the range corresponding to the pud.
6763 flush_hugetlb_tlb_range(vma, range.start, range.end);
6765 flush_hugetlb_tlb_range(vma, start, end);
6767 * No need to call mmu_notifier_invalidate_range() we are downgrading
6768 * page table protection not changing it to point to a new page.
6770 * See Documentation/mm/mmu_notifier.rst
6772 i_mmap_unlock_write(vma->vm_file->f_mapping);
6773 hugetlb_vma_unlock_write(vma);
6774 mmu_notifier_invalidate_range_end(&range);
6776 return pages << h->order;
6779 /* Return true if reservation was successful, false otherwise. */
6780 bool hugetlb_reserve_pages(struct inode *inode,
6782 struct vm_area_struct *vma,
6783 vm_flags_t vm_flags)
6786 struct hstate *h = hstate_inode(inode);
6787 struct hugepage_subpool *spool = subpool_inode(inode);
6788 struct resv_map *resv_map;
6789 struct hugetlb_cgroup *h_cg = NULL;
6790 long gbl_reserve, regions_needed = 0;
6792 /* This should never happen */
6794 VM_WARN(1, "%s called with a negative range\n", __func__);
6799 * vma specific semaphore used for pmd sharing and fault/truncation
6802 hugetlb_vma_lock_alloc(vma);
6805 * Only apply hugepage reservation if asked. At fault time, an
6806 * attempt will be made for VM_NORESERVE to allocate a page
6807 * without using reserves
6809 if (vm_flags & VM_NORESERVE)
6813 * Shared mappings base their reservation on the number of pages that
6814 * are already allocated on behalf of the file. Private mappings need
6815 * to reserve the full area even if read-only as mprotect() may be
6816 * called to make the mapping read-write. Assume !vma is a shm mapping
6818 if (!vma || vma->vm_flags & VM_MAYSHARE) {
6820 * resv_map can not be NULL as hugetlb_reserve_pages is only
6821 * called for inodes for which resv_maps were created (see
6822 * hugetlbfs_get_inode).
6824 resv_map = inode_resv_map(inode);
6826 chg = region_chg(resv_map, from, to, ®ions_needed);
6828 /* Private mapping. */
6829 resv_map = resv_map_alloc();
6835 set_vma_resv_map(vma, resv_map);
6836 set_vma_resv_flags(vma, HPAGE_RESV_OWNER);
6842 if (hugetlb_cgroup_charge_cgroup_rsvd(hstate_index(h),
6843 chg * pages_per_huge_page(h), &h_cg) < 0)
6846 if (vma && !(vma->vm_flags & VM_MAYSHARE) && h_cg) {
6847 /* For private mappings, the hugetlb_cgroup uncharge info hangs
6850 resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, h_cg, h);
6854 * There must be enough pages in the subpool for the mapping. If
6855 * the subpool has a minimum size, there may be some global
6856 * reservations already in place (gbl_reserve).
6858 gbl_reserve = hugepage_subpool_get_pages(spool, chg);
6859 if (gbl_reserve < 0)
6860 goto out_uncharge_cgroup;
6863 * Check enough hugepages are available for the reservation.
6864 * Hand the pages back to the subpool if there are not
6866 if (hugetlb_acct_memory(h, gbl_reserve) < 0)
6870 * Account for the reservations made. Shared mappings record regions
6871 * that have reservations as they are shared by multiple VMAs.
6872 * When the last VMA disappears, the region map says how much
6873 * the reservation was and the page cache tells how much of
6874 * the reservation was consumed. Private mappings are per-VMA and
6875 * only the consumed reservations are tracked. When the VMA
6876 * disappears, the original reservation is the VMA size and the
6877 * consumed reservations are stored in the map. Hence, nothing
6878 * else has to be done for private mappings here
6880 if (!vma || vma->vm_flags & VM_MAYSHARE) {
6881 add = region_add(resv_map, from, to, regions_needed, h, h_cg);
6883 if (unlikely(add < 0)) {
6884 hugetlb_acct_memory(h, -gbl_reserve);
6886 } else if (unlikely(chg > add)) {
6888 * pages in this range were added to the reserve
6889 * map between region_chg and region_add. This
6890 * indicates a race with alloc_huge_page. Adjust
6891 * the subpool and reserve counts modified above
6892 * based on the difference.
6897 * hugetlb_cgroup_uncharge_cgroup_rsvd() will put the
6898 * reference to h_cg->css. See comment below for detail.
6900 hugetlb_cgroup_uncharge_cgroup_rsvd(
6902 (chg - add) * pages_per_huge_page(h), h_cg);
6904 rsv_adjust = hugepage_subpool_put_pages(spool,
6906 hugetlb_acct_memory(h, -rsv_adjust);
6909 * The file_regions will hold their own reference to
6910 * h_cg->css. So we should release the reference held
6911 * via hugetlb_cgroup_charge_cgroup_rsvd() when we are
6914 hugetlb_cgroup_put_rsvd_cgroup(h_cg);
6920 /* put back original number of pages, chg */
6921 (void)hugepage_subpool_put_pages(spool, chg);
6922 out_uncharge_cgroup:
6923 hugetlb_cgroup_uncharge_cgroup_rsvd(hstate_index(h),
6924 chg * pages_per_huge_page(h), h_cg);
6926 hugetlb_vma_lock_free(vma);
6927 if (!vma || vma->vm_flags & VM_MAYSHARE)
6928 /* Only call region_abort if the region_chg succeeded but the
6929 * region_add failed or didn't run.
6931 if (chg >= 0 && add < 0)
6932 region_abort(resv_map, from, to, regions_needed);
6933 if (vma && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
6934 kref_put(&resv_map->refs, resv_map_release);
6935 set_vma_resv_map(vma, NULL);
6940 long hugetlb_unreserve_pages(struct inode *inode, long start, long end,
6943 struct hstate *h = hstate_inode(inode);
6944 struct resv_map *resv_map = inode_resv_map(inode);
6946 struct hugepage_subpool *spool = subpool_inode(inode);
6950 * Since this routine can be called in the evict inode path for all
6951 * hugetlbfs inodes, resv_map could be NULL.
6954 chg = region_del(resv_map, start, end);
6956 * region_del() can fail in the rare case where a region
6957 * must be split and another region descriptor can not be
6958 * allocated. If end == LONG_MAX, it will not fail.
6964 spin_lock(&inode->i_lock);
6965 inode->i_blocks -= (blocks_per_huge_page(h) * freed);
6966 spin_unlock(&inode->i_lock);
6969 * If the subpool has a minimum size, the number of global
6970 * reservations to be released may be adjusted.
6972 * Note that !resv_map implies freed == 0. So (chg - freed)
6973 * won't go negative.
6975 gbl_reserve = hugepage_subpool_put_pages(spool, (chg - freed));
6976 hugetlb_acct_memory(h, -gbl_reserve);
6981 #ifdef CONFIG_ARCH_WANT_HUGE_PMD_SHARE
6982 static unsigned long page_table_shareable(struct vm_area_struct *svma,
6983 struct vm_area_struct *vma,
6984 unsigned long addr, pgoff_t idx)
6986 unsigned long saddr = ((idx - svma->vm_pgoff) << PAGE_SHIFT) +
6988 unsigned long sbase = saddr & PUD_MASK;
6989 unsigned long s_end = sbase + PUD_SIZE;
6991 /* Allow segments to share if only one is marked locked */
6992 unsigned long vm_flags = vma->vm_flags & VM_LOCKED_CLEAR_MASK;
6993 unsigned long svm_flags = svma->vm_flags & VM_LOCKED_CLEAR_MASK;
6996 * match the virtual addresses, permission and the alignment of the
6999 * Also, vma_lock (vm_private_data) is required for sharing.
7001 if (pmd_index(addr) != pmd_index(saddr) ||
7002 vm_flags != svm_flags ||
7003 !range_in_vma(svma, sbase, s_end) ||
7004 !svma->vm_private_data)
7010 bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
7012 unsigned long start = addr & PUD_MASK;
7013 unsigned long end = start + PUD_SIZE;
7015 #ifdef CONFIG_USERFAULTFD
7016 if (uffd_disable_huge_pmd_share(vma))
7020 * check on proper vm_flags and page table alignment
7022 if (!(vma->vm_flags & VM_MAYSHARE))
7024 if (!vma->vm_private_data) /* vma lock required for sharing */
7026 if (!range_in_vma(vma, start, end))
7032 * Determine if start,end range within vma could be mapped by shared pmd.
7033 * If yes, adjust start and end to cover range associated with possible
7034 * shared pmd mappings.
7036 void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
7037 unsigned long *start, unsigned long *end)
7039 unsigned long v_start = ALIGN(vma->vm_start, PUD_SIZE),
7040 v_end = ALIGN_DOWN(vma->vm_end, PUD_SIZE);
7043 * vma needs to span at least one aligned PUD size, and the range
7044 * must be at least partially within in.
7046 if (!(vma->vm_flags & VM_MAYSHARE) || !(v_end > v_start) ||
7047 (*end <= v_start) || (*start >= v_end))
7050 /* Extend the range to be PUD aligned for a worst case scenario */
7051 if (*start > v_start)
7052 *start = ALIGN_DOWN(*start, PUD_SIZE);
7055 *end = ALIGN(*end, PUD_SIZE);
7059 * Search for a shareable pmd page for hugetlb. In any case calls pmd_alloc()
7060 * and returns the corresponding pte. While this is not necessary for the
7061 * !shared pmd case because we can allocate the pmd later as well, it makes the
7062 * code much cleaner. pmd allocation is essential for the shared case because
7063 * pud has to be populated inside the same i_mmap_rwsem section - otherwise
7064 * racing tasks could either miss the sharing (see huge_pte_offset) or select a
7065 * bad pmd for sharing.
7067 pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
7068 unsigned long addr, pud_t *pud)
7070 struct address_space *mapping = vma->vm_file->f_mapping;
7071 pgoff_t idx = ((addr - vma->vm_start) >> PAGE_SHIFT) +
7073 struct vm_area_struct *svma;
7074 unsigned long saddr;
7079 i_mmap_lock_read(mapping);
7080 vma_interval_tree_foreach(svma, &mapping->i_mmap, idx, idx) {
7084 saddr = page_table_shareable(svma, vma, addr, idx);
7086 spte = huge_pte_offset(svma->vm_mm, saddr,
7087 vma_mmu_pagesize(svma));
7089 get_page(virt_to_page(spte));
7098 ptl = huge_pte_lock(hstate_vma(vma), mm, spte);
7099 if (pud_none(*pud)) {
7100 pud_populate(mm, pud,
7101 (pmd_t *)((unsigned long)spte & PAGE_MASK));
7104 put_page(virt_to_page(spte));
7108 pte = (pte_t *)pmd_alloc(mm, pud, addr);
7109 i_mmap_unlock_read(mapping);
7114 * unmap huge page backed by shared pte.
7116 * Hugetlb pte page is ref counted at the time of mapping. If pte is shared
7117 * indicated by page_count > 1, unmap is achieved by clearing pud and
7118 * decrementing the ref count. If count == 1, the pte page is not shared.
7120 * Called with page table lock held.
7122 * returns: 1 successfully unmapped a shared pte page
7123 * 0 the underlying pte page is not shared, or it is the last user
7125 int huge_pmd_unshare(struct mm_struct *mm, struct vm_area_struct *vma,
7126 unsigned long addr, pte_t *ptep)
7128 pgd_t *pgd = pgd_offset(mm, addr);
7129 p4d_t *p4d = p4d_offset(pgd, addr);
7130 pud_t *pud = pud_offset(p4d, addr);
7132 i_mmap_assert_write_locked(vma->vm_file->f_mapping);
7133 hugetlb_vma_assert_locked(vma);
7134 BUG_ON(page_count(virt_to_page(ptep)) == 0);
7135 if (page_count(virt_to_page(ptep)) == 1)
7139 put_page(virt_to_page(ptep));
7144 #else /* !CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
7146 pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
7147 unsigned long addr, pud_t *pud)
7152 int huge_pmd_unshare(struct mm_struct *mm, struct vm_area_struct *vma,
7153 unsigned long addr, pte_t *ptep)
7158 void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
7159 unsigned long *start, unsigned long *end)
7163 bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
7167 #endif /* CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
7169 #ifdef CONFIG_ARCH_WANT_GENERAL_HUGETLB
7170 pte_t *huge_pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma,
7171 unsigned long addr, unsigned long sz)
7178 pgd = pgd_offset(mm, addr);
7179 p4d = p4d_alloc(mm, pgd, addr);
7182 pud = pud_alloc(mm, p4d, addr);
7184 if (sz == PUD_SIZE) {
7187 BUG_ON(sz != PMD_SIZE);
7188 if (want_pmd_share(vma, addr) && pud_none(*pud))
7189 pte = huge_pmd_share(mm, vma, addr, pud);
7191 pte = (pte_t *)pmd_alloc(mm, pud, addr);
7194 BUG_ON(pte && pte_present(*pte) && !pte_huge(*pte));
7200 * huge_pte_offset() - Walk the page table to resolve the hugepage
7201 * entry at address @addr
7203 * Return: Pointer to page table entry (PUD or PMD) for
7204 * address @addr, or NULL if a !p*d_present() entry is encountered and the
7205 * size @sz doesn't match the hugepage size at this level of the page
7208 pte_t *huge_pte_offset(struct mm_struct *mm,
7209 unsigned long addr, unsigned long sz)
7216 pgd = pgd_offset(mm, addr);
7217 if (!pgd_present(*pgd))
7219 p4d = p4d_offset(pgd, addr);
7220 if (!p4d_present(*p4d))
7223 pud = pud_offset(p4d, addr);
7225 /* must be pud huge, non-present or none */
7226 return (pte_t *)pud;
7227 if (!pud_present(*pud))
7229 /* must have a valid entry and size to go further */
7231 pmd = pmd_offset(pud, addr);
7232 /* must be pmd huge, non-present or none */
7233 return (pte_t *)pmd;
7237 * Return a mask that can be used to update an address to the last huge
7238 * page in a page table page mapping size. Used to skip non-present
7239 * page table entries when linearly scanning address ranges. Architectures
7240 * with unique huge page to page table relationships can define their own
7241 * version of this routine.
7243 unsigned long hugetlb_mask_last_page(struct hstate *h)
7245 unsigned long hp_size = huge_page_size(h);
7247 if (hp_size == PUD_SIZE)
7248 return P4D_SIZE - PUD_SIZE;
7249 else if (hp_size == PMD_SIZE)
7250 return PUD_SIZE - PMD_SIZE;
7257 /* See description above. Architectures can provide their own version. */
7258 __weak unsigned long hugetlb_mask_last_page(struct hstate *h)
7260 #ifdef CONFIG_ARCH_WANT_HUGE_PMD_SHARE
7261 if (huge_page_size(h) == PMD_SIZE)
7262 return PUD_SIZE - PMD_SIZE;
7267 #endif /* CONFIG_ARCH_WANT_GENERAL_HUGETLB */
7270 * These functions are overwritable if your architecture needs its own
7273 struct page * __weak
7274 follow_huge_addr(struct mm_struct *mm, unsigned long address,
7277 return ERR_PTR(-EINVAL);
7280 struct page * __weak
7281 follow_huge_pd(struct vm_area_struct *vma,
7282 unsigned long address, hugepd_t hpd, int flags, int pdshift)
7284 WARN(1, "hugepd follow called with no support for hugepage directory format\n");
7288 struct page * __weak
7289 follow_huge_pmd_pte(struct vm_area_struct *vma, unsigned long address, int flags)
7291 struct hstate *h = hstate_vma(vma);
7292 struct mm_struct *mm = vma->vm_mm;
7293 struct page *page = NULL;
7298 * FOLL_PIN is not supported for follow_page(). Ordinary GUP goes via
7299 * follow_hugetlb_page().
7301 if (WARN_ON_ONCE(flags & FOLL_PIN))
7305 ptep = huge_pte_offset(mm, address, huge_page_size(h));
7309 ptl = huge_pte_lock(h, mm, ptep);
7310 pte = huge_ptep_get(ptep);
7311 if (pte_present(pte)) {
7312 page = pte_page(pte) +
7313 ((address & ~huge_page_mask(h)) >> PAGE_SHIFT);
7315 * try_grab_page() should always succeed here, because: a) we
7316 * hold the pmd (ptl) lock, and b) we've just checked that the
7317 * huge pmd (head) page is present in the page tables. The ptl
7318 * prevents the head page and tail pages from being rearranged
7319 * in any way. So this page must be available at this point,
7320 * unless the page refcount overflowed:
7322 if (WARN_ON_ONCE(!try_grab_page(page, flags))) {
7327 if (is_hugetlb_entry_migration(pte)) {
7329 __migration_entry_wait_huge(ptep, ptl);
7333 * hwpoisoned entry is treated as no_page_table in
7334 * follow_page_mask().
7342 struct page * __weak
7343 follow_huge_pud(struct mm_struct *mm, unsigned long address,
7344 pud_t *pud, int flags)
7346 struct page *page = NULL;
7350 if (WARN_ON_ONCE(flags & FOLL_PIN))
7354 ptl = huge_pte_lock(hstate_sizelog(PUD_SHIFT), mm, (pte_t *)pud);
7355 if (!pud_huge(*pud))
7357 pte = huge_ptep_get((pte_t *)pud);
7358 if (pte_present(pte)) {
7359 page = pud_page(*pud) + ((address & ~PUD_MASK) >> PAGE_SHIFT);
7360 if (WARN_ON_ONCE(!try_grab_page(page, flags))) {
7365 if (is_hugetlb_entry_migration(pte)) {
7367 __migration_entry_wait(mm, (pte_t *)pud, ptl);
7371 * hwpoisoned entry is treated as no_page_table in
7372 * follow_page_mask().
7380 struct page * __weak
7381 follow_huge_pgd(struct mm_struct *mm, unsigned long address, pgd_t *pgd, int flags)
7383 if (flags & (FOLL_GET | FOLL_PIN))
7386 return pte_page(*(pte_t *)pgd) + ((address & ~PGDIR_MASK) >> PAGE_SHIFT);
7389 int isolate_hugetlb(struct page *page, struct list_head *list)
7393 spin_lock_irq(&hugetlb_lock);
7394 if (!PageHeadHuge(page) ||
7395 !HPageMigratable(page) ||
7396 !get_page_unless_zero(page)) {
7400 ClearHPageMigratable(page);
7401 list_move_tail(&page->lru, list);
7403 spin_unlock_irq(&hugetlb_lock);
7407 int get_hwpoison_huge_page(struct page *page, bool *hugetlb)
7412 spin_lock_irq(&hugetlb_lock);
7413 if (PageHeadHuge(page)) {
7415 if (HPageFreed(page))
7417 else if (HPageMigratable(page))
7418 ret = get_page_unless_zero(page);
7422 spin_unlock_irq(&hugetlb_lock);
7426 int get_huge_page_for_hwpoison(unsigned long pfn, int flags)
7430 spin_lock_irq(&hugetlb_lock);
7431 ret = __get_huge_page_for_hwpoison(pfn, flags);
7432 spin_unlock_irq(&hugetlb_lock);
7436 void putback_active_hugepage(struct page *page)
7438 spin_lock_irq(&hugetlb_lock);
7439 SetHPageMigratable(page);
7440 list_move_tail(&page->lru, &(page_hstate(page))->hugepage_activelist);
7441 spin_unlock_irq(&hugetlb_lock);
7445 void move_hugetlb_state(struct page *oldpage, struct page *newpage, int reason)
7447 struct hstate *h = page_hstate(oldpage);
7449 hugetlb_cgroup_migrate(oldpage, newpage);
7450 set_page_owner_migrate_reason(newpage, reason);
7453 * transfer temporary state of the new huge page. This is
7454 * reverse to other transitions because the newpage is going to
7455 * be final while the old one will be freed so it takes over
7456 * the temporary status.
7458 * Also note that we have to transfer the per-node surplus state
7459 * here as well otherwise the global surplus count will not match
7462 if (HPageTemporary(newpage)) {
7463 int old_nid = page_to_nid(oldpage);
7464 int new_nid = page_to_nid(newpage);
7466 SetHPageTemporary(oldpage);
7467 ClearHPageTemporary(newpage);
7470 * There is no need to transfer the per-node surplus state
7471 * when we do not cross the node.
7473 if (new_nid == old_nid)
7475 spin_lock_irq(&hugetlb_lock);
7476 if (h->surplus_huge_pages_node[old_nid]) {
7477 h->surplus_huge_pages_node[old_nid]--;
7478 h->surplus_huge_pages_node[new_nid]++;
7480 spin_unlock_irq(&hugetlb_lock);
7484 static void hugetlb_unshare_pmds(struct vm_area_struct *vma,
7485 unsigned long start,
7488 struct hstate *h = hstate_vma(vma);
7489 unsigned long sz = huge_page_size(h);
7490 struct mm_struct *mm = vma->vm_mm;
7491 struct mmu_notifier_range range;
7492 unsigned long address;
7496 if (!(vma->vm_flags & VM_MAYSHARE))
7502 flush_cache_range(vma, start, end);
7504 * No need to call adjust_range_if_pmd_sharing_possible(), because
7505 * we have already done the PUD_SIZE alignment.
7507 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
7509 mmu_notifier_invalidate_range_start(&range);
7510 hugetlb_vma_lock_write(vma);
7511 i_mmap_lock_write(vma->vm_file->f_mapping);
7512 for (address = start; address < end; address += PUD_SIZE) {
7513 ptep = huge_pte_offset(mm, address, sz);
7516 ptl = huge_pte_lock(h, mm, ptep);
7517 huge_pmd_unshare(mm, vma, address, ptep);
7520 flush_hugetlb_tlb_range(vma, start, end);
7521 i_mmap_unlock_write(vma->vm_file->f_mapping);
7522 hugetlb_vma_unlock_write(vma);
7524 * No need to call mmu_notifier_invalidate_range(), see
7525 * Documentation/mm/mmu_notifier.rst.
7527 mmu_notifier_invalidate_range_end(&range);
7531 * This function will unconditionally remove all the shared pmd pgtable entries
7532 * within the specific vma for a hugetlbfs memory range.
7534 void hugetlb_unshare_all_pmds(struct vm_area_struct *vma)
7536 hugetlb_unshare_pmds(vma, ALIGN(vma->vm_start, PUD_SIZE),
7537 ALIGN_DOWN(vma->vm_end, PUD_SIZE));
7541 static bool cma_reserve_called __initdata;
7543 static int __init cmdline_parse_hugetlb_cma(char *p)
7550 if (sscanf(s, "%lu%n", &tmp, &count) != 1)
7553 if (s[count] == ':') {
7554 if (tmp >= MAX_NUMNODES)
7556 nid = array_index_nospec(tmp, MAX_NUMNODES);
7559 tmp = memparse(s, &s);
7560 hugetlb_cma_size_in_node[nid] = tmp;
7561 hugetlb_cma_size += tmp;
7564 * Skip the separator if have one, otherwise
7565 * break the parsing.
7572 hugetlb_cma_size = memparse(p, &p);
7580 early_param("hugetlb_cma", cmdline_parse_hugetlb_cma);
7582 void __init hugetlb_cma_reserve(int order)
7584 unsigned long size, reserved, per_node;
7585 bool node_specific_cma_alloc = false;
7588 cma_reserve_called = true;
7590 if (!hugetlb_cma_size)
7593 for (nid = 0; nid < MAX_NUMNODES; nid++) {
7594 if (hugetlb_cma_size_in_node[nid] == 0)
7597 if (!node_online(nid)) {
7598 pr_warn("hugetlb_cma: invalid node %d specified\n", nid);
7599 hugetlb_cma_size -= hugetlb_cma_size_in_node[nid];
7600 hugetlb_cma_size_in_node[nid] = 0;
7604 if (hugetlb_cma_size_in_node[nid] < (PAGE_SIZE << order)) {
7605 pr_warn("hugetlb_cma: cma area of node %d should be at least %lu MiB\n",
7606 nid, (PAGE_SIZE << order) / SZ_1M);
7607 hugetlb_cma_size -= hugetlb_cma_size_in_node[nid];
7608 hugetlb_cma_size_in_node[nid] = 0;
7610 node_specific_cma_alloc = true;
7614 /* Validate the CMA size again in case some invalid nodes specified. */
7615 if (!hugetlb_cma_size)
7618 if (hugetlb_cma_size < (PAGE_SIZE << order)) {
7619 pr_warn("hugetlb_cma: cma area should be at least %lu MiB\n",
7620 (PAGE_SIZE << order) / SZ_1M);
7621 hugetlb_cma_size = 0;
7625 if (!node_specific_cma_alloc) {
7627 * If 3 GB area is requested on a machine with 4 numa nodes,
7628 * let's allocate 1 GB on first three nodes and ignore the last one.
7630 per_node = DIV_ROUND_UP(hugetlb_cma_size, nr_online_nodes);
7631 pr_info("hugetlb_cma: reserve %lu MiB, up to %lu MiB per node\n",
7632 hugetlb_cma_size / SZ_1M, per_node / SZ_1M);
7636 for_each_online_node(nid) {
7638 char name[CMA_MAX_NAME];
7640 if (node_specific_cma_alloc) {
7641 if (hugetlb_cma_size_in_node[nid] == 0)
7644 size = hugetlb_cma_size_in_node[nid];
7646 size = min(per_node, hugetlb_cma_size - reserved);
7649 size = round_up(size, PAGE_SIZE << order);
7651 snprintf(name, sizeof(name), "hugetlb%d", nid);
7653 * Note that 'order per bit' is based on smallest size that
7654 * may be returned to CMA allocator in the case of
7655 * huge page demotion.
7657 res = cma_declare_contiguous_nid(0, size, 0,
7658 PAGE_SIZE << HUGETLB_PAGE_ORDER,
7660 &hugetlb_cma[nid], nid);
7662 pr_warn("hugetlb_cma: reservation failed: err %d, node %d",
7668 pr_info("hugetlb_cma: reserved %lu MiB on node %d\n",
7671 if (reserved >= hugetlb_cma_size)
7677 * hugetlb_cma_size is used to determine if allocations from
7678 * cma are possible. Set to zero if no cma regions are set up.
7680 hugetlb_cma_size = 0;
7683 static void __init hugetlb_cma_check(void)
7685 if (!hugetlb_cma_size || cma_reserve_called)
7688 pr_warn("hugetlb_cma: the option isn't supported by current arch\n");
7691 #endif /* CONFIG_CMA */