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);
97 static inline bool subpool_is_free(struct hugepage_subpool *spool)
101 if (spool->max_hpages != -1)
102 return spool->used_hpages == 0;
103 if (spool->min_hpages != -1)
104 return spool->rsv_hpages == spool->min_hpages;
109 static inline void unlock_or_release_subpool(struct hugepage_subpool *spool,
110 unsigned long irq_flags)
112 spin_unlock_irqrestore(&spool->lock, irq_flags);
114 /* If no pages are used, and no other handles to the subpool
115 * remain, give up any reservations based on minimum size and
116 * free the subpool */
117 if (subpool_is_free(spool)) {
118 if (spool->min_hpages != -1)
119 hugetlb_acct_memory(spool->hstate,
125 struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages,
128 struct hugepage_subpool *spool;
130 spool = kzalloc(sizeof(*spool), GFP_KERNEL);
134 spin_lock_init(&spool->lock);
136 spool->max_hpages = max_hpages;
138 spool->min_hpages = min_hpages;
140 if (min_hpages != -1 && hugetlb_acct_memory(h, min_hpages)) {
144 spool->rsv_hpages = min_hpages;
149 void hugepage_put_subpool(struct hugepage_subpool *spool)
153 spin_lock_irqsave(&spool->lock, flags);
154 BUG_ON(!spool->count);
156 unlock_or_release_subpool(spool, flags);
160 * Subpool accounting for allocating and reserving pages.
161 * Return -ENOMEM if there are not enough resources to satisfy the
162 * request. Otherwise, return the number of pages by which the
163 * global pools must be adjusted (upward). The returned value may
164 * only be different than the passed value (delta) in the case where
165 * a subpool minimum size must be maintained.
167 static long hugepage_subpool_get_pages(struct hugepage_subpool *spool,
175 spin_lock_irq(&spool->lock);
177 if (spool->max_hpages != -1) { /* maximum size accounting */
178 if ((spool->used_hpages + delta) <= spool->max_hpages)
179 spool->used_hpages += delta;
186 /* minimum size accounting */
187 if (spool->min_hpages != -1 && spool->rsv_hpages) {
188 if (delta > spool->rsv_hpages) {
190 * Asking for more reserves than those already taken on
191 * behalf of subpool. Return difference.
193 ret = delta - spool->rsv_hpages;
194 spool->rsv_hpages = 0;
196 ret = 0; /* reserves already accounted for */
197 spool->rsv_hpages -= delta;
202 spin_unlock_irq(&spool->lock);
207 * Subpool accounting for freeing and unreserving pages.
208 * Return the number of global page reservations that must be dropped.
209 * The return value may only be different than the passed value (delta)
210 * in the case where a subpool minimum size must be maintained.
212 static long hugepage_subpool_put_pages(struct hugepage_subpool *spool,
221 spin_lock_irqsave(&spool->lock, flags);
223 if (spool->max_hpages != -1) /* maximum size accounting */
224 spool->used_hpages -= delta;
226 /* minimum size accounting */
227 if (spool->min_hpages != -1 && spool->used_hpages < spool->min_hpages) {
228 if (spool->rsv_hpages + delta <= spool->min_hpages)
231 ret = spool->rsv_hpages + delta - spool->min_hpages;
233 spool->rsv_hpages += delta;
234 if (spool->rsv_hpages > spool->min_hpages)
235 spool->rsv_hpages = spool->min_hpages;
239 * If hugetlbfs_put_super couldn't free spool due to an outstanding
240 * quota reference, free it now.
242 unlock_or_release_subpool(spool, flags);
247 static inline struct hugepage_subpool *subpool_inode(struct inode *inode)
249 return HUGETLBFS_SB(inode->i_sb)->spool;
252 static inline struct hugepage_subpool *subpool_vma(struct vm_area_struct *vma)
254 return subpool_inode(file_inode(vma->vm_file));
257 /* Helper that removes a struct file_region from the resv_map cache and returns
260 static struct file_region *
261 get_file_region_entry_from_cache(struct resv_map *resv, long from, long to)
263 struct file_region *nrg;
265 VM_BUG_ON(resv->region_cache_count <= 0);
267 resv->region_cache_count--;
268 nrg = list_first_entry(&resv->region_cache, struct file_region, link);
269 list_del(&nrg->link);
277 static void copy_hugetlb_cgroup_uncharge_info(struct file_region *nrg,
278 struct file_region *rg)
280 #ifdef CONFIG_CGROUP_HUGETLB
281 nrg->reservation_counter = rg->reservation_counter;
288 /* Helper that records hugetlb_cgroup uncharge info. */
289 static void record_hugetlb_cgroup_uncharge_info(struct hugetlb_cgroup *h_cg,
291 struct resv_map *resv,
292 struct file_region *nrg)
294 #ifdef CONFIG_CGROUP_HUGETLB
296 nrg->reservation_counter =
297 &h_cg->rsvd_hugepage[hstate_index(h)];
298 nrg->css = &h_cg->css;
300 * The caller will hold exactly one h_cg->css reference for the
301 * whole contiguous reservation region. But this area might be
302 * scattered when there are already some file_regions reside in
303 * it. As a result, many file_regions may share only one css
304 * reference. In order to ensure that one file_region must hold
305 * exactly one h_cg->css reference, we should do css_get for
306 * each file_region and leave the reference held by caller
310 if (!resv->pages_per_hpage)
311 resv->pages_per_hpage = pages_per_huge_page(h);
312 /* pages_per_hpage should be the same for all entries in
315 VM_BUG_ON(resv->pages_per_hpage != pages_per_huge_page(h));
317 nrg->reservation_counter = NULL;
323 static void put_uncharge_info(struct file_region *rg)
325 #ifdef CONFIG_CGROUP_HUGETLB
331 static bool has_same_uncharge_info(struct file_region *rg,
332 struct file_region *org)
334 #ifdef CONFIG_CGROUP_HUGETLB
335 return rg->reservation_counter == org->reservation_counter &&
343 static void coalesce_file_region(struct resv_map *resv, struct file_region *rg)
345 struct file_region *nrg, *prg;
347 prg = list_prev_entry(rg, link);
348 if (&prg->link != &resv->regions && prg->to == rg->from &&
349 has_same_uncharge_info(prg, rg)) {
353 put_uncharge_info(rg);
359 nrg = list_next_entry(rg, link);
360 if (&nrg->link != &resv->regions && nrg->from == rg->to &&
361 has_same_uncharge_info(nrg, rg)) {
362 nrg->from = rg->from;
365 put_uncharge_info(rg);
371 hugetlb_resv_map_add(struct resv_map *map, struct list_head *rg, long from,
372 long to, struct hstate *h, struct hugetlb_cgroup *cg,
373 long *regions_needed)
375 struct file_region *nrg;
377 if (!regions_needed) {
378 nrg = get_file_region_entry_from_cache(map, from, to);
379 record_hugetlb_cgroup_uncharge_info(cg, h, map, nrg);
380 list_add(&nrg->link, rg);
381 coalesce_file_region(map, nrg);
383 *regions_needed += 1;
389 * Must be called with resv->lock held.
391 * Calling this with regions_needed != NULL will count the number of pages
392 * to be added but will not modify the linked list. And regions_needed will
393 * indicate the number of file_regions needed in the cache to carry out to add
394 * the regions for this range.
396 static long add_reservation_in_range(struct resv_map *resv, long f, long t,
397 struct hugetlb_cgroup *h_cg,
398 struct hstate *h, long *regions_needed)
401 struct list_head *head = &resv->regions;
402 long last_accounted_offset = f;
403 struct file_region *iter, *trg = NULL;
404 struct list_head *rg = NULL;
409 /* In this loop, we essentially handle an entry for the range
410 * [last_accounted_offset, iter->from), at every iteration, with some
413 list_for_each_entry_safe(iter, trg, head, link) {
414 /* Skip irrelevant regions that start before our range. */
415 if (iter->from < f) {
416 /* If this region ends after the last accounted offset,
417 * then we need to update last_accounted_offset.
419 if (iter->to > last_accounted_offset)
420 last_accounted_offset = iter->to;
424 /* When we find a region that starts beyond our range, we've
427 if (iter->from >= t) {
428 rg = iter->link.prev;
432 /* Add an entry for last_accounted_offset -> iter->from, and
433 * update last_accounted_offset.
435 if (iter->from > last_accounted_offset)
436 add += hugetlb_resv_map_add(resv, iter->link.prev,
437 last_accounted_offset,
441 last_accounted_offset = iter->to;
444 /* Handle the case where our range extends beyond
445 * last_accounted_offset.
449 if (last_accounted_offset < t)
450 add += hugetlb_resv_map_add(resv, rg, last_accounted_offset,
451 t, h, h_cg, regions_needed);
456 /* Must be called with resv->lock acquired. Will drop lock to allocate entries.
458 static int allocate_file_region_entries(struct resv_map *resv,
460 __must_hold(&resv->lock)
462 LIST_HEAD(allocated_regions);
463 int to_allocate = 0, i = 0;
464 struct file_region *trg = NULL, *rg = NULL;
466 VM_BUG_ON(regions_needed < 0);
469 * Check for sufficient descriptors in the cache to accommodate
470 * the number of in progress add operations plus regions_needed.
472 * This is a while loop because when we drop the lock, some other call
473 * to region_add or region_del may have consumed some region_entries,
474 * so we keep looping here until we finally have enough entries for
475 * (adds_in_progress + regions_needed).
477 while (resv->region_cache_count <
478 (resv->adds_in_progress + regions_needed)) {
479 to_allocate = resv->adds_in_progress + regions_needed -
480 resv->region_cache_count;
482 /* At this point, we should have enough entries in the cache
483 * for all the existing adds_in_progress. We should only be
484 * needing to allocate for regions_needed.
486 VM_BUG_ON(resv->region_cache_count < resv->adds_in_progress);
488 spin_unlock(&resv->lock);
489 for (i = 0; i < to_allocate; i++) {
490 trg = kmalloc(sizeof(*trg), GFP_KERNEL);
493 list_add(&trg->link, &allocated_regions);
496 spin_lock(&resv->lock);
498 list_splice(&allocated_regions, &resv->region_cache);
499 resv->region_cache_count += to_allocate;
505 list_for_each_entry_safe(rg, trg, &allocated_regions, link) {
513 * Add the huge page range represented by [f, t) to the reserve
514 * map. Regions will be taken from the cache to fill in this range.
515 * Sufficient regions should exist in the cache due to the previous
516 * call to region_chg with the same range, but in some cases the cache will not
517 * have sufficient entries due to races with other code doing region_add or
518 * region_del. The extra needed entries will be allocated.
520 * regions_needed is the out value provided by a previous call to region_chg.
522 * Return the number of new huge pages added to the map. This number is greater
523 * than or equal to zero. If file_region entries needed to be allocated for
524 * this operation and we were not able to allocate, it returns -ENOMEM.
525 * region_add of regions of length 1 never allocate file_regions and cannot
526 * fail; region_chg will always allocate at least 1 entry and a region_add for
527 * 1 page will only require at most 1 entry.
529 static long region_add(struct resv_map *resv, long f, long t,
530 long in_regions_needed, struct hstate *h,
531 struct hugetlb_cgroup *h_cg)
533 long add = 0, actual_regions_needed = 0;
535 spin_lock(&resv->lock);
538 /* Count how many regions are actually needed to execute this add. */
539 add_reservation_in_range(resv, f, t, NULL, NULL,
540 &actual_regions_needed);
543 * Check for sufficient descriptors in the cache to accommodate
544 * this add operation. Note that actual_regions_needed may be greater
545 * than in_regions_needed, as the resv_map may have been modified since
546 * the region_chg call. In this case, we need to make sure that we
547 * allocate extra entries, such that we have enough for all the
548 * existing adds_in_progress, plus the excess needed for this
551 if (actual_regions_needed > in_regions_needed &&
552 resv->region_cache_count <
553 resv->adds_in_progress +
554 (actual_regions_needed - in_regions_needed)) {
555 /* region_add operation of range 1 should never need to
556 * allocate file_region entries.
558 VM_BUG_ON(t - f <= 1);
560 if (allocate_file_region_entries(
561 resv, actual_regions_needed - in_regions_needed)) {
568 add = add_reservation_in_range(resv, f, t, h_cg, h, NULL);
570 resv->adds_in_progress -= in_regions_needed;
572 spin_unlock(&resv->lock);
577 * Examine the existing reserve map and determine how many
578 * huge pages in the specified range [f, t) are NOT currently
579 * represented. This routine is called before a subsequent
580 * call to region_add that will actually modify the reserve
581 * map to add the specified range [f, t). region_chg does
582 * not change the number of huge pages represented by the
583 * map. A number of new file_region structures is added to the cache as a
584 * placeholder, for the subsequent region_add call to use. At least 1
585 * file_region structure is added.
587 * out_regions_needed is the number of regions added to the
588 * resv->adds_in_progress. This value needs to be provided to a follow up call
589 * to region_add or region_abort for proper accounting.
591 * Returns the number of huge pages that need to be added to the existing
592 * reservation map for the range [f, t). This number is greater or equal to
593 * zero. -ENOMEM is returned if a new file_region structure or cache entry
594 * is needed and can not be allocated.
596 static long region_chg(struct resv_map *resv, long f, long t,
597 long *out_regions_needed)
601 spin_lock(&resv->lock);
603 /* Count how many hugepages in this range are NOT represented. */
604 chg = add_reservation_in_range(resv, f, t, NULL, NULL,
607 if (*out_regions_needed == 0)
608 *out_regions_needed = 1;
610 if (allocate_file_region_entries(resv, *out_regions_needed))
613 resv->adds_in_progress += *out_regions_needed;
615 spin_unlock(&resv->lock);
620 * Abort the in progress add operation. The adds_in_progress field
621 * of the resv_map keeps track of the operations in progress between
622 * calls to region_chg and region_add. Operations are sometimes
623 * aborted after the call to region_chg. In such cases, region_abort
624 * is called to decrement the adds_in_progress counter. regions_needed
625 * is the value returned by the region_chg call, it is used to decrement
626 * the adds_in_progress counter.
628 * NOTE: The range arguments [f, t) are not needed or used in this
629 * routine. They are kept to make reading the calling code easier as
630 * arguments will match the associated region_chg call.
632 static void region_abort(struct resv_map *resv, long f, long t,
635 spin_lock(&resv->lock);
636 VM_BUG_ON(!resv->region_cache_count);
637 resv->adds_in_progress -= regions_needed;
638 spin_unlock(&resv->lock);
642 * Delete the specified range [f, t) from the reserve map. If the
643 * t parameter is LONG_MAX, this indicates that ALL regions after f
644 * should be deleted. Locate the regions which intersect [f, t)
645 * and either trim, delete or split the existing regions.
647 * Returns the number of huge pages deleted from the reserve map.
648 * In the normal case, the return value is zero or more. In the
649 * case where a region must be split, a new region descriptor must
650 * be allocated. If the allocation fails, -ENOMEM will be returned.
651 * NOTE: If the parameter t == LONG_MAX, then we will never split
652 * a region and possibly return -ENOMEM. Callers specifying
653 * t == LONG_MAX do not need to check for -ENOMEM error.
655 static long region_del(struct resv_map *resv, long f, long t)
657 struct list_head *head = &resv->regions;
658 struct file_region *rg, *trg;
659 struct file_region *nrg = NULL;
663 spin_lock(&resv->lock);
664 list_for_each_entry_safe(rg, trg, head, link) {
666 * Skip regions before the range to be deleted. file_region
667 * ranges are normally of the form [from, to). However, there
668 * may be a "placeholder" entry in the map which is of the form
669 * (from, to) with from == to. Check for placeholder entries
670 * at the beginning of the range to be deleted.
672 if (rg->to <= f && (rg->to != rg->from || rg->to != f))
678 if (f > rg->from && t < rg->to) { /* Must split region */
680 * Check for an entry in the cache before dropping
681 * lock and attempting allocation.
684 resv->region_cache_count > resv->adds_in_progress) {
685 nrg = list_first_entry(&resv->region_cache,
688 list_del(&nrg->link);
689 resv->region_cache_count--;
693 spin_unlock(&resv->lock);
694 nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
701 hugetlb_cgroup_uncharge_file_region(
702 resv, rg, t - f, false);
704 /* New entry for end of split region */
708 copy_hugetlb_cgroup_uncharge_info(nrg, rg);
710 INIT_LIST_HEAD(&nrg->link);
712 /* Original entry is trimmed */
715 list_add(&nrg->link, &rg->link);
720 if (f <= rg->from && t >= rg->to) { /* Remove entire region */
721 del += rg->to - rg->from;
722 hugetlb_cgroup_uncharge_file_region(resv, rg,
723 rg->to - rg->from, true);
729 if (f <= rg->from) { /* Trim beginning of region */
730 hugetlb_cgroup_uncharge_file_region(resv, rg,
731 t - rg->from, false);
735 } else { /* Trim end of region */
736 hugetlb_cgroup_uncharge_file_region(resv, rg,
744 spin_unlock(&resv->lock);
750 * A rare out of memory error was encountered which prevented removal of
751 * the reserve map region for a page. The huge page itself was free'ed
752 * and removed from the page cache. This routine will adjust the subpool
753 * usage count, and the global reserve count if needed. By incrementing
754 * these counts, the reserve map entry which could not be deleted will
755 * appear as a "reserved" entry instead of simply dangling with incorrect
758 void hugetlb_fix_reserve_counts(struct inode *inode)
760 struct hugepage_subpool *spool = subpool_inode(inode);
762 bool reserved = false;
764 rsv_adjust = hugepage_subpool_get_pages(spool, 1);
765 if (rsv_adjust > 0) {
766 struct hstate *h = hstate_inode(inode);
768 if (!hugetlb_acct_memory(h, 1))
770 } else if (!rsv_adjust) {
775 pr_warn("hugetlb: Huge Page Reserved count may go negative.\n");
779 * Count and return the number of huge pages in the reserve map
780 * that intersect with the range [f, t).
782 static long region_count(struct resv_map *resv, long f, long t)
784 struct list_head *head = &resv->regions;
785 struct file_region *rg;
788 spin_lock(&resv->lock);
789 /* Locate each segment we overlap with, and count that overlap. */
790 list_for_each_entry(rg, head, link) {
799 seg_from = max(rg->from, f);
800 seg_to = min(rg->to, t);
802 chg += seg_to - seg_from;
804 spin_unlock(&resv->lock);
810 * Convert the address within this vma to the page offset within
811 * the mapping, in pagecache page units; huge pages here.
813 static pgoff_t vma_hugecache_offset(struct hstate *h,
814 struct vm_area_struct *vma, unsigned long address)
816 return ((address - vma->vm_start) >> huge_page_shift(h)) +
817 (vma->vm_pgoff >> huge_page_order(h));
820 pgoff_t linear_hugepage_index(struct vm_area_struct *vma,
821 unsigned long address)
823 return vma_hugecache_offset(hstate_vma(vma), vma, address);
825 EXPORT_SYMBOL_GPL(linear_hugepage_index);
828 * Return the size of the pages allocated when backing a VMA. In the majority
829 * cases this will be same size as used by the page table entries.
831 unsigned long vma_kernel_pagesize(struct vm_area_struct *vma)
833 if (vma->vm_ops && vma->vm_ops->pagesize)
834 return vma->vm_ops->pagesize(vma);
837 EXPORT_SYMBOL_GPL(vma_kernel_pagesize);
840 * Return the page size being used by the MMU to back a VMA. In the majority
841 * of cases, the page size used by the kernel matches the MMU size. On
842 * architectures where it differs, an architecture-specific 'strong'
843 * version of this symbol is required.
845 __weak unsigned long vma_mmu_pagesize(struct vm_area_struct *vma)
847 return vma_kernel_pagesize(vma);
851 * Flags for MAP_PRIVATE reservations. These are stored in the bottom
852 * bits of the reservation map pointer, which are always clear due to
855 #define HPAGE_RESV_OWNER (1UL << 0)
856 #define HPAGE_RESV_UNMAPPED (1UL << 1)
857 #define HPAGE_RESV_MASK (HPAGE_RESV_OWNER | HPAGE_RESV_UNMAPPED)
860 * These helpers are used to track how many pages are reserved for
861 * faults in a MAP_PRIVATE mapping. Only the process that called mmap()
862 * is guaranteed to have their future faults succeed.
864 * With the exception of hugetlb_dup_vma_private() which is called at fork(),
865 * the reserve counters are updated with the hugetlb_lock held. It is safe
866 * to reset the VMA at fork() time as it is not in use yet and there is no
867 * chance of the global counters getting corrupted as a result of the values.
869 * The private mapping reservation is represented in a subtly different
870 * manner to a shared mapping. A shared mapping has a region map associated
871 * with the underlying file, this region map represents the backing file
872 * pages which have ever had a reservation assigned which this persists even
873 * after the page is instantiated. A private mapping has a region map
874 * associated with the original mmap which is attached to all VMAs which
875 * reference it, this region map represents those offsets which have consumed
876 * reservation ie. where pages have been instantiated.
878 static unsigned long get_vma_private_data(struct vm_area_struct *vma)
880 return (unsigned long)vma->vm_private_data;
883 static void set_vma_private_data(struct vm_area_struct *vma,
886 vma->vm_private_data = (void *)value;
890 resv_map_set_hugetlb_cgroup_uncharge_info(struct resv_map *resv_map,
891 struct hugetlb_cgroup *h_cg,
894 #ifdef CONFIG_CGROUP_HUGETLB
896 resv_map->reservation_counter = NULL;
897 resv_map->pages_per_hpage = 0;
898 resv_map->css = NULL;
900 resv_map->reservation_counter =
901 &h_cg->rsvd_hugepage[hstate_index(h)];
902 resv_map->pages_per_hpage = pages_per_huge_page(h);
903 resv_map->css = &h_cg->css;
908 struct resv_map *resv_map_alloc(void)
910 struct resv_map *resv_map = kmalloc(sizeof(*resv_map), GFP_KERNEL);
911 struct file_region *rg = kmalloc(sizeof(*rg), GFP_KERNEL);
913 if (!resv_map || !rg) {
919 kref_init(&resv_map->refs);
920 spin_lock_init(&resv_map->lock);
921 INIT_LIST_HEAD(&resv_map->regions);
923 resv_map->adds_in_progress = 0;
925 * Initialize these to 0. On shared mappings, 0's here indicate these
926 * fields don't do cgroup accounting. On private mappings, these will be
927 * re-initialized to the proper values, to indicate that hugetlb cgroup
928 * reservations are to be un-charged from here.
930 resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, NULL, NULL);
932 INIT_LIST_HEAD(&resv_map->region_cache);
933 list_add(&rg->link, &resv_map->region_cache);
934 resv_map->region_cache_count = 1;
939 void resv_map_release(struct kref *ref)
941 struct resv_map *resv_map = container_of(ref, struct resv_map, refs);
942 struct list_head *head = &resv_map->region_cache;
943 struct file_region *rg, *trg;
945 /* Clear out any active regions before we release the map. */
946 region_del(resv_map, 0, LONG_MAX);
948 /* ... and any entries left in the cache */
949 list_for_each_entry_safe(rg, trg, head, link) {
954 VM_BUG_ON(resv_map->adds_in_progress);
959 static inline struct resv_map *inode_resv_map(struct inode *inode)
962 * At inode evict time, i_mapping may not point to the original
963 * address space within the inode. This original address space
964 * contains the pointer to the resv_map. So, always use the
965 * address space embedded within the inode.
966 * The VERY common case is inode->mapping == &inode->i_data but,
967 * this may not be true for device special inodes.
969 return (struct resv_map *)(&inode->i_data)->private_data;
972 static struct resv_map *vma_resv_map(struct vm_area_struct *vma)
974 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
975 if (vma->vm_flags & VM_MAYSHARE) {
976 struct address_space *mapping = vma->vm_file->f_mapping;
977 struct inode *inode = mapping->host;
979 return inode_resv_map(inode);
982 return (struct resv_map *)(get_vma_private_data(vma) &
987 static void set_vma_resv_map(struct vm_area_struct *vma, struct resv_map *map)
989 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
990 VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
992 set_vma_private_data(vma, (get_vma_private_data(vma) &
993 HPAGE_RESV_MASK) | (unsigned long)map);
996 static void set_vma_resv_flags(struct vm_area_struct *vma, unsigned long flags)
998 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
999 VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
1001 set_vma_private_data(vma, get_vma_private_data(vma) | flags);
1004 static int is_vma_resv_set(struct vm_area_struct *vma, unsigned long flag)
1006 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
1008 return (get_vma_private_data(vma) & flag) != 0;
1011 void hugetlb_dup_vma_private(struct vm_area_struct *vma)
1013 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
1015 * Clear vm_private_data
1016 * - For MAP_PRIVATE mappings, this is the reserve map which does
1017 * not apply to children. Faults generated by the children are
1018 * not guaranteed to succeed, even if read-only.
1019 * - For shared mappings this is a per-vma semaphore that may be
1020 * allocated in a subsequent call to hugetlb_vm_op_open.
1022 vma->vm_private_data = (void *)0;
1023 if (!(vma->vm_flags & VM_MAYSHARE))
1028 * Reset and decrement one ref on hugepage private reservation.
1029 * Called with mm->mmap_sem writer semaphore held.
1030 * This function should be only used by move_vma() and operate on
1031 * same sized vma. It should never come here with last ref on the
1034 void clear_vma_resv_huge_pages(struct vm_area_struct *vma)
1037 * Clear the old hugetlb private page reservation.
1038 * It has already been transferred to new_vma.
1040 * During a mremap() operation of a hugetlb vma we call move_vma()
1041 * which copies vma into new_vma and unmaps vma. After the copy
1042 * operation both new_vma and vma share a reference to the resv_map
1043 * struct, and at that point vma is about to be unmapped. We don't
1044 * want to return the reservation to the pool at unmap of vma because
1045 * the reservation still lives on in new_vma, so simply decrement the
1046 * ref here and remove the resv_map reference from this vma.
1048 struct resv_map *reservations = vma_resv_map(vma);
1050 if (reservations && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
1051 resv_map_put_hugetlb_cgroup_uncharge_info(reservations);
1052 kref_put(&reservations->refs, resv_map_release);
1055 hugetlb_dup_vma_private(vma);
1058 /* Returns true if the VMA has associated reserve pages */
1059 static bool vma_has_reserves(struct vm_area_struct *vma, long chg)
1061 if (vma->vm_flags & VM_NORESERVE) {
1063 * This address is already reserved by other process(chg == 0),
1064 * so, we should decrement reserved count. Without decrementing,
1065 * reserve count remains after releasing inode, because this
1066 * allocated page will go into page cache and is regarded as
1067 * coming from reserved pool in releasing step. Currently, we
1068 * don't have any other solution to deal with this situation
1069 * properly, so add work-around here.
1071 if (vma->vm_flags & VM_MAYSHARE && chg == 0)
1077 /* Shared mappings always use reserves */
1078 if (vma->vm_flags & VM_MAYSHARE) {
1080 * We know VM_NORESERVE is not set. Therefore, there SHOULD
1081 * be a region map for all pages. The only situation where
1082 * there is no region map is if a hole was punched via
1083 * fallocate. In this case, there really are no reserves to
1084 * use. This situation is indicated if chg != 0.
1093 * Only the process that called mmap() has reserves for
1096 if (is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
1098 * Like the shared case above, a hole punch or truncate
1099 * could have been performed on the private mapping.
1100 * Examine the value of chg to determine if reserves
1101 * actually exist or were previously consumed.
1102 * Very Subtle - The value of chg comes from a previous
1103 * call to vma_needs_reserves(). The reserve map for
1104 * private mappings has different (opposite) semantics
1105 * than that of shared mappings. vma_needs_reserves()
1106 * has already taken this difference in semantics into
1107 * account. Therefore, the meaning of chg is the same
1108 * as in the shared case above. Code could easily be
1109 * combined, but keeping it separate draws attention to
1110 * subtle differences.
1121 static void enqueue_huge_page(struct hstate *h, struct page *page)
1123 int nid = page_to_nid(page);
1125 lockdep_assert_held(&hugetlb_lock);
1126 VM_BUG_ON_PAGE(page_count(page), page);
1128 list_move(&page->lru, &h->hugepage_freelists[nid]);
1129 h->free_huge_pages++;
1130 h->free_huge_pages_node[nid]++;
1131 SetHPageFreed(page);
1134 static struct page *dequeue_huge_page_node_exact(struct hstate *h, int nid)
1137 bool pin = !!(current->flags & PF_MEMALLOC_PIN);
1139 lockdep_assert_held(&hugetlb_lock);
1140 list_for_each_entry(page, &h->hugepage_freelists[nid], lru) {
1141 if (pin && !is_longterm_pinnable_page(page))
1144 if (PageHWPoison(page))
1147 list_move(&page->lru, &h->hugepage_activelist);
1148 set_page_refcounted(page);
1149 ClearHPageFreed(page);
1150 h->free_huge_pages--;
1151 h->free_huge_pages_node[nid]--;
1158 static struct page *dequeue_huge_page_nodemask(struct hstate *h, gfp_t gfp_mask, int nid,
1161 unsigned int cpuset_mems_cookie;
1162 struct zonelist *zonelist;
1165 int node = NUMA_NO_NODE;
1167 zonelist = node_zonelist(nid, gfp_mask);
1170 cpuset_mems_cookie = read_mems_allowed_begin();
1171 for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nmask) {
1174 if (!cpuset_zone_allowed(zone, gfp_mask))
1177 * no need to ask again on the same node. Pool is node rather than
1180 if (zone_to_nid(zone) == node)
1182 node = zone_to_nid(zone);
1184 page = dequeue_huge_page_node_exact(h, node);
1188 if (unlikely(read_mems_allowed_retry(cpuset_mems_cookie)))
1194 static unsigned long available_huge_pages(struct hstate *h)
1196 return h->free_huge_pages - h->resv_huge_pages;
1199 static struct page *dequeue_huge_page_vma(struct hstate *h,
1200 struct vm_area_struct *vma,
1201 unsigned long address, int avoid_reserve,
1204 struct page *page = NULL;
1205 struct mempolicy *mpol;
1207 nodemask_t *nodemask;
1211 * A child process with MAP_PRIVATE mappings created by their parent
1212 * have no page reserves. This check ensures that reservations are
1213 * not "stolen". The child may still get SIGKILLed
1215 if (!vma_has_reserves(vma, chg) && !available_huge_pages(h))
1218 /* If reserves cannot be used, ensure enough pages are in the pool */
1219 if (avoid_reserve && !available_huge_pages(h))
1222 gfp_mask = htlb_alloc_mask(h);
1223 nid = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
1225 if (mpol_is_preferred_many(mpol)) {
1226 page = dequeue_huge_page_nodemask(h, gfp_mask, nid, nodemask);
1228 /* Fallback to all nodes if page==NULL */
1233 page = dequeue_huge_page_nodemask(h, gfp_mask, nid, nodemask);
1235 if (page && !avoid_reserve && vma_has_reserves(vma, chg)) {
1236 SetHPageRestoreReserve(page);
1237 h->resv_huge_pages--;
1240 mpol_cond_put(mpol);
1248 * common helper functions for hstate_next_node_to_{alloc|free}.
1249 * We may have allocated or freed a huge page based on a different
1250 * nodes_allowed previously, so h->next_node_to_{alloc|free} might
1251 * be outside of *nodes_allowed. Ensure that we use an allowed
1252 * node for alloc or free.
1254 static int next_node_allowed(int nid, nodemask_t *nodes_allowed)
1256 nid = next_node_in(nid, *nodes_allowed);
1257 VM_BUG_ON(nid >= MAX_NUMNODES);
1262 static int get_valid_node_allowed(int nid, nodemask_t *nodes_allowed)
1264 if (!node_isset(nid, *nodes_allowed))
1265 nid = next_node_allowed(nid, nodes_allowed);
1270 * returns the previously saved node ["this node"] from which to
1271 * allocate a persistent huge page for the pool and advance the
1272 * next node from which to allocate, handling wrap at end of node
1275 static int hstate_next_node_to_alloc(struct hstate *h,
1276 nodemask_t *nodes_allowed)
1280 VM_BUG_ON(!nodes_allowed);
1282 nid = get_valid_node_allowed(h->next_nid_to_alloc, nodes_allowed);
1283 h->next_nid_to_alloc = next_node_allowed(nid, nodes_allowed);
1289 * helper for remove_pool_huge_page() - return the previously saved
1290 * node ["this node"] from which to free a huge page. Advance the
1291 * next node id whether or not we find a free huge page to free so
1292 * that the next attempt to free addresses the next node.
1294 static int hstate_next_node_to_free(struct hstate *h, nodemask_t *nodes_allowed)
1298 VM_BUG_ON(!nodes_allowed);
1300 nid = get_valid_node_allowed(h->next_nid_to_free, nodes_allowed);
1301 h->next_nid_to_free = next_node_allowed(nid, nodes_allowed);
1306 #define for_each_node_mask_to_alloc(hs, nr_nodes, node, mask) \
1307 for (nr_nodes = nodes_weight(*mask); \
1309 ((node = hstate_next_node_to_alloc(hs, mask)) || 1); \
1312 #define for_each_node_mask_to_free(hs, nr_nodes, node, mask) \
1313 for (nr_nodes = nodes_weight(*mask); \
1315 ((node = hstate_next_node_to_free(hs, mask)) || 1); \
1318 /* used to demote non-gigantic_huge pages as well */
1319 static void __destroy_compound_gigantic_page(struct page *page,
1320 unsigned int order, bool demote)
1323 int nr_pages = 1 << order;
1326 atomic_set(compound_mapcount_ptr(page), 0);
1327 atomic_set(compound_pincount_ptr(page), 0);
1329 for (i = 1; i < nr_pages; i++) {
1330 p = nth_page(page, i);
1332 clear_compound_head(p);
1334 set_page_refcounted(p);
1337 set_compound_order(page, 0);
1339 page[1].compound_nr = 0;
1341 __ClearPageHead(page);
1344 static void destroy_compound_hugetlb_page_for_demote(struct page *page,
1347 __destroy_compound_gigantic_page(page, order, true);
1350 #ifdef CONFIG_ARCH_HAS_GIGANTIC_PAGE
1351 static void destroy_compound_gigantic_page(struct page *page,
1354 __destroy_compound_gigantic_page(page, order, false);
1357 static void free_gigantic_page(struct page *page, unsigned int order)
1360 * If the page isn't allocated using the cma allocator,
1361 * cma_release() returns false.
1364 if (cma_release(hugetlb_cma[page_to_nid(page)], page, 1 << order))
1368 free_contig_range(page_to_pfn(page), 1 << order);
1371 #ifdef CONFIG_CONTIG_ALLOC
1372 static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
1373 int nid, nodemask_t *nodemask)
1375 unsigned long nr_pages = pages_per_huge_page(h);
1376 if (nid == NUMA_NO_NODE)
1377 nid = numa_mem_id();
1384 if (hugetlb_cma[nid]) {
1385 page = cma_alloc(hugetlb_cma[nid], nr_pages,
1386 huge_page_order(h), true);
1391 if (!(gfp_mask & __GFP_THISNODE)) {
1392 for_each_node_mask(node, *nodemask) {
1393 if (node == nid || !hugetlb_cma[node])
1396 page = cma_alloc(hugetlb_cma[node], nr_pages,
1397 huge_page_order(h), true);
1405 return alloc_contig_pages(nr_pages, gfp_mask, nid, nodemask);
1408 #else /* !CONFIG_CONTIG_ALLOC */
1409 static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
1410 int nid, nodemask_t *nodemask)
1414 #endif /* CONFIG_CONTIG_ALLOC */
1416 #else /* !CONFIG_ARCH_HAS_GIGANTIC_PAGE */
1417 static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
1418 int nid, nodemask_t *nodemask)
1422 static inline void free_gigantic_page(struct page *page, unsigned int order) { }
1423 static inline void destroy_compound_gigantic_page(struct page *page,
1424 unsigned int order) { }
1428 * Remove hugetlb page from lists, and update dtor so that page appears
1429 * as just a compound page.
1431 * A reference is held on the page, except in the case of demote.
1433 * Must be called with hugetlb lock held.
1435 static void __remove_hugetlb_page(struct hstate *h, struct page *page,
1436 bool adjust_surplus,
1439 int nid = page_to_nid(page);
1441 VM_BUG_ON_PAGE(hugetlb_cgroup_from_page(page), page);
1442 VM_BUG_ON_PAGE(hugetlb_cgroup_from_page_rsvd(page), page);
1444 lockdep_assert_held(&hugetlb_lock);
1445 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
1448 list_del(&page->lru);
1450 if (HPageFreed(page)) {
1451 h->free_huge_pages--;
1452 h->free_huge_pages_node[nid]--;
1454 if (adjust_surplus) {
1455 h->surplus_huge_pages--;
1456 h->surplus_huge_pages_node[nid]--;
1462 * For non-gigantic pages set the destructor to the normal compound
1463 * page dtor. This is needed in case someone takes an additional
1464 * temporary ref to the page, and freeing is delayed until they drop
1467 * For gigantic pages set the destructor to the null dtor. This
1468 * destructor will never be called. Before freeing the gigantic
1469 * page destroy_compound_gigantic_page will turn the compound page
1470 * into a simple group of pages. After this the destructor does not
1473 * This handles the case where more than one ref is held when and
1474 * after update_and_free_page is called.
1476 * In the case of demote we do not ref count the page as it will soon
1477 * be turned into a page of smaller size.
1480 set_page_refcounted(page);
1481 if (hstate_is_gigantic(h))
1482 set_compound_page_dtor(page, NULL_COMPOUND_DTOR);
1484 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
1487 h->nr_huge_pages_node[nid]--;
1490 static void remove_hugetlb_page(struct hstate *h, struct page *page,
1491 bool adjust_surplus)
1493 __remove_hugetlb_page(h, page, adjust_surplus, false);
1496 static void remove_hugetlb_page_for_demote(struct hstate *h, struct page *page,
1497 bool adjust_surplus)
1499 __remove_hugetlb_page(h, page, adjust_surplus, true);
1502 static void add_hugetlb_page(struct hstate *h, struct page *page,
1503 bool adjust_surplus)
1506 int nid = page_to_nid(page);
1508 VM_BUG_ON_PAGE(!HPageVmemmapOptimized(page), page);
1510 lockdep_assert_held(&hugetlb_lock);
1512 INIT_LIST_HEAD(&page->lru);
1514 h->nr_huge_pages_node[nid]++;
1516 if (adjust_surplus) {
1517 h->surplus_huge_pages++;
1518 h->surplus_huge_pages_node[nid]++;
1521 set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
1522 set_page_private(page, 0);
1524 * We have to set HPageVmemmapOptimized again as above
1525 * set_page_private(page, 0) cleared it.
1527 SetHPageVmemmapOptimized(page);
1530 * This page is about to be managed by the hugetlb allocator and
1531 * should have no users. Drop our reference, and check for others
1534 zeroed = put_page_testzero(page);
1537 * It is VERY unlikely soneone else has taken a ref on
1538 * the page. In this case, we simply return as the
1539 * hugetlb destructor (free_huge_page) will be called
1540 * when this other ref is dropped.
1544 arch_clear_hugepage_flags(page);
1545 enqueue_huge_page(h, page);
1548 static void __update_and_free_page(struct hstate *h, struct page *page)
1551 struct page *subpage;
1553 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
1557 * If we don't know which subpages are hwpoisoned, we can't free
1558 * the hugepage, so it's leaked intentionally.
1560 if (HPageRawHwpUnreliable(page))
1563 if (hugetlb_vmemmap_restore(h, page)) {
1564 spin_lock_irq(&hugetlb_lock);
1566 * If we cannot allocate vmemmap pages, just refuse to free the
1567 * page and put the page back on the hugetlb free list and treat
1568 * as a surplus page.
1570 add_hugetlb_page(h, page, true);
1571 spin_unlock_irq(&hugetlb_lock);
1576 * Move PageHWPoison flag from head page to the raw error pages,
1577 * which makes any healthy subpages reusable.
1579 if (unlikely(PageHWPoison(page)))
1580 hugetlb_clear_page_hwpoison(page);
1582 for (i = 0; i < pages_per_huge_page(h); i++) {
1583 subpage = nth_page(page, i);
1584 subpage->flags &= ~(1 << PG_locked | 1 << PG_error |
1585 1 << PG_referenced | 1 << PG_dirty |
1586 1 << PG_active | 1 << PG_private |
1591 * Non-gigantic pages demoted from CMA allocated gigantic pages
1592 * need to be given back to CMA in free_gigantic_page.
1594 if (hstate_is_gigantic(h) ||
1595 hugetlb_cma_page(page, huge_page_order(h))) {
1596 destroy_compound_gigantic_page(page, huge_page_order(h));
1597 free_gigantic_page(page, huge_page_order(h));
1599 __free_pages(page, huge_page_order(h));
1604 * As update_and_free_page() can be called under any context, so we cannot
1605 * use GFP_KERNEL to allocate vmemmap pages. However, we can defer the
1606 * actual freeing in a workqueue to prevent from using GFP_ATOMIC to allocate
1607 * the vmemmap pages.
1609 * free_hpage_workfn() locklessly retrieves the linked list of pages to be
1610 * freed and frees them one-by-one. As the page->mapping pointer is going
1611 * to be cleared in free_hpage_workfn() anyway, it is reused as the llist_node
1612 * structure of a lockless linked list of huge pages to be freed.
1614 static LLIST_HEAD(hpage_freelist);
1616 static void free_hpage_workfn(struct work_struct *work)
1618 struct llist_node *node;
1620 node = llist_del_all(&hpage_freelist);
1626 page = container_of((struct address_space **)node,
1627 struct page, mapping);
1629 page->mapping = NULL;
1631 * The VM_BUG_ON_PAGE(!PageHuge(page), page) in page_hstate()
1632 * is going to trigger because a previous call to
1633 * remove_hugetlb_page() will set_compound_page_dtor(page,
1634 * NULL_COMPOUND_DTOR), so do not use page_hstate() directly.
1636 h = size_to_hstate(page_size(page));
1638 __update_and_free_page(h, page);
1643 static DECLARE_WORK(free_hpage_work, free_hpage_workfn);
1645 static inline void flush_free_hpage_work(struct hstate *h)
1647 if (hugetlb_vmemmap_optimizable(h))
1648 flush_work(&free_hpage_work);
1651 static void update_and_free_page(struct hstate *h, struct page *page,
1654 if (!HPageVmemmapOptimized(page) || !atomic) {
1655 __update_and_free_page(h, page);
1660 * Defer freeing to avoid using GFP_ATOMIC to allocate vmemmap pages.
1662 * Only call schedule_work() if hpage_freelist is previously
1663 * empty. Otherwise, schedule_work() had been called but the workfn
1664 * hasn't retrieved the list yet.
1666 if (llist_add((struct llist_node *)&page->mapping, &hpage_freelist))
1667 schedule_work(&free_hpage_work);
1670 static void update_and_free_pages_bulk(struct hstate *h, struct list_head *list)
1672 struct page *page, *t_page;
1674 list_for_each_entry_safe(page, t_page, list, lru) {
1675 update_and_free_page(h, page, false);
1680 struct hstate *size_to_hstate(unsigned long size)
1684 for_each_hstate(h) {
1685 if (huge_page_size(h) == size)
1691 void free_huge_page(struct page *page)
1694 * Can't pass hstate in here because it is called from the
1695 * compound page destructor.
1697 struct hstate *h = page_hstate(page);
1698 int nid = page_to_nid(page);
1699 struct hugepage_subpool *spool = hugetlb_page_subpool(page);
1700 bool restore_reserve;
1701 unsigned long flags;
1703 VM_BUG_ON_PAGE(page_count(page), page);
1704 VM_BUG_ON_PAGE(page_mapcount(page), page);
1706 hugetlb_set_page_subpool(page, NULL);
1708 __ClearPageAnonExclusive(page);
1709 page->mapping = NULL;
1710 restore_reserve = HPageRestoreReserve(page);
1711 ClearHPageRestoreReserve(page);
1714 * If HPageRestoreReserve was set on page, page allocation consumed a
1715 * reservation. If the page was associated with a subpool, there
1716 * would have been a page reserved in the subpool before allocation
1717 * via hugepage_subpool_get_pages(). Since we are 'restoring' the
1718 * reservation, do not call hugepage_subpool_put_pages() as this will
1719 * remove the reserved page from the subpool.
1721 if (!restore_reserve) {
1723 * A return code of zero implies that the subpool will be
1724 * under its minimum size if the reservation is not restored
1725 * after page is free. Therefore, force restore_reserve
1728 if (hugepage_subpool_put_pages(spool, 1) == 0)
1729 restore_reserve = true;
1732 spin_lock_irqsave(&hugetlb_lock, flags);
1733 ClearHPageMigratable(page);
1734 hugetlb_cgroup_uncharge_page(hstate_index(h),
1735 pages_per_huge_page(h), page);
1736 hugetlb_cgroup_uncharge_page_rsvd(hstate_index(h),
1737 pages_per_huge_page(h), page);
1738 if (restore_reserve)
1739 h->resv_huge_pages++;
1741 if (HPageTemporary(page)) {
1742 remove_hugetlb_page(h, page, false);
1743 spin_unlock_irqrestore(&hugetlb_lock, flags);
1744 update_and_free_page(h, page, true);
1745 } else if (h->surplus_huge_pages_node[nid]) {
1746 /* remove the page from active list */
1747 remove_hugetlb_page(h, page, true);
1748 spin_unlock_irqrestore(&hugetlb_lock, flags);
1749 update_and_free_page(h, page, true);
1751 arch_clear_hugepage_flags(page);
1752 enqueue_huge_page(h, page);
1753 spin_unlock_irqrestore(&hugetlb_lock, flags);
1758 * Must be called with the hugetlb lock held
1760 static void __prep_account_new_huge_page(struct hstate *h, int nid)
1762 lockdep_assert_held(&hugetlb_lock);
1764 h->nr_huge_pages_node[nid]++;
1767 static void __prep_new_huge_page(struct hstate *h, struct page *page)
1769 hugetlb_vmemmap_optimize(h, page);
1770 INIT_LIST_HEAD(&page->lru);
1771 set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
1772 hugetlb_set_page_subpool(page, NULL);
1773 set_hugetlb_cgroup(page, NULL);
1774 set_hugetlb_cgroup_rsvd(page, NULL);
1777 static void prep_new_huge_page(struct hstate *h, struct page *page, int nid)
1779 __prep_new_huge_page(h, page);
1780 spin_lock_irq(&hugetlb_lock);
1781 __prep_account_new_huge_page(h, nid);
1782 spin_unlock_irq(&hugetlb_lock);
1785 static bool __prep_compound_gigantic_page(struct page *page, unsigned int order,
1789 int nr_pages = 1 << order;
1792 /* we rely on prep_new_huge_page to set the destructor */
1793 set_compound_order(page, order);
1794 __SetPageHead(page);
1795 for (i = 0; i < nr_pages; i++) {
1796 p = nth_page(page, i);
1799 * For gigantic hugepages allocated through bootmem at
1800 * boot, it's safer to be consistent with the not-gigantic
1801 * hugepages and clear the PG_reserved bit from all tail pages
1802 * too. Otherwise drivers using get_user_pages() to access tail
1803 * pages may get the reference counting wrong if they see
1804 * PG_reserved set on a tail page (despite the head page not
1805 * having PG_reserved set). Enforcing this consistency between
1806 * head and tail pages allows drivers to optimize away a check
1807 * on the head page when they need know if put_page() is needed
1808 * after get_user_pages().
1810 __ClearPageReserved(p);
1812 * Subtle and very unlikely
1814 * Gigantic 'page allocators' such as memblock or cma will
1815 * return a set of pages with each page ref counted. We need
1816 * to turn this set of pages into a compound page with tail
1817 * page ref counts set to zero. Code such as speculative page
1818 * cache adding could take a ref on a 'to be' tail page.
1819 * We need to respect any increased ref count, and only set
1820 * the ref count to zero if count is currently 1. If count
1821 * is not 1, we return an error. An error return indicates
1822 * the set of pages can not be converted to a gigantic page.
1823 * The caller who allocated the pages should then discard the
1824 * pages using the appropriate free interface.
1826 * In the case of demote, the ref count will be zero.
1829 if (!page_ref_freeze(p, 1)) {
1830 pr_warn("HugeTLB page can not be used due to unexpected inflated ref count\n");
1834 VM_BUG_ON_PAGE(page_count(p), p);
1837 set_compound_head(p, page);
1839 atomic_set(compound_mapcount_ptr(page), -1);
1840 atomic_set(compound_pincount_ptr(page), 0);
1844 /* undo page modifications made above */
1845 for (j = 0; j < i; j++) {
1846 p = nth_page(page, j);
1848 clear_compound_head(p);
1849 set_page_refcounted(p);
1851 /* need to clear PG_reserved on remaining tail pages */
1852 for (; j < nr_pages; j++) {
1853 p = nth_page(page, j);
1854 __ClearPageReserved(p);
1856 set_compound_order(page, 0);
1858 page[1].compound_nr = 0;
1860 __ClearPageHead(page);
1864 static bool prep_compound_gigantic_page(struct page *page, unsigned int order)
1866 return __prep_compound_gigantic_page(page, order, false);
1869 static bool prep_compound_gigantic_page_for_demote(struct page *page,
1872 return __prep_compound_gigantic_page(page, order, true);
1876 * PageHuge() only returns true for hugetlbfs pages, but not for normal or
1877 * transparent huge pages. See the PageTransHuge() documentation for more
1880 int PageHuge(struct page *page)
1882 if (!PageCompound(page))
1885 page = compound_head(page);
1886 return page[1].compound_dtor == HUGETLB_PAGE_DTOR;
1888 EXPORT_SYMBOL_GPL(PageHuge);
1891 * PageHeadHuge() only returns true for hugetlbfs head page, but not for
1892 * normal or transparent huge pages.
1894 int PageHeadHuge(struct page *page_head)
1896 if (!PageHead(page_head))
1899 return page_head[1].compound_dtor == HUGETLB_PAGE_DTOR;
1901 EXPORT_SYMBOL_GPL(PageHeadHuge);
1904 * Find and lock address space (mapping) in write mode.
1906 * Upon entry, the page is locked which means that page_mapping() is
1907 * stable. Due to locking order, we can only trylock_write. If we can
1908 * not get the lock, simply return NULL to caller.
1910 struct address_space *hugetlb_page_mapping_lock_write(struct page *hpage)
1912 struct address_space *mapping = page_mapping(hpage);
1917 if (i_mmap_trylock_write(mapping))
1923 pgoff_t hugetlb_basepage_index(struct page *page)
1925 struct page *page_head = compound_head(page);
1926 pgoff_t index = page_index(page_head);
1927 unsigned long compound_idx;
1929 if (compound_order(page_head) >= MAX_ORDER)
1930 compound_idx = page_to_pfn(page) - page_to_pfn(page_head);
1932 compound_idx = page - page_head;
1934 return (index << compound_order(page_head)) + compound_idx;
1937 static struct page *alloc_buddy_huge_page(struct hstate *h,
1938 gfp_t gfp_mask, int nid, nodemask_t *nmask,
1939 nodemask_t *node_alloc_noretry)
1941 int order = huge_page_order(h);
1943 bool alloc_try_hard = true;
1947 * By default we always try hard to allocate the page with
1948 * __GFP_RETRY_MAYFAIL flag. However, if we are allocating pages in
1949 * a loop (to adjust global huge page counts) and previous allocation
1950 * failed, do not continue to try hard on the same node. Use the
1951 * node_alloc_noretry bitmap to manage this state information.
1953 if (node_alloc_noretry && node_isset(nid, *node_alloc_noretry))
1954 alloc_try_hard = false;
1955 gfp_mask |= __GFP_COMP|__GFP_NOWARN;
1957 gfp_mask |= __GFP_RETRY_MAYFAIL;
1958 if (nid == NUMA_NO_NODE)
1959 nid = numa_mem_id();
1961 page = __alloc_pages(gfp_mask, order, nid, nmask);
1963 /* Freeze head page */
1964 if (page && !page_ref_freeze(page, 1)) {
1965 __free_pages(page, order);
1966 if (retry) { /* retry once */
1970 /* WOW! twice in a row. */
1971 pr_warn("HugeTLB head page unexpected inflated ref count\n");
1976 __count_vm_event(HTLB_BUDDY_PGALLOC);
1978 __count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
1981 * If we did not specify __GFP_RETRY_MAYFAIL, but still got a page this
1982 * indicates an overall state change. Clear bit so that we resume
1983 * normal 'try hard' allocations.
1985 if (node_alloc_noretry && page && !alloc_try_hard)
1986 node_clear(nid, *node_alloc_noretry);
1989 * If we tried hard to get a page but failed, set bit so that
1990 * subsequent attempts will not try as hard until there is an
1991 * overall state change.
1993 if (node_alloc_noretry && !page && alloc_try_hard)
1994 node_set(nid, *node_alloc_noretry);
2000 * Common helper to allocate a fresh hugetlb page. All specific allocators
2001 * should use this function to get new hugetlb pages
2003 * Note that returned page is 'frozen': ref count of head page and all tail
2006 static struct page *alloc_fresh_huge_page(struct hstate *h,
2007 gfp_t gfp_mask, int nid, nodemask_t *nmask,
2008 nodemask_t *node_alloc_noretry)
2014 if (hstate_is_gigantic(h))
2015 page = alloc_gigantic_page(h, gfp_mask, nid, nmask);
2017 page = alloc_buddy_huge_page(h, gfp_mask,
2018 nid, nmask, node_alloc_noretry);
2022 if (hstate_is_gigantic(h)) {
2023 if (!prep_compound_gigantic_page(page, huge_page_order(h))) {
2025 * Rare failure to convert pages to compound page.
2026 * Free pages and try again - ONCE!
2028 free_gigantic_page(page, huge_page_order(h));
2036 prep_new_huge_page(h, page, page_to_nid(page));
2042 * Allocates a fresh page to the hugetlb allocator pool in the node interleaved
2045 static int alloc_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed,
2046 nodemask_t *node_alloc_noretry)
2050 gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
2052 for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
2053 page = alloc_fresh_huge_page(h, gfp_mask, node, nodes_allowed,
2054 node_alloc_noretry);
2062 free_huge_page(page); /* free it into the hugepage allocator */
2068 * Remove huge page from pool from next node to free. Attempt to keep
2069 * persistent huge pages more or less balanced over allowed nodes.
2070 * This routine only 'removes' the hugetlb page. The caller must make
2071 * an additional call to free the page to low level allocators.
2072 * Called with hugetlb_lock locked.
2074 static struct page *remove_pool_huge_page(struct hstate *h,
2075 nodemask_t *nodes_allowed,
2079 struct page *page = NULL;
2081 lockdep_assert_held(&hugetlb_lock);
2082 for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
2084 * If we're returning unused surplus pages, only examine
2085 * nodes with surplus pages.
2087 if ((!acct_surplus || h->surplus_huge_pages_node[node]) &&
2088 !list_empty(&h->hugepage_freelists[node])) {
2089 page = list_entry(h->hugepage_freelists[node].next,
2091 remove_hugetlb_page(h, page, acct_surplus);
2100 * Dissolve a given free hugepage into free buddy pages. This function does
2101 * nothing for in-use hugepages and non-hugepages.
2102 * This function returns values like below:
2104 * -ENOMEM: failed to allocate vmemmap pages to free the freed hugepages
2105 * when the system is under memory pressure and the feature of
2106 * freeing unused vmemmap pages associated with each hugetlb page
2108 * -EBUSY: failed to dissolved free hugepages or the hugepage is in-use
2109 * (allocated or reserved.)
2110 * 0: successfully dissolved free hugepages or the page is not a
2111 * hugepage (considered as already dissolved)
2113 int dissolve_free_huge_page(struct page *page)
2118 /* Not to disrupt normal path by vainly holding hugetlb_lock */
2119 if (!PageHuge(page))
2122 spin_lock_irq(&hugetlb_lock);
2123 if (!PageHuge(page)) {
2128 if (!page_count(page)) {
2129 struct page *head = compound_head(page);
2130 struct hstate *h = page_hstate(head);
2131 if (!available_huge_pages(h))
2135 * We should make sure that the page is already on the free list
2136 * when it is dissolved.
2138 if (unlikely(!HPageFreed(head))) {
2139 spin_unlock_irq(&hugetlb_lock);
2143 * Theoretically, we should return -EBUSY when we
2144 * encounter this race. In fact, we have a chance
2145 * to successfully dissolve the page if we do a
2146 * retry. Because the race window is quite small.
2147 * If we seize this opportunity, it is an optimization
2148 * for increasing the success rate of dissolving page.
2153 remove_hugetlb_page(h, head, false);
2154 h->max_huge_pages--;
2155 spin_unlock_irq(&hugetlb_lock);
2158 * Normally update_and_free_page will allocate required vmemmmap
2159 * before freeing the page. update_and_free_page will fail to
2160 * free the page if it can not allocate required vmemmap. We
2161 * need to adjust max_huge_pages if the page is not freed.
2162 * Attempt to allocate vmemmmap here so that we can take
2163 * appropriate action on failure.
2165 rc = hugetlb_vmemmap_restore(h, head);
2167 update_and_free_page(h, head, false);
2169 spin_lock_irq(&hugetlb_lock);
2170 add_hugetlb_page(h, head, false);
2171 h->max_huge_pages++;
2172 spin_unlock_irq(&hugetlb_lock);
2178 spin_unlock_irq(&hugetlb_lock);
2183 * Dissolve free hugepages in a given pfn range. Used by memory hotplug to
2184 * make specified memory blocks removable from the system.
2185 * Note that this will dissolve a free gigantic hugepage completely, if any
2186 * part of it lies within the given range.
2187 * Also note that if dissolve_free_huge_page() returns with an error, all
2188 * free hugepages that were dissolved before that error are lost.
2190 int dissolve_free_huge_pages(unsigned long start_pfn, unsigned long end_pfn)
2198 if (!hugepages_supported())
2201 order = huge_page_order(&default_hstate);
2203 order = min(order, huge_page_order(h));
2205 for (pfn = start_pfn; pfn < end_pfn; pfn += 1 << order) {
2206 page = pfn_to_page(pfn);
2207 rc = dissolve_free_huge_page(page);
2216 * Allocates a fresh surplus page from the page allocator.
2218 static struct page *alloc_surplus_huge_page(struct hstate *h, gfp_t gfp_mask,
2219 int nid, nodemask_t *nmask)
2221 struct page *page = NULL;
2223 if (hstate_is_gigantic(h))
2226 spin_lock_irq(&hugetlb_lock);
2227 if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages)
2229 spin_unlock_irq(&hugetlb_lock);
2231 page = alloc_fresh_huge_page(h, gfp_mask, nid, nmask, NULL);
2235 spin_lock_irq(&hugetlb_lock);
2237 * We could have raced with the pool size change.
2238 * Double check that and simply deallocate the new page
2239 * if we would end up overcommiting the surpluses. Abuse
2240 * temporary page to workaround the nasty free_huge_page
2243 if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) {
2244 SetHPageTemporary(page);
2245 spin_unlock_irq(&hugetlb_lock);
2246 free_huge_page(page);
2250 h->surplus_huge_pages++;
2251 h->surplus_huge_pages_node[page_to_nid(page)]++;
2254 spin_unlock_irq(&hugetlb_lock);
2259 static struct page *alloc_migrate_huge_page(struct hstate *h, gfp_t gfp_mask,
2260 int nid, nodemask_t *nmask)
2264 if (hstate_is_gigantic(h))
2267 page = alloc_fresh_huge_page(h, gfp_mask, nid, nmask, NULL);
2271 /* fresh huge pages are frozen */
2272 set_page_refcounted(page);
2275 * We do not account these pages as surplus because they are only
2276 * temporary and will be released properly on the last reference
2278 SetHPageTemporary(page);
2284 * Use the VMA's mpolicy to allocate a huge page from the buddy.
2287 struct page *alloc_buddy_huge_page_with_mpol(struct hstate *h,
2288 struct vm_area_struct *vma, unsigned long addr)
2290 struct page *page = NULL;
2291 struct mempolicy *mpol;
2292 gfp_t gfp_mask = htlb_alloc_mask(h);
2294 nodemask_t *nodemask;
2296 nid = huge_node(vma, addr, gfp_mask, &mpol, &nodemask);
2297 if (mpol_is_preferred_many(mpol)) {
2298 gfp_t gfp = gfp_mask | __GFP_NOWARN;
2300 gfp &= ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
2301 page = alloc_surplus_huge_page(h, gfp, nid, nodemask);
2303 /* Fallback to all nodes if page==NULL */
2308 page = alloc_surplus_huge_page(h, gfp_mask, nid, nodemask);
2309 mpol_cond_put(mpol);
2313 /* page migration callback function */
2314 struct page *alloc_huge_page_nodemask(struct hstate *h, int preferred_nid,
2315 nodemask_t *nmask, gfp_t gfp_mask)
2317 spin_lock_irq(&hugetlb_lock);
2318 if (available_huge_pages(h)) {
2321 page = dequeue_huge_page_nodemask(h, gfp_mask, preferred_nid, nmask);
2323 spin_unlock_irq(&hugetlb_lock);
2327 spin_unlock_irq(&hugetlb_lock);
2329 return alloc_migrate_huge_page(h, gfp_mask, preferred_nid, nmask);
2332 /* mempolicy aware migration callback */
2333 struct page *alloc_huge_page_vma(struct hstate *h, struct vm_area_struct *vma,
2334 unsigned long address)
2336 struct mempolicy *mpol;
2337 nodemask_t *nodemask;
2342 gfp_mask = htlb_alloc_mask(h);
2343 node = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
2344 page = alloc_huge_page_nodemask(h, node, nodemask, gfp_mask);
2345 mpol_cond_put(mpol);
2351 * Increase the hugetlb pool such that it can accommodate a reservation
2354 static int gather_surplus_pages(struct hstate *h, long delta)
2355 __must_hold(&hugetlb_lock)
2357 LIST_HEAD(surplus_list);
2358 struct page *page, *tmp;
2361 long needed, allocated;
2362 bool alloc_ok = true;
2364 lockdep_assert_held(&hugetlb_lock);
2365 needed = (h->resv_huge_pages + delta) - h->free_huge_pages;
2367 h->resv_huge_pages += delta;
2375 spin_unlock_irq(&hugetlb_lock);
2376 for (i = 0; i < needed; i++) {
2377 page = alloc_surplus_huge_page(h, htlb_alloc_mask(h),
2378 NUMA_NO_NODE, NULL);
2383 list_add(&page->lru, &surplus_list);
2389 * After retaking hugetlb_lock, we need to recalculate 'needed'
2390 * because either resv_huge_pages or free_huge_pages may have changed.
2392 spin_lock_irq(&hugetlb_lock);
2393 needed = (h->resv_huge_pages + delta) -
2394 (h->free_huge_pages + allocated);
2399 * We were not able to allocate enough pages to
2400 * satisfy the entire reservation so we free what
2401 * we've allocated so far.
2406 * The surplus_list now contains _at_least_ the number of extra pages
2407 * needed to accommodate the reservation. Add the appropriate number
2408 * of pages to the hugetlb pool and free the extras back to the buddy
2409 * allocator. Commit the entire reservation here to prevent another
2410 * process from stealing the pages as they are added to the pool but
2411 * before they are reserved.
2413 needed += allocated;
2414 h->resv_huge_pages += delta;
2417 /* Free the needed pages to the hugetlb pool */
2418 list_for_each_entry_safe(page, tmp, &surplus_list, lru) {
2421 /* Add the page to the hugetlb allocator */
2422 enqueue_huge_page(h, page);
2425 spin_unlock_irq(&hugetlb_lock);
2428 * Free unnecessary surplus pages to the buddy allocator.
2429 * Pages have no ref count, call free_huge_page directly.
2431 list_for_each_entry_safe(page, tmp, &surplus_list, lru)
2432 free_huge_page(page);
2433 spin_lock_irq(&hugetlb_lock);
2439 * This routine has two main purposes:
2440 * 1) Decrement the reservation count (resv_huge_pages) by the value passed
2441 * in unused_resv_pages. This corresponds to the prior adjustments made
2442 * to the associated reservation map.
2443 * 2) Free any unused surplus pages that may have been allocated to satisfy
2444 * the reservation. As many as unused_resv_pages may be freed.
2446 static void return_unused_surplus_pages(struct hstate *h,
2447 unsigned long unused_resv_pages)
2449 unsigned long nr_pages;
2451 LIST_HEAD(page_list);
2453 lockdep_assert_held(&hugetlb_lock);
2454 /* Uncommit the reservation */
2455 h->resv_huge_pages -= unused_resv_pages;
2457 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
2461 * Part (or even all) of the reservation could have been backed
2462 * by pre-allocated pages. Only free surplus pages.
2464 nr_pages = min(unused_resv_pages, h->surplus_huge_pages);
2467 * We want to release as many surplus pages as possible, spread
2468 * evenly across all nodes with memory. Iterate across these nodes
2469 * until we can no longer free unreserved surplus pages. This occurs
2470 * when the nodes with surplus pages have no free pages.
2471 * remove_pool_huge_page() will balance the freed pages across the
2472 * on-line nodes with memory and will handle the hstate accounting.
2474 while (nr_pages--) {
2475 page = remove_pool_huge_page(h, &node_states[N_MEMORY], 1);
2479 list_add(&page->lru, &page_list);
2483 spin_unlock_irq(&hugetlb_lock);
2484 update_and_free_pages_bulk(h, &page_list);
2485 spin_lock_irq(&hugetlb_lock);
2490 * vma_needs_reservation, vma_commit_reservation and vma_end_reservation
2491 * are used by the huge page allocation routines to manage reservations.
2493 * vma_needs_reservation is called to determine if the huge page at addr
2494 * within the vma has an associated reservation. If a reservation is
2495 * needed, the value 1 is returned. The caller is then responsible for
2496 * managing the global reservation and subpool usage counts. After
2497 * the huge page has been allocated, vma_commit_reservation is called
2498 * to add the page to the reservation map. If the page allocation fails,
2499 * the reservation must be ended instead of committed. vma_end_reservation
2500 * is called in such cases.
2502 * In the normal case, vma_commit_reservation returns the same value
2503 * as the preceding vma_needs_reservation call. The only time this
2504 * is not the case is if a reserve map was changed between calls. It
2505 * is the responsibility of the caller to notice the difference and
2506 * take appropriate action.
2508 * vma_add_reservation is used in error paths where a reservation must
2509 * be restored when a newly allocated huge page must be freed. It is
2510 * to be called after calling vma_needs_reservation to determine if a
2511 * reservation exists.
2513 * vma_del_reservation is used in error paths where an entry in the reserve
2514 * map was created during huge page allocation and must be removed. It is to
2515 * be called after calling vma_needs_reservation to determine if a reservation
2518 enum vma_resv_mode {
2525 static long __vma_reservation_common(struct hstate *h,
2526 struct vm_area_struct *vma, unsigned long addr,
2527 enum vma_resv_mode mode)
2529 struct resv_map *resv;
2532 long dummy_out_regions_needed;
2534 resv = vma_resv_map(vma);
2538 idx = vma_hugecache_offset(h, vma, addr);
2540 case VMA_NEEDS_RESV:
2541 ret = region_chg(resv, idx, idx + 1, &dummy_out_regions_needed);
2542 /* We assume that vma_reservation_* routines always operate on
2543 * 1 page, and that adding to resv map a 1 page entry can only
2544 * ever require 1 region.
2546 VM_BUG_ON(dummy_out_regions_needed != 1);
2548 case VMA_COMMIT_RESV:
2549 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2550 /* region_add calls of range 1 should never fail. */
2554 region_abort(resv, idx, idx + 1, 1);
2558 if (vma->vm_flags & VM_MAYSHARE) {
2559 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2560 /* region_add calls of range 1 should never fail. */
2563 region_abort(resv, idx, idx + 1, 1);
2564 ret = region_del(resv, idx, idx + 1);
2568 if (vma->vm_flags & VM_MAYSHARE) {
2569 region_abort(resv, idx, idx + 1, 1);
2570 ret = region_del(resv, idx, idx + 1);
2572 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2573 /* region_add calls of range 1 should never fail. */
2581 if (vma->vm_flags & VM_MAYSHARE || mode == VMA_DEL_RESV)
2584 * We know private mapping must have HPAGE_RESV_OWNER set.
2586 * In most cases, reserves always exist for private mappings.
2587 * However, a file associated with mapping could have been
2588 * hole punched or truncated after reserves were consumed.
2589 * As subsequent fault on such a range will not use reserves.
2590 * Subtle - The reserve map for private mappings has the
2591 * opposite meaning than that of shared mappings. If NO
2592 * entry is in the reserve map, it means a reservation exists.
2593 * If an entry exists in the reserve map, it means the
2594 * reservation has already been consumed. As a result, the
2595 * return value of this routine is the opposite of the
2596 * value returned from reserve map manipulation routines above.
2605 static long vma_needs_reservation(struct hstate *h,
2606 struct vm_area_struct *vma, unsigned long addr)
2608 return __vma_reservation_common(h, vma, addr, VMA_NEEDS_RESV);
2611 static long vma_commit_reservation(struct hstate *h,
2612 struct vm_area_struct *vma, unsigned long addr)
2614 return __vma_reservation_common(h, vma, addr, VMA_COMMIT_RESV);
2617 static void vma_end_reservation(struct hstate *h,
2618 struct vm_area_struct *vma, unsigned long addr)
2620 (void)__vma_reservation_common(h, vma, addr, VMA_END_RESV);
2623 static long vma_add_reservation(struct hstate *h,
2624 struct vm_area_struct *vma, unsigned long addr)
2626 return __vma_reservation_common(h, vma, addr, VMA_ADD_RESV);
2629 static long vma_del_reservation(struct hstate *h,
2630 struct vm_area_struct *vma, unsigned long addr)
2632 return __vma_reservation_common(h, vma, addr, VMA_DEL_RESV);
2636 * This routine is called to restore reservation information on error paths.
2637 * It should ONLY be called for pages allocated via alloc_huge_page(), and
2638 * the hugetlb mutex should remain held when calling this routine.
2640 * It handles two specific cases:
2641 * 1) A reservation was in place and the page consumed the reservation.
2642 * HPageRestoreReserve is set in the page.
2643 * 2) No reservation was in place for the page, so HPageRestoreReserve is
2644 * not set. However, alloc_huge_page always updates the reserve map.
2646 * In case 1, free_huge_page later in the error path will increment the
2647 * global reserve count. But, free_huge_page does not have enough context
2648 * to adjust the reservation map. This case deals primarily with private
2649 * mappings. Adjust the reserve map here to be consistent with global
2650 * reserve count adjustments to be made by free_huge_page. Make sure the
2651 * reserve map indicates there is a reservation present.
2653 * In case 2, simply undo reserve map modifications done by alloc_huge_page.
2655 void restore_reserve_on_error(struct hstate *h, struct vm_area_struct *vma,
2656 unsigned long address, struct page *page)
2658 long rc = vma_needs_reservation(h, vma, address);
2660 if (HPageRestoreReserve(page)) {
2661 if (unlikely(rc < 0))
2663 * Rare out of memory condition in reserve map
2664 * manipulation. Clear HPageRestoreReserve so that
2665 * global reserve count will not be incremented
2666 * by free_huge_page. This will make it appear
2667 * as though the reservation for this page was
2668 * consumed. This may prevent the task from
2669 * faulting in the page at a later time. This
2670 * is better than inconsistent global huge page
2671 * accounting of reserve counts.
2673 ClearHPageRestoreReserve(page);
2675 (void)vma_add_reservation(h, vma, address);
2677 vma_end_reservation(h, vma, address);
2681 * This indicates there is an entry in the reserve map
2682 * not added by alloc_huge_page. We know it was added
2683 * before the alloc_huge_page call, otherwise
2684 * HPageRestoreReserve would be set on the page.
2685 * Remove the entry so that a subsequent allocation
2686 * does not consume a reservation.
2688 rc = vma_del_reservation(h, vma, address);
2691 * VERY rare out of memory condition. Since
2692 * we can not delete the entry, set
2693 * HPageRestoreReserve so that the reserve
2694 * count will be incremented when the page
2695 * is freed. This reserve will be consumed
2696 * on a subsequent allocation.
2698 SetHPageRestoreReserve(page);
2699 } else if (rc < 0) {
2701 * Rare out of memory condition from
2702 * vma_needs_reservation call. Memory allocation is
2703 * only attempted if a new entry is needed. Therefore,
2704 * this implies there is not an entry in the
2707 * For shared mappings, no entry in the map indicates
2708 * no reservation. We are done.
2710 if (!(vma->vm_flags & VM_MAYSHARE))
2712 * For private mappings, no entry indicates
2713 * a reservation is present. Since we can
2714 * not add an entry, set SetHPageRestoreReserve
2715 * on the page so reserve count will be
2716 * incremented when freed. This reserve will
2717 * be consumed on a subsequent allocation.
2719 SetHPageRestoreReserve(page);
2722 * No reservation present, do nothing
2724 vma_end_reservation(h, vma, address);
2729 * alloc_and_dissolve_huge_page - Allocate a new page and dissolve the old one
2730 * @h: struct hstate old page belongs to
2731 * @old_page: Old page to dissolve
2732 * @list: List to isolate the page in case we need to
2733 * Returns 0 on success, otherwise negated error.
2735 static int alloc_and_dissolve_huge_page(struct hstate *h, struct page *old_page,
2736 struct list_head *list)
2738 gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
2739 int nid = page_to_nid(old_page);
2740 struct page *new_page;
2744 * Before dissolving the page, we need to allocate a new one for the
2745 * pool to remain stable. Here, we allocate the page and 'prep' it
2746 * by doing everything but actually updating counters and adding to
2747 * the pool. This simplifies and let us do most of the processing
2750 new_page = alloc_buddy_huge_page(h, gfp_mask, nid, NULL, NULL);
2753 __prep_new_huge_page(h, new_page);
2756 spin_lock_irq(&hugetlb_lock);
2757 if (!PageHuge(old_page)) {
2759 * Freed from under us. Drop new_page too.
2762 } else if (page_count(old_page)) {
2764 * Someone has grabbed the page, try to isolate it here.
2765 * Fail with -EBUSY if not possible.
2767 spin_unlock_irq(&hugetlb_lock);
2768 ret = isolate_hugetlb(old_page, list);
2769 spin_lock_irq(&hugetlb_lock);
2771 } else if (!HPageFreed(old_page)) {
2773 * Page's refcount is 0 but it has not been enqueued in the
2774 * freelist yet. Race window is small, so we can succeed here if
2777 spin_unlock_irq(&hugetlb_lock);
2782 * Ok, old_page is still a genuine free hugepage. Remove it from
2783 * the freelist and decrease the counters. These will be
2784 * incremented again when calling __prep_account_new_huge_page()
2785 * and enqueue_huge_page() for new_page. The counters will remain
2786 * stable since this happens under the lock.
2788 remove_hugetlb_page(h, old_page, false);
2791 * Ref count on new page is already zero as it was dropped
2792 * earlier. It can be directly added to the pool free list.
2794 __prep_account_new_huge_page(h, nid);
2795 enqueue_huge_page(h, new_page);
2798 * Pages have been replaced, we can safely free the old one.
2800 spin_unlock_irq(&hugetlb_lock);
2801 update_and_free_page(h, old_page, false);
2807 spin_unlock_irq(&hugetlb_lock);
2808 /* Page has a zero ref count, but needs a ref to be freed */
2809 set_page_refcounted(new_page);
2810 update_and_free_page(h, new_page, false);
2815 int isolate_or_dissolve_huge_page(struct page *page, struct list_head *list)
2822 * The page might have been dissolved from under our feet, so make sure
2823 * to carefully check the state under the lock.
2824 * Return success when racing as if we dissolved the page ourselves.
2826 spin_lock_irq(&hugetlb_lock);
2827 if (PageHuge(page)) {
2828 head = compound_head(page);
2829 h = page_hstate(head);
2831 spin_unlock_irq(&hugetlb_lock);
2834 spin_unlock_irq(&hugetlb_lock);
2837 * Fence off gigantic pages as there is a cyclic dependency between
2838 * alloc_contig_range and them. Return -ENOMEM as this has the effect
2839 * of bailing out right away without further retrying.
2841 if (hstate_is_gigantic(h))
2844 if (page_count(head) && !isolate_hugetlb(head, list))
2846 else if (!page_count(head))
2847 ret = alloc_and_dissolve_huge_page(h, head, list);
2852 struct page *alloc_huge_page(struct vm_area_struct *vma,
2853 unsigned long addr, int avoid_reserve)
2855 struct hugepage_subpool *spool = subpool_vma(vma);
2856 struct hstate *h = hstate_vma(vma);
2858 long map_chg, map_commit;
2861 struct hugetlb_cgroup *h_cg;
2862 bool deferred_reserve;
2864 idx = hstate_index(h);
2866 * Examine the region/reserve map to determine if the process
2867 * has a reservation for the page to be allocated. A return
2868 * code of zero indicates a reservation exists (no change).
2870 map_chg = gbl_chg = vma_needs_reservation(h, vma, addr);
2872 return ERR_PTR(-ENOMEM);
2875 * Processes that did not create the mapping will have no
2876 * reserves as indicated by the region/reserve map. Check
2877 * that the allocation will not exceed the subpool limit.
2878 * Allocations for MAP_NORESERVE mappings also need to be
2879 * checked against any subpool limit.
2881 if (map_chg || avoid_reserve) {
2882 gbl_chg = hugepage_subpool_get_pages(spool, 1);
2884 vma_end_reservation(h, vma, addr);
2885 return ERR_PTR(-ENOSPC);
2889 * Even though there was no reservation in the region/reserve
2890 * map, there could be reservations associated with the
2891 * subpool that can be used. This would be indicated if the
2892 * return value of hugepage_subpool_get_pages() is zero.
2893 * However, if avoid_reserve is specified we still avoid even
2894 * the subpool reservations.
2900 /* If this allocation is not consuming a reservation, charge it now.
2902 deferred_reserve = map_chg || avoid_reserve;
2903 if (deferred_reserve) {
2904 ret = hugetlb_cgroup_charge_cgroup_rsvd(
2905 idx, pages_per_huge_page(h), &h_cg);
2907 goto out_subpool_put;
2910 ret = hugetlb_cgroup_charge_cgroup(idx, pages_per_huge_page(h), &h_cg);
2912 goto out_uncharge_cgroup_reservation;
2914 spin_lock_irq(&hugetlb_lock);
2916 * glb_chg is passed to indicate whether or not a page must be taken
2917 * from the global free pool (global change). gbl_chg == 0 indicates
2918 * a reservation exists for the allocation.
2920 page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve, gbl_chg);
2922 spin_unlock_irq(&hugetlb_lock);
2923 page = alloc_buddy_huge_page_with_mpol(h, vma, addr);
2925 goto out_uncharge_cgroup;
2926 if (!avoid_reserve && vma_has_reserves(vma, gbl_chg)) {
2927 SetHPageRestoreReserve(page);
2928 h->resv_huge_pages--;
2930 spin_lock_irq(&hugetlb_lock);
2931 list_add(&page->lru, &h->hugepage_activelist);
2932 set_page_refcounted(page);
2935 hugetlb_cgroup_commit_charge(idx, pages_per_huge_page(h), h_cg, page);
2936 /* If allocation is not consuming a reservation, also store the
2937 * hugetlb_cgroup pointer on the page.
2939 if (deferred_reserve) {
2940 hugetlb_cgroup_commit_charge_rsvd(idx, pages_per_huge_page(h),
2944 spin_unlock_irq(&hugetlb_lock);
2946 hugetlb_set_page_subpool(page, spool);
2948 map_commit = vma_commit_reservation(h, vma, addr);
2949 if (unlikely(map_chg > map_commit)) {
2951 * The page was added to the reservation map between
2952 * vma_needs_reservation and vma_commit_reservation.
2953 * This indicates a race with hugetlb_reserve_pages.
2954 * Adjust for the subpool count incremented above AND
2955 * in hugetlb_reserve_pages for the same page. Also,
2956 * the reservation count added in hugetlb_reserve_pages
2957 * no longer applies.
2961 rsv_adjust = hugepage_subpool_put_pages(spool, 1);
2962 hugetlb_acct_memory(h, -rsv_adjust);
2963 if (deferred_reserve)
2964 hugetlb_cgroup_uncharge_page_rsvd(hstate_index(h),
2965 pages_per_huge_page(h), page);
2969 out_uncharge_cgroup:
2970 hugetlb_cgroup_uncharge_cgroup(idx, pages_per_huge_page(h), h_cg);
2971 out_uncharge_cgroup_reservation:
2972 if (deferred_reserve)
2973 hugetlb_cgroup_uncharge_cgroup_rsvd(idx, pages_per_huge_page(h),
2976 if (map_chg || avoid_reserve)
2977 hugepage_subpool_put_pages(spool, 1);
2978 vma_end_reservation(h, vma, addr);
2979 return ERR_PTR(-ENOSPC);
2982 int alloc_bootmem_huge_page(struct hstate *h, int nid)
2983 __attribute__ ((weak, alias("__alloc_bootmem_huge_page")));
2984 int __alloc_bootmem_huge_page(struct hstate *h, int nid)
2986 struct huge_bootmem_page *m = NULL; /* initialize for clang */
2989 /* do node specific alloc */
2990 if (nid != NUMA_NO_NODE) {
2991 m = memblock_alloc_try_nid_raw(huge_page_size(h), huge_page_size(h),
2992 0, MEMBLOCK_ALLOC_ACCESSIBLE, nid);
2997 /* allocate from next node when distributing huge pages */
2998 for_each_node_mask_to_alloc(h, nr_nodes, node, &node_states[N_MEMORY]) {
2999 m = memblock_alloc_try_nid_raw(
3000 huge_page_size(h), huge_page_size(h),
3001 0, MEMBLOCK_ALLOC_ACCESSIBLE, node);
3003 * Use the beginning of the huge page to store the
3004 * huge_bootmem_page struct (until gather_bootmem
3005 * puts them into the mem_map).
3013 /* Put them into a private list first because mem_map is not up yet */
3014 INIT_LIST_HEAD(&m->list);
3015 list_add(&m->list, &huge_boot_pages);
3021 * Put bootmem huge pages into the standard lists after mem_map is up.
3022 * Note: This only applies to gigantic (order > MAX_ORDER) pages.
3024 static void __init gather_bootmem_prealloc(void)
3026 struct huge_bootmem_page *m;
3028 list_for_each_entry(m, &huge_boot_pages, list) {
3029 struct page *page = virt_to_page(m);
3030 struct hstate *h = m->hstate;
3032 VM_BUG_ON(!hstate_is_gigantic(h));
3033 WARN_ON(page_count(page) != 1);
3034 if (prep_compound_gigantic_page(page, huge_page_order(h))) {
3035 WARN_ON(PageReserved(page));
3036 prep_new_huge_page(h, page, page_to_nid(page));
3037 free_huge_page(page); /* add to the hugepage allocator */
3039 /* VERY unlikely inflated ref count on a tail page */
3040 free_gigantic_page(page, huge_page_order(h));
3044 * We need to restore the 'stolen' pages to totalram_pages
3045 * in order to fix confusing memory reports from free(1) and
3046 * other side-effects, like CommitLimit going negative.
3048 adjust_managed_page_count(page, pages_per_huge_page(h));
3052 static void __init hugetlb_hstate_alloc_pages_onenode(struct hstate *h, int nid)
3057 for (i = 0; i < h->max_huge_pages_node[nid]; ++i) {
3058 if (hstate_is_gigantic(h)) {
3059 if (!alloc_bootmem_huge_page(h, nid))
3063 gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
3065 page = alloc_fresh_huge_page(h, gfp_mask, nid,
3066 &node_states[N_MEMORY], NULL);
3069 free_huge_page(page); /* free it into the hugepage allocator */
3073 if (i == h->max_huge_pages_node[nid])
3076 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
3077 pr_warn("HugeTLB: allocating %u of page size %s failed node%d. Only allocated %lu hugepages.\n",
3078 h->max_huge_pages_node[nid], buf, nid, i);
3079 h->max_huge_pages -= (h->max_huge_pages_node[nid] - i);
3080 h->max_huge_pages_node[nid] = i;
3083 static void __init hugetlb_hstate_alloc_pages(struct hstate *h)
3086 nodemask_t *node_alloc_noretry;
3087 bool node_specific_alloc = false;
3089 /* skip gigantic hugepages allocation if hugetlb_cma enabled */
3090 if (hstate_is_gigantic(h) && hugetlb_cma_size) {
3091 pr_warn_once("HugeTLB: hugetlb_cma is enabled, skip boot time allocation\n");
3095 /* do node specific alloc */
3096 for_each_online_node(i) {
3097 if (h->max_huge_pages_node[i] > 0) {
3098 hugetlb_hstate_alloc_pages_onenode(h, i);
3099 node_specific_alloc = true;
3103 if (node_specific_alloc)
3106 /* below will do all node balanced alloc */
3107 if (!hstate_is_gigantic(h)) {
3109 * Bit mask controlling how hard we retry per-node allocations.
3110 * Ignore errors as lower level routines can deal with
3111 * node_alloc_noretry == NULL. If this kmalloc fails at boot
3112 * time, we are likely in bigger trouble.
3114 node_alloc_noretry = kmalloc(sizeof(*node_alloc_noretry),
3117 /* allocations done at boot time */
3118 node_alloc_noretry = NULL;
3121 /* bit mask controlling how hard we retry per-node allocations */
3122 if (node_alloc_noretry)
3123 nodes_clear(*node_alloc_noretry);
3125 for (i = 0; i < h->max_huge_pages; ++i) {
3126 if (hstate_is_gigantic(h)) {
3127 if (!alloc_bootmem_huge_page(h, NUMA_NO_NODE))
3129 } else if (!alloc_pool_huge_page(h,
3130 &node_states[N_MEMORY],
3131 node_alloc_noretry))
3135 if (i < h->max_huge_pages) {
3138 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
3139 pr_warn("HugeTLB: allocating %lu of page size %s failed. Only allocated %lu hugepages.\n",
3140 h->max_huge_pages, buf, i);
3141 h->max_huge_pages = i;
3143 kfree(node_alloc_noretry);
3146 static void __init hugetlb_init_hstates(void)
3148 struct hstate *h, *h2;
3150 for_each_hstate(h) {
3151 /* oversize hugepages were init'ed in early boot */
3152 if (!hstate_is_gigantic(h))
3153 hugetlb_hstate_alloc_pages(h);
3156 * Set demote order for each hstate. Note that
3157 * h->demote_order is initially 0.
3158 * - We can not demote gigantic pages if runtime freeing
3159 * is not supported, so skip this.
3160 * - If CMA allocation is possible, we can not demote
3161 * HUGETLB_PAGE_ORDER or smaller size pages.
3163 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
3165 if (hugetlb_cma_size && h->order <= HUGETLB_PAGE_ORDER)
3167 for_each_hstate(h2) {
3170 if (h2->order < h->order &&
3171 h2->order > h->demote_order)
3172 h->demote_order = h2->order;
3177 static void __init report_hugepages(void)
3181 for_each_hstate(h) {
3184 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
3185 pr_info("HugeTLB: registered %s page size, pre-allocated %ld pages\n",
3186 buf, h->free_huge_pages);
3187 pr_info("HugeTLB: %d KiB vmemmap can be freed for a %s page\n",
3188 hugetlb_vmemmap_optimizable_size(h) / SZ_1K, buf);
3192 #ifdef CONFIG_HIGHMEM
3193 static void try_to_free_low(struct hstate *h, unsigned long count,
3194 nodemask_t *nodes_allowed)
3197 LIST_HEAD(page_list);
3199 lockdep_assert_held(&hugetlb_lock);
3200 if (hstate_is_gigantic(h))
3204 * Collect pages to be freed on a list, and free after dropping lock
3206 for_each_node_mask(i, *nodes_allowed) {
3207 struct page *page, *next;
3208 struct list_head *freel = &h->hugepage_freelists[i];
3209 list_for_each_entry_safe(page, next, freel, lru) {
3210 if (count >= h->nr_huge_pages)
3212 if (PageHighMem(page))
3214 remove_hugetlb_page(h, page, false);
3215 list_add(&page->lru, &page_list);
3220 spin_unlock_irq(&hugetlb_lock);
3221 update_and_free_pages_bulk(h, &page_list);
3222 spin_lock_irq(&hugetlb_lock);
3225 static inline void try_to_free_low(struct hstate *h, unsigned long count,
3226 nodemask_t *nodes_allowed)
3232 * Increment or decrement surplus_huge_pages. Keep node-specific counters
3233 * balanced by operating on them in a round-robin fashion.
3234 * Returns 1 if an adjustment was made.
3236 static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed,
3241 lockdep_assert_held(&hugetlb_lock);
3242 VM_BUG_ON(delta != -1 && delta != 1);
3245 for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
3246 if (h->surplus_huge_pages_node[node])
3250 for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
3251 if (h->surplus_huge_pages_node[node] <
3252 h->nr_huge_pages_node[node])
3259 h->surplus_huge_pages += delta;
3260 h->surplus_huge_pages_node[node] += delta;
3264 #define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages)
3265 static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,
3266 nodemask_t *nodes_allowed)
3268 unsigned long min_count, ret;
3270 LIST_HEAD(page_list);
3271 NODEMASK_ALLOC(nodemask_t, node_alloc_noretry, GFP_KERNEL);
3274 * Bit mask controlling how hard we retry per-node allocations.
3275 * If we can not allocate the bit mask, do not attempt to allocate
3276 * the requested huge pages.
3278 if (node_alloc_noretry)
3279 nodes_clear(*node_alloc_noretry);
3284 * resize_lock mutex prevents concurrent adjustments to number of
3285 * pages in hstate via the proc/sysfs interfaces.
3287 mutex_lock(&h->resize_lock);
3288 flush_free_hpage_work(h);
3289 spin_lock_irq(&hugetlb_lock);
3292 * Check for a node specific request.
3293 * Changing node specific huge page count may require a corresponding
3294 * change to the global count. In any case, the passed node mask
3295 * (nodes_allowed) will restrict alloc/free to the specified node.
3297 if (nid != NUMA_NO_NODE) {
3298 unsigned long old_count = count;
3300 count += h->nr_huge_pages - h->nr_huge_pages_node[nid];
3302 * User may have specified a large count value which caused the
3303 * above calculation to overflow. In this case, they wanted
3304 * to allocate as many huge pages as possible. Set count to
3305 * largest possible value to align with their intention.
3307 if (count < old_count)
3312 * Gigantic pages runtime allocation depend on the capability for large
3313 * page range allocation.
3314 * If the system does not provide this feature, return an error when
3315 * the user tries to allocate gigantic pages but let the user free the
3316 * boottime allocated gigantic pages.
3318 if (hstate_is_gigantic(h) && !IS_ENABLED(CONFIG_CONTIG_ALLOC)) {
3319 if (count > persistent_huge_pages(h)) {
3320 spin_unlock_irq(&hugetlb_lock);
3321 mutex_unlock(&h->resize_lock);
3322 NODEMASK_FREE(node_alloc_noretry);
3325 /* Fall through to decrease pool */
3329 * Increase the pool size
3330 * First take pages out of surplus state. Then make up the
3331 * remaining difference by allocating fresh huge pages.
3333 * We might race with alloc_surplus_huge_page() here and be unable
3334 * to convert a surplus huge page to a normal huge page. That is
3335 * not critical, though, it just means the overall size of the
3336 * pool might be one hugepage larger than it needs to be, but
3337 * within all the constraints specified by the sysctls.
3339 while (h->surplus_huge_pages && count > persistent_huge_pages(h)) {
3340 if (!adjust_pool_surplus(h, nodes_allowed, -1))
3344 while (count > persistent_huge_pages(h)) {
3346 * If this allocation races such that we no longer need the
3347 * page, free_huge_page will handle it by freeing the page
3348 * and reducing the surplus.
3350 spin_unlock_irq(&hugetlb_lock);
3352 /* yield cpu to avoid soft lockup */
3355 ret = alloc_pool_huge_page(h, nodes_allowed,
3356 node_alloc_noretry);
3357 spin_lock_irq(&hugetlb_lock);
3361 /* Bail for signals. Probably ctrl-c from user */
3362 if (signal_pending(current))
3367 * Decrease the pool size
3368 * First return free pages to the buddy allocator (being careful
3369 * to keep enough around to satisfy reservations). Then place
3370 * pages into surplus state as needed so the pool will shrink
3371 * to the desired size as pages become free.
3373 * By placing pages into the surplus state independent of the
3374 * overcommit value, we are allowing the surplus pool size to
3375 * exceed overcommit. There are few sane options here. Since
3376 * alloc_surplus_huge_page() is checking the global counter,
3377 * though, we'll note that we're not allowed to exceed surplus
3378 * and won't grow the pool anywhere else. Not until one of the
3379 * sysctls are changed, or the surplus pages go out of use.
3381 min_count = h->resv_huge_pages + h->nr_huge_pages - h->free_huge_pages;
3382 min_count = max(count, min_count);
3383 try_to_free_low(h, min_count, nodes_allowed);
3386 * Collect pages to be removed on list without dropping lock
3388 while (min_count < persistent_huge_pages(h)) {
3389 page = remove_pool_huge_page(h, nodes_allowed, 0);
3393 list_add(&page->lru, &page_list);
3395 /* free the pages after dropping lock */
3396 spin_unlock_irq(&hugetlb_lock);
3397 update_and_free_pages_bulk(h, &page_list);
3398 flush_free_hpage_work(h);
3399 spin_lock_irq(&hugetlb_lock);
3401 while (count < persistent_huge_pages(h)) {
3402 if (!adjust_pool_surplus(h, nodes_allowed, 1))
3406 h->max_huge_pages = persistent_huge_pages(h);
3407 spin_unlock_irq(&hugetlb_lock);
3408 mutex_unlock(&h->resize_lock);
3410 NODEMASK_FREE(node_alloc_noretry);
3415 static int demote_free_huge_page(struct hstate *h, struct page *page)
3417 int i, nid = page_to_nid(page);
3418 struct hstate *target_hstate;
3419 struct page *subpage;
3422 target_hstate = size_to_hstate(PAGE_SIZE << h->demote_order);
3424 remove_hugetlb_page_for_demote(h, page, false);
3425 spin_unlock_irq(&hugetlb_lock);
3427 rc = hugetlb_vmemmap_restore(h, page);
3429 /* Allocation of vmemmmap failed, we can not demote page */
3430 spin_lock_irq(&hugetlb_lock);
3431 set_page_refcounted(page);
3432 add_hugetlb_page(h, page, false);
3437 * Use destroy_compound_hugetlb_page_for_demote for all huge page
3438 * sizes as it will not ref count pages.
3440 destroy_compound_hugetlb_page_for_demote(page, huge_page_order(h));
3443 * Taking target hstate mutex synchronizes with set_max_huge_pages.
3444 * Without the mutex, pages added to target hstate could be marked
3447 * Note that we already hold h->resize_lock. To prevent deadlock,
3448 * use the convention of always taking larger size hstate mutex first.
3450 mutex_lock(&target_hstate->resize_lock);
3451 for (i = 0; i < pages_per_huge_page(h);
3452 i += pages_per_huge_page(target_hstate)) {
3453 subpage = nth_page(page, i);
3454 if (hstate_is_gigantic(target_hstate))
3455 prep_compound_gigantic_page_for_demote(subpage,
3456 target_hstate->order);
3458 prep_compound_page(subpage, target_hstate->order);
3459 set_page_private(subpage, 0);
3460 prep_new_huge_page(target_hstate, subpage, nid);
3461 free_huge_page(subpage);
3463 mutex_unlock(&target_hstate->resize_lock);
3465 spin_lock_irq(&hugetlb_lock);
3468 * Not absolutely necessary, but for consistency update max_huge_pages
3469 * based on pool changes for the demoted page.
3471 h->max_huge_pages--;
3472 target_hstate->max_huge_pages +=
3473 pages_per_huge_page(h) / pages_per_huge_page(target_hstate);
3478 static int demote_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed)
3479 __must_hold(&hugetlb_lock)
3484 lockdep_assert_held(&hugetlb_lock);
3486 /* We should never get here if no demote order */
3487 if (!h->demote_order) {
3488 pr_warn("HugeTLB: NULL demote order passed to demote_pool_huge_page.\n");
3489 return -EINVAL; /* internal error */
3492 for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
3493 list_for_each_entry(page, &h->hugepage_freelists[node], lru) {
3494 if (PageHWPoison(page))
3497 return demote_free_huge_page(h, page);
3502 * Only way to get here is if all pages on free lists are poisoned.
3503 * Return -EBUSY so that caller will not retry.
3508 #define HSTATE_ATTR_RO(_name) \
3509 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
3511 #define HSTATE_ATTR_WO(_name) \
3512 static struct kobj_attribute _name##_attr = __ATTR_WO(_name)
3514 #define HSTATE_ATTR(_name) \
3515 static struct kobj_attribute _name##_attr = __ATTR_RW(_name)
3517 static struct kobject *hugepages_kobj;
3518 static struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
3520 static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp);
3522 static struct hstate *kobj_to_hstate(struct kobject *kobj, int *nidp)
3526 for (i = 0; i < HUGE_MAX_HSTATE; i++)
3527 if (hstate_kobjs[i] == kobj) {
3529 *nidp = NUMA_NO_NODE;
3533 return kobj_to_node_hstate(kobj, nidp);
3536 static ssize_t nr_hugepages_show_common(struct kobject *kobj,
3537 struct kobj_attribute *attr, char *buf)
3540 unsigned long nr_huge_pages;
3543 h = kobj_to_hstate(kobj, &nid);
3544 if (nid == NUMA_NO_NODE)
3545 nr_huge_pages = h->nr_huge_pages;
3547 nr_huge_pages = h->nr_huge_pages_node[nid];
3549 return sysfs_emit(buf, "%lu\n", nr_huge_pages);
3552 static ssize_t __nr_hugepages_store_common(bool obey_mempolicy,
3553 struct hstate *h, int nid,
3554 unsigned long count, size_t len)
3557 nodemask_t nodes_allowed, *n_mask;
3559 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
3562 if (nid == NUMA_NO_NODE) {
3564 * global hstate attribute
3566 if (!(obey_mempolicy &&
3567 init_nodemask_of_mempolicy(&nodes_allowed)))
3568 n_mask = &node_states[N_MEMORY];
3570 n_mask = &nodes_allowed;
3573 * Node specific request. count adjustment happens in
3574 * set_max_huge_pages() after acquiring hugetlb_lock.
3576 init_nodemask_of_node(&nodes_allowed, nid);
3577 n_mask = &nodes_allowed;
3580 err = set_max_huge_pages(h, count, nid, n_mask);
3582 return err ? err : len;
3585 static ssize_t nr_hugepages_store_common(bool obey_mempolicy,
3586 struct kobject *kobj, const char *buf,
3590 unsigned long count;
3594 err = kstrtoul(buf, 10, &count);
3598 h = kobj_to_hstate(kobj, &nid);
3599 return __nr_hugepages_store_common(obey_mempolicy, h, nid, count, len);
3602 static ssize_t nr_hugepages_show(struct kobject *kobj,
3603 struct kobj_attribute *attr, char *buf)
3605 return nr_hugepages_show_common(kobj, attr, buf);
3608 static ssize_t nr_hugepages_store(struct kobject *kobj,
3609 struct kobj_attribute *attr, const char *buf, size_t len)
3611 return nr_hugepages_store_common(false, kobj, buf, len);
3613 HSTATE_ATTR(nr_hugepages);
3618 * hstate attribute for optionally mempolicy-based constraint on persistent
3619 * huge page alloc/free.
3621 static ssize_t nr_hugepages_mempolicy_show(struct kobject *kobj,
3622 struct kobj_attribute *attr,
3625 return nr_hugepages_show_common(kobj, attr, buf);
3628 static ssize_t nr_hugepages_mempolicy_store(struct kobject *kobj,
3629 struct kobj_attribute *attr, const char *buf, size_t len)
3631 return nr_hugepages_store_common(true, kobj, buf, len);
3633 HSTATE_ATTR(nr_hugepages_mempolicy);
3637 static ssize_t nr_overcommit_hugepages_show(struct kobject *kobj,
3638 struct kobj_attribute *attr, char *buf)
3640 struct hstate *h = kobj_to_hstate(kobj, NULL);
3641 return sysfs_emit(buf, "%lu\n", h->nr_overcommit_huge_pages);
3644 static ssize_t nr_overcommit_hugepages_store(struct kobject *kobj,
3645 struct kobj_attribute *attr, const char *buf, size_t count)
3648 unsigned long input;
3649 struct hstate *h = kobj_to_hstate(kobj, NULL);
3651 if (hstate_is_gigantic(h))
3654 err = kstrtoul(buf, 10, &input);
3658 spin_lock_irq(&hugetlb_lock);
3659 h->nr_overcommit_huge_pages = input;
3660 spin_unlock_irq(&hugetlb_lock);
3664 HSTATE_ATTR(nr_overcommit_hugepages);
3666 static ssize_t free_hugepages_show(struct kobject *kobj,
3667 struct kobj_attribute *attr, char *buf)
3670 unsigned long free_huge_pages;
3673 h = kobj_to_hstate(kobj, &nid);
3674 if (nid == NUMA_NO_NODE)
3675 free_huge_pages = h->free_huge_pages;
3677 free_huge_pages = h->free_huge_pages_node[nid];
3679 return sysfs_emit(buf, "%lu\n", free_huge_pages);
3681 HSTATE_ATTR_RO(free_hugepages);
3683 static ssize_t resv_hugepages_show(struct kobject *kobj,
3684 struct kobj_attribute *attr, char *buf)
3686 struct hstate *h = kobj_to_hstate(kobj, NULL);
3687 return sysfs_emit(buf, "%lu\n", h->resv_huge_pages);
3689 HSTATE_ATTR_RO(resv_hugepages);
3691 static ssize_t surplus_hugepages_show(struct kobject *kobj,
3692 struct kobj_attribute *attr, char *buf)
3695 unsigned long surplus_huge_pages;
3698 h = kobj_to_hstate(kobj, &nid);
3699 if (nid == NUMA_NO_NODE)
3700 surplus_huge_pages = h->surplus_huge_pages;
3702 surplus_huge_pages = h->surplus_huge_pages_node[nid];
3704 return sysfs_emit(buf, "%lu\n", surplus_huge_pages);
3706 HSTATE_ATTR_RO(surplus_hugepages);
3708 static ssize_t demote_store(struct kobject *kobj,
3709 struct kobj_attribute *attr, const char *buf, size_t len)
3711 unsigned long nr_demote;
3712 unsigned long nr_available;
3713 nodemask_t nodes_allowed, *n_mask;
3718 err = kstrtoul(buf, 10, &nr_demote);
3721 h = kobj_to_hstate(kobj, &nid);
3723 if (nid != NUMA_NO_NODE) {
3724 init_nodemask_of_node(&nodes_allowed, nid);
3725 n_mask = &nodes_allowed;
3727 n_mask = &node_states[N_MEMORY];
3730 /* Synchronize with other sysfs operations modifying huge pages */
3731 mutex_lock(&h->resize_lock);
3732 spin_lock_irq(&hugetlb_lock);
3736 * Check for available pages to demote each time thorough the
3737 * loop as demote_pool_huge_page will drop hugetlb_lock.
3739 if (nid != NUMA_NO_NODE)
3740 nr_available = h->free_huge_pages_node[nid];
3742 nr_available = h->free_huge_pages;
3743 nr_available -= h->resv_huge_pages;
3747 err = demote_pool_huge_page(h, n_mask);
3754 spin_unlock_irq(&hugetlb_lock);
3755 mutex_unlock(&h->resize_lock);
3761 HSTATE_ATTR_WO(demote);
3763 static ssize_t demote_size_show(struct kobject *kobj,
3764 struct kobj_attribute *attr, char *buf)
3766 struct hstate *h = kobj_to_hstate(kobj, NULL);
3767 unsigned long demote_size = (PAGE_SIZE << h->demote_order) / SZ_1K;
3769 return sysfs_emit(buf, "%lukB\n", demote_size);
3772 static ssize_t demote_size_store(struct kobject *kobj,
3773 struct kobj_attribute *attr,
3774 const char *buf, size_t count)
3776 struct hstate *h, *demote_hstate;
3777 unsigned long demote_size;
3778 unsigned int demote_order;
3780 demote_size = (unsigned long)memparse(buf, NULL);
3782 demote_hstate = size_to_hstate(demote_size);
3785 demote_order = demote_hstate->order;
3786 if (demote_order < HUGETLB_PAGE_ORDER)
3789 /* demote order must be smaller than hstate order */
3790 h = kobj_to_hstate(kobj, NULL);
3791 if (demote_order >= h->order)
3794 /* resize_lock synchronizes access to demote size and writes */
3795 mutex_lock(&h->resize_lock);
3796 h->demote_order = demote_order;
3797 mutex_unlock(&h->resize_lock);
3801 HSTATE_ATTR(demote_size);
3803 static struct attribute *hstate_attrs[] = {
3804 &nr_hugepages_attr.attr,
3805 &nr_overcommit_hugepages_attr.attr,
3806 &free_hugepages_attr.attr,
3807 &resv_hugepages_attr.attr,
3808 &surplus_hugepages_attr.attr,
3810 &nr_hugepages_mempolicy_attr.attr,
3815 static const struct attribute_group hstate_attr_group = {
3816 .attrs = hstate_attrs,
3819 static struct attribute *hstate_demote_attrs[] = {
3820 &demote_size_attr.attr,
3825 static const struct attribute_group hstate_demote_attr_group = {
3826 .attrs = hstate_demote_attrs,
3829 static int hugetlb_sysfs_add_hstate(struct hstate *h, struct kobject *parent,
3830 struct kobject **hstate_kobjs,
3831 const struct attribute_group *hstate_attr_group)
3834 int hi = hstate_index(h);
3836 hstate_kobjs[hi] = kobject_create_and_add(h->name, parent);
3837 if (!hstate_kobjs[hi])
3840 retval = sysfs_create_group(hstate_kobjs[hi], hstate_attr_group);
3842 kobject_put(hstate_kobjs[hi]);
3843 hstate_kobjs[hi] = NULL;
3847 if (h->demote_order) {
3848 retval = sysfs_create_group(hstate_kobjs[hi],
3849 &hstate_demote_attr_group);
3851 pr_warn("HugeTLB unable to create demote interfaces for %s\n", h->name);
3852 sysfs_remove_group(hstate_kobjs[hi], hstate_attr_group);
3853 kobject_put(hstate_kobjs[hi]);
3854 hstate_kobjs[hi] = NULL;
3863 static bool hugetlb_sysfs_initialized __ro_after_init;
3866 * node_hstate/s - associate per node hstate attributes, via their kobjects,
3867 * with node devices in node_devices[] using a parallel array. The array
3868 * index of a node device or _hstate == node id.
3869 * This is here to avoid any static dependency of the node device driver, in
3870 * the base kernel, on the hugetlb module.
3872 struct node_hstate {
3873 struct kobject *hugepages_kobj;
3874 struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
3876 static struct node_hstate node_hstates[MAX_NUMNODES];
3879 * A subset of global hstate attributes for node devices
3881 static struct attribute *per_node_hstate_attrs[] = {
3882 &nr_hugepages_attr.attr,
3883 &free_hugepages_attr.attr,
3884 &surplus_hugepages_attr.attr,
3888 static const struct attribute_group per_node_hstate_attr_group = {
3889 .attrs = per_node_hstate_attrs,
3893 * kobj_to_node_hstate - lookup global hstate for node device hstate attr kobj.
3894 * Returns node id via non-NULL nidp.
3896 static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
3900 for (nid = 0; nid < nr_node_ids; nid++) {
3901 struct node_hstate *nhs = &node_hstates[nid];
3903 for (i = 0; i < HUGE_MAX_HSTATE; i++)
3904 if (nhs->hstate_kobjs[i] == kobj) {
3916 * Unregister hstate attributes from a single node device.
3917 * No-op if no hstate attributes attached.
3919 void hugetlb_unregister_node(struct node *node)
3922 struct node_hstate *nhs = &node_hstates[node->dev.id];
3924 if (!nhs->hugepages_kobj)
3925 return; /* no hstate attributes */
3927 for_each_hstate(h) {
3928 int idx = hstate_index(h);
3929 struct kobject *hstate_kobj = nhs->hstate_kobjs[idx];
3933 if (h->demote_order)
3934 sysfs_remove_group(hstate_kobj, &hstate_demote_attr_group);
3935 sysfs_remove_group(hstate_kobj, &per_node_hstate_attr_group);
3936 kobject_put(hstate_kobj);
3937 nhs->hstate_kobjs[idx] = NULL;
3940 kobject_put(nhs->hugepages_kobj);
3941 nhs->hugepages_kobj = NULL;
3946 * Register hstate attributes for a single node device.
3947 * No-op if attributes already registered.
3949 void hugetlb_register_node(struct node *node)
3952 struct node_hstate *nhs = &node_hstates[node->dev.id];
3955 if (!hugetlb_sysfs_initialized)
3958 if (nhs->hugepages_kobj)
3959 return; /* already allocated */
3961 nhs->hugepages_kobj = kobject_create_and_add("hugepages",
3963 if (!nhs->hugepages_kobj)
3966 for_each_hstate(h) {
3967 err = hugetlb_sysfs_add_hstate(h, nhs->hugepages_kobj,
3969 &per_node_hstate_attr_group);
3971 pr_err("HugeTLB: Unable to add hstate %s for node %d\n",
3972 h->name, node->dev.id);
3973 hugetlb_unregister_node(node);
3980 * hugetlb init time: register hstate attributes for all registered node
3981 * devices of nodes that have memory. All on-line nodes should have
3982 * registered their associated device by this time.
3984 static void __init hugetlb_register_all_nodes(void)
3988 for_each_online_node(nid)
3989 hugetlb_register_node(node_devices[nid]);
3991 #else /* !CONFIG_NUMA */
3993 static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
4001 static void hugetlb_register_all_nodes(void) { }
4006 static void __init hugetlb_cma_check(void);
4008 static inline __init void hugetlb_cma_check(void)
4013 static void __init hugetlb_sysfs_init(void)
4018 hugepages_kobj = kobject_create_and_add("hugepages", mm_kobj);
4019 if (!hugepages_kobj)
4022 for_each_hstate(h) {
4023 err = hugetlb_sysfs_add_hstate(h, hugepages_kobj,
4024 hstate_kobjs, &hstate_attr_group);
4026 pr_err("HugeTLB: Unable to add hstate %s", h->name);
4030 hugetlb_sysfs_initialized = true;
4032 hugetlb_register_all_nodes();
4035 static int __init hugetlb_init(void)
4039 BUILD_BUG_ON(sizeof_field(struct page, private) * BITS_PER_BYTE <
4042 if (!hugepages_supported()) {
4043 if (hugetlb_max_hstate || default_hstate_max_huge_pages)
4044 pr_warn("HugeTLB: huge pages not supported, ignoring associated command-line parameters\n");
4049 * Make sure HPAGE_SIZE (HUGETLB_PAGE_ORDER) hstate exists. Some
4050 * architectures depend on setup being done here.
4052 hugetlb_add_hstate(HUGETLB_PAGE_ORDER);
4053 if (!parsed_default_hugepagesz) {
4055 * If we did not parse a default huge page size, set
4056 * default_hstate_idx to HPAGE_SIZE hstate. And, if the
4057 * number of huge pages for this default size was implicitly
4058 * specified, set that here as well.
4059 * Note that the implicit setting will overwrite an explicit
4060 * setting. A warning will be printed in this case.
4062 default_hstate_idx = hstate_index(size_to_hstate(HPAGE_SIZE));
4063 if (default_hstate_max_huge_pages) {
4064 if (default_hstate.max_huge_pages) {
4067 string_get_size(huge_page_size(&default_hstate),
4068 1, STRING_UNITS_2, buf, 32);
4069 pr_warn("HugeTLB: Ignoring hugepages=%lu associated with %s page size\n",
4070 default_hstate.max_huge_pages, buf);
4071 pr_warn("HugeTLB: Using hugepages=%lu for number of default huge pages\n",
4072 default_hstate_max_huge_pages);
4074 default_hstate.max_huge_pages =
4075 default_hstate_max_huge_pages;
4077 for_each_online_node(i)
4078 default_hstate.max_huge_pages_node[i] =
4079 default_hugepages_in_node[i];
4083 hugetlb_cma_check();
4084 hugetlb_init_hstates();
4085 gather_bootmem_prealloc();
4088 hugetlb_sysfs_init();
4089 hugetlb_cgroup_file_init();
4092 num_fault_mutexes = roundup_pow_of_two(8 * num_possible_cpus());
4094 num_fault_mutexes = 1;
4096 hugetlb_fault_mutex_table =
4097 kmalloc_array(num_fault_mutexes, sizeof(struct mutex),
4099 BUG_ON(!hugetlb_fault_mutex_table);
4101 for (i = 0; i < num_fault_mutexes; i++)
4102 mutex_init(&hugetlb_fault_mutex_table[i]);
4105 subsys_initcall(hugetlb_init);
4107 /* Overwritten by architectures with more huge page sizes */
4108 bool __init __attribute((weak)) arch_hugetlb_valid_size(unsigned long size)
4110 return size == HPAGE_SIZE;
4113 void __init hugetlb_add_hstate(unsigned int order)
4118 if (size_to_hstate(PAGE_SIZE << order)) {
4121 BUG_ON(hugetlb_max_hstate >= HUGE_MAX_HSTATE);
4123 h = &hstates[hugetlb_max_hstate++];
4124 mutex_init(&h->resize_lock);
4126 h->mask = ~(huge_page_size(h) - 1);
4127 for (i = 0; i < MAX_NUMNODES; ++i)
4128 INIT_LIST_HEAD(&h->hugepage_freelists[i]);
4129 INIT_LIST_HEAD(&h->hugepage_activelist);
4130 h->next_nid_to_alloc = first_memory_node;
4131 h->next_nid_to_free = first_memory_node;
4132 snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB",
4133 huge_page_size(h)/SZ_1K);
4138 bool __init __weak hugetlb_node_alloc_supported(void)
4143 static void __init hugepages_clear_pages_in_node(void)
4145 if (!hugetlb_max_hstate) {
4146 default_hstate_max_huge_pages = 0;
4147 memset(default_hugepages_in_node, 0,
4148 sizeof(default_hugepages_in_node));
4150 parsed_hstate->max_huge_pages = 0;
4151 memset(parsed_hstate->max_huge_pages_node, 0,
4152 sizeof(parsed_hstate->max_huge_pages_node));
4157 * hugepages command line processing
4158 * hugepages normally follows a valid hugepagsz or default_hugepagsz
4159 * specification. If not, ignore the hugepages value. hugepages can also
4160 * be the first huge page command line option in which case it implicitly
4161 * specifies the number of huge pages for the default size.
4163 static int __init hugepages_setup(char *s)
4166 static unsigned long *last_mhp;
4167 int node = NUMA_NO_NODE;
4172 if (!parsed_valid_hugepagesz) {
4173 pr_warn("HugeTLB: hugepages=%s does not follow a valid hugepagesz, ignoring\n", s);
4174 parsed_valid_hugepagesz = true;
4179 * !hugetlb_max_hstate means we haven't parsed a hugepagesz= parameter
4180 * yet, so this hugepages= parameter goes to the "default hstate".
4181 * Otherwise, it goes with the previously parsed hugepagesz or
4182 * default_hugepagesz.
4184 else if (!hugetlb_max_hstate)
4185 mhp = &default_hstate_max_huge_pages;
4187 mhp = &parsed_hstate->max_huge_pages;
4189 if (mhp == last_mhp) {
4190 pr_warn("HugeTLB: hugepages= specified twice without interleaving hugepagesz=, ignoring hugepages=%s\n", s);
4196 if (sscanf(p, "%lu%n", &tmp, &count) != 1)
4198 /* Parameter is node format */
4199 if (p[count] == ':') {
4200 if (!hugetlb_node_alloc_supported()) {
4201 pr_warn("HugeTLB: architecture can't support node specific alloc, ignoring!\n");
4204 if (tmp >= MAX_NUMNODES || !node_online(tmp))
4206 node = array_index_nospec(tmp, MAX_NUMNODES);
4208 /* Parse hugepages */
4209 if (sscanf(p, "%lu%n", &tmp, &count) != 1)
4211 if (!hugetlb_max_hstate)
4212 default_hugepages_in_node[node] = tmp;
4214 parsed_hstate->max_huge_pages_node[node] = tmp;
4216 /* Go to parse next node*/
4217 if (p[count] == ',')
4230 * Global state is always initialized later in hugetlb_init.
4231 * But we need to allocate gigantic hstates here early to still
4232 * use the bootmem allocator.
4234 if (hugetlb_max_hstate && hstate_is_gigantic(parsed_hstate))
4235 hugetlb_hstate_alloc_pages(parsed_hstate);
4242 pr_warn("HugeTLB: Invalid hugepages parameter %s\n", p);
4243 hugepages_clear_pages_in_node();
4246 __setup("hugepages=", hugepages_setup);
4249 * hugepagesz command line processing
4250 * A specific huge page size can only be specified once with hugepagesz.
4251 * hugepagesz is followed by hugepages on the command line. The global
4252 * variable 'parsed_valid_hugepagesz' is used to determine if prior
4253 * hugepagesz argument was valid.
4255 static int __init hugepagesz_setup(char *s)
4260 parsed_valid_hugepagesz = false;
4261 size = (unsigned long)memparse(s, NULL);
4263 if (!arch_hugetlb_valid_size(size)) {
4264 pr_err("HugeTLB: unsupported hugepagesz=%s\n", s);
4268 h = size_to_hstate(size);
4271 * hstate for this size already exists. This is normally
4272 * an error, but is allowed if the existing hstate is the
4273 * default hstate. More specifically, it is only allowed if
4274 * the number of huge pages for the default hstate was not
4275 * previously specified.
4277 if (!parsed_default_hugepagesz || h != &default_hstate ||
4278 default_hstate.max_huge_pages) {
4279 pr_warn("HugeTLB: hugepagesz=%s specified twice, ignoring\n", s);
4284 * No need to call hugetlb_add_hstate() as hstate already
4285 * exists. But, do set parsed_hstate so that a following
4286 * hugepages= parameter will be applied to this hstate.
4289 parsed_valid_hugepagesz = true;
4293 hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
4294 parsed_valid_hugepagesz = true;
4297 __setup("hugepagesz=", hugepagesz_setup);
4300 * default_hugepagesz command line input
4301 * Only one instance of default_hugepagesz allowed on command line.
4303 static int __init default_hugepagesz_setup(char *s)
4308 parsed_valid_hugepagesz = false;
4309 if (parsed_default_hugepagesz) {
4310 pr_err("HugeTLB: default_hugepagesz previously specified, ignoring %s\n", s);
4314 size = (unsigned long)memparse(s, NULL);
4316 if (!arch_hugetlb_valid_size(size)) {
4317 pr_err("HugeTLB: unsupported default_hugepagesz=%s\n", s);
4321 hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
4322 parsed_valid_hugepagesz = true;
4323 parsed_default_hugepagesz = true;
4324 default_hstate_idx = hstate_index(size_to_hstate(size));
4327 * The number of default huge pages (for this size) could have been
4328 * specified as the first hugetlb parameter: hugepages=X. If so,
4329 * then default_hstate_max_huge_pages is set. If the default huge
4330 * page size is gigantic (>= MAX_ORDER), then the pages must be
4331 * allocated here from bootmem allocator.
4333 if (default_hstate_max_huge_pages) {
4334 default_hstate.max_huge_pages = default_hstate_max_huge_pages;
4335 for_each_online_node(i)
4336 default_hstate.max_huge_pages_node[i] =
4337 default_hugepages_in_node[i];
4338 if (hstate_is_gigantic(&default_hstate))
4339 hugetlb_hstate_alloc_pages(&default_hstate);
4340 default_hstate_max_huge_pages = 0;
4345 __setup("default_hugepagesz=", default_hugepagesz_setup);
4347 static nodemask_t *policy_mbind_nodemask(gfp_t gfp)
4350 struct mempolicy *mpol = get_task_policy(current);
4353 * Only enforce MPOL_BIND policy which overlaps with cpuset policy
4354 * (from policy_nodemask) specifically for hugetlb case
4356 if (mpol->mode == MPOL_BIND &&
4357 (apply_policy_zone(mpol, gfp_zone(gfp)) &&
4358 cpuset_nodemask_valid_mems_allowed(&mpol->nodes)))
4359 return &mpol->nodes;
4364 static unsigned int allowed_mems_nr(struct hstate *h)
4367 unsigned int nr = 0;
4368 nodemask_t *mbind_nodemask;
4369 unsigned int *array = h->free_huge_pages_node;
4370 gfp_t gfp_mask = htlb_alloc_mask(h);
4372 mbind_nodemask = policy_mbind_nodemask(gfp_mask);
4373 for_each_node_mask(node, cpuset_current_mems_allowed) {
4374 if (!mbind_nodemask || node_isset(node, *mbind_nodemask))
4381 #ifdef CONFIG_SYSCTL
4382 static int proc_hugetlb_doulongvec_minmax(struct ctl_table *table, int write,
4383 void *buffer, size_t *length,
4384 loff_t *ppos, unsigned long *out)
4386 struct ctl_table dup_table;
4389 * In order to avoid races with __do_proc_doulongvec_minmax(), we
4390 * can duplicate the @table and alter the duplicate of it.
4393 dup_table.data = out;
4395 return proc_doulongvec_minmax(&dup_table, write, buffer, length, ppos);
4398 static int hugetlb_sysctl_handler_common(bool obey_mempolicy,
4399 struct ctl_table *table, int write,
4400 void *buffer, size_t *length, loff_t *ppos)
4402 struct hstate *h = &default_hstate;
4403 unsigned long tmp = h->max_huge_pages;
4406 if (!hugepages_supported())
4409 ret = proc_hugetlb_doulongvec_minmax(table, write, buffer, length, ppos,
4415 ret = __nr_hugepages_store_common(obey_mempolicy, h,
4416 NUMA_NO_NODE, tmp, *length);
4421 int hugetlb_sysctl_handler(struct ctl_table *table, int write,
4422 void *buffer, size_t *length, loff_t *ppos)
4425 return hugetlb_sysctl_handler_common(false, table, write,
4426 buffer, length, ppos);
4430 int hugetlb_mempolicy_sysctl_handler(struct ctl_table *table, int write,
4431 void *buffer, size_t *length, loff_t *ppos)
4433 return hugetlb_sysctl_handler_common(true, table, write,
4434 buffer, length, ppos);
4436 #endif /* CONFIG_NUMA */
4438 int hugetlb_overcommit_handler(struct ctl_table *table, int write,
4439 void *buffer, size_t *length, loff_t *ppos)
4441 struct hstate *h = &default_hstate;
4445 if (!hugepages_supported())
4448 tmp = h->nr_overcommit_huge_pages;
4450 if (write && hstate_is_gigantic(h))
4453 ret = proc_hugetlb_doulongvec_minmax(table, write, buffer, length, ppos,
4459 spin_lock_irq(&hugetlb_lock);
4460 h->nr_overcommit_huge_pages = tmp;
4461 spin_unlock_irq(&hugetlb_lock);
4467 #endif /* CONFIG_SYSCTL */
4469 void hugetlb_report_meminfo(struct seq_file *m)
4472 unsigned long total = 0;
4474 if (!hugepages_supported())
4477 for_each_hstate(h) {
4478 unsigned long count = h->nr_huge_pages;
4480 total += huge_page_size(h) * count;
4482 if (h == &default_hstate)
4484 "HugePages_Total: %5lu\n"
4485 "HugePages_Free: %5lu\n"
4486 "HugePages_Rsvd: %5lu\n"
4487 "HugePages_Surp: %5lu\n"
4488 "Hugepagesize: %8lu kB\n",
4492 h->surplus_huge_pages,
4493 huge_page_size(h) / SZ_1K);
4496 seq_printf(m, "Hugetlb: %8lu kB\n", total / SZ_1K);
4499 int hugetlb_report_node_meminfo(char *buf, int len, int nid)
4501 struct hstate *h = &default_hstate;
4503 if (!hugepages_supported())
4506 return sysfs_emit_at(buf, len,
4507 "Node %d HugePages_Total: %5u\n"
4508 "Node %d HugePages_Free: %5u\n"
4509 "Node %d HugePages_Surp: %5u\n",
4510 nid, h->nr_huge_pages_node[nid],
4511 nid, h->free_huge_pages_node[nid],
4512 nid, h->surplus_huge_pages_node[nid]);
4515 void hugetlb_show_meminfo_node(int nid)
4519 if (!hugepages_supported())
4523 printk("Node %d hugepages_total=%u hugepages_free=%u hugepages_surp=%u hugepages_size=%lukB\n",
4525 h->nr_huge_pages_node[nid],
4526 h->free_huge_pages_node[nid],
4527 h->surplus_huge_pages_node[nid],
4528 huge_page_size(h) / SZ_1K);
4531 void hugetlb_report_usage(struct seq_file *m, struct mm_struct *mm)
4533 seq_printf(m, "HugetlbPages:\t%8lu kB\n",
4534 atomic_long_read(&mm->hugetlb_usage) << (PAGE_SHIFT - 10));
4537 /* Return the number pages of memory we physically have, in PAGE_SIZE units. */
4538 unsigned long hugetlb_total_pages(void)
4541 unsigned long nr_total_pages = 0;
4544 nr_total_pages += h->nr_huge_pages * pages_per_huge_page(h);
4545 return nr_total_pages;
4548 static int hugetlb_acct_memory(struct hstate *h, long delta)
4555 spin_lock_irq(&hugetlb_lock);
4557 * When cpuset is configured, it breaks the strict hugetlb page
4558 * reservation as the accounting is done on a global variable. Such
4559 * reservation is completely rubbish in the presence of cpuset because
4560 * the reservation is not checked against page availability for the
4561 * current cpuset. Application can still potentially OOM'ed by kernel
4562 * with lack of free htlb page in cpuset that the task is in.
4563 * Attempt to enforce strict accounting with cpuset is almost
4564 * impossible (or too ugly) because cpuset is too fluid that
4565 * task or memory node can be dynamically moved between cpusets.
4567 * The change of semantics for shared hugetlb mapping with cpuset is
4568 * undesirable. However, in order to preserve some of the semantics,
4569 * we fall back to check against current free page availability as
4570 * a best attempt and hopefully to minimize the impact of changing
4571 * semantics that cpuset has.
4573 * Apart from cpuset, we also have memory policy mechanism that
4574 * also determines from which node the kernel will allocate memory
4575 * in a NUMA system. So similar to cpuset, we also should consider
4576 * the memory policy of the current task. Similar to the description
4580 if (gather_surplus_pages(h, delta) < 0)
4583 if (delta > allowed_mems_nr(h)) {
4584 return_unused_surplus_pages(h, delta);
4591 return_unused_surplus_pages(h, (unsigned long) -delta);
4594 spin_unlock_irq(&hugetlb_lock);
4598 static void hugetlb_vm_op_open(struct vm_area_struct *vma)
4600 struct resv_map *resv = vma_resv_map(vma);
4603 * This new VMA should share its siblings reservation map if present.
4604 * The VMA will only ever have a valid reservation map pointer where
4605 * it is being copied for another still existing VMA. As that VMA
4606 * has a reference to the reservation map it cannot disappear until
4607 * after this open call completes. It is therefore safe to take a
4608 * new reference here without additional locking.
4610 if (resv && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
4611 resv_map_dup_hugetlb_cgroup_uncharge_info(resv);
4612 kref_get(&resv->refs);
4616 * vma_lock structure for sharable mappings is vma specific.
4617 * Clear old pointer (if copied via vm_area_dup) and create new.
4619 if (vma->vm_flags & VM_MAYSHARE) {
4620 vma->vm_private_data = NULL;
4621 hugetlb_vma_lock_alloc(vma);
4625 static void hugetlb_vm_op_close(struct vm_area_struct *vma)
4627 struct hstate *h = hstate_vma(vma);
4628 struct resv_map *resv;
4629 struct hugepage_subpool *spool = subpool_vma(vma);
4630 unsigned long reserve, start, end;
4633 hugetlb_vma_lock_free(vma);
4635 resv = vma_resv_map(vma);
4636 if (!resv || !is_vma_resv_set(vma, HPAGE_RESV_OWNER))
4639 start = vma_hugecache_offset(h, vma, vma->vm_start);
4640 end = vma_hugecache_offset(h, vma, vma->vm_end);
4642 reserve = (end - start) - region_count(resv, start, end);
4643 hugetlb_cgroup_uncharge_counter(resv, start, end);
4646 * Decrement reserve counts. The global reserve count may be
4647 * adjusted if the subpool has a minimum size.
4649 gbl_reserve = hugepage_subpool_put_pages(spool, reserve);
4650 hugetlb_acct_memory(h, -gbl_reserve);
4653 kref_put(&resv->refs, resv_map_release);
4656 static int hugetlb_vm_op_split(struct vm_area_struct *vma, unsigned long addr)
4658 if (addr & ~(huge_page_mask(hstate_vma(vma))))
4663 static unsigned long hugetlb_vm_op_pagesize(struct vm_area_struct *vma)
4665 return huge_page_size(hstate_vma(vma));
4669 * We cannot handle pagefaults against hugetlb pages at all. They cause
4670 * handle_mm_fault() to try to instantiate regular-sized pages in the
4671 * hugepage VMA. do_page_fault() is supposed to trap this, so BUG is we get
4674 static vm_fault_t hugetlb_vm_op_fault(struct vm_fault *vmf)
4681 * When a new function is introduced to vm_operations_struct and added
4682 * to hugetlb_vm_ops, please consider adding the function to shm_vm_ops.
4683 * This is because under System V memory model, mappings created via
4684 * shmget/shmat with "huge page" specified are backed by hugetlbfs files,
4685 * their original vm_ops are overwritten with shm_vm_ops.
4687 const struct vm_operations_struct hugetlb_vm_ops = {
4688 .fault = hugetlb_vm_op_fault,
4689 .open = hugetlb_vm_op_open,
4690 .close = hugetlb_vm_op_close,
4691 .may_split = hugetlb_vm_op_split,
4692 .pagesize = hugetlb_vm_op_pagesize,
4695 static pte_t make_huge_pte(struct vm_area_struct *vma, struct page *page,
4699 unsigned int shift = huge_page_shift(hstate_vma(vma));
4702 entry = huge_pte_mkwrite(huge_pte_mkdirty(mk_huge_pte(page,
4703 vma->vm_page_prot)));
4705 entry = huge_pte_wrprotect(mk_huge_pte(page,
4706 vma->vm_page_prot));
4708 entry = pte_mkyoung(entry);
4709 entry = arch_make_huge_pte(entry, shift, vma->vm_flags);
4714 static void set_huge_ptep_writable(struct vm_area_struct *vma,
4715 unsigned long address, pte_t *ptep)
4719 entry = huge_pte_mkwrite(huge_pte_mkdirty(huge_ptep_get(ptep)));
4720 if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1))
4721 update_mmu_cache(vma, address, ptep);
4724 bool is_hugetlb_entry_migration(pte_t pte)
4728 if (huge_pte_none(pte) || pte_present(pte))
4730 swp = pte_to_swp_entry(pte);
4731 if (is_migration_entry(swp))
4737 static bool is_hugetlb_entry_hwpoisoned(pte_t pte)
4741 if (huge_pte_none(pte) || pte_present(pte))
4743 swp = pte_to_swp_entry(pte);
4744 if (is_hwpoison_entry(swp))
4751 hugetlb_install_page(struct vm_area_struct *vma, pte_t *ptep, unsigned long addr,
4752 struct page *new_page)
4754 __SetPageUptodate(new_page);
4755 hugepage_add_new_anon_rmap(new_page, vma, addr);
4756 set_huge_pte_at(vma->vm_mm, addr, ptep, make_huge_pte(vma, new_page, 1));
4757 hugetlb_count_add(pages_per_huge_page(hstate_vma(vma)), vma->vm_mm);
4758 ClearHPageRestoreReserve(new_page);
4759 SetHPageMigratable(new_page);
4762 int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src,
4763 struct vm_area_struct *dst_vma,
4764 struct vm_area_struct *src_vma)
4766 pte_t *src_pte, *dst_pte, entry;
4767 struct page *ptepage;
4769 bool cow = is_cow_mapping(src_vma->vm_flags);
4770 struct hstate *h = hstate_vma(src_vma);
4771 unsigned long sz = huge_page_size(h);
4772 unsigned long npages = pages_per_huge_page(h);
4773 struct mmu_notifier_range range;
4774 unsigned long last_addr_mask;
4778 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, src_vma, src,
4781 mmu_notifier_invalidate_range_start(&range);
4782 mmap_assert_write_locked(src);
4783 raw_write_seqcount_begin(&src->write_protect_seq);
4786 * For shared mappings the vma lock must be held before
4787 * calling huge_pte_offset in the src vma. Otherwise, the
4788 * returned ptep could go away if part of a shared pmd and
4789 * another thread calls huge_pmd_unshare.
4791 hugetlb_vma_lock_read(src_vma);
4794 last_addr_mask = hugetlb_mask_last_page(h);
4795 for (addr = src_vma->vm_start; addr < src_vma->vm_end; addr += sz) {
4796 spinlock_t *src_ptl, *dst_ptl;
4797 src_pte = huge_pte_offset(src, addr, sz);
4799 addr |= last_addr_mask;
4802 dst_pte = huge_pte_alloc(dst, dst_vma, addr, sz);
4809 * If the pagetables are shared don't copy or take references.
4811 * dst_pte == src_pte is the common case of src/dest sharing.
4812 * However, src could have 'unshared' and dst shares with
4813 * another vma. So page_count of ptep page is checked instead
4814 * to reliably determine whether pte is shared.
4816 if (page_count(virt_to_page(dst_pte)) > 1) {
4817 addr |= last_addr_mask;
4821 dst_ptl = huge_pte_lock(h, dst, dst_pte);
4822 src_ptl = huge_pte_lockptr(h, src, src_pte);
4823 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
4824 entry = huge_ptep_get(src_pte);
4826 if (huge_pte_none(entry)) {
4828 * Skip if src entry none.
4831 } else if (unlikely(is_hugetlb_entry_hwpoisoned(entry))) {
4832 bool uffd_wp = huge_pte_uffd_wp(entry);
4834 if (!userfaultfd_wp(dst_vma) && uffd_wp)
4835 entry = huge_pte_clear_uffd_wp(entry);
4836 set_huge_pte_at(dst, addr, dst_pte, entry);
4837 } else if (unlikely(is_hugetlb_entry_migration(entry))) {
4838 swp_entry_t swp_entry = pte_to_swp_entry(entry);
4839 bool uffd_wp = huge_pte_uffd_wp(entry);
4841 if (!is_readable_migration_entry(swp_entry) && cow) {
4843 * COW mappings require pages in both
4844 * parent and child to be set to read.
4846 swp_entry = make_readable_migration_entry(
4847 swp_offset(swp_entry));
4848 entry = swp_entry_to_pte(swp_entry);
4849 if (userfaultfd_wp(src_vma) && uffd_wp)
4850 entry = huge_pte_mkuffd_wp(entry);
4851 set_huge_pte_at(src, addr, src_pte, entry);
4853 if (!userfaultfd_wp(dst_vma) && uffd_wp)
4854 entry = huge_pte_clear_uffd_wp(entry);
4855 set_huge_pte_at(dst, addr, dst_pte, entry);
4856 } else if (unlikely(is_pte_marker(entry))) {
4858 * We copy the pte marker only if the dst vma has
4861 if (userfaultfd_wp(dst_vma))
4862 set_huge_pte_at(dst, addr, dst_pte, entry);
4864 entry = huge_ptep_get(src_pte);
4865 ptepage = pte_page(entry);
4869 * Failing to duplicate the anon rmap is a rare case
4870 * where we see pinned hugetlb pages while they're
4871 * prone to COW. We need to do the COW earlier during
4874 * When pre-allocating the page or copying data, we
4875 * need to be without the pgtable locks since we could
4876 * sleep during the process.
4878 if (!PageAnon(ptepage)) {
4879 page_dup_file_rmap(ptepage, true);
4880 } else if (page_try_dup_anon_rmap(ptepage, true,
4882 pte_t src_pte_old = entry;
4885 spin_unlock(src_ptl);
4886 spin_unlock(dst_ptl);
4887 /* Do not use reserve as it's private owned */
4888 new = alloc_huge_page(dst_vma, addr, 1);
4894 copy_user_huge_page(new, ptepage, addr, dst_vma,
4898 /* Install the new huge page if src pte stable */
4899 dst_ptl = huge_pte_lock(h, dst, dst_pte);
4900 src_ptl = huge_pte_lockptr(h, src, src_pte);
4901 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
4902 entry = huge_ptep_get(src_pte);
4903 if (!pte_same(src_pte_old, entry)) {
4904 restore_reserve_on_error(h, dst_vma, addr,
4907 /* huge_ptep of dst_pte won't change as in child */
4910 hugetlb_install_page(dst_vma, dst_pte, addr, new);
4911 spin_unlock(src_ptl);
4912 spin_unlock(dst_ptl);
4918 * No need to notify as we are downgrading page
4919 * table protection not changing it to point
4922 * See Documentation/mm/mmu_notifier.rst
4924 huge_ptep_set_wrprotect(src, addr, src_pte);
4925 entry = huge_pte_wrprotect(entry);
4928 set_huge_pte_at(dst, addr, dst_pte, entry);
4929 hugetlb_count_add(npages, dst);
4931 spin_unlock(src_ptl);
4932 spin_unlock(dst_ptl);
4936 raw_write_seqcount_end(&src->write_protect_seq);
4937 mmu_notifier_invalidate_range_end(&range);
4939 hugetlb_vma_unlock_read(src_vma);
4945 static void move_huge_pte(struct vm_area_struct *vma, unsigned long old_addr,
4946 unsigned long new_addr, pte_t *src_pte, pte_t *dst_pte)
4948 struct hstate *h = hstate_vma(vma);
4949 struct mm_struct *mm = vma->vm_mm;
4950 spinlock_t *src_ptl, *dst_ptl;
4953 dst_ptl = huge_pte_lock(h, mm, dst_pte);
4954 src_ptl = huge_pte_lockptr(h, mm, src_pte);
4957 * We don't have to worry about the ordering of src and dst ptlocks
4958 * because exclusive mmap_sem (or the i_mmap_lock) prevents deadlock.
4960 if (src_ptl != dst_ptl)
4961 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
4963 pte = huge_ptep_get_and_clear(mm, old_addr, src_pte);
4964 set_huge_pte_at(mm, new_addr, dst_pte, pte);
4966 if (src_ptl != dst_ptl)
4967 spin_unlock(src_ptl);
4968 spin_unlock(dst_ptl);
4971 int move_hugetlb_page_tables(struct vm_area_struct *vma,
4972 struct vm_area_struct *new_vma,
4973 unsigned long old_addr, unsigned long new_addr,
4976 struct hstate *h = hstate_vma(vma);
4977 struct address_space *mapping = vma->vm_file->f_mapping;
4978 unsigned long sz = huge_page_size(h);
4979 struct mm_struct *mm = vma->vm_mm;
4980 unsigned long old_end = old_addr + len;
4981 unsigned long last_addr_mask;
4982 pte_t *src_pte, *dst_pte;
4983 struct mmu_notifier_range range;
4984 bool shared_pmd = false;
4986 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm, old_addr,
4988 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
4990 * In case of shared PMDs, we should cover the maximum possible
4993 flush_cache_range(vma, range.start, range.end);
4995 mmu_notifier_invalidate_range_start(&range);
4996 last_addr_mask = hugetlb_mask_last_page(h);
4997 /* Prevent race with file truncation */
4998 hugetlb_vma_lock_write(vma);
4999 i_mmap_lock_write(mapping);
5000 for (; old_addr < old_end; old_addr += sz, new_addr += sz) {
5001 src_pte = huge_pte_offset(mm, old_addr, sz);
5003 old_addr |= last_addr_mask;
5004 new_addr |= last_addr_mask;
5007 if (huge_pte_none(huge_ptep_get(src_pte)))
5010 if (huge_pmd_unshare(mm, vma, old_addr, src_pte)) {
5012 old_addr |= last_addr_mask;
5013 new_addr |= last_addr_mask;
5017 dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz);
5021 move_huge_pte(vma, old_addr, new_addr, src_pte, dst_pte);
5025 flush_tlb_range(vma, range.start, range.end);
5027 flush_tlb_range(vma, old_end - len, old_end);
5028 mmu_notifier_invalidate_range_end(&range);
5029 i_mmap_unlock_write(mapping);
5030 hugetlb_vma_unlock_write(vma);
5032 return len + old_addr - old_end;
5035 static void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
5036 unsigned long start, unsigned long end,
5037 struct page *ref_page, zap_flags_t zap_flags)
5039 struct mm_struct *mm = vma->vm_mm;
5040 unsigned long address;
5045 struct hstate *h = hstate_vma(vma);
5046 unsigned long sz = huge_page_size(h);
5047 struct mmu_notifier_range range;
5048 unsigned long last_addr_mask;
5049 bool force_flush = false;
5051 WARN_ON(!is_vm_hugetlb_page(vma));
5052 BUG_ON(start & ~huge_page_mask(h));
5053 BUG_ON(end & ~huge_page_mask(h));
5056 * This is a hugetlb vma, all the pte entries should point
5059 tlb_change_page_size(tlb, sz);
5060 tlb_start_vma(tlb, vma);
5063 * If sharing possible, alert mmu notifiers of worst case.
5065 mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, mm, start,
5067 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
5068 mmu_notifier_invalidate_range_start(&range);
5069 last_addr_mask = hugetlb_mask_last_page(h);
5071 for (; address < end; address += sz) {
5072 ptep = huge_pte_offset(mm, address, sz);
5074 address |= last_addr_mask;
5078 ptl = huge_pte_lock(h, mm, ptep);
5079 if (huge_pmd_unshare(mm, vma, address, ptep)) {
5081 tlb_flush_pmd_range(tlb, address & PUD_MASK, PUD_SIZE);
5083 address |= last_addr_mask;
5087 pte = huge_ptep_get(ptep);
5088 if (huge_pte_none(pte)) {
5094 * Migrating hugepage or HWPoisoned hugepage is already
5095 * unmapped and its refcount is dropped, so just clear pte here.
5097 if (unlikely(!pte_present(pte))) {
5099 * If the pte was wr-protected by uffd-wp in any of the
5100 * swap forms, meanwhile the caller does not want to
5101 * drop the uffd-wp bit in this zap, then replace the
5102 * pte with a marker.
5104 if (pte_swp_uffd_wp_any(pte) &&
5105 !(zap_flags & ZAP_FLAG_DROP_MARKER))
5106 set_huge_pte_at(mm, address, ptep,
5107 make_pte_marker(PTE_MARKER_UFFD_WP));
5109 huge_pte_clear(mm, address, ptep, sz);
5114 page = pte_page(pte);
5116 * If a reference page is supplied, it is because a specific
5117 * page is being unmapped, not a range. Ensure the page we
5118 * are about to unmap is the actual page of interest.
5121 if (page != ref_page) {
5126 * Mark the VMA as having unmapped its page so that
5127 * future faults in this VMA will fail rather than
5128 * looking like data was lost
5130 set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED);
5133 pte = huge_ptep_get_and_clear(mm, address, ptep);
5134 tlb_remove_huge_tlb_entry(h, tlb, ptep, address);
5135 if (huge_pte_dirty(pte))
5136 set_page_dirty(page);
5137 /* Leave a uffd-wp pte marker if needed */
5138 if (huge_pte_uffd_wp(pte) &&
5139 !(zap_flags & ZAP_FLAG_DROP_MARKER))
5140 set_huge_pte_at(mm, address, ptep,
5141 make_pte_marker(PTE_MARKER_UFFD_WP));
5142 hugetlb_count_sub(pages_per_huge_page(h), mm);
5143 page_remove_rmap(page, vma, true);
5146 tlb_remove_page_size(tlb, page, huge_page_size(h));
5148 * Bail out after unmapping reference page if supplied
5153 mmu_notifier_invalidate_range_end(&range);
5154 tlb_end_vma(tlb, vma);
5157 * If we unshared PMDs, the TLB flush was not recorded in mmu_gather. We
5158 * could defer the flush until now, since by holding i_mmap_rwsem we
5159 * guaranteed that the last refernece would not be dropped. But we must
5160 * do the flushing before we return, as otherwise i_mmap_rwsem will be
5161 * dropped and the last reference to the shared PMDs page might be
5164 * In theory we could defer the freeing of the PMD pages as well, but
5165 * huge_pmd_unshare() relies on the exact page_count for the PMD page to
5166 * detect sharing, so we cannot defer the release of the page either.
5167 * Instead, do flush now.
5170 tlb_flush_mmu_tlbonly(tlb);
5173 void __unmap_hugepage_range_final(struct mmu_gather *tlb,
5174 struct vm_area_struct *vma, unsigned long start,
5175 unsigned long end, struct page *ref_page,
5176 zap_flags_t zap_flags)
5178 hugetlb_vma_lock_write(vma);
5179 i_mmap_lock_write(vma->vm_file->f_mapping);
5181 __unmap_hugepage_range(tlb, vma, start, end, ref_page, zap_flags);
5184 * Unlock and free the vma lock before releasing i_mmap_rwsem. When
5185 * the vma_lock is freed, this makes the vma ineligible for pmd
5186 * sharing. And, i_mmap_rwsem is required to set up pmd sharing.
5187 * This is important as page tables for this unmapped range will
5188 * be asynchrously deleted. If the page tables are shared, there
5189 * will be issues when accessed by someone else.
5191 hugetlb_vma_unlock_write(vma);
5192 hugetlb_vma_lock_free(vma);
5194 i_mmap_unlock_write(vma->vm_file->f_mapping);
5197 void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
5198 unsigned long end, struct page *ref_page,
5199 zap_flags_t zap_flags)
5201 struct mmu_gather tlb;
5203 tlb_gather_mmu(&tlb, vma->vm_mm);
5204 __unmap_hugepage_range(&tlb, vma, start, end, ref_page, zap_flags);
5205 tlb_finish_mmu(&tlb);
5209 * This is called when the original mapper is failing to COW a MAP_PRIVATE
5210 * mapping it owns the reserve page for. The intention is to unmap the page
5211 * from other VMAs and let the children be SIGKILLed if they are faulting the
5214 static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,
5215 struct page *page, unsigned long address)
5217 struct hstate *h = hstate_vma(vma);
5218 struct vm_area_struct *iter_vma;
5219 struct address_space *mapping;
5223 * vm_pgoff is in PAGE_SIZE units, hence the different calculation
5224 * from page cache lookup which is in HPAGE_SIZE units.
5226 address = address & huge_page_mask(h);
5227 pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) +
5229 mapping = vma->vm_file->f_mapping;
5232 * Take the mapping lock for the duration of the table walk. As
5233 * this mapping should be shared between all the VMAs,
5234 * __unmap_hugepage_range() is called as the lock is already held
5236 i_mmap_lock_write(mapping);
5237 vma_interval_tree_foreach(iter_vma, &mapping->i_mmap, pgoff, pgoff) {
5238 /* Do not unmap the current VMA */
5239 if (iter_vma == vma)
5243 * Shared VMAs have their own reserves and do not affect
5244 * MAP_PRIVATE accounting but it is possible that a shared
5245 * VMA is using the same page so check and skip such VMAs.
5247 if (iter_vma->vm_flags & VM_MAYSHARE)
5251 * Unmap the page from other VMAs without their own reserves.
5252 * They get marked to be SIGKILLed if they fault in these
5253 * areas. This is because a future no-page fault on this VMA
5254 * could insert a zeroed page instead of the data existing
5255 * from the time of fork. This would look like data corruption
5257 if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER))
5258 unmap_hugepage_range(iter_vma, address,
5259 address + huge_page_size(h), page, 0);
5261 i_mmap_unlock_write(mapping);
5265 * hugetlb_wp() should be called with page lock of the original hugepage held.
5266 * Called with hugetlb_fault_mutex_table held and pte_page locked so we
5267 * cannot race with other handlers or page migration.
5268 * Keep the pte_same checks anyway to make transition from the mutex easier.
5270 static vm_fault_t hugetlb_wp(struct mm_struct *mm, struct vm_area_struct *vma,
5271 unsigned long address, pte_t *ptep, unsigned int flags,
5272 struct page *pagecache_page, spinlock_t *ptl)
5274 const bool unshare = flags & FAULT_FLAG_UNSHARE;
5276 struct hstate *h = hstate_vma(vma);
5277 struct page *old_page, *new_page;
5278 int outside_reserve = 0;
5280 unsigned long haddr = address & huge_page_mask(h);
5281 struct mmu_notifier_range range;
5283 VM_BUG_ON(unshare && (flags & FOLL_WRITE));
5284 VM_BUG_ON(!unshare && !(flags & FOLL_WRITE));
5287 * hugetlb does not support FOLL_FORCE-style write faults that keep the
5288 * PTE mapped R/O such as maybe_mkwrite() would do.
5290 if (WARN_ON_ONCE(!unshare && !(vma->vm_flags & VM_WRITE)))
5291 return VM_FAULT_SIGSEGV;
5293 /* Let's take out MAP_SHARED mappings first. */
5294 if (vma->vm_flags & VM_MAYSHARE) {
5295 if (unlikely(unshare))
5297 set_huge_ptep_writable(vma, haddr, ptep);
5301 pte = huge_ptep_get(ptep);
5302 old_page = pte_page(pte);
5304 delayacct_wpcopy_start();
5308 * If no-one else is actually using this page, we're the exclusive
5309 * owner and can reuse this page.
5311 if (page_mapcount(old_page) == 1 && PageAnon(old_page)) {
5312 if (!PageAnonExclusive(old_page))
5313 page_move_anon_rmap(old_page, vma);
5314 if (likely(!unshare))
5315 set_huge_ptep_writable(vma, haddr, ptep);
5317 delayacct_wpcopy_end();
5320 VM_BUG_ON_PAGE(PageAnon(old_page) && PageAnonExclusive(old_page),
5324 * If the process that created a MAP_PRIVATE mapping is about to
5325 * perform a COW due to a shared page count, attempt to satisfy
5326 * the allocation without using the existing reserves. The pagecache
5327 * page is used to determine if the reserve at this address was
5328 * consumed or not. If reserves were used, a partial faulted mapping
5329 * at the time of fork() could consume its reserves on COW instead
5330 * of the full address range.
5332 if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) &&
5333 old_page != pagecache_page)
5334 outside_reserve = 1;
5339 * Drop page table lock as buddy allocator may be called. It will
5340 * be acquired again before returning to the caller, as expected.
5343 new_page = alloc_huge_page(vma, haddr, outside_reserve);
5345 if (IS_ERR(new_page)) {
5347 * If a process owning a MAP_PRIVATE mapping fails to COW,
5348 * it is due to references held by a child and an insufficient
5349 * huge page pool. To guarantee the original mappers
5350 * reliability, unmap the page from child processes. The child
5351 * may get SIGKILLed if it later faults.
5353 if (outside_reserve) {
5354 struct address_space *mapping = vma->vm_file->f_mapping;
5360 * Drop hugetlb_fault_mutex and vma_lock before
5361 * unmapping. unmapping needs to hold vma_lock
5362 * in write mode. Dropping vma_lock in read mode
5363 * here is OK as COW mappings do not interact with
5366 * Reacquire both after unmap operation.
5368 idx = vma_hugecache_offset(h, vma, haddr);
5369 hash = hugetlb_fault_mutex_hash(mapping, idx);
5370 hugetlb_vma_unlock_read(vma);
5371 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
5373 unmap_ref_private(mm, vma, old_page, haddr);
5375 mutex_lock(&hugetlb_fault_mutex_table[hash]);
5376 hugetlb_vma_lock_read(vma);
5378 ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
5380 pte_same(huge_ptep_get(ptep), pte)))
5381 goto retry_avoidcopy;
5383 * race occurs while re-acquiring page table
5384 * lock, and our job is done.
5386 delayacct_wpcopy_end();
5390 ret = vmf_error(PTR_ERR(new_page));
5391 goto out_release_old;
5395 * When the original hugepage is shared one, it does not have
5396 * anon_vma prepared.
5398 if (unlikely(anon_vma_prepare(vma))) {
5400 goto out_release_all;
5403 copy_user_huge_page(new_page, old_page, address, vma,
5404 pages_per_huge_page(h));
5405 __SetPageUptodate(new_page);
5407 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm, haddr,
5408 haddr + huge_page_size(h));
5409 mmu_notifier_invalidate_range_start(&range);
5412 * Retake the page table lock to check for racing updates
5413 * before the page tables are altered
5416 ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
5417 if (likely(ptep && pte_same(huge_ptep_get(ptep), pte))) {
5418 ClearHPageRestoreReserve(new_page);
5420 /* Break COW or unshare */
5421 huge_ptep_clear_flush(vma, haddr, ptep);
5422 mmu_notifier_invalidate_range(mm, range.start, range.end);
5423 page_remove_rmap(old_page, vma, true);
5424 hugepage_add_new_anon_rmap(new_page, vma, haddr);
5425 set_huge_pte_at(mm, haddr, ptep,
5426 make_huge_pte(vma, new_page, !unshare));
5427 SetHPageMigratable(new_page);
5428 /* Make the old page be freed below */
5429 new_page = old_page;
5432 mmu_notifier_invalidate_range_end(&range);
5435 * No restore in case of successful pagetable update (Break COW or
5438 if (new_page != old_page)
5439 restore_reserve_on_error(h, vma, haddr, new_page);
5444 spin_lock(ptl); /* Caller expects lock to be held */
5446 delayacct_wpcopy_end();
5451 * Return whether there is a pagecache page to back given address within VMA.
5452 * Caller follow_hugetlb_page() holds page_table_lock so we cannot lock_page.
5454 static bool hugetlbfs_pagecache_present(struct hstate *h,
5455 struct vm_area_struct *vma, unsigned long address)
5457 struct address_space *mapping;
5461 mapping = vma->vm_file->f_mapping;
5462 idx = vma_hugecache_offset(h, vma, address);
5464 page = find_get_page(mapping, idx);
5467 return page != NULL;
5470 int hugetlb_add_to_page_cache(struct page *page, struct address_space *mapping,
5473 struct folio *folio = page_folio(page);
5474 struct inode *inode = mapping->host;
5475 struct hstate *h = hstate_inode(inode);
5478 __folio_set_locked(folio);
5479 err = __filemap_add_folio(mapping, folio, idx, GFP_KERNEL, NULL);
5481 if (unlikely(err)) {
5482 __folio_clear_locked(folio);
5485 ClearHPageRestoreReserve(page);
5488 * mark folio dirty so that it will not be removed from cache/file
5489 * by non-hugetlbfs specific code paths.
5491 folio_mark_dirty(folio);
5493 spin_lock(&inode->i_lock);
5494 inode->i_blocks += blocks_per_huge_page(h);
5495 spin_unlock(&inode->i_lock);
5499 static inline vm_fault_t hugetlb_handle_userfault(struct vm_area_struct *vma,
5500 struct address_space *mapping,
5503 unsigned long haddr,
5505 unsigned long reason)
5508 struct vm_fault vmf = {
5511 .real_address = addr,
5515 * Hard to debug if it ends up being
5516 * used by a callee that assumes
5517 * something about the other
5518 * uninitialized fields... same as in
5524 * vma_lock and hugetlb_fault_mutex must be dropped before handling
5525 * userfault. Also mmap_lock could be dropped due to handling
5526 * userfault, any vma operation should be careful from here.
5528 hugetlb_vma_unlock_read(vma);
5529 hash = hugetlb_fault_mutex_hash(mapping, idx);
5530 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
5531 return handle_userfault(&vmf, reason);
5534 static vm_fault_t hugetlb_no_page(struct mm_struct *mm,
5535 struct vm_area_struct *vma,
5536 struct address_space *mapping, pgoff_t idx,
5537 unsigned long address, pte_t *ptep,
5538 pte_t old_pte, unsigned int flags)
5540 struct hstate *h = hstate_vma(vma);
5541 vm_fault_t ret = VM_FAULT_SIGBUS;
5547 unsigned long haddr = address & huge_page_mask(h);
5548 bool new_page, new_pagecache_page = false;
5549 u32 hash = hugetlb_fault_mutex_hash(mapping, idx);
5552 * Currently, we are forced to kill the process in the event the
5553 * original mapper has unmapped pages from the child due to a failed
5554 * COW/unsharing. Warn that such a situation has occurred as it may not
5557 if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) {
5558 pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n",
5564 * Use page lock to guard against racing truncation
5565 * before we get page_table_lock.
5568 page = find_lock_page(mapping, idx);
5570 size = i_size_read(mapping->host) >> huge_page_shift(h);
5573 /* Check for page in userfault range */
5574 if (userfaultfd_missing(vma))
5575 return hugetlb_handle_userfault(vma, mapping, idx,
5576 flags, haddr, address,
5579 page = alloc_huge_page(vma, haddr, 0);
5582 * Returning error will result in faulting task being
5583 * sent SIGBUS. The hugetlb fault mutex prevents two
5584 * tasks from racing to fault in the same page which
5585 * could result in false unable to allocate errors.
5586 * Page migration does not take the fault mutex, but
5587 * does a clear then write of pte's under page table
5588 * lock. Page fault code could race with migration,
5589 * notice the clear pte and try to allocate a page
5590 * here. Before returning error, get ptl and make
5591 * sure there really is no pte entry.
5593 ptl = huge_pte_lock(h, mm, ptep);
5595 if (huge_pte_none(huge_ptep_get(ptep)))
5596 ret = vmf_error(PTR_ERR(page));
5600 clear_huge_page(page, address, pages_per_huge_page(h));
5601 __SetPageUptodate(page);
5604 if (vma->vm_flags & VM_MAYSHARE) {
5605 int err = hugetlb_add_to_page_cache(page, mapping, idx);
5608 * err can't be -EEXIST which implies someone
5609 * else consumed the reservation since hugetlb
5610 * fault mutex is held when add a hugetlb page
5611 * to the page cache. So it's safe to call
5612 * restore_reserve_on_error() here.
5614 restore_reserve_on_error(h, vma, haddr, page);
5618 new_pagecache_page = true;
5621 if (unlikely(anon_vma_prepare(vma))) {
5623 goto backout_unlocked;
5629 * If memory error occurs between mmap() and fault, some process
5630 * don't have hwpoisoned swap entry for errored virtual address.
5631 * So we need to block hugepage fault by PG_hwpoison bit check.
5633 if (unlikely(PageHWPoison(page))) {
5634 ret = VM_FAULT_HWPOISON_LARGE |
5635 VM_FAULT_SET_HINDEX(hstate_index(h));
5636 goto backout_unlocked;
5639 /* Check for page in userfault range. */
5640 if (userfaultfd_minor(vma)) {
5643 return hugetlb_handle_userfault(vma, mapping, idx,
5644 flags, haddr, address,
5650 * If we are going to COW a private mapping later, we examine the
5651 * pending reservations for this page now. This will ensure that
5652 * any allocations necessary to record that reservation occur outside
5655 if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
5656 if (vma_needs_reservation(h, vma, haddr) < 0) {
5658 goto backout_unlocked;
5660 /* Just decrements count, does not deallocate */
5661 vma_end_reservation(h, vma, haddr);
5664 ptl = huge_pte_lock(h, mm, ptep);
5666 /* If pte changed from under us, retry */
5667 if (!pte_same(huge_ptep_get(ptep), old_pte))
5671 ClearHPageRestoreReserve(page);
5672 hugepage_add_new_anon_rmap(page, vma, haddr);
5674 page_dup_file_rmap(page, true);
5675 new_pte = make_huge_pte(vma, page, ((vma->vm_flags & VM_WRITE)
5676 && (vma->vm_flags & VM_SHARED)));
5678 * If this pte was previously wr-protected, keep it wr-protected even
5681 if (unlikely(pte_marker_uffd_wp(old_pte)))
5682 new_pte = huge_pte_wrprotect(huge_pte_mkuffd_wp(new_pte));
5683 set_huge_pte_at(mm, haddr, ptep, new_pte);
5685 hugetlb_count_add(pages_per_huge_page(h), mm);
5686 if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
5687 /* Optimization, do the COW without a second fault */
5688 ret = hugetlb_wp(mm, vma, address, ptep, flags, page, ptl);
5694 * Only set HPageMigratable in newly allocated pages. Existing pages
5695 * found in the pagecache may not have HPageMigratableset if they have
5696 * been isolated for migration.
5699 SetHPageMigratable(page);
5703 hugetlb_vma_unlock_read(vma);
5704 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
5710 if (new_page && !new_pagecache_page)
5711 restore_reserve_on_error(h, vma, haddr, page);
5719 u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
5721 unsigned long key[2];
5724 key[0] = (unsigned long) mapping;
5727 hash = jhash2((u32 *)&key, sizeof(key)/(sizeof(u32)), 0);
5729 return hash & (num_fault_mutexes - 1);
5733 * For uniprocessor systems we always use a single mutex, so just
5734 * return 0 and avoid the hashing overhead.
5736 u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
5742 vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,
5743 unsigned long address, unsigned int flags)
5750 struct page *page = NULL;
5751 struct page *pagecache_page = NULL;
5752 struct hstate *h = hstate_vma(vma);
5753 struct address_space *mapping;
5754 int need_wait_lock = 0;
5755 unsigned long haddr = address & huge_page_mask(h);
5757 ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
5760 * Since we hold no locks, ptep could be stale. That is
5761 * OK as we are only making decisions based on content and
5762 * not actually modifying content here.
5764 entry = huge_ptep_get(ptep);
5765 if (unlikely(is_hugetlb_entry_migration(entry))) {
5766 migration_entry_wait_huge(vma, ptep);
5768 } else if (unlikely(is_hugetlb_entry_hwpoisoned(entry)))
5769 return VM_FAULT_HWPOISON_LARGE |
5770 VM_FAULT_SET_HINDEX(hstate_index(h));
5774 * Serialize hugepage allocation and instantiation, so that we don't
5775 * get spurious allocation failures if two CPUs race to instantiate
5776 * the same page in the page cache.
5778 mapping = vma->vm_file->f_mapping;
5779 idx = vma_hugecache_offset(h, vma, haddr);
5780 hash = hugetlb_fault_mutex_hash(mapping, idx);
5781 mutex_lock(&hugetlb_fault_mutex_table[hash]);
5784 * Acquire vma lock before calling huge_pte_alloc and hold
5785 * until finished with ptep. This prevents huge_pmd_unshare from
5786 * being called elsewhere and making the ptep no longer valid.
5788 * ptep could have already be assigned via huge_pte_offset. That
5789 * is OK, as huge_pte_alloc will return the same value unless
5790 * something has changed.
5792 hugetlb_vma_lock_read(vma);
5793 ptep = huge_pte_alloc(mm, vma, haddr, huge_page_size(h));
5795 hugetlb_vma_unlock_read(vma);
5796 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
5797 return VM_FAULT_OOM;
5800 entry = huge_ptep_get(ptep);
5801 /* PTE markers should be handled the same way as none pte */
5802 if (huge_pte_none_mostly(entry))
5804 * hugetlb_no_page will drop vma lock and hugetlb fault
5805 * mutex internally, which make us return immediately.
5807 return hugetlb_no_page(mm, vma, mapping, idx, address, ptep,
5813 * entry could be a migration/hwpoison entry at this point, so this
5814 * check prevents the kernel from going below assuming that we have
5815 * an active hugepage in pagecache. This goto expects the 2nd page
5816 * fault, and is_hugetlb_entry_(migration|hwpoisoned) check will
5817 * properly handle it.
5819 if (!pte_present(entry))
5823 * If we are going to COW/unshare the mapping later, we examine the
5824 * pending reservations for this page now. This will ensure that any
5825 * allocations necessary to record that reservation occur outside the
5826 * spinlock. Also lookup the pagecache page now as it is used to
5827 * determine if a reservation has been consumed.
5829 if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) &&
5830 !(vma->vm_flags & VM_MAYSHARE) && !huge_pte_write(entry)) {
5831 if (vma_needs_reservation(h, vma, haddr) < 0) {
5835 /* Just decrements count, does not deallocate */
5836 vma_end_reservation(h, vma, haddr);
5838 pagecache_page = find_lock_page(mapping, idx);
5841 ptl = huge_pte_lock(h, mm, ptep);
5843 /* Check for a racing update before calling hugetlb_wp() */
5844 if (unlikely(!pte_same(entry, huge_ptep_get(ptep))))
5847 /* Handle userfault-wp first, before trying to lock more pages */
5848 if (userfaultfd_wp(vma) && huge_pte_uffd_wp(huge_ptep_get(ptep)) &&
5849 (flags & FAULT_FLAG_WRITE) && !huge_pte_write(entry)) {
5850 struct vm_fault vmf = {
5853 .real_address = address,
5858 if (pagecache_page) {
5859 unlock_page(pagecache_page);
5860 put_page(pagecache_page);
5862 hugetlb_vma_unlock_read(vma);
5863 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
5864 return handle_userfault(&vmf, VM_UFFD_WP);
5868 * hugetlb_wp() requires page locks of pte_page(entry) and
5869 * pagecache_page, so here we need take the former one
5870 * when page != pagecache_page or !pagecache_page.
5872 page = pte_page(entry);
5873 if (page != pagecache_page)
5874 if (!trylock_page(page)) {
5881 if (flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) {
5882 if (!huge_pte_write(entry)) {
5883 ret = hugetlb_wp(mm, vma, address, ptep, flags,
5884 pagecache_page, ptl);
5886 } else if (likely(flags & FAULT_FLAG_WRITE)) {
5887 entry = huge_pte_mkdirty(entry);
5890 entry = pte_mkyoung(entry);
5891 if (huge_ptep_set_access_flags(vma, haddr, ptep, entry,
5892 flags & FAULT_FLAG_WRITE))
5893 update_mmu_cache(vma, haddr, ptep);
5895 if (page != pagecache_page)
5901 if (pagecache_page) {
5902 unlock_page(pagecache_page);
5903 put_page(pagecache_page);
5906 hugetlb_vma_unlock_read(vma);
5907 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
5909 * Generally it's safe to hold refcount during waiting page lock. But
5910 * here we just wait to defer the next page fault to avoid busy loop and
5911 * the page is not used after unlocked before returning from the current
5912 * page fault. So we are safe from accessing freed page, even if we wait
5913 * here without taking refcount.
5916 wait_on_page_locked(page);
5920 #ifdef CONFIG_USERFAULTFD
5922 * Used by userfaultfd UFFDIO_COPY. Based on mcopy_atomic_pte with
5923 * modifications for huge pages.
5925 int hugetlb_mcopy_atomic_pte(struct mm_struct *dst_mm,
5927 struct vm_area_struct *dst_vma,
5928 unsigned long dst_addr,
5929 unsigned long src_addr,
5930 enum mcopy_atomic_mode mode,
5931 struct page **pagep,
5934 bool is_continue = (mode == MCOPY_ATOMIC_CONTINUE);
5935 struct hstate *h = hstate_vma(dst_vma);
5936 struct address_space *mapping = dst_vma->vm_file->f_mapping;
5937 pgoff_t idx = vma_hugecache_offset(h, dst_vma, dst_addr);
5939 int vm_shared = dst_vma->vm_flags & VM_SHARED;
5945 bool page_in_pagecache = false;
5949 page = find_lock_page(mapping, idx);
5952 page_in_pagecache = true;
5953 } else if (!*pagep) {
5954 /* If a page already exists, then it's UFFDIO_COPY for
5955 * a non-missing case. Return -EEXIST.
5958 hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
5963 page = alloc_huge_page(dst_vma, dst_addr, 0);
5969 ret = copy_huge_page_from_user(page,
5970 (const void __user *) src_addr,
5971 pages_per_huge_page(h), false);
5973 /* fallback to copy_from_user outside mmap_lock */
5974 if (unlikely(ret)) {
5976 /* Free the allocated page which may have
5977 * consumed a reservation.
5979 restore_reserve_on_error(h, dst_vma, dst_addr, page);
5982 /* Allocate a temporary page to hold the copied
5985 page = alloc_huge_page_vma(h, dst_vma, dst_addr);
5991 /* Set the outparam pagep and return to the caller to
5992 * copy the contents outside the lock. Don't free the
5999 hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
6006 page = alloc_huge_page(dst_vma, dst_addr, 0);
6013 copy_user_huge_page(page, *pagep, dst_addr, dst_vma,
6014 pages_per_huge_page(h));
6020 * The memory barrier inside __SetPageUptodate makes sure that
6021 * preceding stores to the page contents become visible before
6022 * the set_pte_at() write.
6024 __SetPageUptodate(page);
6026 /* Add shared, newly allocated pages to the page cache. */
6027 if (vm_shared && !is_continue) {
6028 size = i_size_read(mapping->host) >> huge_page_shift(h);
6031 goto out_release_nounlock;
6034 * Serialization between remove_inode_hugepages() and
6035 * hugetlb_add_to_page_cache() below happens through the
6036 * hugetlb_fault_mutex_table that here must be hold by
6039 ret = hugetlb_add_to_page_cache(page, mapping, idx);
6041 goto out_release_nounlock;
6042 page_in_pagecache = true;
6045 ptl = huge_pte_lock(h, dst_mm, dst_pte);
6048 * We allow to overwrite a pte marker: consider when both MISSING|WP
6049 * registered, we firstly wr-protect a none pte which has no page cache
6050 * page backing it, then access the page.
6053 if (!huge_pte_none_mostly(huge_ptep_get(dst_pte)))
6054 goto out_release_unlock;
6056 if (page_in_pagecache) {
6057 page_dup_file_rmap(page, true);
6059 ClearHPageRestoreReserve(page);
6060 hugepage_add_new_anon_rmap(page, dst_vma, dst_addr);
6064 * For either: (1) CONTINUE on a non-shared VMA, or (2) UFFDIO_COPY
6065 * with wp flag set, don't set pte write bit.
6067 if (wp_copy || (is_continue && !vm_shared))
6070 writable = dst_vma->vm_flags & VM_WRITE;
6072 _dst_pte = make_huge_pte(dst_vma, page, writable);
6074 * Always mark UFFDIO_COPY page dirty; note that this may not be
6075 * extremely important for hugetlbfs for now since swapping is not
6076 * supported, but we should still be clear in that this page cannot be
6077 * thrown away at will, even if write bit not set.
6079 _dst_pte = huge_pte_mkdirty(_dst_pte);
6080 _dst_pte = pte_mkyoung(_dst_pte);
6083 _dst_pte = huge_pte_mkuffd_wp(_dst_pte);
6085 set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
6087 hugetlb_count_add(pages_per_huge_page(h), dst_mm);
6089 /* No need to invalidate - it was non-present before */
6090 update_mmu_cache(dst_vma, dst_addr, dst_pte);
6094 SetHPageMigratable(page);
6095 if (vm_shared || is_continue)
6102 if (vm_shared || is_continue)
6104 out_release_nounlock:
6105 if (!page_in_pagecache)
6106 restore_reserve_on_error(h, dst_vma, dst_addr, page);
6110 #endif /* CONFIG_USERFAULTFD */
6112 static void record_subpages_vmas(struct page *page, struct vm_area_struct *vma,
6113 int refs, struct page **pages,
6114 struct vm_area_struct **vmas)
6118 for (nr = 0; nr < refs; nr++) {
6120 pages[nr] = nth_page(page, nr);
6126 static inline bool __follow_hugetlb_must_fault(unsigned int flags, pte_t *pte,
6129 pte_t pteval = huge_ptep_get(pte);
6132 if (is_swap_pte(pteval))
6134 if (huge_pte_write(pteval))
6136 if (flags & FOLL_WRITE)
6138 if (gup_must_unshare(flags, pte_page(pteval))) {
6145 long follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma,
6146 struct page **pages, struct vm_area_struct **vmas,
6147 unsigned long *position, unsigned long *nr_pages,
6148 long i, unsigned int flags, int *locked)
6150 unsigned long pfn_offset;
6151 unsigned long vaddr = *position;
6152 unsigned long remainder = *nr_pages;
6153 struct hstate *h = hstate_vma(vma);
6154 int err = -EFAULT, refs;
6156 while (vaddr < vma->vm_end && remainder) {
6158 spinlock_t *ptl = NULL;
6159 bool unshare = false;
6164 * If we have a pending SIGKILL, don't keep faulting pages and
6165 * potentially allocating memory.
6167 if (fatal_signal_pending(current)) {
6173 * Some archs (sparc64, sh*) have multiple pte_ts to
6174 * each hugepage. We have to make sure we get the
6175 * first, for the page indexing below to work.
6177 * Note that page table lock is not held when pte is null.
6179 pte = huge_pte_offset(mm, vaddr & huge_page_mask(h),
6182 ptl = huge_pte_lock(h, mm, pte);
6183 absent = !pte || huge_pte_none(huge_ptep_get(pte));
6186 * When coredumping, it suits get_dump_page if we just return
6187 * an error where there's an empty slot with no huge pagecache
6188 * to back it. This way, we avoid allocating a hugepage, and
6189 * the sparse dumpfile avoids allocating disk blocks, but its
6190 * huge holes still show up with zeroes where they need to be.
6192 if (absent && (flags & FOLL_DUMP) &&
6193 !hugetlbfs_pagecache_present(h, vma, vaddr)) {
6201 * We need call hugetlb_fault for both hugepages under migration
6202 * (in which case hugetlb_fault waits for the migration,) and
6203 * hwpoisoned hugepages (in which case we need to prevent the
6204 * caller from accessing to them.) In order to do this, we use
6205 * here is_swap_pte instead of is_hugetlb_entry_migration and
6206 * is_hugetlb_entry_hwpoisoned. This is because it simply covers
6207 * both cases, and because we can't follow correct pages
6208 * directly from any kind of swap entries.
6211 __follow_hugetlb_must_fault(flags, pte, &unshare)) {
6213 unsigned int fault_flags = 0;
6217 if (flags & FOLL_WRITE)
6218 fault_flags |= FAULT_FLAG_WRITE;
6220 fault_flags |= FAULT_FLAG_UNSHARE;
6222 fault_flags |= FAULT_FLAG_ALLOW_RETRY |
6223 FAULT_FLAG_KILLABLE;
6224 if (flags & FOLL_NOWAIT)
6225 fault_flags |= FAULT_FLAG_ALLOW_RETRY |
6226 FAULT_FLAG_RETRY_NOWAIT;
6227 if (flags & FOLL_TRIED) {
6229 * Note: FAULT_FLAG_ALLOW_RETRY and
6230 * FAULT_FLAG_TRIED can co-exist
6232 fault_flags |= FAULT_FLAG_TRIED;
6234 ret = hugetlb_fault(mm, vma, vaddr, fault_flags);
6235 if (ret & VM_FAULT_ERROR) {
6236 err = vm_fault_to_errno(ret, flags);
6240 if (ret & VM_FAULT_RETRY) {
6242 !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
6246 * VM_FAULT_RETRY must not return an
6247 * error, it will return zero
6250 * No need to update "position" as the
6251 * caller will not check it after
6252 * *nr_pages is set to 0.
6259 pfn_offset = (vaddr & ~huge_page_mask(h)) >> PAGE_SHIFT;
6260 page = pte_page(huge_ptep_get(pte));
6262 VM_BUG_ON_PAGE((flags & FOLL_PIN) && PageAnon(page) &&
6263 !PageAnonExclusive(page), page);
6266 * If subpage information not requested, update counters
6267 * and skip the same_page loop below.
6269 if (!pages && !vmas && !pfn_offset &&
6270 (vaddr + huge_page_size(h) < vma->vm_end) &&
6271 (remainder >= pages_per_huge_page(h))) {
6272 vaddr += huge_page_size(h);
6273 remainder -= pages_per_huge_page(h);
6274 i += pages_per_huge_page(h);
6279 /* vaddr may not be aligned to PAGE_SIZE */
6280 refs = min3(pages_per_huge_page(h) - pfn_offset, remainder,
6281 (vma->vm_end - ALIGN_DOWN(vaddr, PAGE_SIZE)) >> PAGE_SHIFT);
6284 record_subpages_vmas(nth_page(page, pfn_offset),
6286 likely(pages) ? pages + i : NULL,
6287 vmas ? vmas + i : NULL);
6291 * try_grab_folio() should always succeed here,
6292 * because: a) we hold the ptl lock, and b) we've just
6293 * checked that the huge page is present in the page
6294 * tables. If the huge page is present, then the tail
6295 * pages must also be present. The ptl prevents the
6296 * head page and tail pages from being rearranged in
6297 * any way. So this page must be available at this
6298 * point, unless the page refcount overflowed:
6300 if (WARN_ON_ONCE(!try_grab_folio(pages[i], refs,
6309 vaddr += (refs << PAGE_SHIFT);
6315 *nr_pages = remainder;
6317 * setting position is actually required only if remainder is
6318 * not zero but it's faster not to add a "if (remainder)"
6326 unsigned long hugetlb_change_protection(struct vm_area_struct *vma,
6327 unsigned long address, unsigned long end,
6328 pgprot_t newprot, unsigned long cp_flags)
6330 struct mm_struct *mm = vma->vm_mm;
6331 unsigned long start = address;
6334 struct hstate *h = hstate_vma(vma);
6335 unsigned long pages = 0, psize = huge_page_size(h);
6336 bool shared_pmd = false;
6337 struct mmu_notifier_range range;
6338 unsigned long last_addr_mask;
6339 bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
6340 bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
6343 * In the case of shared PMDs, the area to flush could be beyond
6344 * start/end. Set range.start/range.end to cover the maximum possible
6345 * range if PMD sharing is possible.
6347 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_VMA,
6348 0, vma, mm, start, end);
6349 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
6351 BUG_ON(address >= end);
6352 flush_cache_range(vma, range.start, range.end);
6354 mmu_notifier_invalidate_range_start(&range);
6355 hugetlb_vma_lock_write(vma);
6356 i_mmap_lock_write(vma->vm_file->f_mapping);
6357 last_addr_mask = hugetlb_mask_last_page(h);
6358 for (; address < end; address += psize) {
6360 ptep = huge_pte_offset(mm, address, psize);
6362 address |= last_addr_mask;
6365 ptl = huge_pte_lock(h, mm, ptep);
6366 if (huge_pmd_unshare(mm, vma, address, ptep)) {
6368 * When uffd-wp is enabled on the vma, unshare
6369 * shouldn't happen at all. Warn about it if it
6370 * happened due to some reason.
6372 WARN_ON_ONCE(uffd_wp || uffd_wp_resolve);
6376 address |= last_addr_mask;
6379 pte = huge_ptep_get(ptep);
6380 if (unlikely(is_hugetlb_entry_hwpoisoned(pte))) {
6384 if (unlikely(is_hugetlb_entry_migration(pte))) {
6385 swp_entry_t entry = pte_to_swp_entry(pte);
6386 struct page *page = pfn_swap_entry_to_page(entry);
6388 if (!is_readable_migration_entry(entry)) {
6392 entry = make_readable_exclusive_migration_entry(
6395 entry = make_readable_migration_entry(
6397 newpte = swp_entry_to_pte(entry);
6399 newpte = pte_swp_mkuffd_wp(newpte);
6400 else if (uffd_wp_resolve)
6401 newpte = pte_swp_clear_uffd_wp(newpte);
6402 set_huge_pte_at(mm, address, ptep, newpte);
6408 if (unlikely(pte_marker_uffd_wp(pte))) {
6410 * This is changing a non-present pte into a none pte,
6411 * no need for huge_ptep_modify_prot_start/commit().
6413 if (uffd_wp_resolve)
6414 huge_pte_clear(mm, address, ptep, psize);
6416 if (!huge_pte_none(pte)) {
6418 unsigned int shift = huge_page_shift(hstate_vma(vma));
6420 old_pte = huge_ptep_modify_prot_start(vma, address, ptep);
6421 pte = huge_pte_modify(old_pte, newprot);
6422 pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
6424 pte = huge_pte_mkuffd_wp(huge_pte_wrprotect(pte));
6425 else if (uffd_wp_resolve)
6426 pte = huge_pte_clear_uffd_wp(pte);
6427 huge_ptep_modify_prot_commit(vma, address, ptep, old_pte, pte);
6431 if (unlikely(uffd_wp))
6432 /* Safe to modify directly (none->non-present). */
6433 set_huge_pte_at(mm, address, ptep,
6434 make_pte_marker(PTE_MARKER_UFFD_WP));
6439 * Must flush TLB before releasing i_mmap_rwsem: x86's huge_pmd_unshare
6440 * may have cleared our pud entry and done put_page on the page table:
6441 * once we release i_mmap_rwsem, another task can do the final put_page
6442 * and that page table be reused and filled with junk. If we actually
6443 * did unshare a page of pmds, flush the range corresponding to the pud.
6446 flush_hugetlb_tlb_range(vma, range.start, range.end);
6448 flush_hugetlb_tlb_range(vma, start, end);
6450 * No need to call mmu_notifier_invalidate_range() we are downgrading
6451 * page table protection not changing it to point to a new page.
6453 * See Documentation/mm/mmu_notifier.rst
6455 i_mmap_unlock_write(vma->vm_file->f_mapping);
6456 hugetlb_vma_unlock_write(vma);
6457 mmu_notifier_invalidate_range_end(&range);
6459 return pages << h->order;
6462 /* Return true if reservation was successful, false otherwise. */
6463 bool hugetlb_reserve_pages(struct inode *inode,
6465 struct vm_area_struct *vma,
6466 vm_flags_t vm_flags)
6469 struct hstate *h = hstate_inode(inode);
6470 struct hugepage_subpool *spool = subpool_inode(inode);
6471 struct resv_map *resv_map;
6472 struct hugetlb_cgroup *h_cg = NULL;
6473 long gbl_reserve, regions_needed = 0;
6475 /* This should never happen */
6477 VM_WARN(1, "%s called with a negative range\n", __func__);
6482 * vma specific semaphore used for pmd sharing synchronization
6484 hugetlb_vma_lock_alloc(vma);
6487 * Only apply hugepage reservation if asked. At fault time, an
6488 * attempt will be made for VM_NORESERVE to allocate a page
6489 * without using reserves
6491 if (vm_flags & VM_NORESERVE)
6495 * Shared mappings base their reservation on the number of pages that
6496 * are already allocated on behalf of the file. Private mappings need
6497 * to reserve the full area even if read-only as mprotect() may be
6498 * called to make the mapping read-write. Assume !vma is a shm mapping
6500 if (!vma || vma->vm_flags & VM_MAYSHARE) {
6502 * resv_map can not be NULL as hugetlb_reserve_pages is only
6503 * called for inodes for which resv_maps were created (see
6504 * hugetlbfs_get_inode).
6506 resv_map = inode_resv_map(inode);
6508 chg = region_chg(resv_map, from, to, ®ions_needed);
6510 /* Private mapping. */
6511 resv_map = resv_map_alloc();
6517 set_vma_resv_map(vma, resv_map);
6518 set_vma_resv_flags(vma, HPAGE_RESV_OWNER);
6524 if (hugetlb_cgroup_charge_cgroup_rsvd(hstate_index(h),
6525 chg * pages_per_huge_page(h), &h_cg) < 0)
6528 if (vma && !(vma->vm_flags & VM_MAYSHARE) && h_cg) {
6529 /* For private mappings, the hugetlb_cgroup uncharge info hangs
6532 resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, h_cg, h);
6536 * There must be enough pages in the subpool for the mapping. If
6537 * the subpool has a minimum size, there may be some global
6538 * reservations already in place (gbl_reserve).
6540 gbl_reserve = hugepage_subpool_get_pages(spool, chg);
6541 if (gbl_reserve < 0)
6542 goto out_uncharge_cgroup;
6545 * Check enough hugepages are available for the reservation.
6546 * Hand the pages back to the subpool if there are not
6548 if (hugetlb_acct_memory(h, gbl_reserve) < 0)
6552 * Account for the reservations made. Shared mappings record regions
6553 * that have reservations as they are shared by multiple VMAs.
6554 * When the last VMA disappears, the region map says how much
6555 * the reservation was and the page cache tells how much of
6556 * the reservation was consumed. Private mappings are per-VMA and
6557 * only the consumed reservations are tracked. When the VMA
6558 * disappears, the original reservation is the VMA size and the
6559 * consumed reservations are stored in the map. Hence, nothing
6560 * else has to be done for private mappings here
6562 if (!vma || vma->vm_flags & VM_MAYSHARE) {
6563 add = region_add(resv_map, from, to, regions_needed, h, h_cg);
6565 if (unlikely(add < 0)) {
6566 hugetlb_acct_memory(h, -gbl_reserve);
6568 } else if (unlikely(chg > add)) {
6570 * pages in this range were added to the reserve
6571 * map between region_chg and region_add. This
6572 * indicates a race with alloc_huge_page. Adjust
6573 * the subpool and reserve counts modified above
6574 * based on the difference.
6579 * hugetlb_cgroup_uncharge_cgroup_rsvd() will put the
6580 * reference to h_cg->css. See comment below for detail.
6582 hugetlb_cgroup_uncharge_cgroup_rsvd(
6584 (chg - add) * pages_per_huge_page(h), h_cg);
6586 rsv_adjust = hugepage_subpool_put_pages(spool,
6588 hugetlb_acct_memory(h, -rsv_adjust);
6591 * The file_regions will hold their own reference to
6592 * h_cg->css. So we should release the reference held
6593 * via hugetlb_cgroup_charge_cgroup_rsvd() when we are
6596 hugetlb_cgroup_put_rsvd_cgroup(h_cg);
6602 /* put back original number of pages, chg */
6603 (void)hugepage_subpool_put_pages(spool, chg);
6604 out_uncharge_cgroup:
6605 hugetlb_cgroup_uncharge_cgroup_rsvd(hstate_index(h),
6606 chg * pages_per_huge_page(h), h_cg);
6608 hugetlb_vma_lock_free(vma);
6609 if (!vma || vma->vm_flags & VM_MAYSHARE)
6610 /* Only call region_abort if the region_chg succeeded but the
6611 * region_add failed or didn't run.
6613 if (chg >= 0 && add < 0)
6614 region_abort(resv_map, from, to, regions_needed);
6615 if (vma && is_vma_resv_set(vma, HPAGE_RESV_OWNER))
6616 kref_put(&resv_map->refs, resv_map_release);
6620 long hugetlb_unreserve_pages(struct inode *inode, long start, long end,
6623 struct hstate *h = hstate_inode(inode);
6624 struct resv_map *resv_map = inode_resv_map(inode);
6626 struct hugepage_subpool *spool = subpool_inode(inode);
6630 * Since this routine can be called in the evict inode path for all
6631 * hugetlbfs inodes, resv_map could be NULL.
6634 chg = region_del(resv_map, start, end);
6636 * region_del() can fail in the rare case where a region
6637 * must be split and another region descriptor can not be
6638 * allocated. If end == LONG_MAX, it will not fail.
6644 spin_lock(&inode->i_lock);
6645 inode->i_blocks -= (blocks_per_huge_page(h) * freed);
6646 spin_unlock(&inode->i_lock);
6649 * If the subpool has a minimum size, the number of global
6650 * reservations to be released may be adjusted.
6652 * Note that !resv_map implies freed == 0. So (chg - freed)
6653 * won't go negative.
6655 gbl_reserve = hugepage_subpool_put_pages(spool, (chg - freed));
6656 hugetlb_acct_memory(h, -gbl_reserve);
6661 #ifdef CONFIG_ARCH_WANT_HUGE_PMD_SHARE
6662 static unsigned long page_table_shareable(struct vm_area_struct *svma,
6663 struct vm_area_struct *vma,
6664 unsigned long addr, pgoff_t idx)
6666 unsigned long saddr = ((idx - svma->vm_pgoff) << PAGE_SHIFT) +
6668 unsigned long sbase = saddr & PUD_MASK;
6669 unsigned long s_end = sbase + PUD_SIZE;
6671 /* Allow segments to share if only one is marked locked */
6672 unsigned long vm_flags = vma->vm_flags & VM_LOCKED_CLEAR_MASK;
6673 unsigned long svm_flags = svma->vm_flags & VM_LOCKED_CLEAR_MASK;
6676 * match the virtual addresses, permission and the alignment of the
6679 * Also, vma_lock (vm_private_data) is required for sharing.
6681 if (pmd_index(addr) != pmd_index(saddr) ||
6682 vm_flags != svm_flags ||
6683 !range_in_vma(svma, sbase, s_end) ||
6684 !svma->vm_private_data)
6690 static bool __vma_aligned_range_pmd_shareable(struct vm_area_struct *vma,
6691 unsigned long start, unsigned long end,
6692 bool check_vma_lock)
6694 #ifdef CONFIG_USERFAULTFD
6695 if (uffd_disable_huge_pmd_share(vma))
6699 * check on proper vm_flags and page table alignment
6701 if (!(vma->vm_flags & VM_MAYSHARE))
6703 if (check_vma_lock && !vma->vm_private_data)
6705 if (!range_in_vma(vma, start, end))
6710 static bool vma_pmd_shareable(struct vm_area_struct *vma)
6712 unsigned long start = ALIGN(vma->vm_start, PUD_SIZE),
6713 end = ALIGN_DOWN(vma->vm_end, PUD_SIZE);
6718 return __vma_aligned_range_pmd_shareable(vma, start, end, false);
6721 static bool vma_addr_pmd_shareable(struct vm_area_struct *vma,
6724 unsigned long start = addr & PUD_MASK;
6725 unsigned long end = start + PUD_SIZE;
6727 return __vma_aligned_range_pmd_shareable(vma, start, end, true);
6730 bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
6732 return vma_addr_pmd_shareable(vma, addr);
6736 * Determine if start,end range within vma could be mapped by shared pmd.
6737 * If yes, adjust start and end to cover range associated with possible
6738 * shared pmd mappings.
6740 void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
6741 unsigned long *start, unsigned long *end)
6743 unsigned long v_start = ALIGN(vma->vm_start, PUD_SIZE),
6744 v_end = ALIGN_DOWN(vma->vm_end, PUD_SIZE);
6747 * vma needs to span at least one aligned PUD size, and the range
6748 * must be at least partially within in.
6750 if (!(vma->vm_flags & VM_MAYSHARE) || !(v_end > v_start) ||
6751 (*end <= v_start) || (*start >= v_end))
6754 /* Extend the range to be PUD aligned for a worst case scenario */
6755 if (*start > v_start)
6756 *start = ALIGN_DOWN(*start, PUD_SIZE);
6759 *end = ALIGN(*end, PUD_SIZE);
6762 static bool __vma_shareable_flags_pmd(struct vm_area_struct *vma)
6764 return vma->vm_flags & (VM_MAYSHARE | VM_SHARED) &&
6765 vma->vm_private_data;
6768 void hugetlb_vma_lock_read(struct vm_area_struct *vma)
6770 if (__vma_shareable_flags_pmd(vma)) {
6771 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
6773 down_read(&vma_lock->rw_sema);
6777 void hugetlb_vma_unlock_read(struct vm_area_struct *vma)
6779 if (__vma_shareable_flags_pmd(vma)) {
6780 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
6782 up_read(&vma_lock->rw_sema);
6786 void hugetlb_vma_lock_write(struct vm_area_struct *vma)
6788 if (__vma_shareable_flags_pmd(vma)) {
6789 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
6791 down_write(&vma_lock->rw_sema);
6795 void hugetlb_vma_unlock_write(struct vm_area_struct *vma)
6797 if (__vma_shareable_flags_pmd(vma)) {
6798 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
6800 up_write(&vma_lock->rw_sema);
6804 int hugetlb_vma_trylock_write(struct vm_area_struct *vma)
6806 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
6808 if (!__vma_shareable_flags_pmd(vma))
6811 return down_write_trylock(&vma_lock->rw_sema);
6814 void hugetlb_vma_assert_locked(struct vm_area_struct *vma)
6816 if (__vma_shareable_flags_pmd(vma)) {
6817 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
6819 lockdep_assert_held(&vma_lock->rw_sema);
6823 void hugetlb_vma_lock_release(struct kref *kref)
6825 struct hugetlb_vma_lock *vma_lock = container_of(kref,
6826 struct hugetlb_vma_lock, refs);
6831 static void hugetlb_vma_lock_free(struct vm_area_struct *vma)
6834 * Only present in sharable vmas.
6836 if (!vma || !__vma_shareable_flags_pmd(vma))
6839 if (vma->vm_private_data) {
6840 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
6843 * vma_lock structure may or not be released, but it
6844 * certainly will no longer be attached to vma so clear
6847 vma_lock->vma = NULL;
6848 kref_put(&vma_lock->refs, hugetlb_vma_lock_release);
6849 vma->vm_private_data = NULL;
6853 static void hugetlb_vma_lock_alloc(struct vm_area_struct *vma)
6855 struct hugetlb_vma_lock *vma_lock;
6857 /* Only establish in (flags) sharable vmas */
6858 if (!vma || !(vma->vm_flags & VM_MAYSHARE))
6861 /* Should never get here with non-NULL vm_private_data */
6862 if (vma->vm_private_data)
6865 /* Check size/alignment for pmd sharing possible */
6866 if (!vma_pmd_shareable(vma))
6869 vma_lock = kmalloc(sizeof(*vma_lock), GFP_KERNEL);
6872 * If we can not allocate structure, then vma can not
6873 * participate in pmd sharing.
6877 kref_init(&vma_lock->refs);
6878 init_rwsem(&vma_lock->rw_sema);
6879 vma_lock->vma = vma;
6880 vma->vm_private_data = vma_lock;
6884 * Search for a shareable pmd page for hugetlb. In any case calls pmd_alloc()
6885 * and returns the corresponding pte. While this is not necessary for the
6886 * !shared pmd case because we can allocate the pmd later as well, it makes the
6887 * code much cleaner. pmd allocation is essential for the shared case because
6888 * pud has to be populated inside the same i_mmap_rwsem section - otherwise
6889 * racing tasks could either miss the sharing (see huge_pte_offset) or select a
6890 * bad pmd for sharing.
6892 pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
6893 unsigned long addr, pud_t *pud)
6895 struct address_space *mapping = vma->vm_file->f_mapping;
6896 pgoff_t idx = ((addr - vma->vm_start) >> PAGE_SHIFT) +
6898 struct vm_area_struct *svma;
6899 unsigned long saddr;
6904 i_mmap_lock_read(mapping);
6905 vma_interval_tree_foreach(svma, &mapping->i_mmap, idx, idx) {
6909 saddr = page_table_shareable(svma, vma, addr, idx);
6911 spte = huge_pte_offset(svma->vm_mm, saddr,
6912 vma_mmu_pagesize(svma));
6914 get_page(virt_to_page(spte));
6923 ptl = huge_pte_lock(hstate_vma(vma), mm, spte);
6924 if (pud_none(*pud)) {
6925 pud_populate(mm, pud,
6926 (pmd_t *)((unsigned long)spte & PAGE_MASK));
6929 put_page(virt_to_page(spte));
6933 pte = (pte_t *)pmd_alloc(mm, pud, addr);
6934 i_mmap_unlock_read(mapping);
6939 * unmap huge page backed by shared pte.
6941 * Hugetlb pte page is ref counted at the time of mapping. If pte is shared
6942 * indicated by page_count > 1, unmap is achieved by clearing pud and
6943 * decrementing the ref count. If count == 1, the pte page is not shared.
6945 * Called with page table lock held.
6947 * returns: 1 successfully unmapped a shared pte page
6948 * 0 the underlying pte page is not shared, or it is the last user
6950 int huge_pmd_unshare(struct mm_struct *mm, struct vm_area_struct *vma,
6951 unsigned long addr, pte_t *ptep)
6953 pgd_t *pgd = pgd_offset(mm, addr);
6954 p4d_t *p4d = p4d_offset(pgd, addr);
6955 pud_t *pud = pud_offset(p4d, addr);
6957 i_mmap_assert_write_locked(vma->vm_file->f_mapping);
6958 hugetlb_vma_assert_locked(vma);
6959 BUG_ON(page_count(virt_to_page(ptep)) == 0);
6960 if (page_count(virt_to_page(ptep)) == 1)
6964 put_page(virt_to_page(ptep));
6969 #else /* !CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
6971 void hugetlb_vma_lock_read(struct vm_area_struct *vma)
6975 void hugetlb_vma_unlock_read(struct vm_area_struct *vma)
6979 void hugetlb_vma_lock_write(struct vm_area_struct *vma)
6983 void hugetlb_vma_unlock_write(struct vm_area_struct *vma)
6987 int hugetlb_vma_trylock_write(struct vm_area_struct *vma)
6992 void hugetlb_vma_assert_locked(struct vm_area_struct *vma)
6996 void hugetlb_vma_lock_release(struct kref *kref)
7000 static void hugetlb_vma_lock_free(struct vm_area_struct *vma)
7004 static void hugetlb_vma_lock_alloc(struct vm_area_struct *vma)
7008 pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
7009 unsigned long addr, pud_t *pud)
7014 int huge_pmd_unshare(struct mm_struct *mm, struct vm_area_struct *vma,
7015 unsigned long addr, pte_t *ptep)
7020 void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
7021 unsigned long *start, unsigned long *end)
7025 bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
7029 #endif /* CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
7031 #ifdef CONFIG_ARCH_WANT_GENERAL_HUGETLB
7032 pte_t *huge_pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma,
7033 unsigned long addr, unsigned long sz)
7040 pgd = pgd_offset(mm, addr);
7041 p4d = p4d_alloc(mm, pgd, addr);
7044 pud = pud_alloc(mm, p4d, addr);
7046 if (sz == PUD_SIZE) {
7049 BUG_ON(sz != PMD_SIZE);
7050 if (want_pmd_share(vma, addr) && pud_none(*pud))
7051 pte = huge_pmd_share(mm, vma, addr, pud);
7053 pte = (pte_t *)pmd_alloc(mm, pud, addr);
7056 BUG_ON(pte && pte_present(*pte) && !pte_huge(*pte));
7062 * huge_pte_offset() - Walk the page table to resolve the hugepage
7063 * entry at address @addr
7065 * Return: Pointer to page table entry (PUD or PMD) for
7066 * address @addr, or NULL if a !p*d_present() entry is encountered and the
7067 * size @sz doesn't match the hugepage size at this level of the page
7070 pte_t *huge_pte_offset(struct mm_struct *mm,
7071 unsigned long addr, unsigned long sz)
7078 pgd = pgd_offset(mm, addr);
7079 if (!pgd_present(*pgd))
7081 p4d = p4d_offset(pgd, addr);
7082 if (!p4d_present(*p4d))
7085 pud = pud_offset(p4d, addr);
7087 /* must be pud huge, non-present or none */
7088 return (pte_t *)pud;
7089 if (!pud_present(*pud))
7091 /* must have a valid entry and size to go further */
7093 pmd = pmd_offset(pud, addr);
7094 /* must be pmd huge, non-present or none */
7095 return (pte_t *)pmd;
7099 * Return a mask that can be used to update an address to the last huge
7100 * page in a page table page mapping size. Used to skip non-present
7101 * page table entries when linearly scanning address ranges. Architectures
7102 * with unique huge page to page table relationships can define their own
7103 * version of this routine.
7105 unsigned long hugetlb_mask_last_page(struct hstate *h)
7107 unsigned long hp_size = huge_page_size(h);
7109 if (hp_size == PUD_SIZE)
7110 return P4D_SIZE - PUD_SIZE;
7111 else if (hp_size == PMD_SIZE)
7112 return PUD_SIZE - PMD_SIZE;
7119 /* See description above. Architectures can provide their own version. */
7120 __weak unsigned long hugetlb_mask_last_page(struct hstate *h)
7122 #ifdef CONFIG_ARCH_WANT_HUGE_PMD_SHARE
7123 if (huge_page_size(h) == PMD_SIZE)
7124 return PUD_SIZE - PMD_SIZE;
7129 #endif /* CONFIG_ARCH_WANT_GENERAL_HUGETLB */
7132 * These functions are overwritable if your architecture needs its own
7135 struct page * __weak
7136 follow_huge_addr(struct mm_struct *mm, unsigned long address,
7139 return ERR_PTR(-EINVAL);
7142 struct page * __weak
7143 follow_huge_pd(struct vm_area_struct *vma,
7144 unsigned long address, hugepd_t hpd, int flags, int pdshift)
7146 WARN(1, "hugepd follow called with no support for hugepage directory format\n");
7150 struct page * __weak
7151 follow_huge_pmd(struct mm_struct *mm, unsigned long address,
7152 pmd_t *pmd, int flags)
7154 struct page *page = NULL;
7159 * FOLL_PIN is not supported for follow_page(). Ordinary GUP goes via
7160 * follow_hugetlb_page().
7162 if (WARN_ON_ONCE(flags & FOLL_PIN))
7166 ptl = pmd_lockptr(mm, pmd);
7169 * make sure that the address range covered by this pmd is not
7170 * unmapped from other threads.
7172 if (!pmd_huge(*pmd))
7174 pte = huge_ptep_get((pte_t *)pmd);
7175 if (pte_present(pte)) {
7176 page = pmd_page(*pmd) + ((address & ~PMD_MASK) >> PAGE_SHIFT);
7178 * try_grab_page() should always succeed here, because: a) we
7179 * hold the pmd (ptl) lock, and b) we've just checked that the
7180 * huge pmd (head) page is present in the page tables. The ptl
7181 * prevents the head page and tail pages from being rearranged
7182 * in any way. So this page must be available at this point,
7183 * unless the page refcount overflowed:
7185 if (WARN_ON_ONCE(!try_grab_page(page, flags))) {
7190 if (is_hugetlb_entry_migration(pte)) {
7192 __migration_entry_wait_huge((pte_t *)pmd, ptl);
7196 * hwpoisoned entry is treated as no_page_table in
7197 * follow_page_mask().
7205 struct page * __weak
7206 follow_huge_pud(struct mm_struct *mm, unsigned long address,
7207 pud_t *pud, int flags)
7209 struct page *page = NULL;
7213 if (WARN_ON_ONCE(flags & FOLL_PIN))
7217 ptl = huge_pte_lock(hstate_sizelog(PUD_SHIFT), mm, (pte_t *)pud);
7218 if (!pud_huge(*pud))
7220 pte = huge_ptep_get((pte_t *)pud);
7221 if (pte_present(pte)) {
7222 page = pud_page(*pud) + ((address & ~PUD_MASK) >> PAGE_SHIFT);
7223 if (WARN_ON_ONCE(!try_grab_page(page, flags))) {
7228 if (is_hugetlb_entry_migration(pte)) {
7230 __migration_entry_wait(mm, (pte_t *)pud, ptl);
7234 * hwpoisoned entry is treated as no_page_table in
7235 * follow_page_mask().
7243 struct page * __weak
7244 follow_huge_pgd(struct mm_struct *mm, unsigned long address, pgd_t *pgd, int flags)
7246 if (flags & (FOLL_GET | FOLL_PIN))
7249 return pte_page(*(pte_t *)pgd) + ((address & ~PGDIR_MASK) >> PAGE_SHIFT);
7252 int isolate_hugetlb(struct page *page, struct list_head *list)
7256 spin_lock_irq(&hugetlb_lock);
7257 if (!PageHeadHuge(page) ||
7258 !HPageMigratable(page) ||
7259 !get_page_unless_zero(page)) {
7263 ClearHPageMigratable(page);
7264 list_move_tail(&page->lru, list);
7266 spin_unlock_irq(&hugetlb_lock);
7270 int get_hwpoison_huge_page(struct page *page, bool *hugetlb)
7275 spin_lock_irq(&hugetlb_lock);
7276 if (PageHeadHuge(page)) {
7278 if (HPageFreed(page))
7280 else if (HPageMigratable(page))
7281 ret = get_page_unless_zero(page);
7285 spin_unlock_irq(&hugetlb_lock);
7289 int get_huge_page_for_hwpoison(unsigned long pfn, int flags)
7293 spin_lock_irq(&hugetlb_lock);
7294 ret = __get_huge_page_for_hwpoison(pfn, flags);
7295 spin_unlock_irq(&hugetlb_lock);
7299 void putback_active_hugepage(struct page *page)
7301 spin_lock_irq(&hugetlb_lock);
7302 SetHPageMigratable(page);
7303 list_move_tail(&page->lru, &(page_hstate(page))->hugepage_activelist);
7304 spin_unlock_irq(&hugetlb_lock);
7308 void move_hugetlb_state(struct page *oldpage, struct page *newpage, int reason)
7310 struct hstate *h = page_hstate(oldpage);
7312 hugetlb_cgroup_migrate(oldpage, newpage);
7313 set_page_owner_migrate_reason(newpage, reason);
7316 * transfer temporary state of the new huge page. This is
7317 * reverse to other transitions because the newpage is going to
7318 * be final while the old one will be freed so it takes over
7319 * the temporary status.
7321 * Also note that we have to transfer the per-node surplus state
7322 * here as well otherwise the global surplus count will not match
7325 if (HPageTemporary(newpage)) {
7326 int old_nid = page_to_nid(oldpage);
7327 int new_nid = page_to_nid(newpage);
7329 SetHPageTemporary(oldpage);
7330 ClearHPageTemporary(newpage);
7333 * There is no need to transfer the per-node surplus state
7334 * when we do not cross the node.
7336 if (new_nid == old_nid)
7338 spin_lock_irq(&hugetlb_lock);
7339 if (h->surplus_huge_pages_node[old_nid]) {
7340 h->surplus_huge_pages_node[old_nid]--;
7341 h->surplus_huge_pages_node[new_nid]++;
7343 spin_unlock_irq(&hugetlb_lock);
7348 * This function will unconditionally remove all the shared pmd pgtable entries
7349 * within the specific vma for a hugetlbfs memory range.
7351 void hugetlb_unshare_all_pmds(struct vm_area_struct *vma)
7353 struct hstate *h = hstate_vma(vma);
7354 unsigned long sz = huge_page_size(h);
7355 struct mm_struct *mm = vma->vm_mm;
7356 struct mmu_notifier_range range;
7357 unsigned long address, start, end;
7361 if (!(vma->vm_flags & VM_MAYSHARE))
7364 start = ALIGN(vma->vm_start, PUD_SIZE);
7365 end = ALIGN_DOWN(vma->vm_end, PUD_SIZE);
7370 flush_cache_range(vma, start, end);
7372 * No need to call adjust_range_if_pmd_sharing_possible(), because
7373 * we have already done the PUD_SIZE alignment.
7375 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
7377 mmu_notifier_invalidate_range_start(&range);
7378 hugetlb_vma_lock_write(vma);
7379 i_mmap_lock_write(vma->vm_file->f_mapping);
7380 for (address = start; address < end; address += PUD_SIZE) {
7381 ptep = huge_pte_offset(mm, address, sz);
7384 ptl = huge_pte_lock(h, mm, ptep);
7385 huge_pmd_unshare(mm, vma, address, ptep);
7388 flush_hugetlb_tlb_range(vma, start, end);
7389 i_mmap_unlock_write(vma->vm_file->f_mapping);
7390 hugetlb_vma_unlock_write(vma);
7392 * No need to call mmu_notifier_invalidate_range(), see
7393 * Documentation/mm/mmu_notifier.rst.
7395 mmu_notifier_invalidate_range_end(&range);
7399 static bool cma_reserve_called __initdata;
7401 static int __init cmdline_parse_hugetlb_cma(char *p)
7408 if (sscanf(s, "%lu%n", &tmp, &count) != 1)
7411 if (s[count] == ':') {
7412 if (tmp >= MAX_NUMNODES)
7414 nid = array_index_nospec(tmp, MAX_NUMNODES);
7417 tmp = memparse(s, &s);
7418 hugetlb_cma_size_in_node[nid] = tmp;
7419 hugetlb_cma_size += tmp;
7422 * Skip the separator if have one, otherwise
7423 * break the parsing.
7430 hugetlb_cma_size = memparse(p, &p);
7438 early_param("hugetlb_cma", cmdline_parse_hugetlb_cma);
7440 void __init hugetlb_cma_reserve(int order)
7442 unsigned long size, reserved, per_node;
7443 bool node_specific_cma_alloc = false;
7446 cma_reserve_called = true;
7448 if (!hugetlb_cma_size)
7451 for (nid = 0; nid < MAX_NUMNODES; nid++) {
7452 if (hugetlb_cma_size_in_node[nid] == 0)
7455 if (!node_online(nid)) {
7456 pr_warn("hugetlb_cma: invalid node %d specified\n", nid);
7457 hugetlb_cma_size -= hugetlb_cma_size_in_node[nid];
7458 hugetlb_cma_size_in_node[nid] = 0;
7462 if (hugetlb_cma_size_in_node[nid] < (PAGE_SIZE << order)) {
7463 pr_warn("hugetlb_cma: cma area of node %d should be at least %lu MiB\n",
7464 nid, (PAGE_SIZE << order) / SZ_1M);
7465 hugetlb_cma_size -= hugetlb_cma_size_in_node[nid];
7466 hugetlb_cma_size_in_node[nid] = 0;
7468 node_specific_cma_alloc = true;
7472 /* Validate the CMA size again in case some invalid nodes specified. */
7473 if (!hugetlb_cma_size)
7476 if (hugetlb_cma_size < (PAGE_SIZE << order)) {
7477 pr_warn("hugetlb_cma: cma area should be at least %lu MiB\n",
7478 (PAGE_SIZE << order) / SZ_1M);
7479 hugetlb_cma_size = 0;
7483 if (!node_specific_cma_alloc) {
7485 * If 3 GB area is requested on a machine with 4 numa nodes,
7486 * let's allocate 1 GB on first three nodes and ignore the last one.
7488 per_node = DIV_ROUND_UP(hugetlb_cma_size, nr_online_nodes);
7489 pr_info("hugetlb_cma: reserve %lu MiB, up to %lu MiB per node\n",
7490 hugetlb_cma_size / SZ_1M, per_node / SZ_1M);
7494 for_each_online_node(nid) {
7496 char name[CMA_MAX_NAME];
7498 if (node_specific_cma_alloc) {
7499 if (hugetlb_cma_size_in_node[nid] == 0)
7502 size = hugetlb_cma_size_in_node[nid];
7504 size = min(per_node, hugetlb_cma_size - reserved);
7507 size = round_up(size, PAGE_SIZE << order);
7509 snprintf(name, sizeof(name), "hugetlb%d", nid);
7511 * Note that 'order per bit' is based on smallest size that
7512 * may be returned to CMA allocator in the case of
7513 * huge page demotion.
7515 res = cma_declare_contiguous_nid(0, size, 0,
7516 PAGE_SIZE << HUGETLB_PAGE_ORDER,
7518 &hugetlb_cma[nid], nid);
7520 pr_warn("hugetlb_cma: reservation failed: err %d, node %d",
7526 pr_info("hugetlb_cma: reserved %lu MiB on node %d\n",
7529 if (reserved >= hugetlb_cma_size)
7535 * hugetlb_cma_size is used to determine if allocations from
7536 * cma are possible. Set to zero if no cma regions are set up.
7538 hugetlb_cma_size = 0;
7541 static void __init hugetlb_cma_check(void)
7543 if (!hugetlb_cma_size || cma_reserve_called)
7546 pr_warn("hugetlb_cma: the option isn't supported by current arch\n");
7549 #endif /* CONFIG_CMA */