xref: /openbmc/linux/mm/hugetlb.c (revision 8ebc80a25f9d9bf7a8e368b266d5b740c485c362)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  * Generic hugetlb support.
46d49e352SNadia Yvette Chambers  * (C) Nadia Yvette Chambers, April 2004
51da177e4SLinus Torvalds  */
61da177e4SLinus Torvalds #include <linux/list.h>
71da177e4SLinus Torvalds #include <linux/init.h>
81da177e4SLinus Torvalds #include <linux/mm.h>
9e1759c21SAlexey Dobriyan #include <linux/seq_file.h>
101da177e4SLinus Torvalds #include <linux/sysctl.h>
111da177e4SLinus Torvalds #include <linux/highmem.h>
12cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
131da177e4SLinus Torvalds #include <linux/nodemask.h>
1463551ae0SDavid Gibson #include <linux/pagemap.h>
155da7ca86SChristoph Lameter #include <linux/mempolicy.h>
163b32123dSGideon Israel Dsouza #include <linux/compiler.h>
17aea47ff3SChristoph Lameter #include <linux/cpuset.h>
183935baa9SDavid Gibson #include <linux/mutex.h>
1997ad1087SMike Rapoport #include <linux/memblock.h>
20a3437870SNishanth Aravamudan #include <linux/sysfs.h>
215a0e3ad6STejun Heo #include <linux/slab.h>
22bbe88753SJoonsoo Kim #include <linux/sched/mm.h>
2363489f8eSMike Kravetz #include <linux/mmdebug.h>
24174cd4b1SIngo Molnar #include <linux/sched/signal.h>
250fe6e20bSNaoya Horiguchi #include <linux/rmap.h>
26c6247f72SMatthew Wilcox #include <linux/string_helpers.h>
27fd6a03edSNaoya Horiguchi #include <linux/swap.h>
28fd6a03edSNaoya Horiguchi #include <linux/swapops.h>
298382d914SDavidlohr Bueso #include <linux/jhash.h>
3098fa15f3SAnshuman Khandual #include <linux/numa.h>
31c77c0a8aSWaiman Long #include <linux/llist.h>
32cf11e85fSRoman Gushchin #include <linux/cma.h>
338cc5fcbbSMina Almasry #include <linux/migrate.h>
34f9317f77SMike Kravetz #include <linux/nospec.h>
35662ce1dcSYang Yang #include <linux/delayacct.h>
36b958d4d0SMuchun Song #include <linux/memory.h>
37af19487fSAxel Rasmussen #include <linux/mm_inline.h>
38d6606683SLinus Torvalds 
3963551ae0SDavid Gibson #include <asm/page.h>
40ca15ca40SMike Rapoport #include <asm/pgalloc.h>
4124669e58SAneesh Kumar K.V #include <asm/tlb.h>
4263551ae0SDavid Gibson 
4324669e58SAneesh Kumar K.V #include <linux/io.h>
4463551ae0SDavid Gibson #include <linux/hugetlb.h>
459dd540e2SAneesh Kumar K.V #include <linux/hugetlb_cgroup.h>
469a305230SLee Schermerhorn #include <linux/node.h>
47ab5ac90aSMichal Hocko #include <linux/page_owner.h>
487835e98bSNick Piggin #include "internal.h"
49f41f2ed4SMuchun Song #include "hugetlb_vmemmap.h"
501da177e4SLinus Torvalds 
51c3f38a38SAneesh Kumar K.V int hugetlb_max_hstate __read_mostly;
52e5ff2159SAndi Kleen unsigned int default_hstate_idx;
53e5ff2159SAndi Kleen struct hstate hstates[HUGE_MAX_HSTATE];
54cf11e85fSRoman Gushchin 
55dbda8feaSBarry Song #ifdef CONFIG_CMA
56cf11e85fSRoman Gushchin static struct cma *hugetlb_cma[MAX_NUMNODES];
5738e719abSBaolin Wang static unsigned long hugetlb_cma_size_in_node[MAX_NUMNODES] __initdata;
hugetlb_cma_folio(struct folio * folio,unsigned int order)582f6c57d6SSidhartha Kumar static bool hugetlb_cma_folio(struct folio *folio, unsigned int order)
59a01f4390SMike Kravetz {
602f6c57d6SSidhartha Kumar 	return cma_pages_valid(hugetlb_cma[folio_nid(folio)], &folio->page,
61a01f4390SMike Kravetz 				1 << order);
62a01f4390SMike Kravetz }
63a01f4390SMike Kravetz #else
hugetlb_cma_folio(struct folio * folio,unsigned int order)642f6c57d6SSidhartha Kumar static bool hugetlb_cma_folio(struct folio *folio, unsigned int order)
65a01f4390SMike Kravetz {
66a01f4390SMike Kravetz 	return false;
67a01f4390SMike Kravetz }
68dbda8feaSBarry Song #endif
69dbda8feaSBarry Song static unsigned long hugetlb_cma_size __initdata;
70cf11e85fSRoman Gushchin 
7153ba51d2SJon Tollefson __initdata LIST_HEAD(huge_boot_pages);
7253ba51d2SJon Tollefson 
73e5ff2159SAndi Kleen /* for command line parsing */
74e5ff2159SAndi Kleen static struct hstate * __initdata parsed_hstate;
75e5ff2159SAndi Kleen static unsigned long __initdata default_hstate_max_huge_pages;
769fee021dSVaishali Thakkar static bool __initdata parsed_valid_hugepagesz = true;
77282f4214SMike Kravetz static bool __initdata parsed_default_hugepagesz;
78b5389086SZhenguo Yao static unsigned int default_hugepages_in_node[MAX_NUMNODES] __initdata;
79e5ff2159SAndi Kleen 
803935baa9SDavid Gibson /*
8131caf665SNaoya Horiguchi  * Protects updates to hugepage_freelists, hugepage_activelist, nr_huge_pages,
8231caf665SNaoya Horiguchi  * free_huge_pages, and surplus_huge_pages.
833935baa9SDavid Gibson  */
84c3f38a38SAneesh Kumar K.V DEFINE_SPINLOCK(hugetlb_lock);
850bd0f9fbSEric Paris 
868382d914SDavidlohr Bueso /*
878382d914SDavidlohr Bueso  * Serializes faults on the same logical page.  This is used to
888382d914SDavidlohr Bueso  * prevent spurious OOMs when the hugepage pool is fully utilized.
898382d914SDavidlohr Bueso  */
908382d914SDavidlohr Bueso static int num_fault_mutexes;
91c672c7f2SMike Kravetz struct mutex *hugetlb_fault_mutex_table ____cacheline_aligned_in_smp;
928382d914SDavidlohr Bueso 
937ca02d0aSMike Kravetz /* Forward declaration */
947ca02d0aSMike Kravetz static int hugetlb_acct_memory(struct hstate *h, long delta);
958d9bfb26SMike Kravetz static void hugetlb_vma_lock_free(struct vm_area_struct *vma);
968d9bfb26SMike Kravetz static void hugetlb_vma_lock_alloc(struct vm_area_struct *vma);
97ecfbd733SMike Kravetz static void __hugetlb_vma_unlock_write_free(struct vm_area_struct *vma);
98b30c14cdSJames Houghton static void hugetlb_unshare_pmds(struct vm_area_struct *vma,
99b30c14cdSJames Houghton 		unsigned long start, unsigned long end);
100bf491692SRik van Riel static struct resv_map *vma_resv_map(struct vm_area_struct *vma);
1017ca02d0aSMike Kravetz 
subpool_is_free(struct hugepage_subpool * spool)1021d88433bSMiaohe Lin static inline bool subpool_is_free(struct hugepage_subpool *spool)
1031d88433bSMiaohe Lin {
1041d88433bSMiaohe Lin 	if (spool->count)
1051d88433bSMiaohe Lin 		return false;
1061d88433bSMiaohe Lin 	if (spool->max_hpages != -1)
1071d88433bSMiaohe Lin 		return spool->used_hpages == 0;
1081d88433bSMiaohe Lin 	if (spool->min_hpages != -1)
1091d88433bSMiaohe Lin 		return spool->rsv_hpages == spool->min_hpages;
1101d88433bSMiaohe Lin 
1111d88433bSMiaohe Lin 	return true;
1121d88433bSMiaohe Lin }
1131d88433bSMiaohe Lin 
unlock_or_release_subpool(struct hugepage_subpool * spool,unsigned long irq_flags)114db71ef79SMike Kravetz static inline void unlock_or_release_subpool(struct hugepage_subpool *spool,
115db71ef79SMike Kravetz 						unsigned long irq_flags)
11690481622SDavid Gibson {
117db71ef79SMike Kravetz 	spin_unlock_irqrestore(&spool->lock, irq_flags);
11890481622SDavid Gibson 
11990481622SDavid Gibson 	/* If no pages are used, and no other handles to the subpool
1207c8de358SEthon Paul 	 * remain, give up any reservations based on minimum size and
1217ca02d0aSMike Kravetz 	 * free the subpool */
1221d88433bSMiaohe Lin 	if (subpool_is_free(spool)) {
1237ca02d0aSMike Kravetz 		if (spool->min_hpages != -1)
1247ca02d0aSMike Kravetz 			hugetlb_acct_memory(spool->hstate,
1257ca02d0aSMike Kravetz 						-spool->min_hpages);
12690481622SDavid Gibson 		kfree(spool);
12790481622SDavid Gibson 	}
1287ca02d0aSMike Kravetz }
12990481622SDavid Gibson 
hugepage_new_subpool(struct hstate * h,long max_hpages,long min_hpages)1307ca02d0aSMike Kravetz struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages,
1317ca02d0aSMike Kravetz 						long min_hpages)
13290481622SDavid Gibson {
13390481622SDavid Gibson 	struct hugepage_subpool *spool;
13490481622SDavid Gibson 
135c6a91820SMike Kravetz 	spool = kzalloc(sizeof(*spool), GFP_KERNEL);
13690481622SDavid Gibson 	if (!spool)
13790481622SDavid Gibson 		return NULL;
13890481622SDavid Gibson 
13990481622SDavid Gibson 	spin_lock_init(&spool->lock);
14090481622SDavid Gibson 	spool->count = 1;
1417ca02d0aSMike Kravetz 	spool->max_hpages = max_hpages;
1427ca02d0aSMike Kravetz 	spool->hstate = h;
1437ca02d0aSMike Kravetz 	spool->min_hpages = min_hpages;
1447ca02d0aSMike Kravetz 
1457ca02d0aSMike Kravetz 	if (min_hpages != -1 && hugetlb_acct_memory(h, min_hpages)) {
1467ca02d0aSMike Kravetz 		kfree(spool);
1477ca02d0aSMike Kravetz 		return NULL;
1487ca02d0aSMike Kravetz 	}
1497ca02d0aSMike Kravetz 	spool->rsv_hpages = min_hpages;
15090481622SDavid Gibson 
15190481622SDavid Gibson 	return spool;
15290481622SDavid Gibson }
15390481622SDavid Gibson 
hugepage_put_subpool(struct hugepage_subpool * spool)15490481622SDavid Gibson void hugepage_put_subpool(struct hugepage_subpool *spool)
15590481622SDavid Gibson {
156db71ef79SMike Kravetz 	unsigned long flags;
157db71ef79SMike Kravetz 
158db71ef79SMike Kravetz 	spin_lock_irqsave(&spool->lock, flags);
15990481622SDavid Gibson 	BUG_ON(!spool->count);
16090481622SDavid Gibson 	spool->count--;
161db71ef79SMike Kravetz 	unlock_or_release_subpool(spool, flags);
16290481622SDavid Gibson }
16390481622SDavid Gibson 
1641c5ecae3SMike Kravetz /*
1651c5ecae3SMike Kravetz  * Subpool accounting for allocating and reserving pages.
1661c5ecae3SMike Kravetz  * Return -ENOMEM if there are not enough resources to satisfy the
1679e7ee400SRandy Dunlap  * request.  Otherwise, return the number of pages by which the
1681c5ecae3SMike Kravetz  * global pools must be adjusted (upward).  The returned value may
1691c5ecae3SMike Kravetz  * only be different than the passed value (delta) in the case where
1707c8de358SEthon Paul  * a subpool minimum size must be maintained.
1711c5ecae3SMike Kravetz  */
hugepage_subpool_get_pages(struct hugepage_subpool * spool,long delta)1721c5ecae3SMike Kravetz static long hugepage_subpool_get_pages(struct hugepage_subpool *spool,
17390481622SDavid Gibson 				      long delta)
17490481622SDavid Gibson {
1751c5ecae3SMike Kravetz 	long ret = delta;
17690481622SDavid Gibson 
17790481622SDavid Gibson 	if (!spool)
1781c5ecae3SMike Kravetz 		return ret;
17990481622SDavid Gibson 
180db71ef79SMike Kravetz 	spin_lock_irq(&spool->lock);
18190481622SDavid Gibson 
1821c5ecae3SMike Kravetz 	if (spool->max_hpages != -1) {		/* maximum size accounting */
1831c5ecae3SMike Kravetz 		if ((spool->used_hpages + delta) <= spool->max_hpages)
1841c5ecae3SMike Kravetz 			spool->used_hpages += delta;
1851c5ecae3SMike Kravetz 		else {
1861c5ecae3SMike Kravetz 			ret = -ENOMEM;
1871c5ecae3SMike Kravetz 			goto unlock_ret;
1881c5ecae3SMike Kravetz 		}
1891c5ecae3SMike Kravetz 	}
1901c5ecae3SMike Kravetz 
19109a95e29SMike Kravetz 	/* minimum size accounting */
19209a95e29SMike Kravetz 	if (spool->min_hpages != -1 && spool->rsv_hpages) {
1931c5ecae3SMike Kravetz 		if (delta > spool->rsv_hpages) {
1941c5ecae3SMike Kravetz 			/*
1951c5ecae3SMike Kravetz 			 * Asking for more reserves than those already taken on
1961c5ecae3SMike Kravetz 			 * behalf of subpool.  Return difference.
1971c5ecae3SMike Kravetz 			 */
1981c5ecae3SMike Kravetz 			ret = delta - spool->rsv_hpages;
1991c5ecae3SMike Kravetz 			spool->rsv_hpages = 0;
2001c5ecae3SMike Kravetz 		} else {
2011c5ecae3SMike Kravetz 			ret = 0;	/* reserves already accounted for */
2021c5ecae3SMike Kravetz 			spool->rsv_hpages -= delta;
2031c5ecae3SMike Kravetz 		}
2041c5ecae3SMike Kravetz 	}
2051c5ecae3SMike Kravetz 
2061c5ecae3SMike Kravetz unlock_ret:
207db71ef79SMike Kravetz 	spin_unlock_irq(&spool->lock);
20890481622SDavid Gibson 	return ret;
20990481622SDavid Gibson }
21090481622SDavid Gibson 
2111c5ecae3SMike Kravetz /*
2121c5ecae3SMike Kravetz  * Subpool accounting for freeing and unreserving pages.
2131c5ecae3SMike Kravetz  * Return the number of global page reservations that must be dropped.
2141c5ecae3SMike Kravetz  * The return value may only be different than the passed value (delta)
2151c5ecae3SMike Kravetz  * in the case where a subpool minimum size must be maintained.
2161c5ecae3SMike Kravetz  */
hugepage_subpool_put_pages(struct hugepage_subpool * spool,long delta)2171c5ecae3SMike Kravetz static long hugepage_subpool_put_pages(struct hugepage_subpool *spool,
21890481622SDavid Gibson 				       long delta)
21990481622SDavid Gibson {
2201c5ecae3SMike Kravetz 	long ret = delta;
221db71ef79SMike Kravetz 	unsigned long flags;
2221c5ecae3SMike Kravetz 
22390481622SDavid Gibson 	if (!spool)
2241c5ecae3SMike Kravetz 		return delta;
22590481622SDavid Gibson 
226db71ef79SMike Kravetz 	spin_lock_irqsave(&spool->lock, flags);
2271c5ecae3SMike Kravetz 
2281c5ecae3SMike Kravetz 	if (spool->max_hpages != -1)		/* maximum size accounting */
22990481622SDavid Gibson 		spool->used_hpages -= delta;
2301c5ecae3SMike Kravetz 
23109a95e29SMike Kravetz 	 /* minimum size accounting */
23209a95e29SMike Kravetz 	if (spool->min_hpages != -1 && spool->used_hpages < spool->min_hpages) {
2331c5ecae3SMike Kravetz 		if (spool->rsv_hpages + delta <= spool->min_hpages)
2341c5ecae3SMike Kravetz 			ret = 0;
2351c5ecae3SMike Kravetz 		else
2361c5ecae3SMike Kravetz 			ret = spool->rsv_hpages + delta - spool->min_hpages;
2371c5ecae3SMike Kravetz 
2381c5ecae3SMike Kravetz 		spool->rsv_hpages += delta;
2391c5ecae3SMike Kravetz 		if (spool->rsv_hpages > spool->min_hpages)
2401c5ecae3SMike Kravetz 			spool->rsv_hpages = spool->min_hpages;
2411c5ecae3SMike Kravetz 	}
2421c5ecae3SMike Kravetz 
2431c5ecae3SMike Kravetz 	/*
2441c5ecae3SMike Kravetz 	 * If hugetlbfs_put_super couldn't free spool due to an outstanding
2451c5ecae3SMike Kravetz 	 * quota reference, free it now.
2461c5ecae3SMike Kravetz 	 */
247db71ef79SMike Kravetz 	unlock_or_release_subpool(spool, flags);
2481c5ecae3SMike Kravetz 
2491c5ecae3SMike Kravetz 	return ret;
25090481622SDavid Gibson }
25190481622SDavid Gibson 
subpool_inode(struct inode * inode)25290481622SDavid Gibson static inline struct hugepage_subpool *subpool_inode(struct inode *inode)
25390481622SDavid Gibson {
25490481622SDavid Gibson 	return HUGETLBFS_SB(inode->i_sb)->spool;
25590481622SDavid Gibson }
25690481622SDavid Gibson 
subpool_vma(struct vm_area_struct * vma)25790481622SDavid Gibson static inline struct hugepage_subpool *subpool_vma(struct vm_area_struct *vma)
25890481622SDavid Gibson {
259496ad9aaSAl Viro 	return subpool_inode(file_inode(vma->vm_file));
26090481622SDavid Gibson }
26190481622SDavid Gibson 
262e700898fSMike Kravetz /*
263e700898fSMike Kravetz  * hugetlb vma_lock helper routines
264e700898fSMike Kravetz  */
hugetlb_vma_lock_read(struct vm_area_struct * vma)265e700898fSMike Kravetz void hugetlb_vma_lock_read(struct vm_area_struct *vma)
266e700898fSMike Kravetz {
267e700898fSMike Kravetz 	if (__vma_shareable_lock(vma)) {
268e700898fSMike Kravetz 		struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
269e700898fSMike Kravetz 
270e700898fSMike Kravetz 		down_read(&vma_lock->rw_sema);
271bf491692SRik van Riel 	} else if (__vma_private_lock(vma)) {
272bf491692SRik van Riel 		struct resv_map *resv_map = vma_resv_map(vma);
273bf491692SRik van Riel 
274bf491692SRik van Riel 		down_read(&resv_map->rw_sema);
275e700898fSMike Kravetz 	}
276e700898fSMike Kravetz }
277e700898fSMike Kravetz 
hugetlb_vma_unlock_read(struct vm_area_struct * vma)278e700898fSMike Kravetz void hugetlb_vma_unlock_read(struct vm_area_struct *vma)
279e700898fSMike Kravetz {
280e700898fSMike Kravetz 	if (__vma_shareable_lock(vma)) {
281e700898fSMike Kravetz 		struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
282e700898fSMike Kravetz 
283e700898fSMike Kravetz 		up_read(&vma_lock->rw_sema);
284bf491692SRik van Riel 	} else if (__vma_private_lock(vma)) {
285bf491692SRik van Riel 		struct resv_map *resv_map = vma_resv_map(vma);
286bf491692SRik van Riel 
287bf491692SRik van Riel 		up_read(&resv_map->rw_sema);
288e700898fSMike Kravetz 	}
289e700898fSMike Kravetz }
290e700898fSMike Kravetz 
hugetlb_vma_lock_write(struct vm_area_struct * vma)291e700898fSMike Kravetz void hugetlb_vma_lock_write(struct vm_area_struct *vma)
292e700898fSMike Kravetz {
293e700898fSMike Kravetz 	if (__vma_shareable_lock(vma)) {
294e700898fSMike Kravetz 		struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
295e700898fSMike Kravetz 
296e700898fSMike Kravetz 		down_write(&vma_lock->rw_sema);
297bf491692SRik van Riel 	} else if (__vma_private_lock(vma)) {
298bf491692SRik van Riel 		struct resv_map *resv_map = vma_resv_map(vma);
299bf491692SRik van Riel 
300bf491692SRik van Riel 		down_write(&resv_map->rw_sema);
301e700898fSMike Kravetz 	}
302e700898fSMike Kravetz }
303e700898fSMike Kravetz 
hugetlb_vma_unlock_write(struct vm_area_struct * vma)304e700898fSMike Kravetz void hugetlb_vma_unlock_write(struct vm_area_struct *vma)
305e700898fSMike Kravetz {
306e700898fSMike Kravetz 	if (__vma_shareable_lock(vma)) {
307e700898fSMike Kravetz 		struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
308e700898fSMike Kravetz 
309e700898fSMike Kravetz 		up_write(&vma_lock->rw_sema);
310bf491692SRik van Riel 	} else if (__vma_private_lock(vma)) {
311bf491692SRik van Riel 		struct resv_map *resv_map = vma_resv_map(vma);
312bf491692SRik van Riel 
313bf491692SRik van Riel 		up_write(&resv_map->rw_sema);
314e700898fSMike Kravetz 	}
315e700898fSMike Kravetz }
316e700898fSMike Kravetz 
hugetlb_vma_trylock_write(struct vm_area_struct * vma)317e700898fSMike Kravetz int hugetlb_vma_trylock_write(struct vm_area_struct *vma)
318e700898fSMike Kravetz {
319bf491692SRik van Riel 
320bf491692SRik van Riel 	if (__vma_shareable_lock(vma)) {
321e700898fSMike Kravetz 		struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
322e700898fSMike Kravetz 
323e700898fSMike Kravetz 		return down_write_trylock(&vma_lock->rw_sema);
324bf491692SRik van Riel 	} else if (__vma_private_lock(vma)) {
325bf491692SRik van Riel 		struct resv_map *resv_map = vma_resv_map(vma);
326bf491692SRik van Riel 
327bf491692SRik van Riel 		return down_write_trylock(&resv_map->rw_sema);
328bf491692SRik van Riel 	}
329bf491692SRik van Riel 
330bf491692SRik van Riel 	return 1;
331e700898fSMike Kravetz }
332e700898fSMike Kravetz 
hugetlb_vma_assert_locked(struct vm_area_struct * vma)333e700898fSMike Kravetz void hugetlb_vma_assert_locked(struct vm_area_struct *vma)
334e700898fSMike Kravetz {
335e700898fSMike Kravetz 	if (__vma_shareable_lock(vma)) {
336e700898fSMike Kravetz 		struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
337e700898fSMike Kravetz 
338e700898fSMike Kravetz 		lockdep_assert_held(&vma_lock->rw_sema);
339bf491692SRik van Riel 	} else if (__vma_private_lock(vma)) {
340bf491692SRik van Riel 		struct resv_map *resv_map = vma_resv_map(vma);
341bf491692SRik van Riel 
342bf491692SRik van Riel 		lockdep_assert_held(&resv_map->rw_sema);
343e700898fSMike Kravetz 	}
344e700898fSMike Kravetz }
345e700898fSMike Kravetz 
hugetlb_vma_lock_release(struct kref * kref)346e700898fSMike Kravetz void hugetlb_vma_lock_release(struct kref *kref)
347e700898fSMike Kravetz {
348e700898fSMike Kravetz 	struct hugetlb_vma_lock *vma_lock = container_of(kref,
349e700898fSMike Kravetz 			struct hugetlb_vma_lock, refs);
350e700898fSMike Kravetz 
351e700898fSMike Kravetz 	kfree(vma_lock);
352e700898fSMike Kravetz }
353e700898fSMike Kravetz 
__hugetlb_vma_unlock_write_put(struct hugetlb_vma_lock * vma_lock)354e700898fSMike Kravetz static void __hugetlb_vma_unlock_write_put(struct hugetlb_vma_lock *vma_lock)
355e700898fSMike Kravetz {
356e700898fSMike Kravetz 	struct vm_area_struct *vma = vma_lock->vma;
357e700898fSMike Kravetz 
358e700898fSMike Kravetz 	/*
359e700898fSMike Kravetz 	 * vma_lock structure may or not be released as a result of put,
360e700898fSMike Kravetz 	 * it certainly will no longer be attached to vma so clear pointer.
361e700898fSMike Kravetz 	 * Semaphore synchronizes access to vma_lock->vma field.
362e700898fSMike Kravetz 	 */
363e700898fSMike Kravetz 	vma_lock->vma = NULL;
364e700898fSMike Kravetz 	vma->vm_private_data = NULL;
365e700898fSMike Kravetz 	up_write(&vma_lock->rw_sema);
366e700898fSMike Kravetz 	kref_put(&vma_lock->refs, hugetlb_vma_lock_release);
367e700898fSMike Kravetz }
368e700898fSMike Kravetz 
__hugetlb_vma_unlock_write_free(struct vm_area_struct * vma)369e700898fSMike Kravetz static void __hugetlb_vma_unlock_write_free(struct vm_area_struct *vma)
370e700898fSMike Kravetz {
371e700898fSMike Kravetz 	if (__vma_shareable_lock(vma)) {
372e700898fSMike Kravetz 		struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
373e700898fSMike Kravetz 
374e700898fSMike Kravetz 		__hugetlb_vma_unlock_write_put(vma_lock);
375bf491692SRik van Riel 	} else if (__vma_private_lock(vma)) {
376bf491692SRik van Riel 		struct resv_map *resv_map = vma_resv_map(vma);
377bf491692SRik van Riel 
378bf491692SRik van Riel 		/* no free for anon vmas, but still need to unlock */
379bf491692SRik van Riel 		up_write(&resv_map->rw_sema);
380e700898fSMike Kravetz 	}
381e700898fSMike Kravetz }
382e700898fSMike Kravetz 
hugetlb_vma_lock_free(struct vm_area_struct * vma)383e700898fSMike Kravetz static void hugetlb_vma_lock_free(struct vm_area_struct *vma)
384e700898fSMike Kravetz {
385e700898fSMike Kravetz 	/*
386e700898fSMike Kravetz 	 * Only present in sharable vmas.
387e700898fSMike Kravetz 	 */
388e700898fSMike Kravetz 	if (!vma || !__vma_shareable_lock(vma))
389e700898fSMike Kravetz 		return;
390e700898fSMike Kravetz 
391e700898fSMike Kravetz 	if (vma->vm_private_data) {
392e700898fSMike Kravetz 		struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
393e700898fSMike Kravetz 
394e700898fSMike Kravetz 		down_write(&vma_lock->rw_sema);
395e700898fSMike Kravetz 		__hugetlb_vma_unlock_write_put(vma_lock);
396e700898fSMike Kravetz 	}
397e700898fSMike Kravetz }
398e700898fSMike Kravetz 
hugetlb_vma_lock_alloc(struct vm_area_struct * vma)399e700898fSMike Kravetz static void hugetlb_vma_lock_alloc(struct vm_area_struct *vma)
400e700898fSMike Kravetz {
401e700898fSMike Kravetz 	struct hugetlb_vma_lock *vma_lock;
402e700898fSMike Kravetz 
403e700898fSMike Kravetz 	/* Only establish in (flags) sharable vmas */
404e700898fSMike Kravetz 	if (!vma || !(vma->vm_flags & VM_MAYSHARE))
405e700898fSMike Kravetz 		return;
406e700898fSMike Kravetz 
407e700898fSMike Kravetz 	/* Should never get here with non-NULL vm_private_data */
408e700898fSMike Kravetz 	if (vma->vm_private_data)
409e700898fSMike Kravetz 		return;
410e700898fSMike Kravetz 
411e700898fSMike Kravetz 	vma_lock = kmalloc(sizeof(*vma_lock), GFP_KERNEL);
412e700898fSMike Kravetz 	if (!vma_lock) {
413e700898fSMike Kravetz 		/*
414e700898fSMike Kravetz 		 * If we can not allocate structure, then vma can not
415e700898fSMike Kravetz 		 * participate in pmd sharing.  This is only a possible
416e700898fSMike Kravetz 		 * performance enhancement and memory saving issue.
417e700898fSMike Kravetz 		 * However, the lock is also used to synchronize page
418e700898fSMike Kravetz 		 * faults with truncation.  If the lock is not present,
419e700898fSMike Kravetz 		 * unlikely races could leave pages in a file past i_size
420e700898fSMike Kravetz 		 * until the file is removed.  Warn in the unlikely case of
421e700898fSMike Kravetz 		 * allocation failure.
422e700898fSMike Kravetz 		 */
423e700898fSMike Kravetz 		pr_warn_once("HugeTLB: unable to allocate vma specific lock\n");
424e700898fSMike Kravetz 		return;
425e700898fSMike Kravetz 	}
426e700898fSMike Kravetz 
427e700898fSMike Kravetz 	kref_init(&vma_lock->refs);
428e700898fSMike Kravetz 	init_rwsem(&vma_lock->rw_sema);
429e700898fSMike Kravetz 	vma_lock->vma = vma;
430e700898fSMike Kravetz 	vma->vm_private_data = vma_lock;
431e700898fSMike Kravetz }
432e700898fSMike Kravetz 
4330db9d74eSMina Almasry /* Helper that removes a struct file_region from the resv_map cache and returns
4340db9d74eSMina Almasry  * it for use.
4350db9d74eSMina Almasry  */
4360db9d74eSMina Almasry static struct file_region *
get_file_region_entry_from_cache(struct resv_map * resv,long from,long to)4370db9d74eSMina Almasry get_file_region_entry_from_cache(struct resv_map *resv, long from, long to)
4380db9d74eSMina Almasry {
4393259914fSXU pengfei 	struct file_region *nrg;
4400db9d74eSMina Almasry 
4410db9d74eSMina Almasry 	VM_BUG_ON(resv->region_cache_count <= 0);
4420db9d74eSMina Almasry 
4430db9d74eSMina Almasry 	resv->region_cache_count--;
4440db9d74eSMina Almasry 	nrg = list_first_entry(&resv->region_cache, struct file_region, link);
4450db9d74eSMina Almasry 	list_del(&nrg->link);
4460db9d74eSMina Almasry 
4470db9d74eSMina Almasry 	nrg->from = from;
4480db9d74eSMina Almasry 	nrg->to = to;
4490db9d74eSMina Almasry 
4500db9d74eSMina Almasry 	return nrg;
4510db9d74eSMina Almasry }
4520db9d74eSMina Almasry 
copy_hugetlb_cgroup_uncharge_info(struct file_region * nrg,struct file_region * rg)453075a61d0SMina Almasry static void copy_hugetlb_cgroup_uncharge_info(struct file_region *nrg,
454075a61d0SMina Almasry 					      struct file_region *rg)
455075a61d0SMina Almasry {
456075a61d0SMina Almasry #ifdef CONFIG_CGROUP_HUGETLB
457075a61d0SMina Almasry 	nrg->reservation_counter = rg->reservation_counter;
458075a61d0SMina Almasry 	nrg->css = rg->css;
459075a61d0SMina Almasry 	if (rg->css)
460075a61d0SMina Almasry 		css_get(rg->css);
461075a61d0SMina Almasry #endif
462075a61d0SMina Almasry }
463075a61d0SMina Almasry 
464075a61d0SMina Almasry /* Helper that records hugetlb_cgroup uncharge info. */
record_hugetlb_cgroup_uncharge_info(struct hugetlb_cgroup * h_cg,struct hstate * h,struct resv_map * resv,struct file_region * nrg)465075a61d0SMina Almasry static void record_hugetlb_cgroup_uncharge_info(struct hugetlb_cgroup *h_cg,
466075a61d0SMina Almasry 						struct hstate *h,
467075a61d0SMina Almasry 						struct resv_map *resv,
468075a61d0SMina Almasry 						struct file_region *nrg)
469075a61d0SMina Almasry {
470075a61d0SMina Almasry #ifdef CONFIG_CGROUP_HUGETLB
471075a61d0SMina Almasry 	if (h_cg) {
472075a61d0SMina Almasry 		nrg->reservation_counter =
473075a61d0SMina Almasry 			&h_cg->rsvd_hugepage[hstate_index(h)];
474075a61d0SMina Almasry 		nrg->css = &h_cg->css;
475d85aecf2SMiaohe Lin 		/*
476d85aecf2SMiaohe Lin 		 * The caller will hold exactly one h_cg->css reference for the
477d85aecf2SMiaohe Lin 		 * whole contiguous reservation region. But this area might be
478d85aecf2SMiaohe Lin 		 * scattered when there are already some file_regions reside in
479d85aecf2SMiaohe Lin 		 * it. As a result, many file_regions may share only one css
480d85aecf2SMiaohe Lin 		 * reference. In order to ensure that one file_region must hold
481d85aecf2SMiaohe Lin 		 * exactly one h_cg->css reference, we should do css_get for
482d85aecf2SMiaohe Lin 		 * each file_region and leave the reference held by caller
483d85aecf2SMiaohe Lin 		 * untouched.
484d85aecf2SMiaohe Lin 		 */
485d85aecf2SMiaohe Lin 		css_get(&h_cg->css);
486075a61d0SMina Almasry 		if (!resv->pages_per_hpage)
487075a61d0SMina Almasry 			resv->pages_per_hpage = pages_per_huge_page(h);
488075a61d0SMina Almasry 		/* pages_per_hpage should be the same for all entries in
489075a61d0SMina Almasry 		 * a resv_map.
490075a61d0SMina Almasry 		 */
491075a61d0SMina Almasry 		VM_BUG_ON(resv->pages_per_hpage != pages_per_huge_page(h));
492075a61d0SMina Almasry 	} else {
493075a61d0SMina Almasry 		nrg->reservation_counter = NULL;
494075a61d0SMina Almasry 		nrg->css = NULL;
495075a61d0SMina Almasry 	}
496075a61d0SMina Almasry #endif
497075a61d0SMina Almasry }
498075a61d0SMina Almasry 
put_uncharge_info(struct file_region * rg)499d85aecf2SMiaohe Lin static void put_uncharge_info(struct file_region *rg)
500d85aecf2SMiaohe Lin {
501d85aecf2SMiaohe Lin #ifdef CONFIG_CGROUP_HUGETLB
502d85aecf2SMiaohe Lin 	if (rg->css)
503d85aecf2SMiaohe Lin 		css_put(rg->css);
504d85aecf2SMiaohe Lin #endif
505d85aecf2SMiaohe Lin }
506d85aecf2SMiaohe Lin 
has_same_uncharge_info(struct file_region * rg,struct file_region * org)507a9b3f867SMina Almasry static bool has_same_uncharge_info(struct file_region *rg,
508a9b3f867SMina Almasry 				   struct file_region *org)
509a9b3f867SMina Almasry {
510a9b3f867SMina Almasry #ifdef CONFIG_CGROUP_HUGETLB
5110739eb43SBaolin Wang 	return rg->reservation_counter == org->reservation_counter &&
512a9b3f867SMina Almasry 	       rg->css == org->css;
513a9b3f867SMina Almasry 
514a9b3f867SMina Almasry #else
515a9b3f867SMina Almasry 	return true;
516a9b3f867SMina Almasry #endif
517a9b3f867SMina Almasry }
518a9b3f867SMina Almasry 
coalesce_file_region(struct resv_map * resv,struct file_region * rg)519a9b3f867SMina Almasry static void coalesce_file_region(struct resv_map *resv, struct file_region *rg)
520a9b3f867SMina Almasry {
5213259914fSXU pengfei 	struct file_region *nrg, *prg;
522a9b3f867SMina Almasry 
523a9b3f867SMina Almasry 	prg = list_prev_entry(rg, link);
524a9b3f867SMina Almasry 	if (&prg->link != &resv->regions && prg->to == rg->from &&
525a9b3f867SMina Almasry 	    has_same_uncharge_info(prg, rg)) {
526a9b3f867SMina Almasry 		prg->to = rg->to;
527a9b3f867SMina Almasry 
528a9b3f867SMina Almasry 		list_del(&rg->link);
529d85aecf2SMiaohe Lin 		put_uncharge_info(rg);
530a9b3f867SMina Almasry 		kfree(rg);
531a9b3f867SMina Almasry 
5327db5e7b6SWei Yang 		rg = prg;
533a9b3f867SMina Almasry 	}
534a9b3f867SMina Almasry 
535a9b3f867SMina Almasry 	nrg = list_next_entry(rg, link);
536a9b3f867SMina Almasry 	if (&nrg->link != &resv->regions && nrg->from == rg->to &&
537a9b3f867SMina Almasry 	    has_same_uncharge_info(nrg, rg)) {
538a9b3f867SMina Almasry 		nrg->from = rg->from;
539a9b3f867SMina Almasry 
540a9b3f867SMina Almasry 		list_del(&rg->link);
541d85aecf2SMiaohe Lin 		put_uncharge_info(rg);
542a9b3f867SMina Almasry 		kfree(rg);
543a9b3f867SMina Almasry 	}
544a9b3f867SMina Almasry }
545a9b3f867SMina Almasry 
5462103cf9cSPeter Xu static inline long
hugetlb_resv_map_add(struct resv_map * map,struct list_head * rg,long from,long to,struct hstate * h,struct hugetlb_cgroup * cg,long * regions_needed)54784448c8eSJakob Koschel hugetlb_resv_map_add(struct resv_map *map, struct list_head *rg, long from,
5482103cf9cSPeter Xu 		     long to, struct hstate *h, struct hugetlb_cgroup *cg,
5492103cf9cSPeter Xu 		     long *regions_needed)
5502103cf9cSPeter Xu {
5512103cf9cSPeter Xu 	struct file_region *nrg;
5522103cf9cSPeter Xu 
5532103cf9cSPeter Xu 	if (!regions_needed) {
5542103cf9cSPeter Xu 		nrg = get_file_region_entry_from_cache(map, from, to);
5552103cf9cSPeter Xu 		record_hugetlb_cgroup_uncharge_info(cg, h, map, nrg);
55684448c8eSJakob Koschel 		list_add(&nrg->link, rg);
5572103cf9cSPeter Xu 		coalesce_file_region(map, nrg);
5582103cf9cSPeter Xu 	} else
5592103cf9cSPeter Xu 		*regions_needed += 1;
5602103cf9cSPeter Xu 
5612103cf9cSPeter Xu 	return to - from;
5622103cf9cSPeter Xu }
5632103cf9cSPeter Xu 
564972a3da3SWei Yang /*
565972a3da3SWei Yang  * Must be called with resv->lock held.
566972a3da3SWei Yang  *
567972a3da3SWei Yang  * Calling this with regions_needed != NULL will count the number of pages
568972a3da3SWei Yang  * to be added but will not modify the linked list. And regions_needed will
569972a3da3SWei Yang  * indicate the number of file_regions needed in the cache to carry out to add
570972a3da3SWei Yang  * the regions for this range.
571d75c6af9SMina Almasry  */
add_reservation_in_range(struct resv_map * resv,long f,long t,struct hugetlb_cgroup * h_cg,struct hstate * h,long * regions_needed)572d75c6af9SMina Almasry static long add_reservation_in_range(struct resv_map *resv, long f, long t,
573075a61d0SMina Almasry 				     struct hugetlb_cgroup *h_cg,
574972a3da3SWei Yang 				     struct hstate *h, long *regions_needed)
575d75c6af9SMina Almasry {
5760db9d74eSMina Almasry 	long add = 0;
577d75c6af9SMina Almasry 	struct list_head *head = &resv->regions;
5780db9d74eSMina Almasry 	long last_accounted_offset = f;
57984448c8eSJakob Koschel 	struct file_region *iter, *trg = NULL;
58084448c8eSJakob Koschel 	struct list_head *rg = NULL;
581d75c6af9SMina Almasry 
5820db9d74eSMina Almasry 	if (regions_needed)
5830db9d74eSMina Almasry 		*regions_needed = 0;
584d75c6af9SMina Almasry 
5850db9d74eSMina Almasry 	/* In this loop, we essentially handle an entry for the range
58684448c8eSJakob Koschel 	 * [last_accounted_offset, iter->from), at every iteration, with some
5870db9d74eSMina Almasry 	 * bounds checking.
5880db9d74eSMina Almasry 	 */
58984448c8eSJakob Koschel 	list_for_each_entry_safe(iter, trg, head, link) {
5900db9d74eSMina Almasry 		/* Skip irrelevant regions that start before our range. */
59184448c8eSJakob Koschel 		if (iter->from < f) {
5920db9d74eSMina Almasry 			/* If this region ends after the last accounted offset,
5930db9d74eSMina Almasry 			 * then we need to update last_accounted_offset.
5940db9d74eSMina Almasry 			 */
59584448c8eSJakob Koschel 			if (iter->to > last_accounted_offset)
59684448c8eSJakob Koschel 				last_accounted_offset = iter->to;
5970db9d74eSMina Almasry 			continue;
5980db9d74eSMina Almasry 		}
599d75c6af9SMina Almasry 
6000db9d74eSMina Almasry 		/* When we find a region that starts beyond our range, we've
6010db9d74eSMina Almasry 		 * finished.
6020db9d74eSMina Almasry 		 */
60384448c8eSJakob Koschel 		if (iter->from >= t) {
60484448c8eSJakob Koschel 			rg = iter->link.prev;
605d75c6af9SMina Almasry 			break;
60684448c8eSJakob Koschel 		}
607d75c6af9SMina Almasry 
60884448c8eSJakob Koschel 		/* Add an entry for last_accounted_offset -> iter->from, and
6090db9d74eSMina Almasry 		 * update last_accounted_offset.
610d75c6af9SMina Almasry 		 */
61184448c8eSJakob Koschel 		if (iter->from > last_accounted_offset)
61284448c8eSJakob Koschel 			add += hugetlb_resv_map_add(resv, iter->link.prev,
6132103cf9cSPeter Xu 						    last_accounted_offset,
61484448c8eSJakob Koschel 						    iter->from, h, h_cg,
6152103cf9cSPeter Xu 						    regions_needed);
616d75c6af9SMina Almasry 
61784448c8eSJakob Koschel 		last_accounted_offset = iter->to;
6180db9d74eSMina Almasry 	}
6190db9d74eSMina Almasry 
6200db9d74eSMina Almasry 	/* Handle the case where our range extends beyond
6210db9d74eSMina Almasry 	 * last_accounted_offset.
6220db9d74eSMina Almasry 	 */
62384448c8eSJakob Koschel 	if (!rg)
62484448c8eSJakob Koschel 		rg = head->prev;
6252103cf9cSPeter Xu 	if (last_accounted_offset < t)
6262103cf9cSPeter Xu 		add += hugetlb_resv_map_add(resv, rg, last_accounted_offset,
6272103cf9cSPeter Xu 					    t, h, h_cg, regions_needed);
6280db9d74eSMina Almasry 
6290db9d74eSMina Almasry 	return add;
6300db9d74eSMina Almasry }
6310db9d74eSMina Almasry 
6320db9d74eSMina Almasry /* Must be called with resv->lock acquired. Will drop lock to allocate entries.
6330db9d74eSMina Almasry  */
allocate_file_region_entries(struct resv_map * resv,int regions_needed)6340db9d74eSMina Almasry static int allocate_file_region_entries(struct resv_map *resv,
6350db9d74eSMina Almasry 					int regions_needed)
6360db9d74eSMina Almasry 	__must_hold(&resv->lock)
6370db9d74eSMina Almasry {
63834665341SMiaohe Lin 	LIST_HEAD(allocated_regions);
6390db9d74eSMina Almasry 	int to_allocate = 0, i = 0;
6400db9d74eSMina Almasry 	struct file_region *trg = NULL, *rg = NULL;
6410db9d74eSMina Almasry 
6420db9d74eSMina Almasry 	VM_BUG_ON(regions_needed < 0);
6430db9d74eSMina Almasry 
6440db9d74eSMina Almasry 	/*
6450db9d74eSMina Almasry 	 * Check for sufficient descriptors in the cache to accommodate
6460db9d74eSMina Almasry 	 * the number of in progress add operations plus regions_needed.
6470db9d74eSMina Almasry 	 *
6480db9d74eSMina Almasry 	 * This is a while loop because when we drop the lock, some other call
6490db9d74eSMina Almasry 	 * to region_add or region_del may have consumed some region_entries,
6500db9d74eSMina Almasry 	 * so we keep looping here until we finally have enough entries for
6510db9d74eSMina Almasry 	 * (adds_in_progress + regions_needed).
6520db9d74eSMina Almasry 	 */
6530db9d74eSMina Almasry 	while (resv->region_cache_count <
6540db9d74eSMina Almasry 	       (resv->adds_in_progress + regions_needed)) {
6550db9d74eSMina Almasry 		to_allocate = resv->adds_in_progress + regions_needed -
6560db9d74eSMina Almasry 			      resv->region_cache_count;
6570db9d74eSMina Almasry 
6580db9d74eSMina Almasry 		/* At this point, we should have enough entries in the cache
659f0953a1bSIngo Molnar 		 * for all the existing adds_in_progress. We should only be
6600db9d74eSMina Almasry 		 * needing to allocate for regions_needed.
6610db9d74eSMina Almasry 		 */
6620db9d74eSMina Almasry 		VM_BUG_ON(resv->region_cache_count < resv->adds_in_progress);
6630db9d74eSMina Almasry 
6640db9d74eSMina Almasry 		spin_unlock(&resv->lock);
6650db9d74eSMina Almasry 		for (i = 0; i < to_allocate; i++) {
6660db9d74eSMina Almasry 			trg = kmalloc(sizeof(*trg), GFP_KERNEL);
6670db9d74eSMina Almasry 			if (!trg)
6680db9d74eSMina Almasry 				goto out_of_memory;
6690db9d74eSMina Almasry 			list_add(&trg->link, &allocated_regions);
6700db9d74eSMina Almasry 		}
6710db9d74eSMina Almasry 
6720db9d74eSMina Almasry 		spin_lock(&resv->lock);
6730db9d74eSMina Almasry 
674d3ec7b6eSWei Yang 		list_splice(&allocated_regions, &resv->region_cache);
675d3ec7b6eSWei Yang 		resv->region_cache_count += to_allocate;
6760db9d74eSMina Almasry 	}
6770db9d74eSMina Almasry 
6780db9d74eSMina Almasry 	return 0;
6790db9d74eSMina Almasry 
6800db9d74eSMina Almasry out_of_memory:
6810db9d74eSMina Almasry 	list_for_each_entry_safe(rg, trg, &allocated_regions, link) {
682d75c6af9SMina Almasry 		list_del(&rg->link);
683d75c6af9SMina Almasry 		kfree(rg);
684d75c6af9SMina Almasry 	}
6850db9d74eSMina Almasry 	return -ENOMEM;
686d75c6af9SMina Almasry }
687d75c6af9SMina Almasry 
6881dd308a7SMike Kravetz /*
6891dd308a7SMike Kravetz  * Add the huge page range represented by [f, t) to the reserve
6900db9d74eSMina Almasry  * map.  Regions will be taken from the cache to fill in this range.
6910db9d74eSMina Almasry  * Sufficient regions should exist in the cache due to the previous
6920db9d74eSMina Almasry  * call to region_chg with the same range, but in some cases the cache will not
6930db9d74eSMina Almasry  * have sufficient entries due to races with other code doing region_add or
6940db9d74eSMina Almasry  * region_del.  The extra needed entries will be allocated.
695cf3ad20bSMike Kravetz  *
6960db9d74eSMina Almasry  * regions_needed is the out value provided by a previous call to region_chg.
6970db9d74eSMina Almasry  *
6980db9d74eSMina Almasry  * Return the number of new huge pages added to the map.  This number is greater
6990db9d74eSMina Almasry  * than or equal to zero.  If file_region entries needed to be allocated for
7007c8de358SEthon Paul  * this operation and we were not able to allocate, it returns -ENOMEM.
7010db9d74eSMina Almasry  * region_add of regions of length 1 never allocate file_regions and cannot
7020db9d74eSMina Almasry  * fail; region_chg will always allocate at least 1 entry and a region_add for
7030db9d74eSMina Almasry  * 1 page will only require at most 1 entry.
7041dd308a7SMike Kravetz  */
region_add(struct resv_map * resv,long f,long t,long in_regions_needed,struct hstate * h,struct hugetlb_cgroup * h_cg)7050db9d74eSMina Almasry static long region_add(struct resv_map *resv, long f, long t,
706075a61d0SMina Almasry 		       long in_regions_needed, struct hstate *h,
707075a61d0SMina Almasry 		       struct hugetlb_cgroup *h_cg)
70896822904SAndy Whitcroft {
7090db9d74eSMina Almasry 	long add = 0, actual_regions_needed = 0;
71096822904SAndy Whitcroft 
7117b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
7120db9d74eSMina Almasry retry:
7130db9d74eSMina Almasry 
7140db9d74eSMina Almasry 	/* Count how many regions are actually needed to execute this add. */
715972a3da3SWei Yang 	add_reservation_in_range(resv, f, t, NULL, NULL,
716972a3da3SWei Yang 				 &actual_regions_needed);
71796822904SAndy Whitcroft 
7185e911373SMike Kravetz 	/*
7190db9d74eSMina Almasry 	 * Check for sufficient descriptors in the cache to accommodate
7200db9d74eSMina Almasry 	 * this add operation. Note that actual_regions_needed may be greater
7210db9d74eSMina Almasry 	 * than in_regions_needed, as the resv_map may have been modified since
7220db9d74eSMina Almasry 	 * the region_chg call. In this case, we need to make sure that we
7230db9d74eSMina Almasry 	 * allocate extra entries, such that we have enough for all the
7240db9d74eSMina Almasry 	 * existing adds_in_progress, plus the excess needed for this
7250db9d74eSMina Almasry 	 * operation.
7265e911373SMike Kravetz 	 */
7270db9d74eSMina Almasry 	if (actual_regions_needed > in_regions_needed &&
7280db9d74eSMina Almasry 	    resv->region_cache_count <
7290db9d74eSMina Almasry 		    resv->adds_in_progress +
7300db9d74eSMina Almasry 			    (actual_regions_needed - in_regions_needed)) {
7310db9d74eSMina Almasry 		/* region_add operation of range 1 should never need to
7320db9d74eSMina Almasry 		 * allocate file_region entries.
7330db9d74eSMina Almasry 		 */
7340db9d74eSMina Almasry 		VM_BUG_ON(t - f <= 1);
7355e911373SMike Kravetz 
7360db9d74eSMina Almasry 		if (allocate_file_region_entries(
7370db9d74eSMina Almasry 			    resv, actual_regions_needed - in_regions_needed)) {
7380db9d74eSMina Almasry 			return -ENOMEM;
7395e911373SMike Kravetz 		}
7405e911373SMike Kravetz 
7410db9d74eSMina Almasry 		goto retry;
7420db9d74eSMina Almasry 	}
743cf3ad20bSMike Kravetz 
744972a3da3SWei Yang 	add = add_reservation_in_range(resv, f, t, h_cg, h, NULL);
7450db9d74eSMina Almasry 
7460db9d74eSMina Almasry 	resv->adds_in_progress -= in_regions_needed;
7470db9d74eSMina Almasry 
7487b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
749cf3ad20bSMike Kravetz 	return add;
75096822904SAndy Whitcroft }
75196822904SAndy Whitcroft 
7521dd308a7SMike Kravetz /*
7531dd308a7SMike Kravetz  * Examine the existing reserve map and determine how many
7541dd308a7SMike Kravetz  * huge pages in the specified range [f, t) are NOT currently
7551dd308a7SMike Kravetz  * represented.  This routine is called before a subsequent
7561dd308a7SMike Kravetz  * call to region_add that will actually modify the reserve
7571dd308a7SMike Kravetz  * map to add the specified range [f, t).  region_chg does
7581dd308a7SMike Kravetz  * not change the number of huge pages represented by the
7590db9d74eSMina Almasry  * map.  A number of new file_region structures is added to the cache as a
7600db9d74eSMina Almasry  * placeholder, for the subsequent region_add call to use. At least 1
7610db9d74eSMina Almasry  * file_region structure is added.
7620db9d74eSMina Almasry  *
7630db9d74eSMina Almasry  * out_regions_needed is the number of regions added to the
7640db9d74eSMina Almasry  * resv->adds_in_progress.  This value needs to be provided to a follow up call
7650db9d74eSMina Almasry  * to region_add or region_abort for proper accounting.
7665e911373SMike Kravetz  *
7675e911373SMike Kravetz  * Returns the number of huge pages that need to be added to the existing
7685e911373SMike Kravetz  * reservation map for the range [f, t).  This number is greater or equal to
7695e911373SMike Kravetz  * zero.  -ENOMEM is returned if a new file_region structure or cache entry
7705e911373SMike Kravetz  * is needed and can not be allocated.
7711dd308a7SMike Kravetz  */
region_chg(struct resv_map * resv,long f,long t,long * out_regions_needed)7720db9d74eSMina Almasry static long region_chg(struct resv_map *resv, long f, long t,
7730db9d74eSMina Almasry 		       long *out_regions_needed)
77496822904SAndy Whitcroft {
77596822904SAndy Whitcroft 	long chg = 0;
77696822904SAndy Whitcroft 
7777b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
7785e911373SMike Kravetz 
779972a3da3SWei Yang 	/* Count how many hugepages in this range are NOT represented. */
780075a61d0SMina Almasry 	chg = add_reservation_in_range(resv, f, t, NULL, NULL,
781972a3da3SWei Yang 				       out_regions_needed);
7825e911373SMike Kravetz 
7830db9d74eSMina Almasry 	if (*out_regions_needed == 0)
7840db9d74eSMina Almasry 		*out_regions_needed = 1;
7855e911373SMike Kravetz 
7860db9d74eSMina Almasry 	if (allocate_file_region_entries(resv, *out_regions_needed))
7875e911373SMike Kravetz 		return -ENOMEM;
7885e911373SMike Kravetz 
7890db9d74eSMina Almasry 	resv->adds_in_progress += *out_regions_needed;
79096822904SAndy Whitcroft 
7917b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
79296822904SAndy Whitcroft 	return chg;
79396822904SAndy Whitcroft }
79496822904SAndy Whitcroft 
7951dd308a7SMike Kravetz /*
7965e911373SMike Kravetz  * Abort the in progress add operation.  The adds_in_progress field
7975e911373SMike Kravetz  * of the resv_map keeps track of the operations in progress between
7985e911373SMike Kravetz  * calls to region_chg and region_add.  Operations are sometimes
7995e911373SMike Kravetz  * aborted after the call to region_chg.  In such cases, region_abort
8000db9d74eSMina Almasry  * is called to decrement the adds_in_progress counter. regions_needed
8010db9d74eSMina Almasry  * is the value returned by the region_chg call, it is used to decrement
8020db9d74eSMina Almasry  * the adds_in_progress counter.
8035e911373SMike Kravetz  *
8045e911373SMike Kravetz  * NOTE: The range arguments [f, t) are not needed or used in this
8055e911373SMike Kravetz  * routine.  They are kept to make reading the calling code easier as
8065e911373SMike Kravetz  * arguments will match the associated region_chg call.
8075e911373SMike Kravetz  */
region_abort(struct resv_map * resv,long f,long t,long regions_needed)8080db9d74eSMina Almasry static void region_abort(struct resv_map *resv, long f, long t,
8090db9d74eSMina Almasry 			 long regions_needed)
8105e911373SMike Kravetz {
8115e911373SMike Kravetz 	spin_lock(&resv->lock);
8125e911373SMike Kravetz 	VM_BUG_ON(!resv->region_cache_count);
8130db9d74eSMina Almasry 	resv->adds_in_progress -= regions_needed;
8145e911373SMike Kravetz 	spin_unlock(&resv->lock);
8155e911373SMike Kravetz }
8165e911373SMike Kravetz 
8175e911373SMike Kravetz /*
818feba16e2SMike Kravetz  * Delete the specified range [f, t) from the reserve map.  If the
819feba16e2SMike Kravetz  * t parameter is LONG_MAX, this indicates that ALL regions after f
820feba16e2SMike Kravetz  * should be deleted.  Locate the regions which intersect [f, t)
821feba16e2SMike Kravetz  * and either trim, delete or split the existing regions.
822feba16e2SMike Kravetz  *
823feba16e2SMike Kravetz  * Returns the number of huge pages deleted from the reserve map.
824feba16e2SMike Kravetz  * In the normal case, the return value is zero or more.  In the
825feba16e2SMike Kravetz  * case where a region must be split, a new region descriptor must
826feba16e2SMike Kravetz  * be allocated.  If the allocation fails, -ENOMEM will be returned.
827feba16e2SMike Kravetz  * NOTE: If the parameter t == LONG_MAX, then we will never split
828feba16e2SMike Kravetz  * a region and possibly return -ENOMEM.  Callers specifying
829feba16e2SMike Kravetz  * t == LONG_MAX do not need to check for -ENOMEM error.
8301dd308a7SMike Kravetz  */
region_del(struct resv_map * resv,long f,long t)831feba16e2SMike Kravetz static long region_del(struct resv_map *resv, long f, long t)
83296822904SAndy Whitcroft {
8331406ec9bSJoonsoo Kim 	struct list_head *head = &resv->regions;
83496822904SAndy Whitcroft 	struct file_region *rg, *trg;
835feba16e2SMike Kravetz 	struct file_region *nrg = NULL;
836feba16e2SMike Kravetz 	long del = 0;
83796822904SAndy Whitcroft 
838feba16e2SMike Kravetz retry:
8397b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
840feba16e2SMike Kravetz 	list_for_each_entry_safe(rg, trg, head, link) {
841dbe409e4SMike Kravetz 		/*
842dbe409e4SMike Kravetz 		 * Skip regions before the range to be deleted.  file_region
843dbe409e4SMike Kravetz 		 * ranges are normally of the form [from, to).  However, there
844dbe409e4SMike Kravetz 		 * may be a "placeholder" entry in the map which is of the form
845dbe409e4SMike Kravetz 		 * (from, to) with from == to.  Check for placeholder entries
846dbe409e4SMike Kravetz 		 * at the beginning of the range to be deleted.
847dbe409e4SMike Kravetz 		 */
848dbe409e4SMike Kravetz 		if (rg->to <= f && (rg->to != rg->from || rg->to != f))
849feba16e2SMike Kravetz 			continue;
850dbe409e4SMike Kravetz 
851feba16e2SMike Kravetz 		if (rg->from >= t)
85296822904SAndy Whitcroft 			break;
85396822904SAndy Whitcroft 
854feba16e2SMike Kravetz 		if (f > rg->from && t < rg->to) { /* Must split region */
855feba16e2SMike Kravetz 			/*
856feba16e2SMike Kravetz 			 * Check for an entry in the cache before dropping
857feba16e2SMike Kravetz 			 * lock and attempting allocation.
858feba16e2SMike Kravetz 			 */
859feba16e2SMike Kravetz 			if (!nrg &&
860feba16e2SMike Kravetz 			    resv->region_cache_count > resv->adds_in_progress) {
861feba16e2SMike Kravetz 				nrg = list_first_entry(&resv->region_cache,
862feba16e2SMike Kravetz 							struct file_region,
863feba16e2SMike Kravetz 							link);
864feba16e2SMike Kravetz 				list_del(&nrg->link);
865feba16e2SMike Kravetz 				resv->region_cache_count--;
86696822904SAndy Whitcroft 			}
86796822904SAndy Whitcroft 
868feba16e2SMike Kravetz 			if (!nrg) {
869feba16e2SMike Kravetz 				spin_unlock(&resv->lock);
870feba16e2SMike Kravetz 				nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
871feba16e2SMike Kravetz 				if (!nrg)
872feba16e2SMike Kravetz 					return -ENOMEM;
873feba16e2SMike Kravetz 				goto retry;
874feba16e2SMike Kravetz 			}
875feba16e2SMike Kravetz 
876feba16e2SMike Kravetz 			del += t - f;
87779aa925bSMike Kravetz 			hugetlb_cgroup_uncharge_file_region(
878d85aecf2SMiaohe Lin 				resv, rg, t - f, false);
879feba16e2SMike Kravetz 
880feba16e2SMike Kravetz 			/* New entry for end of split region */
881feba16e2SMike Kravetz 			nrg->from = t;
882feba16e2SMike Kravetz 			nrg->to = rg->to;
883075a61d0SMina Almasry 
884075a61d0SMina Almasry 			copy_hugetlb_cgroup_uncharge_info(nrg, rg);
885075a61d0SMina Almasry 
886feba16e2SMike Kravetz 			INIT_LIST_HEAD(&nrg->link);
887feba16e2SMike Kravetz 
888feba16e2SMike Kravetz 			/* Original entry is trimmed */
889feba16e2SMike Kravetz 			rg->to = f;
890feba16e2SMike Kravetz 
891feba16e2SMike Kravetz 			list_add(&nrg->link, &rg->link);
892feba16e2SMike Kravetz 			nrg = NULL;
89396822904SAndy Whitcroft 			break;
894feba16e2SMike Kravetz 		}
895feba16e2SMike Kravetz 
896feba16e2SMike Kravetz 		if (f <= rg->from && t >= rg->to) { /* Remove entire region */
897feba16e2SMike Kravetz 			del += rg->to - rg->from;
898075a61d0SMina Almasry 			hugetlb_cgroup_uncharge_file_region(resv, rg,
899d85aecf2SMiaohe Lin 							    rg->to - rg->from, true);
90096822904SAndy Whitcroft 			list_del(&rg->link);
90196822904SAndy Whitcroft 			kfree(rg);
902feba16e2SMike Kravetz 			continue;
90396822904SAndy Whitcroft 		}
9047b24d861SDavidlohr Bueso 
905feba16e2SMike Kravetz 		if (f <= rg->from) {	/* Trim beginning of region */
906075a61d0SMina Almasry 			hugetlb_cgroup_uncharge_file_region(resv, rg,
907d85aecf2SMiaohe Lin 							    t - rg->from, false);
908075a61d0SMina Almasry 
90979aa925bSMike Kravetz 			del += t - rg->from;
91079aa925bSMike Kravetz 			rg->from = t;
91179aa925bSMike Kravetz 		} else {		/* Trim end of region */
912075a61d0SMina Almasry 			hugetlb_cgroup_uncharge_file_region(resv, rg,
913d85aecf2SMiaohe Lin 							    rg->to - f, false);
91479aa925bSMike Kravetz 
91579aa925bSMike Kravetz 			del += rg->to - f;
91679aa925bSMike Kravetz 			rg->to = f;
917feba16e2SMike Kravetz 		}
918feba16e2SMike Kravetz 	}
919feba16e2SMike Kravetz 
9207b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
921feba16e2SMike Kravetz 	kfree(nrg);
922feba16e2SMike Kravetz 	return del;
92396822904SAndy Whitcroft }
92496822904SAndy Whitcroft 
9251dd308a7SMike Kravetz /*
926b5cec28dSMike Kravetz  * A rare out of memory error was encountered which prevented removal of
927b5cec28dSMike Kravetz  * the reserve map region for a page.  The huge page itself was free'ed
928b5cec28dSMike Kravetz  * and removed from the page cache.  This routine will adjust the subpool
929b5cec28dSMike Kravetz  * usage count, and the global reserve count if needed.  By incrementing
930b5cec28dSMike Kravetz  * these counts, the reserve map entry which could not be deleted will
931b5cec28dSMike Kravetz  * appear as a "reserved" entry instead of simply dangling with incorrect
932b5cec28dSMike Kravetz  * counts.
933b5cec28dSMike Kravetz  */
hugetlb_fix_reserve_counts(struct inode * inode)93472e2936cSzhong jiang void hugetlb_fix_reserve_counts(struct inode *inode)
935b5cec28dSMike Kravetz {
936b5cec28dSMike Kravetz 	struct hugepage_subpool *spool = subpool_inode(inode);
937b5cec28dSMike Kravetz 	long rsv_adjust;
938da56388cSMiaohe Lin 	bool reserved = false;
939b5cec28dSMike Kravetz 
940b5cec28dSMike Kravetz 	rsv_adjust = hugepage_subpool_get_pages(spool, 1);
941da56388cSMiaohe Lin 	if (rsv_adjust > 0) {
942b5cec28dSMike Kravetz 		struct hstate *h = hstate_inode(inode);
943b5cec28dSMike Kravetz 
944da56388cSMiaohe Lin 		if (!hugetlb_acct_memory(h, 1))
945da56388cSMiaohe Lin 			reserved = true;
946da56388cSMiaohe Lin 	} else if (!rsv_adjust) {
947da56388cSMiaohe Lin 		reserved = true;
948b5cec28dSMike Kravetz 	}
949da56388cSMiaohe Lin 
950da56388cSMiaohe Lin 	if (!reserved)
951da56388cSMiaohe Lin 		pr_warn("hugetlb: Huge Page Reserved count may go negative.\n");
952b5cec28dSMike Kravetz }
953b5cec28dSMike Kravetz 
954b5cec28dSMike Kravetz /*
9551dd308a7SMike Kravetz  * Count and return the number of huge pages in the reserve map
9561dd308a7SMike Kravetz  * that intersect with the range [f, t).
9571dd308a7SMike Kravetz  */
region_count(struct resv_map * resv,long f,long t)9581406ec9bSJoonsoo Kim static long region_count(struct resv_map *resv, long f, long t)
95984afd99bSAndy Whitcroft {
9601406ec9bSJoonsoo Kim 	struct list_head *head = &resv->regions;
96184afd99bSAndy Whitcroft 	struct file_region *rg;
96284afd99bSAndy Whitcroft 	long chg = 0;
96384afd99bSAndy Whitcroft 
9647b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
96584afd99bSAndy Whitcroft 	/* Locate each segment we overlap with, and count that overlap. */
96684afd99bSAndy Whitcroft 	list_for_each_entry(rg, head, link) {
967f2135a4aSWang Sheng-Hui 		long seg_from;
968f2135a4aSWang Sheng-Hui 		long seg_to;
96984afd99bSAndy Whitcroft 
97084afd99bSAndy Whitcroft 		if (rg->to <= f)
97184afd99bSAndy Whitcroft 			continue;
97284afd99bSAndy Whitcroft 		if (rg->from >= t)
97384afd99bSAndy Whitcroft 			break;
97484afd99bSAndy Whitcroft 
97584afd99bSAndy Whitcroft 		seg_from = max(rg->from, f);
97684afd99bSAndy Whitcroft 		seg_to = min(rg->to, t);
97784afd99bSAndy Whitcroft 
97884afd99bSAndy Whitcroft 		chg += seg_to - seg_from;
97984afd99bSAndy Whitcroft 	}
9807b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
98184afd99bSAndy Whitcroft 
98284afd99bSAndy Whitcroft 	return chg;
98384afd99bSAndy Whitcroft }
98484afd99bSAndy Whitcroft 
98596822904SAndy Whitcroft /*
986e7c4b0bfSAndy Whitcroft  * Convert the address within this vma to the page offset within
987e7c4b0bfSAndy Whitcroft  * the mapping, in pagecache page units; huge pages here.
988e7c4b0bfSAndy Whitcroft  */
vma_hugecache_offset(struct hstate * h,struct vm_area_struct * vma,unsigned long address)989a5516438SAndi Kleen static pgoff_t vma_hugecache_offset(struct hstate *h,
990a5516438SAndi Kleen 			struct vm_area_struct *vma, unsigned long address)
991e7c4b0bfSAndy Whitcroft {
992a5516438SAndi Kleen 	return ((address - vma->vm_start) >> huge_page_shift(h)) +
993a5516438SAndi Kleen 			(vma->vm_pgoff >> huge_page_order(h));
994e7c4b0bfSAndy Whitcroft }
995e7c4b0bfSAndy Whitcroft 
linear_hugepage_index(struct vm_area_struct * vma,unsigned long address)9960fe6e20bSNaoya Horiguchi pgoff_t linear_hugepage_index(struct vm_area_struct *vma,
9970fe6e20bSNaoya Horiguchi 				     unsigned long address)
9980fe6e20bSNaoya Horiguchi {
9990fe6e20bSNaoya Horiguchi 	return vma_hugecache_offset(hstate_vma(vma), vma, address);
10000fe6e20bSNaoya Horiguchi }
1001dee41079SDan Williams EXPORT_SYMBOL_GPL(linear_hugepage_index);
10020fe6e20bSNaoya Horiguchi 
10038cfd014eSMatthew Wilcox (Oracle) /**
10048cfd014eSMatthew Wilcox (Oracle)  * vma_kernel_pagesize - Page size granularity for this VMA.
10058cfd014eSMatthew Wilcox (Oracle)  * @vma: The user mapping.
10068cfd014eSMatthew Wilcox (Oracle)  *
10078cfd014eSMatthew Wilcox (Oracle)  * Folios in this VMA will be aligned to, and at least the size of the
10088cfd014eSMatthew Wilcox (Oracle)  * number of bytes returned by this function.
10098cfd014eSMatthew Wilcox (Oracle)  *
10108cfd014eSMatthew Wilcox (Oracle)  * Return: The default size of the folios allocated when backing a VMA.
101108fba699SMel Gorman  */
vma_kernel_pagesize(struct vm_area_struct * vma)101208fba699SMel Gorman unsigned long vma_kernel_pagesize(struct vm_area_struct *vma)
101308fba699SMel Gorman {
101405ea8860SDan Williams 	if (vma->vm_ops && vma->vm_ops->pagesize)
101505ea8860SDan Williams 		return vma->vm_ops->pagesize(vma);
101608fba699SMel Gorman 	return PAGE_SIZE;
101708fba699SMel Gorman }
1018f340ca0fSJoerg Roedel EXPORT_SYMBOL_GPL(vma_kernel_pagesize);
101908fba699SMel Gorman 
102008fba699SMel Gorman /*
10213340289dSMel Gorman  * Return the page size being used by the MMU to back a VMA. In the majority
10223340289dSMel Gorman  * of cases, the page size used by the kernel matches the MMU size. On
102309135cc5SDan Williams  * architectures where it differs, an architecture-specific 'strong'
102409135cc5SDan Williams  * version of this symbol is required.
10253340289dSMel Gorman  */
vma_mmu_pagesize(struct vm_area_struct * vma)102609135cc5SDan Williams __weak unsigned long vma_mmu_pagesize(struct vm_area_struct *vma)
10273340289dSMel Gorman {
10283340289dSMel Gorman 	return vma_kernel_pagesize(vma);
10293340289dSMel Gorman }
10303340289dSMel Gorman 
10313340289dSMel Gorman /*
103284afd99bSAndy Whitcroft  * Flags for MAP_PRIVATE reservations.  These are stored in the bottom
103384afd99bSAndy Whitcroft  * bits of the reservation map pointer, which are always clear due to
103484afd99bSAndy Whitcroft  * alignment.
103584afd99bSAndy Whitcroft  */
103684afd99bSAndy Whitcroft #define HPAGE_RESV_OWNER    (1UL << 0)
103784afd99bSAndy Whitcroft #define HPAGE_RESV_UNMAPPED (1UL << 1)
103804f2cbe3SMel Gorman #define HPAGE_RESV_MASK (HPAGE_RESV_OWNER | HPAGE_RESV_UNMAPPED)
103984afd99bSAndy Whitcroft 
1040a1e78772SMel Gorman /*
1041a1e78772SMel Gorman  * These helpers are used to track how many pages are reserved for
1042a1e78772SMel Gorman  * faults in a MAP_PRIVATE mapping. Only the process that called mmap()
1043a1e78772SMel Gorman  * is guaranteed to have their future faults succeed.
1044a1e78772SMel Gorman  *
10458d9bfb26SMike Kravetz  * With the exception of hugetlb_dup_vma_private() which is called at fork(),
1046a1e78772SMel Gorman  * the reserve counters are updated with the hugetlb_lock held. It is safe
1047a1e78772SMel Gorman  * to reset the VMA at fork() time as it is not in use yet and there is no
1048a1e78772SMel Gorman  * chance of the global counters getting corrupted as a result of the values.
104984afd99bSAndy Whitcroft  *
105084afd99bSAndy Whitcroft  * The private mapping reservation is represented in a subtly different
105184afd99bSAndy Whitcroft  * manner to a shared mapping.  A shared mapping has a region map associated
105284afd99bSAndy Whitcroft  * with the underlying file, this region map represents the backing file
105384afd99bSAndy Whitcroft  * pages which have ever had a reservation assigned which this persists even
105484afd99bSAndy Whitcroft  * after the page is instantiated.  A private mapping has a region map
105584afd99bSAndy Whitcroft  * associated with the original mmap which is attached to all VMAs which
105684afd99bSAndy Whitcroft  * reference it, this region map represents those offsets which have consumed
105784afd99bSAndy Whitcroft  * reservation ie. where pages have been instantiated.
1058a1e78772SMel Gorman  */
get_vma_private_data(struct vm_area_struct * vma)1059e7c4b0bfSAndy Whitcroft static unsigned long get_vma_private_data(struct vm_area_struct *vma)
1060e7c4b0bfSAndy Whitcroft {
1061e7c4b0bfSAndy Whitcroft 	return (unsigned long)vma->vm_private_data;
1062e7c4b0bfSAndy Whitcroft }
1063e7c4b0bfSAndy Whitcroft 
set_vma_private_data(struct vm_area_struct * vma,unsigned long value)1064e7c4b0bfSAndy Whitcroft static void set_vma_private_data(struct vm_area_struct *vma,
1065e7c4b0bfSAndy Whitcroft 							unsigned long value)
1066e7c4b0bfSAndy Whitcroft {
1067e7c4b0bfSAndy Whitcroft 	vma->vm_private_data = (void *)value;
1068e7c4b0bfSAndy Whitcroft }
1069e7c4b0bfSAndy Whitcroft 
1070e9fe92aeSMina Almasry static void
resv_map_set_hugetlb_cgroup_uncharge_info(struct resv_map * resv_map,struct hugetlb_cgroup * h_cg,struct hstate * h)1071e9fe92aeSMina Almasry resv_map_set_hugetlb_cgroup_uncharge_info(struct resv_map *resv_map,
1072e9fe92aeSMina Almasry 					  struct hugetlb_cgroup *h_cg,
1073e9fe92aeSMina Almasry 					  struct hstate *h)
1074e9fe92aeSMina Almasry {
1075e9fe92aeSMina Almasry #ifdef CONFIG_CGROUP_HUGETLB
1076e9fe92aeSMina Almasry 	if (!h_cg || !h) {
1077e9fe92aeSMina Almasry 		resv_map->reservation_counter = NULL;
1078e9fe92aeSMina Almasry 		resv_map->pages_per_hpage = 0;
1079e9fe92aeSMina Almasry 		resv_map->css = NULL;
1080e9fe92aeSMina Almasry 	} else {
1081e9fe92aeSMina Almasry 		resv_map->reservation_counter =
1082e9fe92aeSMina Almasry 			&h_cg->rsvd_hugepage[hstate_index(h)];
1083e9fe92aeSMina Almasry 		resv_map->pages_per_hpage = pages_per_huge_page(h);
1084e9fe92aeSMina Almasry 		resv_map->css = &h_cg->css;
1085e9fe92aeSMina Almasry 	}
1086e9fe92aeSMina Almasry #endif
1087e9fe92aeSMina Almasry }
1088e9fe92aeSMina Almasry 
resv_map_alloc(void)10899119a41eSJoonsoo Kim struct resv_map *resv_map_alloc(void)
109084afd99bSAndy Whitcroft {
109184afd99bSAndy Whitcroft 	struct resv_map *resv_map = kmalloc(sizeof(*resv_map), GFP_KERNEL);
10925e911373SMike Kravetz 	struct file_region *rg = kmalloc(sizeof(*rg), GFP_KERNEL);
10935e911373SMike Kravetz 
10945e911373SMike Kravetz 	if (!resv_map || !rg) {
10955e911373SMike Kravetz 		kfree(resv_map);
10965e911373SMike Kravetz 		kfree(rg);
109784afd99bSAndy Whitcroft 		return NULL;
10985e911373SMike Kravetz 	}
109984afd99bSAndy Whitcroft 
110084afd99bSAndy Whitcroft 	kref_init(&resv_map->refs);
11017b24d861SDavidlohr Bueso 	spin_lock_init(&resv_map->lock);
110284afd99bSAndy Whitcroft 	INIT_LIST_HEAD(&resv_map->regions);
1103bf491692SRik van Riel 	init_rwsem(&resv_map->rw_sema);
110484afd99bSAndy Whitcroft 
11055e911373SMike Kravetz 	resv_map->adds_in_progress = 0;
1106e9fe92aeSMina Almasry 	/*
1107e9fe92aeSMina Almasry 	 * Initialize these to 0. On shared mappings, 0's here indicate these
1108e9fe92aeSMina Almasry 	 * fields don't do cgroup accounting. On private mappings, these will be
1109e9fe92aeSMina Almasry 	 * re-initialized to the proper values, to indicate that hugetlb cgroup
1110e9fe92aeSMina Almasry 	 * reservations are to be un-charged from here.
1111e9fe92aeSMina Almasry 	 */
1112e9fe92aeSMina Almasry 	resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, NULL, NULL);
11135e911373SMike Kravetz 
11145e911373SMike Kravetz 	INIT_LIST_HEAD(&resv_map->region_cache);
11155e911373SMike Kravetz 	list_add(&rg->link, &resv_map->region_cache);
11165e911373SMike Kravetz 	resv_map->region_cache_count = 1;
11175e911373SMike Kravetz 
111884afd99bSAndy Whitcroft 	return resv_map;
111984afd99bSAndy Whitcroft }
112084afd99bSAndy Whitcroft 
resv_map_release(struct kref * ref)11219119a41eSJoonsoo Kim void resv_map_release(struct kref *ref)
112284afd99bSAndy Whitcroft {
112384afd99bSAndy Whitcroft 	struct resv_map *resv_map = container_of(ref, struct resv_map, refs);
11245e911373SMike Kravetz 	struct list_head *head = &resv_map->region_cache;
11255e911373SMike Kravetz 	struct file_region *rg, *trg;
112684afd99bSAndy Whitcroft 
112784afd99bSAndy Whitcroft 	/* Clear out any active regions before we release the map. */
1128feba16e2SMike Kravetz 	region_del(resv_map, 0, LONG_MAX);
11295e911373SMike Kravetz 
11305e911373SMike Kravetz 	/* ... and any entries left in the cache */
11315e911373SMike Kravetz 	list_for_each_entry_safe(rg, trg, head, link) {
11325e911373SMike Kravetz 		list_del(&rg->link);
11335e911373SMike Kravetz 		kfree(rg);
11345e911373SMike Kravetz 	}
11355e911373SMike Kravetz 
11365e911373SMike Kravetz 	VM_BUG_ON(resv_map->adds_in_progress);
11375e911373SMike Kravetz 
113884afd99bSAndy Whitcroft 	kfree(resv_map);
113984afd99bSAndy Whitcroft }
114084afd99bSAndy Whitcroft 
inode_resv_map(struct inode * inode)11414e35f483SJoonsoo Kim static inline struct resv_map *inode_resv_map(struct inode *inode)
11424e35f483SJoonsoo Kim {
1143f27a5136SMike Kravetz 	/*
1144f27a5136SMike Kravetz 	 * At inode evict time, i_mapping may not point to the original
1145f27a5136SMike Kravetz 	 * address space within the inode.  This original address space
1146f27a5136SMike Kravetz 	 * contains the pointer to the resv_map.  So, always use the
1147f27a5136SMike Kravetz 	 * address space embedded within the inode.
1148f27a5136SMike Kravetz 	 * The VERY common case is inode->mapping == &inode->i_data but,
1149f27a5136SMike Kravetz 	 * this may not be true for device special inodes.
1150f27a5136SMike Kravetz 	 */
1151f27a5136SMike Kravetz 	return (struct resv_map *)(&inode->i_data)->private_data;
11524e35f483SJoonsoo Kim }
11534e35f483SJoonsoo Kim 
vma_resv_map(struct vm_area_struct * vma)115484afd99bSAndy Whitcroft static struct resv_map *vma_resv_map(struct vm_area_struct *vma)
1155a1e78772SMel Gorman {
115681d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
11574e35f483SJoonsoo Kim 	if (vma->vm_flags & VM_MAYSHARE) {
11584e35f483SJoonsoo Kim 		struct address_space *mapping = vma->vm_file->f_mapping;
11594e35f483SJoonsoo Kim 		struct inode *inode = mapping->host;
11604e35f483SJoonsoo Kim 
11614e35f483SJoonsoo Kim 		return inode_resv_map(inode);
11624e35f483SJoonsoo Kim 
11634e35f483SJoonsoo Kim 	} else {
116484afd99bSAndy Whitcroft 		return (struct resv_map *)(get_vma_private_data(vma) &
116584afd99bSAndy Whitcroft 							~HPAGE_RESV_MASK);
11664e35f483SJoonsoo Kim 	}
1167a1e78772SMel Gorman }
1168a1e78772SMel Gorman 
set_vma_resv_map(struct vm_area_struct * vma,struct resv_map * map)116984afd99bSAndy Whitcroft static void set_vma_resv_map(struct vm_area_struct *vma, struct resv_map *map)
1170a1e78772SMel Gorman {
117181d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
117281d1b09cSSasha Levin 	VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
1173a1e78772SMel Gorman 
117492fe9dcbSRik van Riel 	set_vma_private_data(vma, (unsigned long)map);
117504f2cbe3SMel Gorman }
117604f2cbe3SMel Gorman 
set_vma_resv_flags(struct vm_area_struct * vma,unsigned long flags)117704f2cbe3SMel Gorman static void set_vma_resv_flags(struct vm_area_struct *vma, unsigned long flags)
117804f2cbe3SMel Gorman {
117981d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
118081d1b09cSSasha Levin 	VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
1181e7c4b0bfSAndy Whitcroft 
1182e7c4b0bfSAndy Whitcroft 	set_vma_private_data(vma, get_vma_private_data(vma) | flags);
118304f2cbe3SMel Gorman }
118404f2cbe3SMel Gorman 
is_vma_resv_set(struct vm_area_struct * vma,unsigned long flag)118504f2cbe3SMel Gorman static int is_vma_resv_set(struct vm_area_struct *vma, unsigned long flag)
118604f2cbe3SMel Gorman {
118781d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
1188e7c4b0bfSAndy Whitcroft 
1189e7c4b0bfSAndy Whitcroft 	return (get_vma_private_data(vma) & flag) != 0;
1190a1e78772SMel Gorman }
1191a1e78772SMel Gorman 
__vma_private_lock(struct vm_area_struct * vma)1192512b420aSMike Kravetz bool __vma_private_lock(struct vm_area_struct *vma)
1193512b420aSMike Kravetz {
1194512b420aSMike Kravetz 	return !(vma->vm_flags & VM_MAYSHARE) &&
1195512b420aSMike Kravetz 		get_vma_private_data(vma) & ~HPAGE_RESV_MASK &&
1196512b420aSMike Kravetz 		is_vma_resv_set(vma, HPAGE_RESV_OWNER);
1197512b420aSMike Kravetz }
1198512b420aSMike Kravetz 
hugetlb_dup_vma_private(struct vm_area_struct * vma)11998d9bfb26SMike Kravetz void hugetlb_dup_vma_private(struct vm_area_struct *vma)
1200a1e78772SMel Gorman {
120181d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
12028d9bfb26SMike Kravetz 	/*
12038d9bfb26SMike Kravetz 	 * Clear vm_private_data
1204612b8a31SMike Kravetz 	 * - For shared mappings this is a per-vma semaphore that may be
1205612b8a31SMike Kravetz 	 *   allocated in a subsequent call to hugetlb_vm_op_open.
1206612b8a31SMike Kravetz 	 *   Before clearing, make sure pointer is not associated with vma
1207612b8a31SMike Kravetz 	 *   as this will leak the structure.  This is the case when called
1208612b8a31SMike Kravetz 	 *   via clear_vma_resv_huge_pages() and hugetlb_vm_op_open has already
1209612b8a31SMike Kravetz 	 *   been called to allocate a new structure.
12108d9bfb26SMike Kravetz 	 * - For MAP_PRIVATE mappings, this is the reserve map which does
12118d9bfb26SMike Kravetz 	 *   not apply to children.  Faults generated by the children are
12128d9bfb26SMike Kravetz 	 *   not guaranteed to succeed, even if read-only.
12138d9bfb26SMike Kravetz 	 */
1214612b8a31SMike Kravetz 	if (vma->vm_flags & VM_MAYSHARE) {
1215612b8a31SMike Kravetz 		struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
1216612b8a31SMike Kravetz 
1217612b8a31SMike Kravetz 		if (vma_lock && vma_lock->vma != vma)
1218612b8a31SMike Kravetz 			vma->vm_private_data = NULL;
1219612b8a31SMike Kravetz 	} else
1220612b8a31SMike Kravetz 		vma->vm_private_data = NULL;
1221a1e78772SMel Gorman }
1222a1e78772SMel Gorman 
1223550a7d60SMina Almasry /*
1224550a7d60SMina Almasry  * Reset and decrement one ref on hugepage private reservation.
12258651a137SLorenzo Stoakes  * Called with mm->mmap_lock writer semaphore held.
1226550a7d60SMina Almasry  * This function should be only used by move_vma() and operate on
1227550a7d60SMina Almasry  * same sized vma. It should never come here with last ref on the
1228550a7d60SMina Almasry  * reservation.
1229550a7d60SMina Almasry  */
clear_vma_resv_huge_pages(struct vm_area_struct * vma)1230550a7d60SMina Almasry void clear_vma_resv_huge_pages(struct vm_area_struct *vma)
1231550a7d60SMina Almasry {
1232550a7d60SMina Almasry 	/*
1233550a7d60SMina Almasry 	 * Clear the old hugetlb private page reservation.
1234550a7d60SMina Almasry 	 * It has already been transferred to new_vma.
1235550a7d60SMina Almasry 	 *
1236550a7d60SMina Almasry 	 * During a mremap() operation of a hugetlb vma we call move_vma()
1237550a7d60SMina Almasry 	 * which copies vma into new_vma and unmaps vma. After the copy
1238550a7d60SMina Almasry 	 * operation both new_vma and vma share a reference to the resv_map
1239550a7d60SMina Almasry 	 * struct, and at that point vma is about to be unmapped. We don't
1240550a7d60SMina Almasry 	 * want to return the reservation to the pool at unmap of vma because
1241550a7d60SMina Almasry 	 * the reservation still lives on in new_vma, so simply decrement the
1242550a7d60SMina Almasry 	 * ref here and remove the resv_map reference from this vma.
1243550a7d60SMina Almasry 	 */
1244550a7d60SMina Almasry 	struct resv_map *reservations = vma_resv_map(vma);
1245550a7d60SMina Almasry 
1246afe041c2SBui Quang Minh 	if (reservations && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
1247afe041c2SBui Quang Minh 		resv_map_put_hugetlb_cgroup_uncharge_info(reservations);
1248550a7d60SMina Almasry 		kref_put(&reservations->refs, resv_map_release);
1249afe041c2SBui Quang Minh 	}
1250550a7d60SMina Almasry 
12518d9bfb26SMike Kravetz 	hugetlb_dup_vma_private(vma);
1252550a7d60SMina Almasry }
1253550a7d60SMina Almasry 
1254a1e78772SMel Gorman /* Returns true if the VMA has associated reserve pages */
vma_has_reserves(struct vm_area_struct * vma,long chg)1255559ec2f8SNicholas Krause static bool vma_has_reserves(struct vm_area_struct *vma, long chg)
1256a1e78772SMel Gorman {
1257af0ed73eSJoonsoo Kim 	if (vma->vm_flags & VM_NORESERVE) {
1258af0ed73eSJoonsoo Kim 		/*
1259af0ed73eSJoonsoo Kim 		 * This address is already reserved by other process(chg == 0),
1260af0ed73eSJoonsoo Kim 		 * so, we should decrement reserved count. Without decrementing,
1261af0ed73eSJoonsoo Kim 		 * reserve count remains after releasing inode, because this
1262af0ed73eSJoonsoo Kim 		 * allocated page will go into page cache and is regarded as
1263af0ed73eSJoonsoo Kim 		 * coming from reserved pool in releasing step.  Currently, we
1264af0ed73eSJoonsoo Kim 		 * don't have any other solution to deal with this situation
1265af0ed73eSJoonsoo Kim 		 * properly, so add work-around here.
1266af0ed73eSJoonsoo Kim 		 */
1267af0ed73eSJoonsoo Kim 		if (vma->vm_flags & VM_MAYSHARE && chg == 0)
1268559ec2f8SNicholas Krause 			return true;
1269af0ed73eSJoonsoo Kim 		else
1270559ec2f8SNicholas Krause 			return false;
1271af0ed73eSJoonsoo Kim 	}
1272a63884e9SJoonsoo Kim 
1273a63884e9SJoonsoo Kim 	/* Shared mappings always use reserves */
12741fb1b0e9SMike Kravetz 	if (vma->vm_flags & VM_MAYSHARE) {
12751fb1b0e9SMike Kravetz 		/*
12761fb1b0e9SMike Kravetz 		 * We know VM_NORESERVE is not set.  Therefore, there SHOULD
12771fb1b0e9SMike Kravetz 		 * be a region map for all pages.  The only situation where
12781fb1b0e9SMike Kravetz 		 * there is no region map is if a hole was punched via
12797c8de358SEthon Paul 		 * fallocate.  In this case, there really are no reserves to
12801fb1b0e9SMike Kravetz 		 * use.  This situation is indicated if chg != 0.
12811fb1b0e9SMike Kravetz 		 */
12821fb1b0e9SMike Kravetz 		if (chg)
12831fb1b0e9SMike Kravetz 			return false;
12841fb1b0e9SMike Kravetz 		else
1285559ec2f8SNicholas Krause 			return true;
12861fb1b0e9SMike Kravetz 	}
1287a63884e9SJoonsoo Kim 
1288a63884e9SJoonsoo Kim 	/*
1289a63884e9SJoonsoo Kim 	 * Only the process that called mmap() has reserves for
1290a63884e9SJoonsoo Kim 	 * private mappings.
1291a63884e9SJoonsoo Kim 	 */
129267961f9dSMike Kravetz 	if (is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
129367961f9dSMike Kravetz 		/*
129467961f9dSMike Kravetz 		 * Like the shared case above, a hole punch or truncate
129567961f9dSMike Kravetz 		 * could have been performed on the private mapping.
129667961f9dSMike Kravetz 		 * Examine the value of chg to determine if reserves
129767961f9dSMike Kravetz 		 * actually exist or were previously consumed.
129867961f9dSMike Kravetz 		 * Very Subtle - The value of chg comes from a previous
129967961f9dSMike Kravetz 		 * call to vma_needs_reserves().  The reserve map for
130067961f9dSMike Kravetz 		 * private mappings has different (opposite) semantics
130167961f9dSMike Kravetz 		 * than that of shared mappings.  vma_needs_reserves()
130267961f9dSMike Kravetz 		 * has already taken this difference in semantics into
130367961f9dSMike Kravetz 		 * account.  Therefore, the meaning of chg is the same
130467961f9dSMike Kravetz 		 * as in the shared case above.  Code could easily be
130567961f9dSMike Kravetz 		 * combined, but keeping it separate draws attention to
130667961f9dSMike Kravetz 		 * subtle differences.
130767961f9dSMike Kravetz 		 */
130867961f9dSMike Kravetz 		if (chg)
130967961f9dSMike Kravetz 			return false;
131067961f9dSMike Kravetz 		else
1311559ec2f8SNicholas Krause 			return true;
131267961f9dSMike Kravetz 	}
1313a63884e9SJoonsoo Kim 
1314559ec2f8SNicholas Krause 	return false;
1315a1e78772SMel Gorman }
1316a1e78772SMel Gorman 
enqueue_hugetlb_folio(struct hstate * h,struct folio * folio)1317240d67a8SSidhartha Kumar static void enqueue_hugetlb_folio(struct hstate *h, struct folio *folio)
13181da177e4SLinus Torvalds {
1319240d67a8SSidhartha Kumar 	int nid = folio_nid(folio);
13209487ca60SMike Kravetz 
13219487ca60SMike Kravetz 	lockdep_assert_held(&hugetlb_lock);
1322240d67a8SSidhartha Kumar 	VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
1323b65a4edaSMike Kravetz 
1324240d67a8SSidhartha Kumar 	list_move(&folio->lru, &h->hugepage_freelists[nid]);
1325a5516438SAndi Kleen 	h->free_huge_pages++;
1326a5516438SAndi Kleen 	h->free_huge_pages_node[nid]++;
1327240d67a8SSidhartha Kumar 	folio_set_hugetlb_freed(folio);
13281da177e4SLinus Torvalds }
13291da177e4SLinus Torvalds 
dequeue_hugetlb_folio_node_exact(struct hstate * h,int nid)1330a36f1e90SSidhartha Kumar static struct folio *dequeue_hugetlb_folio_node_exact(struct hstate *h,
1331a36f1e90SSidhartha Kumar 								int nid)
1332bf50bab2SNaoya Horiguchi {
1333a36f1e90SSidhartha Kumar 	struct folio *folio;
13341a08ae36SPavel Tatashin 	bool pin = !!(current->flags & PF_MEMALLOC_PIN);
1335bf50bab2SNaoya Horiguchi 
13369487ca60SMike Kravetz 	lockdep_assert_held(&hugetlb_lock);
1337a36f1e90SSidhartha Kumar 	list_for_each_entry(folio, &h->hugepage_freelists[nid], lru) {
1338a36f1e90SSidhartha Kumar 		if (pin && !folio_is_longterm_pinnable(folio))
1339bbe88753SJoonsoo Kim 			continue;
1340bbe88753SJoonsoo Kim 
1341a36f1e90SSidhartha Kumar 		if (folio_test_hwpoison(folio))
13426664bfc8SWei Yang 			continue;
1343bbe88753SJoonsoo Kim 
1344a36f1e90SSidhartha Kumar 		list_move(&folio->lru, &h->hugepage_activelist);
1345a36f1e90SSidhartha Kumar 		folio_ref_unfreeze(folio, 1);
1346a36f1e90SSidhartha Kumar 		folio_clear_hugetlb_freed(folio);
1347bf50bab2SNaoya Horiguchi 		h->free_huge_pages--;
1348bf50bab2SNaoya Horiguchi 		h->free_huge_pages_node[nid]--;
1349a36f1e90SSidhartha Kumar 		return folio;
1350bf50bab2SNaoya Horiguchi 	}
1351bf50bab2SNaoya Horiguchi 
13526664bfc8SWei Yang 	return NULL;
13536664bfc8SWei Yang }
13546664bfc8SWei Yang 
dequeue_hugetlb_folio_nodemask(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nmask)1355a36f1e90SSidhartha Kumar static struct folio *dequeue_hugetlb_folio_nodemask(struct hstate *h, gfp_t gfp_mask,
1356a36f1e90SSidhartha Kumar 							int nid, nodemask_t *nmask)
135794310cbcSAnshuman Khandual {
13583e59fcb0SMichal Hocko 	unsigned int cpuset_mems_cookie;
13593e59fcb0SMichal Hocko 	struct zonelist *zonelist;
13603e59fcb0SMichal Hocko 	struct zone *zone;
13613e59fcb0SMichal Hocko 	struct zoneref *z;
136298fa15f3SAnshuman Khandual 	int node = NUMA_NO_NODE;
13633e59fcb0SMichal Hocko 
13643e59fcb0SMichal Hocko 	zonelist = node_zonelist(nid, gfp_mask);
13653e59fcb0SMichal Hocko 
13663e59fcb0SMichal Hocko retry_cpuset:
13673e59fcb0SMichal Hocko 	cpuset_mems_cookie = read_mems_allowed_begin();
13683e59fcb0SMichal Hocko 	for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nmask) {
1369a36f1e90SSidhartha Kumar 		struct folio *folio;
137094310cbcSAnshuman Khandual 
13713e59fcb0SMichal Hocko 		if (!cpuset_zone_allowed(zone, gfp_mask))
13723e59fcb0SMichal Hocko 			continue;
13733e59fcb0SMichal Hocko 		/*
13743e59fcb0SMichal Hocko 		 * no need to ask again on the same node. Pool is node rather than
13753e59fcb0SMichal Hocko 		 * zone aware
13763e59fcb0SMichal Hocko 		 */
13773e59fcb0SMichal Hocko 		if (zone_to_nid(zone) == node)
13783e59fcb0SMichal Hocko 			continue;
13793e59fcb0SMichal Hocko 		node = zone_to_nid(zone);
138094310cbcSAnshuman Khandual 
1381a36f1e90SSidhartha Kumar 		folio = dequeue_hugetlb_folio_node_exact(h, node);
1382a36f1e90SSidhartha Kumar 		if (folio)
1383a36f1e90SSidhartha Kumar 			return folio;
138494310cbcSAnshuman Khandual 	}
13853e59fcb0SMichal Hocko 	if (unlikely(read_mems_allowed_retry(cpuset_mems_cookie)))
13863e59fcb0SMichal Hocko 		goto retry_cpuset;
13873e59fcb0SMichal Hocko 
138894310cbcSAnshuman Khandual 	return NULL;
138994310cbcSAnshuman Khandual }
139094310cbcSAnshuman Khandual 
available_huge_pages(struct hstate * h)13918346d69dSXin Hao static unsigned long available_huge_pages(struct hstate *h)
13928346d69dSXin Hao {
13938346d69dSXin Hao 	return h->free_huge_pages - h->resv_huge_pages;
13948346d69dSXin Hao }
13958346d69dSXin Hao 
dequeue_hugetlb_folio_vma(struct hstate * h,struct vm_area_struct * vma,unsigned long address,int avoid_reserve,long chg)1396ff7d853bSSidhartha Kumar static struct folio *dequeue_hugetlb_folio_vma(struct hstate *h,
1397a5516438SAndi Kleen 				struct vm_area_struct *vma,
1398af0ed73eSJoonsoo Kim 				unsigned long address, int avoid_reserve,
1399af0ed73eSJoonsoo Kim 				long chg)
14001da177e4SLinus Torvalds {
1401a36f1e90SSidhartha Kumar 	struct folio *folio = NULL;
1402480eccf9SLee Schermerhorn 	struct mempolicy *mpol;
140304ec6264SVlastimil Babka 	gfp_t gfp_mask;
14043e59fcb0SMichal Hocko 	nodemask_t *nodemask;
140504ec6264SVlastimil Babka 	int nid;
14061da177e4SLinus Torvalds 
1407a1e78772SMel Gorman 	/*
1408a1e78772SMel Gorman 	 * A child process with MAP_PRIVATE mappings created by their parent
1409a1e78772SMel Gorman 	 * have no page reserves. This check ensures that reservations are
1410a1e78772SMel Gorman 	 * not "stolen". The child may still get SIGKILLed
1411a1e78772SMel Gorman 	 */
14128346d69dSXin Hao 	if (!vma_has_reserves(vma, chg) && !available_huge_pages(h))
1413c0ff7453SMiao Xie 		goto err;
1414a1e78772SMel Gorman 
141504f2cbe3SMel Gorman 	/* If reserves cannot be used, ensure enough pages are in the pool */
14168346d69dSXin Hao 	if (avoid_reserve && !available_huge_pages(h))
14176eab04a8SJustin P. Mattock 		goto err;
141804f2cbe3SMel Gorman 
141904ec6264SVlastimil Babka 	gfp_mask = htlb_alloc_mask(h);
142004ec6264SVlastimil Babka 	nid = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
1421cfcaa66fSBen Widawsky 
1422cfcaa66fSBen Widawsky 	if (mpol_is_preferred_many(mpol)) {
1423a36f1e90SSidhartha Kumar 		folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask,
1424a36f1e90SSidhartha Kumar 							nid, nodemask);
1425cfcaa66fSBen Widawsky 
1426cfcaa66fSBen Widawsky 		/* Fallback to all nodes if page==NULL */
1427cfcaa66fSBen Widawsky 		nodemask = NULL;
1428cfcaa66fSBen Widawsky 	}
1429cfcaa66fSBen Widawsky 
1430a36f1e90SSidhartha Kumar 	if (!folio)
1431a36f1e90SSidhartha Kumar 		folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask,
1432a36f1e90SSidhartha Kumar 							nid, nodemask);
1433cfcaa66fSBen Widawsky 
1434a36f1e90SSidhartha Kumar 	if (folio && !avoid_reserve && vma_has_reserves(vma, chg)) {
1435a36f1e90SSidhartha Kumar 		folio_set_hugetlb_restore_reserve(folio);
1436a63884e9SJoonsoo Kim 		h->resv_huge_pages--;
1437bf50bab2SNaoya Horiguchi 	}
1438cc9a6c87SMel Gorman 
1439cc9a6c87SMel Gorman 	mpol_cond_put(mpol);
1440ff7d853bSSidhartha Kumar 	return folio;
1441cc9a6c87SMel Gorman 
1442c0ff7453SMiao Xie err:
1443cc9a6c87SMel Gorman 	return NULL;
14441da177e4SLinus Torvalds }
14451da177e4SLinus Torvalds 
14461cac6f2cSLuiz Capitulino /*
14471cac6f2cSLuiz Capitulino  * common helper functions for hstate_next_node_to_{alloc|free}.
14481cac6f2cSLuiz Capitulino  * We may have allocated or freed a huge page based on a different
14491cac6f2cSLuiz Capitulino  * nodes_allowed previously, so h->next_node_to_{alloc|free} might
14501cac6f2cSLuiz Capitulino  * be outside of *nodes_allowed.  Ensure that we use an allowed
14511cac6f2cSLuiz Capitulino  * node for alloc or free.
14521cac6f2cSLuiz Capitulino  */
next_node_allowed(int nid,nodemask_t * nodes_allowed)14531cac6f2cSLuiz Capitulino static int next_node_allowed(int nid, nodemask_t *nodes_allowed)
14541cac6f2cSLuiz Capitulino {
14550edaf86cSAndrew Morton 	nid = next_node_in(nid, *nodes_allowed);
14561cac6f2cSLuiz Capitulino 	VM_BUG_ON(nid >= MAX_NUMNODES);
14571cac6f2cSLuiz Capitulino 
14581cac6f2cSLuiz Capitulino 	return nid;
14591cac6f2cSLuiz Capitulino }
14601cac6f2cSLuiz Capitulino 
get_valid_node_allowed(int nid,nodemask_t * nodes_allowed)14611cac6f2cSLuiz Capitulino static int get_valid_node_allowed(int nid, nodemask_t *nodes_allowed)
14621cac6f2cSLuiz Capitulino {
14631cac6f2cSLuiz Capitulino 	if (!node_isset(nid, *nodes_allowed))
14641cac6f2cSLuiz Capitulino 		nid = next_node_allowed(nid, nodes_allowed);
14651cac6f2cSLuiz Capitulino 	return nid;
14661cac6f2cSLuiz Capitulino }
14671cac6f2cSLuiz Capitulino 
14681cac6f2cSLuiz Capitulino /*
14691cac6f2cSLuiz Capitulino  * returns the previously saved node ["this node"] from which to
14701cac6f2cSLuiz Capitulino  * allocate a persistent huge page for the pool and advance the
14711cac6f2cSLuiz Capitulino  * next node from which to allocate, handling wrap at end of node
14721cac6f2cSLuiz Capitulino  * mask.
14731cac6f2cSLuiz Capitulino  */
hstate_next_node_to_alloc(struct hstate * h,nodemask_t * nodes_allowed)14741cac6f2cSLuiz Capitulino static int hstate_next_node_to_alloc(struct hstate *h,
14751cac6f2cSLuiz Capitulino 					nodemask_t *nodes_allowed)
14761cac6f2cSLuiz Capitulino {
14771cac6f2cSLuiz Capitulino 	int nid;
14781cac6f2cSLuiz Capitulino 
14791cac6f2cSLuiz Capitulino 	VM_BUG_ON(!nodes_allowed);
14801cac6f2cSLuiz Capitulino 
14811cac6f2cSLuiz Capitulino 	nid = get_valid_node_allowed(h->next_nid_to_alloc, nodes_allowed);
14821cac6f2cSLuiz Capitulino 	h->next_nid_to_alloc = next_node_allowed(nid, nodes_allowed);
14831cac6f2cSLuiz Capitulino 
14841cac6f2cSLuiz Capitulino 	return nid;
14851cac6f2cSLuiz Capitulino }
14861cac6f2cSLuiz Capitulino 
14871cac6f2cSLuiz Capitulino /*
148810c6ec49SMike Kravetz  * helper for remove_pool_huge_page() - return the previously saved
14891cac6f2cSLuiz Capitulino  * node ["this node"] from which to free a huge page.  Advance the
14901cac6f2cSLuiz Capitulino  * next node id whether or not we find a free huge page to free so
14911cac6f2cSLuiz Capitulino  * that the next attempt to free addresses the next node.
14921cac6f2cSLuiz Capitulino  */
hstate_next_node_to_free(struct hstate * h,nodemask_t * nodes_allowed)14931cac6f2cSLuiz Capitulino static int hstate_next_node_to_free(struct hstate *h, nodemask_t *nodes_allowed)
14941cac6f2cSLuiz Capitulino {
14951cac6f2cSLuiz Capitulino 	int nid;
14961cac6f2cSLuiz Capitulino 
14971cac6f2cSLuiz Capitulino 	VM_BUG_ON(!nodes_allowed);
14981cac6f2cSLuiz Capitulino 
14991cac6f2cSLuiz Capitulino 	nid = get_valid_node_allowed(h->next_nid_to_free, nodes_allowed);
15001cac6f2cSLuiz Capitulino 	h->next_nid_to_free = next_node_allowed(nid, nodes_allowed);
15011cac6f2cSLuiz Capitulino 
15021cac6f2cSLuiz Capitulino 	return nid;
15031cac6f2cSLuiz Capitulino }
15041cac6f2cSLuiz Capitulino 
15051cac6f2cSLuiz Capitulino #define for_each_node_mask_to_alloc(hs, nr_nodes, node, mask)		\
15061cac6f2cSLuiz Capitulino 	for (nr_nodes = nodes_weight(*mask);				\
15071cac6f2cSLuiz Capitulino 		nr_nodes > 0 &&						\
15081cac6f2cSLuiz Capitulino 		((node = hstate_next_node_to_alloc(hs, mask)) || 1);	\
15091cac6f2cSLuiz Capitulino 		nr_nodes--)
15101cac6f2cSLuiz Capitulino 
15111cac6f2cSLuiz Capitulino #define for_each_node_mask_to_free(hs, nr_nodes, node, mask)		\
15121cac6f2cSLuiz Capitulino 	for (nr_nodes = nodes_weight(*mask);				\
15131cac6f2cSLuiz Capitulino 		nr_nodes > 0 &&						\
15141cac6f2cSLuiz Capitulino 		((node = hstate_next_node_to_free(hs, mask)) || 1);	\
15151cac6f2cSLuiz Capitulino 		nr_nodes--)
15161cac6f2cSLuiz Capitulino 
15178531fc6fSMike Kravetz /* used to demote non-gigantic_huge pages as well */
__destroy_compound_gigantic_folio(struct folio * folio,unsigned int order,bool demote)1518911565b8SSidhartha Kumar static void __destroy_compound_gigantic_folio(struct folio *folio,
151934d9e35bSMike Kravetz 					unsigned int order, bool demote)
1520944d9fecSLuiz Capitulino {
1521944d9fecSLuiz Capitulino 	int i;
1522944d9fecSLuiz Capitulino 	int nr_pages = 1 << order;
152314455eabSCheng Li 	struct page *p;
1524944d9fecSLuiz Capitulino 
152546f27228SMatthew Wilcox (Oracle) 	atomic_set(&folio->_entire_mapcount, 0);
1526eec20426SMatthew Wilcox (Oracle) 	atomic_set(&folio->_nr_pages_mapped, 0);
152794688e8eSMatthew Wilcox (Oracle) 	atomic_set(&folio->_pincount, 0);
152847e29d32SJohn Hubbard 
152914455eabSCheng Li 	for (i = 1; i < nr_pages; i++) {
1530911565b8SSidhartha Kumar 		p = folio_page(folio, i);
15316c141973SMike Kravetz 		p->flags &= ~PAGE_FLAGS_CHECK_AT_FREE;
1532a01f4390SMike Kravetz 		p->mapping = NULL;
15331d798ca3SKirill A. Shutemov 		clear_compound_head(p);
153434d9e35bSMike Kravetz 		if (!demote)
1535944d9fecSLuiz Capitulino 			set_page_refcounted(p);
1536944d9fecSLuiz Capitulino 	}
1537944d9fecSLuiz Capitulino 
1538911565b8SSidhartha Kumar 	__folio_clear_head(folio);
1539944d9fecSLuiz Capitulino }
1540944d9fecSLuiz Capitulino 
destroy_compound_hugetlb_folio_for_demote(struct folio * folio,unsigned int order)1541911565b8SSidhartha Kumar static void destroy_compound_hugetlb_folio_for_demote(struct folio *folio,
15428531fc6fSMike Kravetz 					unsigned int order)
15438531fc6fSMike Kravetz {
1544911565b8SSidhartha Kumar 	__destroy_compound_gigantic_folio(folio, order, true);
15458531fc6fSMike Kravetz }
15468531fc6fSMike Kravetz 
15478531fc6fSMike Kravetz #ifdef CONFIG_ARCH_HAS_GIGANTIC_PAGE
destroy_compound_gigantic_folio(struct folio * folio,unsigned int order)1548911565b8SSidhartha Kumar static void destroy_compound_gigantic_folio(struct folio *folio,
154934d9e35bSMike Kravetz 					unsigned int order)
155034d9e35bSMike Kravetz {
1551911565b8SSidhartha Kumar 	__destroy_compound_gigantic_folio(folio, order, false);
155234d9e35bSMike Kravetz }
155334d9e35bSMike Kravetz 
free_gigantic_folio(struct folio * folio,unsigned int order)15547f325a8dSSidhartha Kumar static void free_gigantic_folio(struct folio *folio, unsigned int order)
1555944d9fecSLuiz Capitulino {
1556cf11e85fSRoman Gushchin 	/*
1557cf11e85fSRoman Gushchin 	 * If the page isn't allocated using the cma allocator,
1558cf11e85fSRoman Gushchin 	 * cma_release() returns false.
1559cf11e85fSRoman Gushchin 	 */
1560dbda8feaSBarry Song #ifdef CONFIG_CMA
15617f325a8dSSidhartha Kumar 	int nid = folio_nid(folio);
15627f325a8dSSidhartha Kumar 
15637f325a8dSSidhartha Kumar 	if (cma_release(hugetlb_cma[nid], &folio->page, 1 << order))
1564cf11e85fSRoman Gushchin 		return;
1565dbda8feaSBarry Song #endif
1566cf11e85fSRoman Gushchin 
15677f325a8dSSidhartha Kumar 	free_contig_range(folio_pfn(folio), 1 << order);
1568944d9fecSLuiz Capitulino }
1569944d9fecSLuiz Capitulino 
15704eb0716eSAlexandre Ghiti #ifdef CONFIG_CONTIG_ALLOC
alloc_gigantic_folio(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nodemask)157119fc1a7eSSidhartha Kumar static struct folio *alloc_gigantic_folio(struct hstate *h, gfp_t gfp_mask,
1572d9cc948fSMichal Hocko 		int nid, nodemask_t *nodemask)
1573944d9fecSLuiz Capitulino {
157419fc1a7eSSidhartha Kumar 	struct page *page;
157504adbc3fSMiaohe Lin 	unsigned long nr_pages = pages_per_huge_page(h);
1576953f064aSLi Xinhai 	if (nid == NUMA_NO_NODE)
1577953f064aSLi Xinhai 		nid = numa_mem_id();
1578944d9fecSLuiz Capitulino 
1579dbda8feaSBarry Song #ifdef CONFIG_CMA
1580dbda8feaSBarry Song 	{
1581cf11e85fSRoman Gushchin 		int node;
1582cf11e85fSRoman Gushchin 
1583953f064aSLi Xinhai 		if (hugetlb_cma[nid]) {
1584953f064aSLi Xinhai 			page = cma_alloc(hugetlb_cma[nid], nr_pages,
1585953f064aSLi Xinhai 					huge_page_order(h), true);
1586953f064aSLi Xinhai 			if (page)
158719fc1a7eSSidhartha Kumar 				return page_folio(page);
1588953f064aSLi Xinhai 		}
1589953f064aSLi Xinhai 
1590953f064aSLi Xinhai 		if (!(gfp_mask & __GFP_THISNODE)) {
1591cf11e85fSRoman Gushchin 			for_each_node_mask(node, *nodemask) {
1592953f064aSLi Xinhai 				if (node == nid || !hugetlb_cma[node])
1593cf11e85fSRoman Gushchin 					continue;
1594cf11e85fSRoman Gushchin 
1595cf11e85fSRoman Gushchin 				page = cma_alloc(hugetlb_cma[node], nr_pages,
1596cf11e85fSRoman Gushchin 						huge_page_order(h), true);
1597cf11e85fSRoman Gushchin 				if (page)
159819fc1a7eSSidhartha Kumar 					return page_folio(page);
1599cf11e85fSRoman Gushchin 			}
1600cf11e85fSRoman Gushchin 		}
1601953f064aSLi Xinhai 	}
1602dbda8feaSBarry Song #endif
1603cf11e85fSRoman Gushchin 
160419fc1a7eSSidhartha Kumar 	page = alloc_contig_pages(nr_pages, gfp_mask, nid, nodemask);
160519fc1a7eSSidhartha Kumar 	return page ? page_folio(page) : NULL;
1606944d9fecSLuiz Capitulino }
1607944d9fecSLuiz Capitulino 
16084eb0716eSAlexandre Ghiti #else /* !CONFIG_CONTIG_ALLOC */
alloc_gigantic_folio(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nodemask)160919fc1a7eSSidhartha Kumar static struct folio *alloc_gigantic_folio(struct hstate *h, gfp_t gfp_mask,
16104eb0716eSAlexandre Ghiti 					int nid, nodemask_t *nodemask)
16114eb0716eSAlexandre Ghiti {
16124eb0716eSAlexandre Ghiti 	return NULL;
16134eb0716eSAlexandre Ghiti }
16144eb0716eSAlexandre Ghiti #endif /* CONFIG_CONTIG_ALLOC */
1615944d9fecSLuiz Capitulino 
1616e1073d1eSAneesh Kumar K.V #else /* !CONFIG_ARCH_HAS_GIGANTIC_PAGE */
alloc_gigantic_folio(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nodemask)161719fc1a7eSSidhartha Kumar static struct folio *alloc_gigantic_folio(struct hstate *h, gfp_t gfp_mask,
16184eb0716eSAlexandre Ghiti 					int nid, nodemask_t *nodemask)
16194eb0716eSAlexandre Ghiti {
16204eb0716eSAlexandre Ghiti 	return NULL;
16214eb0716eSAlexandre Ghiti }
free_gigantic_folio(struct folio * folio,unsigned int order)16227f325a8dSSidhartha Kumar static inline void free_gigantic_folio(struct folio *folio,
16237f325a8dSSidhartha Kumar 						unsigned int order) { }
destroy_compound_gigantic_folio(struct folio * folio,unsigned int order)1624911565b8SSidhartha Kumar static inline void destroy_compound_gigantic_folio(struct folio *folio,
1625d00181b9SKirill A. Shutemov 						unsigned int order) { }
1626944d9fecSLuiz Capitulino #endif
1627944d9fecSLuiz Capitulino 
__clear_hugetlb_destructor(struct hstate * h,struct folio * folio)162832c87719SMike Kravetz static inline void __clear_hugetlb_destructor(struct hstate *h,
162932c87719SMike Kravetz 						struct folio *folio)
163032c87719SMike Kravetz {
163132c87719SMike Kravetz 	lockdep_assert_held(&hugetlb_lock);
163232c87719SMike Kravetz 
16332431b5f2SMatthew Wilcox (Oracle) 	__folio_clear_hugetlb(folio);
163432c87719SMike Kravetz }
163532c87719SMike Kravetz 
163632c87719SMike Kravetz /*
163732c87719SMike Kravetz  * Remove hugetlb folio from lists.
163832c87719SMike Kravetz  * If vmemmap exists for the folio, update dtor so that the folio appears
163932c87719SMike Kravetz  * as just a compound page.  Otherwise, wait until after allocating vmemmap
164032c87719SMike Kravetz  * to update dtor.
164134d9e35bSMike Kravetz  *
1642cfd5082bSSidhartha Kumar  * A reference is held on the folio, except in the case of demote.
16436eb4e88aSMike Kravetz  *
16446eb4e88aSMike Kravetz  * Must be called with hugetlb lock held.
16456eb4e88aSMike Kravetz  */
__remove_hugetlb_folio(struct hstate * h,struct folio * folio,bool adjust_surplus,bool demote)1646cfd5082bSSidhartha Kumar static void __remove_hugetlb_folio(struct hstate *h, struct folio *folio,
164734d9e35bSMike Kravetz 							bool adjust_surplus,
164834d9e35bSMike Kravetz 							bool demote)
16496eb4e88aSMike Kravetz {
1650cfd5082bSSidhartha Kumar 	int nid = folio_nid(folio);
16516eb4e88aSMike Kravetz 
1652f074732dSSidhartha Kumar 	VM_BUG_ON_FOLIO(hugetlb_cgroup_from_folio(folio), folio);
1653f074732dSSidhartha Kumar 	VM_BUG_ON_FOLIO(hugetlb_cgroup_from_folio_rsvd(folio), folio);
16546eb4e88aSMike Kravetz 
16559487ca60SMike Kravetz 	lockdep_assert_held(&hugetlb_lock);
16566eb4e88aSMike Kravetz 	if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
16576eb4e88aSMike Kravetz 		return;
16586eb4e88aSMike Kravetz 
1659cfd5082bSSidhartha Kumar 	list_del(&folio->lru);
16606eb4e88aSMike Kravetz 
1661cfd5082bSSidhartha Kumar 	if (folio_test_hugetlb_freed(folio)) {
16626eb4e88aSMike Kravetz 		h->free_huge_pages--;
16636eb4e88aSMike Kravetz 		h->free_huge_pages_node[nid]--;
16646eb4e88aSMike Kravetz 	}
16656eb4e88aSMike Kravetz 	if (adjust_surplus) {
16666eb4e88aSMike Kravetz 		h->surplus_huge_pages--;
16676eb4e88aSMike Kravetz 		h->surplus_huge_pages_node[nid]--;
16686eb4e88aSMike Kravetz 	}
16696eb4e88aSMike Kravetz 
1670e32d20c0SMike Kravetz 	/*
167132c87719SMike Kravetz 	 * We can only clear the hugetlb destructor after allocating vmemmap
167232c87719SMike Kravetz 	 * pages.  Otherwise, someone (memory error handling) may try to write
167332c87719SMike Kravetz 	 * to tail struct pages.
167432c87719SMike Kravetz 	 */
167532c87719SMike Kravetz 	if (!folio_test_hugetlb_vmemmap_optimized(folio))
167632c87719SMike Kravetz 		__clear_hugetlb_destructor(h, folio);
167732c87719SMike Kravetz 
167832c87719SMike Kravetz 	 /*
167934d9e35bSMike Kravetz 	  * In the case of demote we do not ref count the page as it will soon
168034d9e35bSMike Kravetz 	  * be turned into a page of smaller size.
1681e32d20c0SMike Kravetz 	 */
168234d9e35bSMike Kravetz 	if (!demote)
1683cfd5082bSSidhartha Kumar 		folio_ref_unfreeze(folio, 1);
16846eb4e88aSMike Kravetz 
16856eb4e88aSMike Kravetz 	h->nr_huge_pages--;
16866eb4e88aSMike Kravetz 	h->nr_huge_pages_node[nid]--;
16876eb4e88aSMike Kravetz }
16886eb4e88aSMike Kravetz 
remove_hugetlb_folio(struct hstate * h,struct folio * folio,bool adjust_surplus)1689cfd5082bSSidhartha Kumar static void remove_hugetlb_folio(struct hstate *h, struct folio *folio,
169034d9e35bSMike Kravetz 							bool adjust_surplus)
169134d9e35bSMike Kravetz {
1692cfd5082bSSidhartha Kumar 	__remove_hugetlb_folio(h, folio, adjust_surplus, false);
169334d9e35bSMike Kravetz }
169434d9e35bSMike Kravetz 
remove_hugetlb_folio_for_demote(struct hstate * h,struct folio * folio,bool adjust_surplus)1695cfd5082bSSidhartha Kumar static void remove_hugetlb_folio_for_demote(struct hstate *h, struct folio *folio,
16968531fc6fSMike Kravetz 							bool adjust_surplus)
16978531fc6fSMike Kravetz {
1698cfd5082bSSidhartha Kumar 	__remove_hugetlb_folio(h, folio, adjust_surplus, true);
16998531fc6fSMike Kravetz }
17008531fc6fSMike Kravetz 
add_hugetlb_folio(struct hstate * h,struct folio * folio,bool adjust_surplus)17012f6c57d6SSidhartha Kumar static void add_hugetlb_folio(struct hstate *h, struct folio *folio,
1702ad2fa371SMuchun Song 			     bool adjust_surplus)
1703ad2fa371SMuchun Song {
1704ad2fa371SMuchun Song 	int zeroed;
17052f6c57d6SSidhartha Kumar 	int nid = folio_nid(folio);
1706ad2fa371SMuchun Song 
17072f6c57d6SSidhartha Kumar 	VM_BUG_ON_FOLIO(!folio_test_hugetlb_vmemmap_optimized(folio), folio);
1708ad2fa371SMuchun Song 
1709ad2fa371SMuchun Song 	lockdep_assert_held(&hugetlb_lock);
1710ad2fa371SMuchun Song 
17112f6c57d6SSidhartha Kumar 	INIT_LIST_HEAD(&folio->lru);
1712ad2fa371SMuchun Song 	h->nr_huge_pages++;
1713ad2fa371SMuchun Song 	h->nr_huge_pages_node[nid]++;
1714ad2fa371SMuchun Song 
1715ad2fa371SMuchun Song 	if (adjust_surplus) {
1716ad2fa371SMuchun Song 		h->surplus_huge_pages++;
1717ad2fa371SMuchun Song 		h->surplus_huge_pages_node[nid]++;
1718ad2fa371SMuchun Song 	}
1719ad2fa371SMuchun Song 
17202431b5f2SMatthew Wilcox (Oracle) 	__folio_set_hugetlb(folio);
17212f6c57d6SSidhartha Kumar 	folio_change_private(folio, NULL);
1722a9e1eab2SMiaohe Lin 	/*
17232f6c57d6SSidhartha Kumar 	 * We have to set hugetlb_vmemmap_optimized again as above
17242f6c57d6SSidhartha Kumar 	 * folio_change_private(folio, NULL) cleared it.
1725a9e1eab2SMiaohe Lin 	 */
17262f6c57d6SSidhartha Kumar 	folio_set_hugetlb_vmemmap_optimized(folio);
1727ad2fa371SMuchun Song 
1728ad2fa371SMuchun Song 	/*
17292f6c57d6SSidhartha Kumar 	 * This folio is about to be managed by the hugetlb allocator and
1730b65a4edaSMike Kravetz 	 * should have no users.  Drop our reference, and check for others
1731b65a4edaSMike Kravetz 	 * just in case.
1732ad2fa371SMuchun Song 	 */
17332f6c57d6SSidhartha Kumar 	zeroed = folio_put_testzero(folio);
17342f6c57d6SSidhartha Kumar 	if (unlikely(!zeroed))
1735b65a4edaSMike Kravetz 		/*
1736454a00c4SMatthew Wilcox (Oracle) 		 * It is VERY unlikely soneone else has taken a ref
1737454a00c4SMatthew Wilcox (Oracle) 		 * on the folio.  In this case, we simply return as
1738454a00c4SMatthew Wilcox (Oracle) 		 * free_huge_folio() will be called when this other ref
1739454a00c4SMatthew Wilcox (Oracle) 		 * is dropped.
1740b65a4edaSMike Kravetz 		 */
1741b65a4edaSMike Kravetz 		return;
1742b65a4edaSMike Kravetz 
17432f6c57d6SSidhartha Kumar 	arch_clear_hugepage_flags(&folio->page);
1744240d67a8SSidhartha Kumar 	enqueue_hugetlb_folio(h, folio);
1745ad2fa371SMuchun Song }
1746ad2fa371SMuchun Song 
__update_and_free_hugetlb_folio(struct hstate * h,struct folio * folio)17476f6956cfSSidhartha Kumar static void __update_and_free_hugetlb_folio(struct hstate *h,
17486f6956cfSSidhartha Kumar 						struct folio *folio)
17496af2acb6SAdam Litke {
17504eb0716eSAlexandre Ghiti 	if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
1751944d9fecSLuiz Capitulino 		return;
175218229df5SAndy Whitcroft 
1753161df60eSNaoya Horiguchi 	/*
1754161df60eSNaoya Horiguchi 	 * If we don't know which subpages are hwpoisoned, we can't free
1755161df60eSNaoya Horiguchi 	 * the hugepage, so it's leaked intentionally.
1756161df60eSNaoya Horiguchi 	 */
17577f325a8dSSidhartha Kumar 	if (folio_test_hugetlb_raw_hwp_unreliable(folio))
1758161df60eSNaoya Horiguchi 		return;
1759161df60eSNaoya Horiguchi 
17606f6956cfSSidhartha Kumar 	if (hugetlb_vmemmap_restore(h, &folio->page)) {
1761ad2fa371SMuchun Song 		spin_lock_irq(&hugetlb_lock);
1762ad2fa371SMuchun Song 		/*
1763ad2fa371SMuchun Song 		 * If we cannot allocate vmemmap pages, just refuse to free the
1764ad2fa371SMuchun Song 		 * page and put the page back on the hugetlb free list and treat
1765ad2fa371SMuchun Song 		 * as a surplus page.
1766ad2fa371SMuchun Song 		 */
17677f325a8dSSidhartha Kumar 		add_hugetlb_folio(h, folio, true);
1768ad2fa371SMuchun Song 		spin_unlock_irq(&hugetlb_lock);
1769ad2fa371SMuchun Song 		return;
1770ad2fa371SMuchun Song 	}
1771ad2fa371SMuchun Song 
1772161df60eSNaoya Horiguchi 	/*
177332c87719SMike Kravetz 	 * If vmemmap pages were allocated above, then we need to clear the
177432c87719SMike Kravetz 	 * hugetlb destructor under the hugetlb lock.
177532c87719SMike Kravetz 	 */
17767e0a3228SMiaohe Lin 	if (folio_test_hugetlb(folio)) {
177732c87719SMike Kravetz 		spin_lock_irq(&hugetlb_lock);
177832c87719SMike Kravetz 		__clear_hugetlb_destructor(h, folio);
177932c87719SMike Kravetz 		spin_unlock_irq(&hugetlb_lock);
178032c87719SMike Kravetz 	}
178132c87719SMike Kravetz 
1782a01f4390SMike Kravetz 	/*
17832ae4d582SMiaohe Lin 	 * Move PageHWPoison flag from head page to the raw error pages,
17842ae4d582SMiaohe Lin 	 * which makes any healthy subpages reusable.
17852ae4d582SMiaohe Lin 	 */
17862ae4d582SMiaohe Lin 	if (unlikely(folio_test_hwpoison(folio)))
17872ae4d582SMiaohe Lin 		folio_clear_hugetlb_hwpoison(folio);
17882ae4d582SMiaohe Lin 
17892ae4d582SMiaohe Lin 	/*
1790a01f4390SMike Kravetz 	 * Non-gigantic pages demoted from CMA allocated gigantic pages
17917f325a8dSSidhartha Kumar 	 * need to be given back to CMA in free_gigantic_folio.
1792a01f4390SMike Kravetz 	 */
1793a01f4390SMike Kravetz 	if (hstate_is_gigantic(h) ||
17942f6c57d6SSidhartha Kumar 	    hugetlb_cma_folio(folio, huge_page_order(h))) {
1795911565b8SSidhartha Kumar 		destroy_compound_gigantic_folio(folio, huge_page_order(h));
17967f325a8dSSidhartha Kumar 		free_gigantic_folio(folio, huge_page_order(h));
1797944d9fecSLuiz Capitulino 	} else {
17980275e402SMatthew Wilcox (Oracle) 		INIT_LIST_HEAD(&folio->_deferred_list);
17996f6956cfSSidhartha Kumar 		__free_pages(&folio->page, huge_page_order(h));
18006af2acb6SAdam Litke 	}
1801944d9fecSLuiz Capitulino }
18026af2acb6SAdam Litke 
1803b65d4adbSMuchun Song /*
1804d6ef19e2SSidhartha Kumar  * As update_and_free_hugetlb_folio() can be called under any context, so we cannot
1805b65d4adbSMuchun Song  * use GFP_KERNEL to allocate vmemmap pages. However, we can defer the
1806b65d4adbSMuchun Song  * actual freeing in a workqueue to prevent from using GFP_ATOMIC to allocate
1807b65d4adbSMuchun Song  * the vmemmap pages.
1808b65d4adbSMuchun Song  *
1809b65d4adbSMuchun Song  * free_hpage_workfn() locklessly retrieves the linked list of pages to be
1810b65d4adbSMuchun Song  * freed and frees them one-by-one. As the page->mapping pointer is going
1811b65d4adbSMuchun Song  * to be cleared in free_hpage_workfn() anyway, it is reused as the llist_node
1812b65d4adbSMuchun Song  * structure of a lockless linked list of huge pages to be freed.
1813b65d4adbSMuchun Song  */
1814b65d4adbSMuchun Song static LLIST_HEAD(hpage_freelist);
1815b65d4adbSMuchun Song 
free_hpage_workfn(struct work_struct * work)1816b65d4adbSMuchun Song static void free_hpage_workfn(struct work_struct *work)
1817b65d4adbSMuchun Song {
1818b65d4adbSMuchun Song 	struct llist_node *node;
1819b65d4adbSMuchun Song 
1820b65d4adbSMuchun Song 	node = llist_del_all(&hpage_freelist);
1821b65d4adbSMuchun Song 
1822b65d4adbSMuchun Song 	while (node) {
1823b65d4adbSMuchun Song 		struct page *page;
1824b65d4adbSMuchun Song 		struct hstate *h;
1825b65d4adbSMuchun Song 
1826b65d4adbSMuchun Song 		page = container_of((struct address_space **)node,
1827b65d4adbSMuchun Song 				     struct page, mapping);
1828b65d4adbSMuchun Song 		node = node->next;
1829b65d4adbSMuchun Song 		page->mapping = NULL;
1830b65d4adbSMuchun Song 		/*
1831affd26b1SSidhartha Kumar 		 * The VM_BUG_ON_FOLIO(!folio_test_hugetlb(folio), folio) in
1832affd26b1SSidhartha Kumar 		 * folio_hstate() is going to trigger because a previous call to
18339c5ccf2dSMatthew Wilcox (Oracle) 		 * remove_hugetlb_folio() will clear the hugetlb bit, so do
18349c5ccf2dSMatthew Wilcox (Oracle) 		 * not use folio_hstate() directly.
1835b65d4adbSMuchun Song 		 */
1836b65d4adbSMuchun Song 		h = size_to_hstate(page_size(page));
1837b65d4adbSMuchun Song 
18386f6956cfSSidhartha Kumar 		__update_and_free_hugetlb_folio(h, page_folio(page));
1839b65d4adbSMuchun Song 
1840b65d4adbSMuchun Song 		cond_resched();
1841b65d4adbSMuchun Song 	}
1842b65d4adbSMuchun Song }
1843b65d4adbSMuchun Song static DECLARE_WORK(free_hpage_work, free_hpage_workfn);
1844b65d4adbSMuchun Song 
flush_free_hpage_work(struct hstate * h)1845b65d4adbSMuchun Song static inline void flush_free_hpage_work(struct hstate *h)
1846b65d4adbSMuchun Song {
18476213834cSMuchun Song 	if (hugetlb_vmemmap_optimizable(h))
1848b65d4adbSMuchun Song 		flush_work(&free_hpage_work);
1849b65d4adbSMuchun Song }
1850b65d4adbSMuchun Song 
update_and_free_hugetlb_folio(struct hstate * h,struct folio * folio,bool atomic)1851d6ef19e2SSidhartha Kumar static void update_and_free_hugetlb_folio(struct hstate *h, struct folio *folio,
1852b65d4adbSMuchun Song 				 bool atomic)
1853b65d4adbSMuchun Song {
1854d6ef19e2SSidhartha Kumar 	if (!folio_test_hugetlb_vmemmap_optimized(folio) || !atomic) {
18556f6956cfSSidhartha Kumar 		__update_and_free_hugetlb_folio(h, folio);
1856b65d4adbSMuchun Song 		return;
1857b65d4adbSMuchun Song 	}
1858b65d4adbSMuchun Song 
1859b65d4adbSMuchun Song 	/*
1860b65d4adbSMuchun Song 	 * Defer freeing to avoid using GFP_ATOMIC to allocate vmemmap pages.
1861b65d4adbSMuchun Song 	 *
1862b65d4adbSMuchun Song 	 * Only call schedule_work() if hpage_freelist is previously
1863b65d4adbSMuchun Song 	 * empty. Otherwise, schedule_work() had been called but the workfn
1864b65d4adbSMuchun Song 	 * hasn't retrieved the list yet.
1865b65d4adbSMuchun Song 	 */
1866d6ef19e2SSidhartha Kumar 	if (llist_add((struct llist_node *)&folio->mapping, &hpage_freelist))
1867b65d4adbSMuchun Song 		schedule_work(&free_hpage_work);
1868b65d4adbSMuchun Song }
1869b65d4adbSMuchun Song 
update_and_free_pages_bulk(struct hstate * h,struct list_head * list)187010c6ec49SMike Kravetz static void update_and_free_pages_bulk(struct hstate *h, struct list_head *list)
187110c6ec49SMike Kravetz {
187210c6ec49SMike Kravetz 	struct page *page, *t_page;
1873d6ef19e2SSidhartha Kumar 	struct folio *folio;
187410c6ec49SMike Kravetz 
187510c6ec49SMike Kravetz 	list_for_each_entry_safe(page, t_page, list, lru) {
1876d6ef19e2SSidhartha Kumar 		folio = page_folio(page);
1877d6ef19e2SSidhartha Kumar 		update_and_free_hugetlb_folio(h, folio, false);
187810c6ec49SMike Kravetz 		cond_resched();
187910c6ec49SMike Kravetz 	}
188010c6ec49SMike Kravetz }
188110c6ec49SMike Kravetz 
size_to_hstate(unsigned long size)1882e5ff2159SAndi Kleen struct hstate *size_to_hstate(unsigned long size)
1883e5ff2159SAndi Kleen {
1884e5ff2159SAndi Kleen 	struct hstate *h;
1885e5ff2159SAndi Kleen 
1886e5ff2159SAndi Kleen 	for_each_hstate(h) {
1887e5ff2159SAndi Kleen 		if (huge_page_size(h) == size)
1888e5ff2159SAndi Kleen 			return h;
1889e5ff2159SAndi Kleen 	}
1890e5ff2159SAndi Kleen 	return NULL;
1891e5ff2159SAndi Kleen }
1892e5ff2159SAndi Kleen 
free_huge_folio(struct folio * folio)1893454a00c4SMatthew Wilcox (Oracle) void free_huge_folio(struct folio *folio)
189427a85ef1SDavid Gibson {
1895a5516438SAndi Kleen 	/*
1896a5516438SAndi Kleen 	 * Can't pass hstate in here because it is called from the
1897a5516438SAndi Kleen 	 * compound page destructor.
1898a5516438SAndi Kleen 	 */
18990356c4b9SSidhartha Kumar 	struct hstate *h = folio_hstate(folio);
19000356c4b9SSidhartha Kumar 	int nid = folio_nid(folio);
19010356c4b9SSidhartha Kumar 	struct hugepage_subpool *spool = hugetlb_folio_subpool(folio);
190207443a85SJoonsoo Kim 	bool restore_reserve;
1903db71ef79SMike Kravetz 	unsigned long flags;
190427a85ef1SDavid Gibson 
19050356c4b9SSidhartha Kumar 	VM_BUG_ON_FOLIO(folio_ref_count(folio), folio);
19060356c4b9SSidhartha Kumar 	VM_BUG_ON_FOLIO(folio_mapcount(folio), folio);
19078ace22bcSYongkai Wu 
19080356c4b9SSidhartha Kumar 	hugetlb_set_folio_subpool(folio, NULL);
19090356c4b9SSidhartha Kumar 	if (folio_test_anon(folio))
19100356c4b9SSidhartha Kumar 		__ClearPageAnonExclusive(&folio->page);
19110356c4b9SSidhartha Kumar 	folio->mapping = NULL;
19120356c4b9SSidhartha Kumar 	restore_reserve = folio_test_hugetlb_restore_reserve(folio);
19130356c4b9SSidhartha Kumar 	folio_clear_hugetlb_restore_reserve(folio);
191427a85ef1SDavid Gibson 
19151c5ecae3SMike Kravetz 	/*
1916d6995da3SMike Kravetz 	 * If HPageRestoreReserve was set on page, page allocation consumed a
19170919e1b6SMike Kravetz 	 * reservation.  If the page was associated with a subpool, there
19180919e1b6SMike Kravetz 	 * would have been a page reserved in the subpool before allocation
19190919e1b6SMike Kravetz 	 * via hugepage_subpool_get_pages().  Since we are 'restoring' the
19206c26d310SMiaohe Lin 	 * reservation, do not call hugepage_subpool_put_pages() as this will
19210919e1b6SMike Kravetz 	 * remove the reserved page from the subpool.
19220919e1b6SMike Kravetz 	 */
19230919e1b6SMike Kravetz 	if (!restore_reserve) {
19240919e1b6SMike Kravetz 		/*
19250919e1b6SMike Kravetz 		 * A return code of zero implies that the subpool will be
19260919e1b6SMike Kravetz 		 * under its minimum size if the reservation is not restored
19270919e1b6SMike Kravetz 		 * after page is free.  Therefore, force restore_reserve
19280919e1b6SMike Kravetz 		 * operation.
19291c5ecae3SMike Kravetz 		 */
19301c5ecae3SMike Kravetz 		if (hugepage_subpool_put_pages(spool, 1) == 0)
19311c5ecae3SMike Kravetz 			restore_reserve = true;
19320919e1b6SMike Kravetz 	}
19331c5ecae3SMike Kravetz 
1934db71ef79SMike Kravetz 	spin_lock_irqsave(&hugetlb_lock, flags);
19350356c4b9SSidhartha Kumar 	folio_clear_hugetlb_migratable(folio);
1936d4ab0316SSidhartha Kumar 	hugetlb_cgroup_uncharge_folio(hstate_index(h),
1937d4ab0316SSidhartha Kumar 				     pages_per_huge_page(h), folio);
1938d4ab0316SSidhartha Kumar 	hugetlb_cgroup_uncharge_folio_rsvd(hstate_index(h),
1939d4ab0316SSidhartha Kumar 					  pages_per_huge_page(h), folio);
194007443a85SJoonsoo Kim 	if (restore_reserve)
194107443a85SJoonsoo Kim 		h->resv_huge_pages++;
194207443a85SJoonsoo Kim 
19430356c4b9SSidhartha Kumar 	if (folio_test_hugetlb_temporary(folio)) {
1944cfd5082bSSidhartha Kumar 		remove_hugetlb_folio(h, folio, false);
1945db71ef79SMike Kravetz 		spin_unlock_irqrestore(&hugetlb_lock, flags);
1946d6ef19e2SSidhartha Kumar 		update_and_free_hugetlb_folio(h, folio, true);
1947ab5ac90aSMichal Hocko 	} else if (h->surplus_huge_pages_node[nid]) {
19480edaecfaSAneesh Kumar K.V 		/* remove the page from active list */
1949cfd5082bSSidhartha Kumar 		remove_hugetlb_folio(h, folio, true);
1950db71ef79SMike Kravetz 		spin_unlock_irqrestore(&hugetlb_lock, flags);
1951d6ef19e2SSidhartha Kumar 		update_and_free_hugetlb_folio(h, folio, true);
19527893d1d5SAdam Litke 	} else {
1953454a00c4SMatthew Wilcox (Oracle) 		arch_clear_hugepage_flags(&folio->page);
1954240d67a8SSidhartha Kumar 		enqueue_hugetlb_folio(h, folio);
1955db71ef79SMike Kravetz 		spin_unlock_irqrestore(&hugetlb_lock, flags);
195627a85ef1SDavid Gibson 	}
19571121828aSMike Kravetz }
195827a85ef1SDavid Gibson 
1959d3d99fccSOscar Salvador /*
1960d3d99fccSOscar Salvador  * Must be called with the hugetlb lock held
1961d3d99fccSOscar Salvador  */
__prep_account_new_huge_page(struct hstate * h,int nid)1962d3d99fccSOscar Salvador static void __prep_account_new_huge_page(struct hstate *h, int nid)
1963d3d99fccSOscar Salvador {
1964d3d99fccSOscar Salvador 	lockdep_assert_held(&hugetlb_lock);
1965d3d99fccSOscar Salvador 	h->nr_huge_pages++;
1966d3d99fccSOscar Salvador 	h->nr_huge_pages_node[nid]++;
1967d3d99fccSOscar Salvador }
1968d3d99fccSOscar Salvador 
__prep_new_hugetlb_folio(struct hstate * h,struct folio * folio)1969de656ed3SSidhartha Kumar static void __prep_new_hugetlb_folio(struct hstate *h, struct folio *folio)
1970b7ba30c6SAndi Kleen {
1971de656ed3SSidhartha Kumar 	hugetlb_vmemmap_optimize(h, &folio->page);
1972de656ed3SSidhartha Kumar 	INIT_LIST_HEAD(&folio->lru);
19732431b5f2SMatthew Wilcox (Oracle) 	__folio_set_hugetlb(folio);
1974de656ed3SSidhartha Kumar 	hugetlb_set_folio_subpool(folio, NULL);
1975de656ed3SSidhartha Kumar 	set_hugetlb_cgroup(folio, NULL);
1976de656ed3SSidhartha Kumar 	set_hugetlb_cgroup_rsvd(folio, NULL);
1977d3d99fccSOscar Salvador }
1978d3d99fccSOscar Salvador 
prep_new_hugetlb_folio(struct hstate * h,struct folio * folio,int nid)1979d1c60955SSidhartha Kumar static void prep_new_hugetlb_folio(struct hstate *h, struct folio *folio, int nid)
1980d3d99fccSOscar Salvador {
1981de656ed3SSidhartha Kumar 	__prep_new_hugetlb_folio(h, folio);
1982db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
1983d3d99fccSOscar Salvador 	__prep_account_new_huge_page(h, nid);
1984db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
1985b7ba30c6SAndi Kleen }
1986b7ba30c6SAndi Kleen 
__prep_compound_gigantic_folio(struct folio * folio,unsigned int order,bool demote)1987d1c60955SSidhartha Kumar static bool __prep_compound_gigantic_folio(struct folio *folio,
1988d1c60955SSidhartha Kumar 					unsigned int order, bool demote)
198920a0307cSWu Fengguang {
19907118fc29SMike Kravetz 	int i, j;
199120a0307cSWu Fengguang 	int nr_pages = 1 << order;
199214455eabSCheng Li 	struct page *p;
199320a0307cSWu Fengguang 
1994d1c60955SSidhartha Kumar 	__folio_clear_reserved(folio);
19952b21624fSMike Kravetz 	for (i = 0; i < nr_pages; i++) {
1996d1c60955SSidhartha Kumar 		p = folio_page(folio, i);
199714455eabSCheng Li 
1998ef5a22beSAndrea Arcangeli 		/*
1999ef5a22beSAndrea Arcangeli 		 * For gigantic hugepages allocated through bootmem at
2000ef5a22beSAndrea Arcangeli 		 * boot, it's safer to be consistent with the not-gigantic
2001ef5a22beSAndrea Arcangeli 		 * hugepages and clear the PG_reserved bit from all tail pages
20027c8de358SEthon Paul 		 * too.  Otherwise drivers using get_user_pages() to access tail
2003ef5a22beSAndrea Arcangeli 		 * pages may get the reference counting wrong if they see
2004ef5a22beSAndrea Arcangeli 		 * PG_reserved set on a tail page (despite the head page not
2005ef5a22beSAndrea Arcangeli 		 * having PG_reserved set).  Enforcing this consistency between
2006ef5a22beSAndrea Arcangeli 		 * head and tail pages allows drivers to optimize away a check
2007ef5a22beSAndrea Arcangeli 		 * on the head page when they need know if put_page() is needed
2008ef5a22beSAndrea Arcangeli 		 * after get_user_pages().
2009ef5a22beSAndrea Arcangeli 		 */
20107fb0728aSMike Kravetz 		if (i != 0)	/* head page cleared above */
2011ef5a22beSAndrea Arcangeli 			__ClearPageReserved(p);
20127118fc29SMike Kravetz 		/*
20137118fc29SMike Kravetz 		 * Subtle and very unlikely
20147118fc29SMike Kravetz 		 *
20157118fc29SMike Kravetz 		 * Gigantic 'page allocators' such as memblock or cma will
20167118fc29SMike Kravetz 		 * return a set of pages with each page ref counted.  We need
20177118fc29SMike Kravetz 		 * to turn this set of pages into a compound page with tail
20187118fc29SMike Kravetz 		 * page ref counts set to zero.  Code such as speculative page
20197118fc29SMike Kravetz 		 * cache adding could take a ref on a 'to be' tail page.
20207118fc29SMike Kravetz 		 * We need to respect any increased ref count, and only set
20217118fc29SMike Kravetz 		 * the ref count to zero if count is currently 1.  If count
2022416d85edSMike Kravetz 		 * is not 1, we return an error.  An error return indicates
2023416d85edSMike Kravetz 		 * the set of pages can not be converted to a gigantic page.
2024416d85edSMike Kravetz 		 * The caller who allocated the pages should then discard the
2025416d85edSMike Kravetz 		 * pages using the appropriate free interface.
202634d9e35bSMike Kravetz 		 *
202734d9e35bSMike Kravetz 		 * In the case of demote, the ref count will be zero.
20287118fc29SMike Kravetz 		 */
202934d9e35bSMike Kravetz 		if (!demote) {
20307118fc29SMike Kravetz 			if (!page_ref_freeze(p, 1)) {
2031416d85edSMike Kravetz 				pr_warn("HugeTLB page can not be used due to unexpected inflated ref count\n");
20327118fc29SMike Kravetz 				goto out_error;
20337118fc29SMike Kravetz 			}
203434d9e35bSMike Kravetz 		} else {
203534d9e35bSMike Kravetz 			VM_BUG_ON_PAGE(page_count(p), p);
203634d9e35bSMike Kravetz 		}
20372b21624fSMike Kravetz 		if (i != 0)
2038d1c60955SSidhartha Kumar 			set_compound_head(p, &folio->page);
203920a0307cSWu Fengguang 	}
2040e3b7bf97STarun Sahu 	__folio_set_head(folio);
2041e3b7bf97STarun Sahu 	/* we rely on prep_new_hugetlb_folio to set the destructor */
2042e3b7bf97STarun Sahu 	folio_set_order(folio, order);
204346f27228SMatthew Wilcox (Oracle) 	atomic_set(&folio->_entire_mapcount, -1);
2044eec20426SMatthew Wilcox (Oracle) 	atomic_set(&folio->_nr_pages_mapped, 0);
204594688e8eSMatthew Wilcox (Oracle) 	atomic_set(&folio->_pincount, 0);
20467118fc29SMike Kravetz 	return true;
20477118fc29SMike Kravetz 
20487118fc29SMike Kravetz out_error:
20492b21624fSMike Kravetz 	/* undo page modifications made above */
20502b21624fSMike Kravetz 	for (j = 0; j < i; j++) {
2051d1c60955SSidhartha Kumar 		p = folio_page(folio, j);
20522b21624fSMike Kravetz 		if (j != 0)
20537118fc29SMike Kravetz 			clear_compound_head(p);
20547118fc29SMike Kravetz 		set_page_refcounted(p);
20557118fc29SMike Kravetz 	}
20567118fc29SMike Kravetz 	/* need to clear PG_reserved on remaining tail pages  */
205714455eabSCheng Li 	for (; j < nr_pages; j++) {
2058d1c60955SSidhartha Kumar 		p = folio_page(folio, j);
20597118fc29SMike Kravetz 		__ClearPageReserved(p);
206014455eabSCheng Li 	}
20617118fc29SMike Kravetz 	return false;
206220a0307cSWu Fengguang }
206320a0307cSWu Fengguang 
prep_compound_gigantic_folio(struct folio * folio,unsigned int order)2064d1c60955SSidhartha Kumar static bool prep_compound_gigantic_folio(struct folio *folio,
20658531fc6fSMike Kravetz 							unsigned int order)
20668531fc6fSMike Kravetz {
2067d1c60955SSidhartha Kumar 	return __prep_compound_gigantic_folio(folio, order, false);
2068d1c60955SSidhartha Kumar }
2069d1c60955SSidhartha Kumar 
prep_compound_gigantic_folio_for_demote(struct folio * folio,unsigned int order)2070d1c60955SSidhartha Kumar static bool prep_compound_gigantic_folio_for_demote(struct folio *folio,
2071d1c60955SSidhartha Kumar 							unsigned int order)
2072d1c60955SSidhartha Kumar {
2073d1c60955SSidhartha Kumar 	return __prep_compound_gigantic_folio(folio, order, true);
20748531fc6fSMike Kravetz }
20758531fc6fSMike Kravetz 
20767795912cSAndrew Morton /*
2077c0d0381aSMike Kravetz  * Find and lock address space (mapping) in write mode.
2078c0d0381aSMike Kravetz  *
2079336bf30eSMike Kravetz  * Upon entry, the page is locked which means that page_mapping() is
2080336bf30eSMike Kravetz  * stable.  Due to locking order, we can only trylock_write.  If we can
2081336bf30eSMike Kravetz  * not get the lock, simply return NULL to caller.
2082c0d0381aSMike Kravetz  */
hugetlb_page_mapping_lock_write(struct page * hpage)2083c0d0381aSMike Kravetz struct address_space *hugetlb_page_mapping_lock_write(struct page *hpage)
2084c0d0381aSMike Kravetz {
2085336bf30eSMike Kravetz 	struct address_space *mapping = page_mapping(hpage);
2086c0d0381aSMike Kravetz 
2087c0d0381aSMike Kravetz 	if (!mapping)
2088c0d0381aSMike Kravetz 		return mapping;
2089c0d0381aSMike Kravetz 
2090c0d0381aSMike Kravetz 	if (i_mmap_trylock_write(mapping))
2091c0d0381aSMike Kravetz 		return mapping;
2092c0d0381aSMike Kravetz 
2093c0d0381aSMike Kravetz 	return NULL;
2094c0d0381aSMike Kravetz }
2095c0d0381aSMike Kravetz 
hugetlb_basepage_index(struct page * page)2096fe19bd3dSHugh Dickins pgoff_t hugetlb_basepage_index(struct page *page)
209713d60f4bSZhang Yi {
209813d60f4bSZhang Yi 	struct page *page_head = compound_head(page);
209913d60f4bSZhang Yi 	pgoff_t index = page_index(page_head);
210013d60f4bSZhang Yi 	unsigned long compound_idx;
210113d60f4bSZhang Yi 
210223baf831SKirill A. Shutemov 	if (compound_order(page_head) > MAX_ORDER)
210313d60f4bSZhang Yi 		compound_idx = page_to_pfn(page) - page_to_pfn(page_head);
210413d60f4bSZhang Yi 	else
210513d60f4bSZhang Yi 		compound_idx = page - page_head;
210613d60f4bSZhang Yi 
210713d60f4bSZhang Yi 	return (index << compound_order(page_head)) + compound_idx;
210813d60f4bSZhang Yi }
210913d60f4bSZhang Yi 
alloc_buddy_hugetlb_folio(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nmask,nodemask_t * node_alloc_noretry)211019fc1a7eSSidhartha Kumar static struct folio *alloc_buddy_hugetlb_folio(struct hstate *h,
2111f60858f9SMike Kravetz 		gfp_t gfp_mask, int nid, nodemask_t *nmask,
2112f60858f9SMike Kravetz 		nodemask_t *node_alloc_noretry)
21131da177e4SLinus Torvalds {
2114af0fb9dfSMichal Hocko 	int order = huge_page_order(h);
21151da177e4SLinus Torvalds 	struct page *page;
2116f60858f9SMike Kravetz 	bool alloc_try_hard = true;
21172b21624fSMike Kravetz 	bool retry = true;
2118f96efd58SJoe Jin 
2119f60858f9SMike Kravetz 	/*
2120f60858f9SMike Kravetz 	 * By default we always try hard to allocate the page with
2121f60858f9SMike Kravetz 	 * __GFP_RETRY_MAYFAIL flag.  However, if we are allocating pages in
2122f60858f9SMike Kravetz 	 * a loop (to adjust global huge page counts) and previous allocation
2123f60858f9SMike Kravetz 	 * failed, do not continue to try hard on the same node.  Use the
2124f60858f9SMike Kravetz 	 * node_alloc_noretry bitmap to manage this state information.
2125f60858f9SMike Kravetz 	 */
2126f60858f9SMike Kravetz 	if (node_alloc_noretry && node_isset(nid, *node_alloc_noretry))
2127f60858f9SMike Kravetz 		alloc_try_hard = false;
2128f60858f9SMike Kravetz 	gfp_mask |= __GFP_COMP|__GFP_NOWARN;
2129f60858f9SMike Kravetz 	if (alloc_try_hard)
2130f60858f9SMike Kravetz 		gfp_mask |= __GFP_RETRY_MAYFAIL;
2131af0fb9dfSMichal Hocko 	if (nid == NUMA_NO_NODE)
2132af0fb9dfSMichal Hocko 		nid = numa_mem_id();
21332b21624fSMike Kravetz retry:
213484172f4bSMatthew Wilcox (Oracle) 	page = __alloc_pages(gfp_mask, order, nid, nmask);
21352b21624fSMike Kravetz 
21362b21624fSMike Kravetz 	/* Freeze head page */
21372b21624fSMike Kravetz 	if (page && !page_ref_freeze(page, 1)) {
21382b21624fSMike Kravetz 		__free_pages(page, order);
21392b21624fSMike Kravetz 		if (retry) {	/* retry once */
21402b21624fSMike Kravetz 			retry = false;
21412b21624fSMike Kravetz 			goto retry;
21422b21624fSMike Kravetz 		}
21432b21624fSMike Kravetz 		/* WOW!  twice in a row. */
21442b21624fSMike Kravetz 		pr_warn("HugeTLB head page unexpected inflated ref count\n");
21452b21624fSMike Kravetz 		page = NULL;
21462b21624fSMike Kravetz 	}
21472b21624fSMike Kravetz 
2148f60858f9SMike Kravetz 	/*
2149f60858f9SMike Kravetz 	 * If we did not specify __GFP_RETRY_MAYFAIL, but still got a page this
2150f60858f9SMike Kravetz 	 * indicates an overall state change.  Clear bit so that we resume
2151f60858f9SMike Kravetz 	 * normal 'try hard' allocations.
2152f60858f9SMike Kravetz 	 */
2153f60858f9SMike Kravetz 	if (node_alloc_noretry && page && !alloc_try_hard)
2154f60858f9SMike Kravetz 		node_clear(nid, *node_alloc_noretry);
2155f60858f9SMike Kravetz 
2156f60858f9SMike Kravetz 	/*
2157f60858f9SMike Kravetz 	 * If we tried hard to get a page but failed, set bit so that
2158f60858f9SMike Kravetz 	 * subsequent attempts will not try as hard until there is an
2159f60858f9SMike Kravetz 	 * overall state change.
2160f60858f9SMike Kravetz 	 */
2161f60858f9SMike Kravetz 	if (node_alloc_noretry && !page && alloc_try_hard)
2162f60858f9SMike Kravetz 		node_set(nid, *node_alloc_noretry);
2163f60858f9SMike Kravetz 
216419fc1a7eSSidhartha Kumar 	if (!page) {
216519fc1a7eSSidhartha Kumar 		__count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
216619fc1a7eSSidhartha Kumar 		return NULL;
216719fc1a7eSSidhartha Kumar 	}
216819fc1a7eSSidhartha Kumar 
216919fc1a7eSSidhartha Kumar 	__count_vm_event(HTLB_BUDDY_PGALLOC);
217019fc1a7eSSidhartha Kumar 	return page_folio(page);
217163b4613cSNishanth Aravamudan }
217263b4613cSNishanth Aravamudan 
2173af0fb9dfSMichal Hocko /*
21740c397daeSMichal Hocko  * Common helper to allocate a fresh hugetlb page. All specific allocators
21750c397daeSMichal Hocko  * should use this function to get new hugetlb pages
21762b21624fSMike Kravetz  *
21772b21624fSMike Kravetz  * Note that returned page is 'frozen':  ref count of head page and all tail
21782b21624fSMike Kravetz  * pages is zero.
21790c397daeSMichal Hocko  */
alloc_fresh_hugetlb_folio(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nmask,nodemask_t * node_alloc_noretry)218019fc1a7eSSidhartha Kumar static struct folio *alloc_fresh_hugetlb_folio(struct hstate *h,
2181f60858f9SMike Kravetz 		gfp_t gfp_mask, int nid, nodemask_t *nmask,
2182f60858f9SMike Kravetz 		nodemask_t *node_alloc_noretry)
21830c397daeSMichal Hocko {
21847f325a8dSSidhartha Kumar 	struct folio *folio;
21857118fc29SMike Kravetz 	bool retry = false;
21860c397daeSMichal Hocko 
21877118fc29SMike Kravetz retry:
21880c397daeSMichal Hocko 	if (hstate_is_gigantic(h))
218919fc1a7eSSidhartha Kumar 		folio = alloc_gigantic_folio(h, gfp_mask, nid, nmask);
21900c397daeSMichal Hocko 	else
219119fc1a7eSSidhartha Kumar 		folio = alloc_buddy_hugetlb_folio(h, gfp_mask,
2192f60858f9SMike Kravetz 				nid, nmask, node_alloc_noretry);
219319fc1a7eSSidhartha Kumar 	if (!folio)
21940c397daeSMichal Hocko 		return NULL;
21957118fc29SMike Kravetz 	if (hstate_is_gigantic(h)) {
2196d1c60955SSidhartha Kumar 		if (!prep_compound_gigantic_folio(folio, huge_page_order(h))) {
21977118fc29SMike Kravetz 			/*
21987118fc29SMike Kravetz 			 * Rare failure to convert pages to compound page.
21997118fc29SMike Kravetz 			 * Free pages and try again - ONCE!
22007118fc29SMike Kravetz 			 */
22017f325a8dSSidhartha Kumar 			free_gigantic_folio(folio, huge_page_order(h));
22027118fc29SMike Kravetz 			if (!retry) {
22037118fc29SMike Kravetz 				retry = true;
22047118fc29SMike Kravetz 				goto retry;
22057118fc29SMike Kravetz 			}
22067118fc29SMike Kravetz 			return NULL;
22077118fc29SMike Kravetz 		}
22087118fc29SMike Kravetz 	}
2209d1c60955SSidhartha Kumar 	prep_new_hugetlb_folio(h, folio, folio_nid(folio));
22100c397daeSMichal Hocko 
221119fc1a7eSSidhartha Kumar 	return folio;
22120c397daeSMichal Hocko }
22130c397daeSMichal Hocko 
22140c397daeSMichal Hocko /*
2215af0fb9dfSMichal Hocko  * Allocates a fresh page to the hugetlb allocator pool in the node interleaved
2216af0fb9dfSMichal Hocko  * manner.
2217af0fb9dfSMichal Hocko  */
alloc_pool_huge_page(struct hstate * h,nodemask_t * nodes_allowed,nodemask_t * node_alloc_noretry)2218f60858f9SMike Kravetz static int alloc_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed,
2219f60858f9SMike Kravetz 				nodemask_t *node_alloc_noretry)
2220b2261026SJoonsoo Kim {
222119fc1a7eSSidhartha Kumar 	struct folio *folio;
2222b2261026SJoonsoo Kim 	int nr_nodes, node;
2223af0fb9dfSMichal Hocko 	gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
2224b2261026SJoonsoo Kim 
2225b2261026SJoonsoo Kim 	for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
222619fc1a7eSSidhartha Kumar 		folio = alloc_fresh_hugetlb_folio(h, gfp_mask, node,
222719fc1a7eSSidhartha Kumar 					nodes_allowed, node_alloc_noretry);
222819fc1a7eSSidhartha Kumar 		if (folio) {
2229454a00c4SMatthew Wilcox (Oracle) 			free_huge_folio(folio); /* free it into the hugepage allocator */
223019fc1a7eSSidhartha Kumar 			return 1;
223119fc1a7eSSidhartha Kumar 		}
2232b2261026SJoonsoo Kim 	}
2233b2261026SJoonsoo Kim 
2234af0fb9dfSMichal Hocko 	return 0;
2235b2261026SJoonsoo Kim }
2236b2261026SJoonsoo Kim 
2237e8c5c824SLee Schermerhorn /*
223810c6ec49SMike Kravetz  * Remove huge page from pool from next node to free.  Attempt to keep
223910c6ec49SMike Kravetz  * persistent huge pages more or less balanced over allowed nodes.
224010c6ec49SMike Kravetz  * This routine only 'removes' the hugetlb page.  The caller must make
224110c6ec49SMike Kravetz  * an additional call to free the page to low level allocators.
2242e8c5c824SLee Schermerhorn  * Called with hugetlb_lock locked.
2243e8c5c824SLee Schermerhorn  */
remove_pool_huge_page(struct hstate * h,nodemask_t * nodes_allowed,bool acct_surplus)224410c6ec49SMike Kravetz static struct page *remove_pool_huge_page(struct hstate *h,
224510c6ec49SMike Kravetz 						nodemask_t *nodes_allowed,
22466ae11b27SLee Schermerhorn 						 bool acct_surplus)
2247e8c5c824SLee Schermerhorn {
2248b2261026SJoonsoo Kim 	int nr_nodes, node;
224910c6ec49SMike Kravetz 	struct page *page = NULL;
2250cfd5082bSSidhartha Kumar 	struct folio *folio;
2251e8c5c824SLee Schermerhorn 
22529487ca60SMike Kravetz 	lockdep_assert_held(&hugetlb_lock);
2253b2261026SJoonsoo Kim 	for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
2254685f3457SLee Schermerhorn 		/*
2255685f3457SLee Schermerhorn 		 * If we're returning unused surplus pages, only examine
2256685f3457SLee Schermerhorn 		 * nodes with surplus pages.
2257685f3457SLee Schermerhorn 		 */
2258b2261026SJoonsoo Kim 		if ((!acct_surplus || h->surplus_huge_pages_node[node]) &&
2259b2261026SJoonsoo Kim 		    !list_empty(&h->hugepage_freelists[node])) {
226010c6ec49SMike Kravetz 			page = list_entry(h->hugepage_freelists[node].next,
2261e8c5c824SLee Schermerhorn 					  struct page, lru);
2262cfd5082bSSidhartha Kumar 			folio = page_folio(page);
2263cfd5082bSSidhartha Kumar 			remove_hugetlb_folio(h, folio, acct_surplus);
22649a76db09SLee Schermerhorn 			break;
2265e8c5c824SLee Schermerhorn 		}
2266b2261026SJoonsoo Kim 	}
2267e8c5c824SLee Schermerhorn 
226810c6ec49SMike Kravetz 	return page;
2269e8c5c824SLee Schermerhorn }
2270e8c5c824SLee Schermerhorn 
2271c8721bbbSNaoya Horiguchi /*
2272c8721bbbSNaoya Horiguchi  * Dissolve a given free hugepage into free buddy pages. This function does
2273faf53defSNaoya Horiguchi  * nothing for in-use hugepages and non-hugepages.
2274faf53defSNaoya Horiguchi  * This function returns values like below:
2275faf53defSNaoya Horiguchi  *
2276ad2fa371SMuchun Song  *  -ENOMEM: failed to allocate vmemmap pages to free the freed hugepages
2277ad2fa371SMuchun Song  *           when the system is under memory pressure and the feature of
2278ad2fa371SMuchun Song  *           freeing unused vmemmap pages associated with each hugetlb page
2279ad2fa371SMuchun Song  *           is enabled.
2280faf53defSNaoya Horiguchi  *  -EBUSY:  failed to dissolved free hugepages or the hugepage is in-use
2281faf53defSNaoya Horiguchi  *           (allocated or reserved.)
2282faf53defSNaoya Horiguchi  *       0:  successfully dissolved free hugepages or the page is not a
2283faf53defSNaoya Horiguchi  *           hugepage (considered as already dissolved)
2284c8721bbbSNaoya Horiguchi  */
dissolve_free_huge_page(struct page * page)2285c3114a84SAnshuman Khandual int dissolve_free_huge_page(struct page *page)
2286c8721bbbSNaoya Horiguchi {
22876bc9b564SNaoya Horiguchi 	int rc = -EBUSY;
22881a7cdab5SSidhartha Kumar 	struct folio *folio = page_folio(page);
2289082d5b6bSGerald Schaefer 
22907ffddd49SMuchun Song retry:
2291faf53defSNaoya Horiguchi 	/* Not to disrupt normal path by vainly holding hugetlb_lock */
22921a7cdab5SSidhartha Kumar 	if (!folio_test_hugetlb(folio))
2293faf53defSNaoya Horiguchi 		return 0;
2294faf53defSNaoya Horiguchi 
2295db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
22961a7cdab5SSidhartha Kumar 	if (!folio_test_hugetlb(folio)) {
2297faf53defSNaoya Horiguchi 		rc = 0;
2298faf53defSNaoya Horiguchi 		goto out;
2299faf53defSNaoya Horiguchi 	}
2300faf53defSNaoya Horiguchi 
23011a7cdab5SSidhartha Kumar 	if (!folio_ref_count(folio)) {
23021a7cdab5SSidhartha Kumar 		struct hstate *h = folio_hstate(folio);
23038346d69dSXin Hao 		if (!available_huge_pages(h))
2304082d5b6bSGerald Schaefer 			goto out;
23057ffddd49SMuchun Song 
23067ffddd49SMuchun Song 		/*
23077ffddd49SMuchun Song 		 * We should make sure that the page is already on the free list
23087ffddd49SMuchun Song 		 * when it is dissolved.
23097ffddd49SMuchun Song 		 */
23101a7cdab5SSidhartha Kumar 		if (unlikely(!folio_test_hugetlb_freed(folio))) {
2311db71ef79SMike Kravetz 			spin_unlock_irq(&hugetlb_lock);
23127ffddd49SMuchun Song 			cond_resched();
23137ffddd49SMuchun Song 
23147ffddd49SMuchun Song 			/*
23157ffddd49SMuchun Song 			 * Theoretically, we should return -EBUSY when we
23167ffddd49SMuchun Song 			 * encounter this race. In fact, we have a chance
23177ffddd49SMuchun Song 			 * to successfully dissolve the page if we do a
23187ffddd49SMuchun Song 			 * retry. Because the race window is quite small.
23197ffddd49SMuchun Song 			 * If we seize this opportunity, it is an optimization
23207ffddd49SMuchun Song 			 * for increasing the success rate of dissolving page.
23217ffddd49SMuchun Song 			 */
23227ffddd49SMuchun Song 			goto retry;
23237ffddd49SMuchun Song 		}
23247ffddd49SMuchun Song 
2325cfd5082bSSidhartha Kumar 		remove_hugetlb_folio(h, folio, false);
2326ad2fa371SMuchun Song 		h->max_huge_pages--;
2327ad2fa371SMuchun Song 		spin_unlock_irq(&hugetlb_lock);
2328ad2fa371SMuchun Song 
2329c3114a84SAnshuman Khandual 		/*
2330d6ef19e2SSidhartha Kumar 		 * Normally update_and_free_hugtlb_folio will allocate required vmemmmap
2331d6ef19e2SSidhartha Kumar 		 * before freeing the page.  update_and_free_hugtlb_folio will fail to
2332ad2fa371SMuchun Song 		 * free the page if it can not allocate required vmemmap.  We
2333ad2fa371SMuchun Song 		 * need to adjust max_huge_pages if the page is not freed.
2334ad2fa371SMuchun Song 		 * Attempt to allocate vmemmmap here so that we can take
2335ad2fa371SMuchun Song 		 * appropriate action on failure.
2336ad2fa371SMuchun Song 		 */
23371a7cdab5SSidhartha Kumar 		rc = hugetlb_vmemmap_restore(h, &folio->page);
2338ad2fa371SMuchun Song 		if (!rc) {
2339d6ef19e2SSidhartha Kumar 			update_and_free_hugetlb_folio(h, folio, false);
2340ad2fa371SMuchun Song 		} else {
2341ad2fa371SMuchun Song 			spin_lock_irq(&hugetlb_lock);
23422f6c57d6SSidhartha Kumar 			add_hugetlb_folio(h, folio, false);
2343ad2fa371SMuchun Song 			h->max_huge_pages++;
2344ad2fa371SMuchun Song 			spin_unlock_irq(&hugetlb_lock);
2345ad2fa371SMuchun Song 		}
2346ad2fa371SMuchun Song 
2347ad2fa371SMuchun Song 		return rc;
2348c8721bbbSNaoya Horiguchi 	}
2349082d5b6bSGerald Schaefer out:
2350db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
2351082d5b6bSGerald Schaefer 	return rc;
2352c8721bbbSNaoya Horiguchi }
2353c8721bbbSNaoya Horiguchi 
2354c8721bbbSNaoya Horiguchi /*
2355c8721bbbSNaoya Horiguchi  * Dissolve free hugepages in a given pfn range. Used by memory hotplug to
2356c8721bbbSNaoya Horiguchi  * make specified memory blocks removable from the system.
23572247bb33SGerald Schaefer  * Note that this will dissolve a free gigantic hugepage completely, if any
23582247bb33SGerald Schaefer  * part of it lies within the given range.
2359082d5b6bSGerald Schaefer  * Also note that if dissolve_free_huge_page() returns with an error, all
2360082d5b6bSGerald Schaefer  * free hugepages that were dissolved before that error are lost.
2361c8721bbbSNaoya Horiguchi  */
dissolve_free_huge_pages(unsigned long start_pfn,unsigned long end_pfn)2362082d5b6bSGerald Schaefer int dissolve_free_huge_pages(unsigned long start_pfn, unsigned long end_pfn)
2363c8721bbbSNaoya Horiguchi {
2364c8721bbbSNaoya Horiguchi 	unsigned long pfn;
2365eb03aa00SGerald Schaefer 	struct page *page;
2366082d5b6bSGerald Schaefer 	int rc = 0;
2367dc2628f3SMuchun Song 	unsigned int order;
2368dc2628f3SMuchun Song 	struct hstate *h;
2369c8721bbbSNaoya Horiguchi 
2370d0177639SLi Zhong 	if (!hugepages_supported())
2371082d5b6bSGerald Schaefer 		return rc;
2372d0177639SLi Zhong 
2373dc2628f3SMuchun Song 	order = huge_page_order(&default_hstate);
2374dc2628f3SMuchun Song 	for_each_hstate(h)
2375dc2628f3SMuchun Song 		order = min(order, huge_page_order(h));
2376dc2628f3SMuchun Song 
2377dc2628f3SMuchun Song 	for (pfn = start_pfn; pfn < end_pfn; pfn += 1 << order) {
2378eb03aa00SGerald Schaefer 		page = pfn_to_page(pfn);
2379eb03aa00SGerald Schaefer 		rc = dissolve_free_huge_page(page);
2380eb03aa00SGerald Schaefer 		if (rc)
2381082d5b6bSGerald Schaefer 			break;
2382eb03aa00SGerald Schaefer 	}
2383082d5b6bSGerald Schaefer 
2384082d5b6bSGerald Schaefer 	return rc;
2385c8721bbbSNaoya Horiguchi }
2386c8721bbbSNaoya Horiguchi 
2387ab5ac90aSMichal Hocko /*
2388ab5ac90aSMichal Hocko  * Allocates a fresh surplus page from the page allocator.
2389ab5ac90aSMichal Hocko  */
alloc_surplus_hugetlb_folio(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nmask)23903a740e8bSSidhartha Kumar static struct folio *alloc_surplus_hugetlb_folio(struct hstate *h,
23913a740e8bSSidhartha Kumar 				gfp_t gfp_mask,	int nid, nodemask_t *nmask)
23927893d1d5SAdam Litke {
239319fc1a7eSSidhartha Kumar 	struct folio *folio = NULL;
23947893d1d5SAdam Litke 
2395bae7f4aeSLuiz Capitulino 	if (hstate_is_gigantic(h))
2396aa888a74SAndi Kleen 		return NULL;
2397aa888a74SAndi Kleen 
2398db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
23999980d744SMichal Hocko 	if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages)
24009980d744SMichal Hocko 		goto out_unlock;
2401db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
2402d1c3fb1fSNishanth Aravamudan 
240319fc1a7eSSidhartha Kumar 	folio = alloc_fresh_hugetlb_folio(h, gfp_mask, nid, nmask, NULL);
240419fc1a7eSSidhartha Kumar 	if (!folio)
24050c397daeSMichal Hocko 		return NULL;
2406d1c3fb1fSNishanth Aravamudan 
2407db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
24089980d744SMichal Hocko 	/*
24099980d744SMichal Hocko 	 * We could have raced with the pool size change.
24109980d744SMichal Hocko 	 * Double check that and simply deallocate the new page
24119980d744SMichal Hocko 	 * if we would end up overcommiting the surpluses. Abuse
2412454a00c4SMatthew Wilcox (Oracle) 	 * temporary page to workaround the nasty free_huge_folio
24139980d744SMichal Hocko 	 * codeflow
24149980d744SMichal Hocko 	 */
24159980d744SMichal Hocko 	if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) {
241619fc1a7eSSidhartha Kumar 		folio_set_hugetlb_temporary(folio);
2417db71ef79SMike Kravetz 		spin_unlock_irq(&hugetlb_lock);
2418454a00c4SMatthew Wilcox (Oracle) 		free_huge_folio(folio);
24192bf753e6SKai Shen 		return NULL;
2420b65a4edaSMike Kravetz 	}
2421b65a4edaSMike Kravetz 
24229980d744SMichal Hocko 	h->surplus_huge_pages++;
242319fc1a7eSSidhartha Kumar 	h->surplus_huge_pages_node[folio_nid(folio)]++;
24249980d744SMichal Hocko 
24259980d744SMichal Hocko out_unlock:
2426db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
24277893d1d5SAdam Litke 
24283a740e8bSSidhartha Kumar 	return folio;
24297893d1d5SAdam Litke }
24307893d1d5SAdam Litke 
alloc_migrate_hugetlb_folio(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nmask)2431e37d3e83SSidhartha Kumar static struct folio *alloc_migrate_hugetlb_folio(struct hstate *h, gfp_t gfp_mask,
2432ab5ac90aSMichal Hocko 				     int nid, nodemask_t *nmask)
2433ab5ac90aSMichal Hocko {
243419fc1a7eSSidhartha Kumar 	struct folio *folio;
2435ab5ac90aSMichal Hocko 
2436ab5ac90aSMichal Hocko 	if (hstate_is_gigantic(h))
2437ab5ac90aSMichal Hocko 		return NULL;
2438ab5ac90aSMichal Hocko 
243919fc1a7eSSidhartha Kumar 	folio = alloc_fresh_hugetlb_folio(h, gfp_mask, nid, nmask, NULL);
244019fc1a7eSSidhartha Kumar 	if (!folio)
2441ab5ac90aSMichal Hocko 		return NULL;
2442ab5ac90aSMichal Hocko 
24432b21624fSMike Kravetz 	/* fresh huge pages are frozen */
244419fc1a7eSSidhartha Kumar 	folio_ref_unfreeze(folio, 1);
2445ab5ac90aSMichal Hocko 	/*
2446ab5ac90aSMichal Hocko 	 * We do not account these pages as surplus because they are only
2447ab5ac90aSMichal Hocko 	 * temporary and will be released properly on the last reference
2448ab5ac90aSMichal Hocko 	 */
244919fc1a7eSSidhartha Kumar 	folio_set_hugetlb_temporary(folio);
2450ab5ac90aSMichal Hocko 
2451e37d3e83SSidhartha Kumar 	return folio;
2452ab5ac90aSMichal Hocko }
2453ab5ac90aSMichal Hocko 
2454e4e574b7SAdam Litke /*
2455099730d6SDave Hansen  * Use the VMA's mpolicy to allocate a huge page from the buddy.
2456099730d6SDave Hansen  */
2457e0ec90eeSDave Hansen static
alloc_buddy_hugetlb_folio_with_mpol(struct hstate * h,struct vm_area_struct * vma,unsigned long addr)2458ff7d853bSSidhartha Kumar struct folio *alloc_buddy_hugetlb_folio_with_mpol(struct hstate *h,
2459099730d6SDave Hansen 		struct vm_area_struct *vma, unsigned long addr)
2460099730d6SDave Hansen {
24613a740e8bSSidhartha Kumar 	struct folio *folio = NULL;
2462aaf14e40SMichal Hocko 	struct mempolicy *mpol;
2463aaf14e40SMichal Hocko 	gfp_t gfp_mask = htlb_alloc_mask(h);
2464aaf14e40SMichal Hocko 	int nid;
2465aaf14e40SMichal Hocko 	nodemask_t *nodemask;
2466aaf14e40SMichal Hocko 
2467aaf14e40SMichal Hocko 	nid = huge_node(vma, addr, gfp_mask, &mpol, &nodemask);
2468cfcaa66fSBen Widawsky 	if (mpol_is_preferred_many(mpol)) {
2469cfcaa66fSBen Widawsky 		gfp_t gfp = gfp_mask | __GFP_NOWARN;
2470cfcaa66fSBen Widawsky 
2471cfcaa66fSBen Widawsky 		gfp &=  ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
24723a740e8bSSidhartha Kumar 		folio = alloc_surplus_hugetlb_folio(h, gfp, nid, nodemask);
2473cfcaa66fSBen Widawsky 
2474cfcaa66fSBen Widawsky 		/* Fallback to all nodes if page==NULL */
2475cfcaa66fSBen Widawsky 		nodemask = NULL;
2476cfcaa66fSBen Widawsky 	}
2477cfcaa66fSBen Widawsky 
24783a740e8bSSidhartha Kumar 	if (!folio)
24793a740e8bSSidhartha Kumar 		folio = alloc_surplus_hugetlb_folio(h, gfp_mask, nid, nodemask);
2480aaf14e40SMichal Hocko 	mpol_cond_put(mpol);
2481ff7d853bSSidhartha Kumar 	return folio;
2482099730d6SDave Hansen }
2483099730d6SDave Hansen 
2484e37d3e83SSidhartha Kumar /* folio migration callback function */
alloc_hugetlb_folio_nodemask(struct hstate * h,int preferred_nid,nodemask_t * nmask,gfp_t gfp_mask)2485e37d3e83SSidhartha Kumar struct folio *alloc_hugetlb_folio_nodemask(struct hstate *h, int preferred_nid,
2486d92bbc27SJoonsoo Kim 		nodemask_t *nmask, gfp_t gfp_mask)
24874db9b2efSMichal Hocko {
2488db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
24898346d69dSXin Hao 	if (available_huge_pages(h)) {
2490a36f1e90SSidhartha Kumar 		struct folio *folio;
24913e59fcb0SMichal Hocko 
2492a36f1e90SSidhartha Kumar 		folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask,
2493a36f1e90SSidhartha Kumar 						preferred_nid, nmask);
2494a36f1e90SSidhartha Kumar 		if (folio) {
2495db71ef79SMike Kravetz 			spin_unlock_irq(&hugetlb_lock);
2496e37d3e83SSidhartha Kumar 			return folio;
24974db9b2efSMichal Hocko 		}
24984db9b2efSMichal Hocko 	}
2499db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
25004db9b2efSMichal Hocko 
2501e37d3e83SSidhartha Kumar 	return alloc_migrate_hugetlb_folio(h, gfp_mask, preferred_nid, nmask);
25024db9b2efSMichal Hocko }
25034db9b2efSMichal Hocko 
2504ebd63723SMichal Hocko /* mempolicy aware migration callback */
alloc_hugetlb_folio_vma(struct hstate * h,struct vm_area_struct * vma,unsigned long address)2505d0ce0e47SSidhartha Kumar struct folio *alloc_hugetlb_folio_vma(struct hstate *h, struct vm_area_struct *vma,
2506389c8178SMichal Hocko 		unsigned long address)
2507ebd63723SMichal Hocko {
2508ebd63723SMichal Hocko 	struct mempolicy *mpol;
2509ebd63723SMichal Hocko 	nodemask_t *nodemask;
2510e37d3e83SSidhartha Kumar 	struct folio *folio;
2511ebd63723SMichal Hocko 	gfp_t gfp_mask;
2512ebd63723SMichal Hocko 	int node;
2513ebd63723SMichal Hocko 
2514ebd63723SMichal Hocko 	gfp_mask = htlb_alloc_mask(h);
2515ebd63723SMichal Hocko 	node = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
2516e37d3e83SSidhartha Kumar 	folio = alloc_hugetlb_folio_nodemask(h, node, nodemask, gfp_mask);
2517ebd63723SMichal Hocko 	mpol_cond_put(mpol);
2518ebd63723SMichal Hocko 
2519d0ce0e47SSidhartha Kumar 	return folio;
2520ebd63723SMichal Hocko }
2521ebd63723SMichal Hocko 
policy_mbind_nodemask(gfp_t gfp)2522c311d651SAristeu Rozanski static nodemask_t *policy_mbind_nodemask(gfp_t gfp)
2523c311d651SAristeu Rozanski {
2524c311d651SAristeu Rozanski #ifdef CONFIG_NUMA
2525c311d651SAristeu Rozanski 	struct mempolicy *mpol = get_task_policy(current);
2526c311d651SAristeu Rozanski 
2527c311d651SAristeu Rozanski 	/*
2528c311d651SAristeu Rozanski 	 * Only enforce MPOL_BIND policy which overlaps with cpuset policy
2529c311d651SAristeu Rozanski 	 * (from policy_nodemask) specifically for hugetlb case
2530c311d651SAristeu Rozanski 	 */
2531c311d651SAristeu Rozanski 	if (mpol->mode == MPOL_BIND &&
2532c311d651SAristeu Rozanski 		(apply_policy_zone(mpol, gfp_zone(gfp)) &&
2533c311d651SAristeu Rozanski 		 cpuset_nodemask_valid_mems_allowed(&mpol->nodes)))
2534c311d651SAristeu Rozanski 		return &mpol->nodes;
2535c311d651SAristeu Rozanski #endif
2536c311d651SAristeu Rozanski 	return NULL;
2537c311d651SAristeu Rozanski }
2538c311d651SAristeu Rozanski 
2539bf50bab2SNaoya Horiguchi /*
254025985edcSLucas De Marchi  * Increase the hugetlb pool such that it can accommodate a reservation
2541e4e574b7SAdam Litke  * of size 'delta'.
2542e4e574b7SAdam Litke  */
gather_surplus_pages(struct hstate * h,long delta)25430a4f3d1bSLiu Xiang static int gather_surplus_pages(struct hstate *h, long delta)
25441b2a1e7bSJules Irenge 	__must_hold(&hugetlb_lock)
2545e4e574b7SAdam Litke {
254634665341SMiaohe Lin 	LIST_HEAD(surplus_list);
2547454a00c4SMatthew Wilcox (Oracle) 	struct folio *folio, *tmp;
25480a4f3d1bSLiu Xiang 	int ret;
25490a4f3d1bSLiu Xiang 	long i;
25500a4f3d1bSLiu Xiang 	long needed, allocated;
255128073b02SHillf Danton 	bool alloc_ok = true;
2552c311d651SAristeu Rozanski 	int node;
2553c311d651SAristeu Rozanski 	nodemask_t *mbind_nodemask = policy_mbind_nodemask(htlb_alloc_mask(h));
2554e4e574b7SAdam Litke 
25559487ca60SMike Kravetz 	lockdep_assert_held(&hugetlb_lock);
2556a5516438SAndi Kleen 	needed = (h->resv_huge_pages + delta) - h->free_huge_pages;
2557ac09b3a1SAdam Litke 	if (needed <= 0) {
2558a5516438SAndi Kleen 		h->resv_huge_pages += delta;
2559e4e574b7SAdam Litke 		return 0;
2560ac09b3a1SAdam Litke 	}
2561e4e574b7SAdam Litke 
2562e4e574b7SAdam Litke 	allocated = 0;
2563e4e574b7SAdam Litke 
2564e4e574b7SAdam Litke 	ret = -ENOMEM;
2565e4e574b7SAdam Litke retry:
2566db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
2567e4e574b7SAdam Litke 	for (i = 0; i < needed; i++) {
2568c311d651SAristeu Rozanski 		folio = NULL;
2569c311d651SAristeu Rozanski 		for_each_node_mask(node, cpuset_current_mems_allowed) {
2570c311d651SAristeu Rozanski 			if (!mbind_nodemask || node_isset(node, *mbind_nodemask)) {
25713a740e8bSSidhartha Kumar 				folio = alloc_surplus_hugetlb_folio(h, htlb_alloc_mask(h),
2572c311d651SAristeu Rozanski 						node, NULL);
2573c311d651SAristeu Rozanski 				if (folio)
2574c311d651SAristeu Rozanski 					break;
2575c311d651SAristeu Rozanski 			}
2576c311d651SAristeu Rozanski 		}
25773a740e8bSSidhartha Kumar 		if (!folio) {
257828073b02SHillf Danton 			alloc_ok = false;
257928073b02SHillf Danton 			break;
258028073b02SHillf Danton 		}
25813a740e8bSSidhartha Kumar 		list_add(&folio->lru, &surplus_list);
258269ed779aSDavid Rientjes 		cond_resched();
2583e4e574b7SAdam Litke 	}
258428073b02SHillf Danton 	allocated += i;
2585e4e574b7SAdam Litke 
2586e4e574b7SAdam Litke 	/*
2587e4e574b7SAdam Litke 	 * After retaking hugetlb_lock, we need to recalculate 'needed'
2588e4e574b7SAdam Litke 	 * because either resv_huge_pages or free_huge_pages may have changed.
2589e4e574b7SAdam Litke 	 */
2590db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
2591a5516438SAndi Kleen 	needed = (h->resv_huge_pages + delta) -
2592a5516438SAndi Kleen 			(h->free_huge_pages + allocated);
259328073b02SHillf Danton 	if (needed > 0) {
259428073b02SHillf Danton 		if (alloc_ok)
2595e4e574b7SAdam Litke 			goto retry;
259628073b02SHillf Danton 		/*
259728073b02SHillf Danton 		 * We were not able to allocate enough pages to
259828073b02SHillf Danton 		 * satisfy the entire reservation so we free what
259928073b02SHillf Danton 		 * we've allocated so far.
260028073b02SHillf Danton 		 */
260128073b02SHillf Danton 		goto free;
260228073b02SHillf Danton 	}
2603e4e574b7SAdam Litke 	/*
2604e4e574b7SAdam Litke 	 * The surplus_list now contains _at_least_ the number of extra pages
260525985edcSLucas De Marchi 	 * needed to accommodate the reservation.  Add the appropriate number
2606e4e574b7SAdam Litke 	 * of pages to the hugetlb pool and free the extras back to the buddy
2607ac09b3a1SAdam Litke 	 * allocator.  Commit the entire reservation here to prevent another
2608ac09b3a1SAdam Litke 	 * process from stealing the pages as they are added to the pool but
2609ac09b3a1SAdam Litke 	 * before they are reserved.
2610e4e574b7SAdam Litke 	 */
2611e4e574b7SAdam Litke 	needed += allocated;
2612a5516438SAndi Kleen 	h->resv_huge_pages += delta;
2613e4e574b7SAdam Litke 	ret = 0;
2614a9869b83SNaoya Horiguchi 
261519fc3f0aSAdam Litke 	/* Free the needed pages to the hugetlb pool */
2616454a00c4SMatthew Wilcox (Oracle) 	list_for_each_entry_safe(folio, tmp, &surplus_list, lru) {
261719fc3f0aSAdam Litke 		if ((--needed) < 0)
261819fc3f0aSAdam Litke 			break;
2619b65a4edaSMike Kravetz 		/* Add the page to the hugetlb allocator */
2620454a00c4SMatthew Wilcox (Oracle) 		enqueue_hugetlb_folio(h, folio);
262119fc3f0aSAdam Litke 	}
262228073b02SHillf Danton free:
2623db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
262419fc3f0aSAdam Litke 
2625b65a4edaSMike Kravetz 	/*
2626b65a4edaSMike Kravetz 	 * Free unnecessary surplus pages to the buddy allocator.
2627454a00c4SMatthew Wilcox (Oracle) 	 * Pages have no ref count, call free_huge_folio directly.
2628b65a4edaSMike Kravetz 	 */
2629454a00c4SMatthew Wilcox (Oracle) 	list_for_each_entry_safe(folio, tmp, &surplus_list, lru)
2630454a00c4SMatthew Wilcox (Oracle) 		free_huge_folio(folio);
2631db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
2632e4e574b7SAdam Litke 
2633e4e574b7SAdam Litke 	return ret;
2634e4e574b7SAdam Litke }
2635e4e574b7SAdam Litke 
2636e4e574b7SAdam Litke /*
2637e5bbc8a6SMike Kravetz  * This routine has two main purposes:
2638e5bbc8a6SMike Kravetz  * 1) Decrement the reservation count (resv_huge_pages) by the value passed
2639e5bbc8a6SMike Kravetz  *    in unused_resv_pages.  This corresponds to the prior adjustments made
2640e5bbc8a6SMike Kravetz  *    to the associated reservation map.
2641e5bbc8a6SMike Kravetz  * 2) Free any unused surplus pages that may have been allocated to satisfy
2642e5bbc8a6SMike Kravetz  *    the reservation.  As many as unused_resv_pages may be freed.
2643e4e574b7SAdam Litke  */
return_unused_surplus_pages(struct hstate * h,unsigned long unused_resv_pages)2644a5516438SAndi Kleen static void return_unused_surplus_pages(struct hstate *h,
2645a5516438SAndi Kleen 					unsigned long unused_resv_pages)
2646e4e574b7SAdam Litke {
2647e4e574b7SAdam Litke 	unsigned long nr_pages;
264810c6ec49SMike Kravetz 	struct page *page;
264910c6ec49SMike Kravetz 	LIST_HEAD(page_list);
265010c6ec49SMike Kravetz 
26519487ca60SMike Kravetz 	lockdep_assert_held(&hugetlb_lock);
265210c6ec49SMike Kravetz 	/* Uncommit the reservation */
265310c6ec49SMike Kravetz 	h->resv_huge_pages -= unused_resv_pages;
2654e4e574b7SAdam Litke 
2655c0531714SNaoya Horiguchi 	if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
2656e5bbc8a6SMike Kravetz 		goto out;
2657aa888a74SAndi Kleen 
2658e5bbc8a6SMike Kravetz 	/*
2659e5bbc8a6SMike Kravetz 	 * Part (or even all) of the reservation could have been backed
2660e5bbc8a6SMike Kravetz 	 * by pre-allocated pages. Only free surplus pages.
2661e5bbc8a6SMike Kravetz 	 */
2662a5516438SAndi Kleen 	nr_pages = min(unused_resv_pages, h->surplus_huge_pages);
2663e4e574b7SAdam Litke 
2664685f3457SLee Schermerhorn 	/*
2665685f3457SLee Schermerhorn 	 * We want to release as many surplus pages as possible, spread
26669b5e5d0fSLee Schermerhorn 	 * evenly across all nodes with memory. Iterate across these nodes
26679b5e5d0fSLee Schermerhorn 	 * until we can no longer free unreserved surplus pages. This occurs
26689b5e5d0fSLee Schermerhorn 	 * when the nodes with surplus pages have no free pages.
266910c6ec49SMike Kravetz 	 * remove_pool_huge_page() will balance the freed pages across the
26709b5e5d0fSLee Schermerhorn 	 * on-line nodes with memory and will handle the hstate accounting.
2671685f3457SLee Schermerhorn 	 */
2672685f3457SLee Schermerhorn 	while (nr_pages--) {
267310c6ec49SMike Kravetz 		page = remove_pool_huge_page(h, &node_states[N_MEMORY], 1);
267410c6ec49SMike Kravetz 		if (!page)
2675e5bbc8a6SMike Kravetz 			goto out;
267610c6ec49SMike Kravetz 
267710c6ec49SMike Kravetz 		list_add(&page->lru, &page_list);
2678e4e574b7SAdam Litke 	}
2679e5bbc8a6SMike Kravetz 
2680e5bbc8a6SMike Kravetz out:
2681db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
268210c6ec49SMike Kravetz 	update_and_free_pages_bulk(h, &page_list);
2683db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
2684e4e574b7SAdam Litke }
2685e4e574b7SAdam Litke 
26865e911373SMike Kravetz 
2687c37f9fb1SAndy Whitcroft /*
2688feba16e2SMike Kravetz  * vma_needs_reservation, vma_commit_reservation and vma_end_reservation
26895e911373SMike Kravetz  * are used by the huge page allocation routines to manage reservations.
2690cf3ad20bSMike Kravetz  *
2691cf3ad20bSMike Kravetz  * vma_needs_reservation is called to determine if the huge page at addr
2692cf3ad20bSMike Kravetz  * within the vma has an associated reservation.  If a reservation is
2693cf3ad20bSMike Kravetz  * needed, the value 1 is returned.  The caller is then responsible for
2694cf3ad20bSMike Kravetz  * managing the global reservation and subpool usage counts.  After
2695cf3ad20bSMike Kravetz  * the huge page has been allocated, vma_commit_reservation is called
2696feba16e2SMike Kravetz  * to add the page to the reservation map.  If the page allocation fails,
2697feba16e2SMike Kravetz  * the reservation must be ended instead of committed.  vma_end_reservation
2698feba16e2SMike Kravetz  * is called in such cases.
2699cf3ad20bSMike Kravetz  *
2700cf3ad20bSMike Kravetz  * In the normal case, vma_commit_reservation returns the same value
2701cf3ad20bSMike Kravetz  * as the preceding vma_needs_reservation call.  The only time this
2702cf3ad20bSMike Kravetz  * is not the case is if a reserve map was changed between calls.  It
2703cf3ad20bSMike Kravetz  * is the responsibility of the caller to notice the difference and
2704cf3ad20bSMike Kravetz  * take appropriate action.
270596b96a96SMike Kravetz  *
270696b96a96SMike Kravetz  * vma_add_reservation is used in error paths where a reservation must
270796b96a96SMike Kravetz  * be restored when a newly allocated huge page must be freed.  It is
270896b96a96SMike Kravetz  * to be called after calling vma_needs_reservation to determine if a
270996b96a96SMike Kravetz  * reservation exists.
2710846be085SMike Kravetz  *
2711846be085SMike Kravetz  * vma_del_reservation is used in error paths where an entry in the reserve
2712846be085SMike Kravetz  * map was created during huge page allocation and must be removed.  It is to
2713846be085SMike Kravetz  * be called after calling vma_needs_reservation to determine if a reservation
2714846be085SMike Kravetz  * exists.
2715c37f9fb1SAndy Whitcroft  */
27165e911373SMike Kravetz enum vma_resv_mode {
27175e911373SMike Kravetz 	VMA_NEEDS_RESV,
27185e911373SMike Kravetz 	VMA_COMMIT_RESV,
2719feba16e2SMike Kravetz 	VMA_END_RESV,
272096b96a96SMike Kravetz 	VMA_ADD_RESV,
2721846be085SMike Kravetz 	VMA_DEL_RESV,
27225e911373SMike Kravetz };
__vma_reservation_common(struct hstate * h,struct vm_area_struct * vma,unsigned long addr,enum vma_resv_mode mode)2723cf3ad20bSMike Kravetz static long __vma_reservation_common(struct hstate *h,
2724cf3ad20bSMike Kravetz 				struct vm_area_struct *vma, unsigned long addr,
27255e911373SMike Kravetz 				enum vma_resv_mode mode)
2726c37f9fb1SAndy Whitcroft {
27274e35f483SJoonsoo Kim 	struct resv_map *resv;
27284e35f483SJoonsoo Kim 	pgoff_t idx;
2729cf3ad20bSMike Kravetz 	long ret;
27300db9d74eSMina Almasry 	long dummy_out_regions_needed;
2731c37f9fb1SAndy Whitcroft 
27324e35f483SJoonsoo Kim 	resv = vma_resv_map(vma);
27334e35f483SJoonsoo Kim 	if (!resv)
2734c37f9fb1SAndy Whitcroft 		return 1;
2735c37f9fb1SAndy Whitcroft 
27364e35f483SJoonsoo Kim 	idx = vma_hugecache_offset(h, vma, addr);
27375e911373SMike Kravetz 	switch (mode) {
27385e911373SMike Kravetz 	case VMA_NEEDS_RESV:
27390db9d74eSMina Almasry 		ret = region_chg(resv, idx, idx + 1, &dummy_out_regions_needed);
27400db9d74eSMina Almasry 		/* We assume that vma_reservation_* routines always operate on
27410db9d74eSMina Almasry 		 * 1 page, and that adding to resv map a 1 page entry can only
27420db9d74eSMina Almasry 		 * ever require 1 region.
27430db9d74eSMina Almasry 		 */
27440db9d74eSMina Almasry 		VM_BUG_ON(dummy_out_regions_needed != 1);
27455e911373SMike Kravetz 		break;
27465e911373SMike Kravetz 	case VMA_COMMIT_RESV:
2747075a61d0SMina Almasry 		ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
27480db9d74eSMina Almasry 		/* region_add calls of range 1 should never fail. */
27490db9d74eSMina Almasry 		VM_BUG_ON(ret < 0);
27505e911373SMike Kravetz 		break;
2751feba16e2SMike Kravetz 	case VMA_END_RESV:
27520db9d74eSMina Almasry 		region_abort(resv, idx, idx + 1, 1);
27535e911373SMike Kravetz 		ret = 0;
27545e911373SMike Kravetz 		break;
275596b96a96SMike Kravetz 	case VMA_ADD_RESV:
27560db9d74eSMina Almasry 		if (vma->vm_flags & VM_MAYSHARE) {
2757075a61d0SMina Almasry 			ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
27580db9d74eSMina Almasry 			/* region_add calls of range 1 should never fail. */
27590db9d74eSMina Almasry 			VM_BUG_ON(ret < 0);
27600db9d74eSMina Almasry 		} else {
27610db9d74eSMina Almasry 			region_abort(resv, idx, idx + 1, 1);
276296b96a96SMike Kravetz 			ret = region_del(resv, idx, idx + 1);
276396b96a96SMike Kravetz 		}
276496b96a96SMike Kravetz 		break;
2765846be085SMike Kravetz 	case VMA_DEL_RESV:
2766846be085SMike Kravetz 		if (vma->vm_flags & VM_MAYSHARE) {
2767846be085SMike Kravetz 			region_abort(resv, idx, idx + 1, 1);
2768846be085SMike Kravetz 			ret = region_del(resv, idx, idx + 1);
2769846be085SMike Kravetz 		} else {
2770846be085SMike Kravetz 			ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2771846be085SMike Kravetz 			/* region_add calls of range 1 should never fail. */
2772846be085SMike Kravetz 			VM_BUG_ON(ret < 0);
2773846be085SMike Kravetz 		}
2774846be085SMike Kravetz 		break;
27755e911373SMike Kravetz 	default:
27765e911373SMike Kravetz 		BUG();
27775e911373SMike Kravetz 	}
277884afd99bSAndy Whitcroft 
2779846be085SMike Kravetz 	if (vma->vm_flags & VM_MAYSHARE || mode == VMA_DEL_RESV)
2780cf3ad20bSMike Kravetz 		return ret;
278167961f9dSMike Kravetz 	/*
2782bf3d12b9SMiaohe Lin 	 * We know private mapping must have HPAGE_RESV_OWNER set.
2783bf3d12b9SMiaohe Lin 	 *
278467961f9dSMike Kravetz 	 * In most cases, reserves always exist for private mappings.
278567961f9dSMike Kravetz 	 * However, a file associated with mapping could have been
278667961f9dSMike Kravetz 	 * hole punched or truncated after reserves were consumed.
278767961f9dSMike Kravetz 	 * As subsequent fault on such a range will not use reserves.
278867961f9dSMike Kravetz 	 * Subtle - The reserve map for private mappings has the
278967961f9dSMike Kravetz 	 * opposite meaning than that of shared mappings.  If NO
279067961f9dSMike Kravetz 	 * entry is in the reserve map, it means a reservation exists.
279167961f9dSMike Kravetz 	 * If an entry exists in the reserve map, it means the
279267961f9dSMike Kravetz 	 * reservation has already been consumed.  As a result, the
279367961f9dSMike Kravetz 	 * return value of this routine is the opposite of the
279467961f9dSMike Kravetz 	 * value returned from reserve map manipulation routines above.
279567961f9dSMike Kravetz 	 */
2796bf3d12b9SMiaohe Lin 	if (ret > 0)
279767961f9dSMike Kravetz 		return 0;
2798bf3d12b9SMiaohe Lin 	if (ret == 0)
279967961f9dSMike Kravetz 		return 1;
2800bf3d12b9SMiaohe Lin 	return ret;
280184afd99bSAndy Whitcroft }
2802cf3ad20bSMike Kravetz 
vma_needs_reservation(struct hstate * h,struct vm_area_struct * vma,unsigned long addr)2803cf3ad20bSMike Kravetz static long vma_needs_reservation(struct hstate *h,
2804a5516438SAndi Kleen 			struct vm_area_struct *vma, unsigned long addr)
2805c37f9fb1SAndy Whitcroft {
28065e911373SMike Kravetz 	return __vma_reservation_common(h, vma, addr, VMA_NEEDS_RESV);
2807cf3ad20bSMike Kravetz }
2808c37f9fb1SAndy Whitcroft 
vma_commit_reservation(struct hstate * h,struct vm_area_struct * vma,unsigned long addr)2809cf3ad20bSMike Kravetz static long vma_commit_reservation(struct hstate *h,
2810cf3ad20bSMike Kravetz 			struct vm_area_struct *vma, unsigned long addr)
2811cf3ad20bSMike Kravetz {
28125e911373SMike Kravetz 	return __vma_reservation_common(h, vma, addr, VMA_COMMIT_RESV);
28135e911373SMike Kravetz }
28145e911373SMike Kravetz 
vma_end_reservation(struct hstate * h,struct vm_area_struct * vma,unsigned long addr)2815feba16e2SMike Kravetz static void vma_end_reservation(struct hstate *h,
28165e911373SMike Kravetz 			struct vm_area_struct *vma, unsigned long addr)
28175e911373SMike Kravetz {
2818feba16e2SMike Kravetz 	(void)__vma_reservation_common(h, vma, addr, VMA_END_RESV);
2819c37f9fb1SAndy Whitcroft }
2820c37f9fb1SAndy Whitcroft 
vma_add_reservation(struct hstate * h,struct vm_area_struct * vma,unsigned long addr)282196b96a96SMike Kravetz static long vma_add_reservation(struct hstate *h,
282296b96a96SMike Kravetz 			struct vm_area_struct *vma, unsigned long addr)
282396b96a96SMike Kravetz {
282496b96a96SMike Kravetz 	return __vma_reservation_common(h, vma, addr, VMA_ADD_RESV);
282596b96a96SMike Kravetz }
282696b96a96SMike Kravetz 
vma_del_reservation(struct hstate * h,struct vm_area_struct * vma,unsigned long addr)2827846be085SMike Kravetz static long vma_del_reservation(struct hstate *h,
2828846be085SMike Kravetz 			struct vm_area_struct *vma, unsigned long addr)
282996b96a96SMike Kravetz {
2830846be085SMike Kravetz 	return __vma_reservation_common(h, vma, addr, VMA_DEL_RESV);
2831846be085SMike Kravetz }
2832846be085SMike Kravetz 
2833846be085SMike Kravetz /*
2834846be085SMike Kravetz  * This routine is called to restore reservation information on error paths.
2835d0ce0e47SSidhartha Kumar  * It should ONLY be called for folios allocated via alloc_hugetlb_folio(),
2836d0ce0e47SSidhartha Kumar  * and the hugetlb mutex should remain held when calling this routine.
2837846be085SMike Kravetz  *
2838846be085SMike Kravetz  * It handles two specific cases:
2839d2d7bb44SSidhartha Kumar  * 1) A reservation was in place and the folio consumed the reservation.
2840d2d7bb44SSidhartha Kumar  *    hugetlb_restore_reserve is set in the folio.
2841d2d7bb44SSidhartha Kumar  * 2) No reservation was in place for the page, so hugetlb_restore_reserve is
2842d0ce0e47SSidhartha Kumar  *    not set.  However, alloc_hugetlb_folio always updates the reserve map.
2843846be085SMike Kravetz  *
2844454a00c4SMatthew Wilcox (Oracle)  * In case 1, free_huge_folio later in the error path will increment the
2845454a00c4SMatthew Wilcox (Oracle)  * global reserve count.  But, free_huge_folio does not have enough context
2846846be085SMike Kravetz  * to adjust the reservation map.  This case deals primarily with private
2847846be085SMike Kravetz  * mappings.  Adjust the reserve map here to be consistent with global
2848454a00c4SMatthew Wilcox (Oracle)  * reserve count adjustments to be made by free_huge_folio.  Make sure the
2849846be085SMike Kravetz  * reserve map indicates there is a reservation present.
2850846be085SMike Kravetz  *
2851d0ce0e47SSidhartha Kumar  * In case 2, simply undo reserve map modifications done by alloc_hugetlb_folio.
2852846be085SMike Kravetz  */
restore_reserve_on_error(struct hstate * h,struct vm_area_struct * vma,unsigned long address,struct folio * folio)2853846be085SMike Kravetz void restore_reserve_on_error(struct hstate *h, struct vm_area_struct *vma,
2854d2d7bb44SSidhartha Kumar 			unsigned long address, struct folio *folio)
2855846be085SMike Kravetz {
285696b96a96SMike Kravetz 	long rc = vma_needs_reservation(h, vma, address);
285796b96a96SMike Kravetz 
28580ffdc38eSSidhartha Kumar 	if (folio_test_hugetlb_restore_reserve(folio)) {
2859846be085SMike Kravetz 		if (unlikely(rc < 0))
286096b96a96SMike Kravetz 			/*
286196b96a96SMike Kravetz 			 * Rare out of memory condition in reserve map
28620ffdc38eSSidhartha Kumar 			 * manipulation.  Clear hugetlb_restore_reserve so
28630ffdc38eSSidhartha Kumar 			 * that global reserve count will not be incremented
2864454a00c4SMatthew Wilcox (Oracle) 			 * by free_huge_folio.  This will make it appear
28650ffdc38eSSidhartha Kumar 			 * as though the reservation for this folio was
286696b96a96SMike Kravetz 			 * consumed.  This may prevent the task from
28670ffdc38eSSidhartha Kumar 			 * faulting in the folio at a later time.  This
286896b96a96SMike Kravetz 			 * is better than inconsistent global huge page
286996b96a96SMike Kravetz 			 * accounting of reserve counts.
287096b96a96SMike Kravetz 			 */
28710ffdc38eSSidhartha Kumar 			folio_clear_hugetlb_restore_reserve(folio);
2872846be085SMike Kravetz 		else if (rc)
2873846be085SMike Kravetz 			(void)vma_add_reservation(h, vma, address);
2874846be085SMike Kravetz 		else
2875846be085SMike Kravetz 			vma_end_reservation(h, vma, address);
2876846be085SMike Kravetz 	} else {
2877846be085SMike Kravetz 		if (!rc) {
287896b96a96SMike Kravetz 			/*
2879846be085SMike Kravetz 			 * This indicates there is an entry in the reserve map
2880d0ce0e47SSidhartha Kumar 			 * not added by alloc_hugetlb_folio.  We know it was added
2881d0ce0e47SSidhartha Kumar 			 * before the alloc_hugetlb_folio call, otherwise
28820ffdc38eSSidhartha Kumar 			 * hugetlb_restore_reserve would be set on the folio.
2883846be085SMike Kravetz 			 * Remove the entry so that a subsequent allocation
2884846be085SMike Kravetz 			 * does not consume a reservation.
288596b96a96SMike Kravetz 			 */
2886846be085SMike Kravetz 			rc = vma_del_reservation(h, vma, address);
2887846be085SMike Kravetz 			if (rc < 0)
2888846be085SMike Kravetz 				/*
2889846be085SMike Kravetz 				 * VERY rare out of memory condition.  Since
2890846be085SMike Kravetz 				 * we can not delete the entry, set
28910ffdc38eSSidhartha Kumar 				 * hugetlb_restore_reserve so that the reserve
28920ffdc38eSSidhartha Kumar 				 * count will be incremented when the folio
2893846be085SMike Kravetz 				 * is freed.  This reserve will be consumed
2894846be085SMike Kravetz 				 * on a subsequent allocation.
2895846be085SMike Kravetz 				 */
28960ffdc38eSSidhartha Kumar 				folio_set_hugetlb_restore_reserve(folio);
2897846be085SMike Kravetz 		} else if (rc < 0) {
2898846be085SMike Kravetz 			/*
2899846be085SMike Kravetz 			 * Rare out of memory condition from
2900846be085SMike Kravetz 			 * vma_needs_reservation call.  Memory allocation is
2901846be085SMike Kravetz 			 * only attempted if a new entry is needed.  Therefore,
2902846be085SMike Kravetz 			 * this implies there is not an entry in the
2903846be085SMike Kravetz 			 * reserve map.
2904846be085SMike Kravetz 			 *
2905846be085SMike Kravetz 			 * For shared mappings, no entry in the map indicates
2906846be085SMike Kravetz 			 * no reservation.  We are done.
2907846be085SMike Kravetz 			 */
2908846be085SMike Kravetz 			if (!(vma->vm_flags & VM_MAYSHARE))
2909846be085SMike Kravetz 				/*
2910846be085SMike Kravetz 				 * For private mappings, no entry indicates
2911846be085SMike Kravetz 				 * a reservation is present.  Since we can
29120ffdc38eSSidhartha Kumar 				 * not add an entry, set hugetlb_restore_reserve
29130ffdc38eSSidhartha Kumar 				 * on the folio so reserve count will be
2914846be085SMike Kravetz 				 * incremented when freed.  This reserve will
2915846be085SMike Kravetz 				 * be consumed on a subsequent allocation.
2916846be085SMike Kravetz 				 */
29170ffdc38eSSidhartha Kumar 				folio_set_hugetlb_restore_reserve(folio);
291896b96a96SMike Kravetz 		} else
2919846be085SMike Kravetz 			/*
2920846be085SMike Kravetz 			 * No reservation present, do nothing
2921846be085SMike Kravetz 			 */
292296b96a96SMike Kravetz 			 vma_end_reservation(h, vma, address);
292396b96a96SMike Kravetz 	}
292496b96a96SMike Kravetz }
292596b96a96SMike Kravetz 
2926369fa227SOscar Salvador /*
292719fc1a7eSSidhartha Kumar  * alloc_and_dissolve_hugetlb_folio - Allocate a new folio and dissolve
292819fc1a7eSSidhartha Kumar  * the old one
2929369fa227SOscar Salvador  * @h: struct hstate old page belongs to
293019fc1a7eSSidhartha Kumar  * @old_folio: Old folio to dissolve
2931ae37c7ffSOscar Salvador  * @list: List to isolate the page in case we need to
2932369fa227SOscar Salvador  * Returns 0 on success, otherwise negated error.
2933369fa227SOscar Salvador  */
alloc_and_dissolve_hugetlb_folio(struct hstate * h,struct folio * old_folio,struct list_head * list)293419fc1a7eSSidhartha Kumar static int alloc_and_dissolve_hugetlb_folio(struct hstate *h,
293519fc1a7eSSidhartha Kumar 			struct folio *old_folio, struct list_head *list)
2936369fa227SOscar Salvador {
2937369fa227SOscar Salvador 	gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
2938de656ed3SSidhartha Kumar 	int nid = folio_nid(old_folio);
2939de656ed3SSidhartha Kumar 	struct folio *new_folio;
2940369fa227SOscar Salvador 	int ret = 0;
2941369fa227SOscar Salvador 
2942369fa227SOscar Salvador 	/*
294319fc1a7eSSidhartha Kumar 	 * Before dissolving the folio, we need to allocate a new one for the
294419fc1a7eSSidhartha Kumar 	 * pool to remain stable.  Here, we allocate the folio and 'prep' it
2945f41f2ed4SMuchun Song 	 * by doing everything but actually updating counters and adding to
2946f41f2ed4SMuchun Song 	 * the pool.  This simplifies and let us do most of the processing
2947f41f2ed4SMuchun Song 	 * under the lock.
2948369fa227SOscar Salvador 	 */
294919fc1a7eSSidhartha Kumar 	new_folio = alloc_buddy_hugetlb_folio(h, gfp_mask, nid, NULL, NULL);
295019fc1a7eSSidhartha Kumar 	if (!new_folio)
2951369fa227SOscar Salvador 		return -ENOMEM;
2952de656ed3SSidhartha Kumar 	__prep_new_hugetlb_folio(h, new_folio);
2953369fa227SOscar Salvador 
2954369fa227SOscar Salvador retry:
2955369fa227SOscar Salvador 	spin_lock_irq(&hugetlb_lock);
2956de656ed3SSidhartha Kumar 	if (!folio_test_hugetlb(old_folio)) {
2957369fa227SOscar Salvador 		/*
295819fc1a7eSSidhartha Kumar 		 * Freed from under us. Drop new_folio too.
2959369fa227SOscar Salvador 		 */
2960369fa227SOscar Salvador 		goto free_new;
2961de656ed3SSidhartha Kumar 	} else if (folio_ref_count(old_folio)) {
29629747b9e9SBaolin Wang 		bool isolated;
29639747b9e9SBaolin Wang 
2964369fa227SOscar Salvador 		/*
296519fc1a7eSSidhartha Kumar 		 * Someone has grabbed the folio, try to isolate it here.
2966ae37c7ffSOscar Salvador 		 * Fail with -EBUSY if not possible.
2967369fa227SOscar Salvador 		 */
2968ae37c7ffSOscar Salvador 		spin_unlock_irq(&hugetlb_lock);
29699747b9e9SBaolin Wang 		isolated = isolate_hugetlb(old_folio, list);
29709747b9e9SBaolin Wang 		ret = isolated ? 0 : -EBUSY;
2971ae37c7ffSOscar Salvador 		spin_lock_irq(&hugetlb_lock);
2972369fa227SOscar Salvador 		goto free_new;
2973de656ed3SSidhartha Kumar 	} else if (!folio_test_hugetlb_freed(old_folio)) {
2974369fa227SOscar Salvador 		/*
297519fc1a7eSSidhartha Kumar 		 * Folio's refcount is 0 but it has not been enqueued in the
2976369fa227SOscar Salvador 		 * freelist yet. Race window is small, so we can succeed here if
2977369fa227SOscar Salvador 		 * we retry.
2978369fa227SOscar Salvador 		 */
2979369fa227SOscar Salvador 		spin_unlock_irq(&hugetlb_lock);
2980369fa227SOscar Salvador 		cond_resched();
2981369fa227SOscar Salvador 		goto retry;
2982369fa227SOscar Salvador 	} else {
2983369fa227SOscar Salvador 		/*
298419fc1a7eSSidhartha Kumar 		 * Ok, old_folio is still a genuine free hugepage. Remove it from
2985369fa227SOscar Salvador 		 * the freelist and decrease the counters. These will be
2986369fa227SOscar Salvador 		 * incremented again when calling __prep_account_new_huge_page()
2987240d67a8SSidhartha Kumar 		 * and enqueue_hugetlb_folio() for new_folio. The counters will
2988240d67a8SSidhartha Kumar 		 * remain stable since this happens under the lock.
2989369fa227SOscar Salvador 		 */
2990cfd5082bSSidhartha Kumar 		remove_hugetlb_folio(h, old_folio, false);
2991369fa227SOscar Salvador 
2992369fa227SOscar Salvador 		/*
299319fc1a7eSSidhartha Kumar 		 * Ref count on new_folio is already zero as it was dropped
2994b65a4edaSMike Kravetz 		 * earlier.  It can be directly added to the pool free list.
2995369fa227SOscar Salvador 		 */
2996369fa227SOscar Salvador 		__prep_account_new_huge_page(h, nid);
2997240d67a8SSidhartha Kumar 		enqueue_hugetlb_folio(h, new_folio);
2998369fa227SOscar Salvador 
2999369fa227SOscar Salvador 		/*
300019fc1a7eSSidhartha Kumar 		 * Folio has been replaced, we can safely free the old one.
3001369fa227SOscar Salvador 		 */
3002369fa227SOscar Salvador 		spin_unlock_irq(&hugetlb_lock);
3003d6ef19e2SSidhartha Kumar 		update_and_free_hugetlb_folio(h, old_folio, false);
3004369fa227SOscar Salvador 	}
3005369fa227SOscar Salvador 
3006369fa227SOscar Salvador 	return ret;
3007369fa227SOscar Salvador 
3008369fa227SOscar Salvador free_new:
3009369fa227SOscar Salvador 	spin_unlock_irq(&hugetlb_lock);
301019fc1a7eSSidhartha Kumar 	/* Folio has a zero ref count, but needs a ref to be freed */
3011de656ed3SSidhartha Kumar 	folio_ref_unfreeze(new_folio, 1);
3012d6ef19e2SSidhartha Kumar 	update_and_free_hugetlb_folio(h, new_folio, false);
3013369fa227SOscar Salvador 
3014369fa227SOscar Salvador 	return ret;
3015369fa227SOscar Salvador }
3016369fa227SOscar Salvador 
isolate_or_dissolve_huge_page(struct page * page,struct list_head * list)3017ae37c7ffSOscar Salvador int isolate_or_dissolve_huge_page(struct page *page, struct list_head *list)
3018369fa227SOscar Salvador {
3019369fa227SOscar Salvador 	struct hstate *h;
3020d5e33bd8SSidhartha Kumar 	struct folio *folio = page_folio(page);
3021ae37c7ffSOscar Salvador 	int ret = -EBUSY;
3022369fa227SOscar Salvador 
3023369fa227SOscar Salvador 	/*
3024369fa227SOscar Salvador 	 * The page might have been dissolved from under our feet, so make sure
3025369fa227SOscar Salvador 	 * to carefully check the state under the lock.
3026369fa227SOscar Salvador 	 * Return success when racing as if we dissolved the page ourselves.
3027369fa227SOscar Salvador 	 */
3028369fa227SOscar Salvador 	spin_lock_irq(&hugetlb_lock);
3029d5e33bd8SSidhartha Kumar 	if (folio_test_hugetlb(folio)) {
3030d5e33bd8SSidhartha Kumar 		h = folio_hstate(folio);
3031369fa227SOscar Salvador 	} else {
3032369fa227SOscar Salvador 		spin_unlock_irq(&hugetlb_lock);
3033369fa227SOscar Salvador 		return 0;
3034369fa227SOscar Salvador 	}
3035369fa227SOscar Salvador 	spin_unlock_irq(&hugetlb_lock);
3036369fa227SOscar Salvador 
3037369fa227SOscar Salvador 	/*
3038369fa227SOscar Salvador 	 * Fence off gigantic pages as there is a cyclic dependency between
3039369fa227SOscar Salvador 	 * alloc_contig_range and them. Return -ENOMEM as this has the effect
3040369fa227SOscar Salvador 	 * of bailing out right away without further retrying.
3041369fa227SOscar Salvador 	 */
3042369fa227SOscar Salvador 	if (hstate_is_gigantic(h))
3043369fa227SOscar Salvador 		return -ENOMEM;
3044369fa227SOscar Salvador 
30459747b9e9SBaolin Wang 	if (folio_ref_count(folio) && isolate_hugetlb(folio, list))
3046ae37c7ffSOscar Salvador 		ret = 0;
3047d5e33bd8SSidhartha Kumar 	else if (!folio_ref_count(folio))
304819fc1a7eSSidhartha Kumar 		ret = alloc_and_dissolve_hugetlb_folio(h, folio, list);
3049ae37c7ffSOscar Salvador 
3050ae37c7ffSOscar Salvador 	return ret;
3051369fa227SOscar Salvador }
3052369fa227SOscar Salvador 
alloc_hugetlb_folio(struct vm_area_struct * vma,unsigned long addr,int avoid_reserve)3053d0ce0e47SSidhartha Kumar struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
305404f2cbe3SMel Gorman 				    unsigned long addr, int avoid_reserve)
3055348ea204SAdam Litke {
305690481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_vma(vma);
3057a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
3058d4ab0316SSidhartha Kumar 	struct folio *folio;
3059d85f69b0SMike Kravetz 	long map_chg, map_commit;
3060d85f69b0SMike Kravetz 	long gbl_chg;
30616d76dcf4SAneesh Kumar K.V 	int ret, idx;
3062d0ce0e47SSidhartha Kumar 	struct hugetlb_cgroup *h_cg = NULL;
306308cf9fafSMina Almasry 	bool deferred_reserve;
30642fc39cecSAdam Litke 
30656d76dcf4SAneesh Kumar K.V 	idx = hstate_index(h);
3066a1e78772SMel Gorman 	/*
3067d85f69b0SMike Kravetz 	 * Examine the region/reserve map to determine if the process
3068d85f69b0SMike Kravetz 	 * has a reservation for the page to be allocated.  A return
3069d85f69b0SMike Kravetz 	 * code of zero indicates a reservation exists (no change).
3070a1e78772SMel Gorman 	 */
3071d85f69b0SMike Kravetz 	map_chg = gbl_chg = vma_needs_reservation(h, vma, addr);
3072d85f69b0SMike Kravetz 	if (map_chg < 0)
307376dcee75SAneesh Kumar K.V 		return ERR_PTR(-ENOMEM);
3074d85f69b0SMike Kravetz 
3075d85f69b0SMike Kravetz 	/*
3076d85f69b0SMike Kravetz 	 * Processes that did not create the mapping will have no
3077d85f69b0SMike Kravetz 	 * reserves as indicated by the region/reserve map. Check
3078d85f69b0SMike Kravetz 	 * that the allocation will not exceed the subpool limit.
3079d85f69b0SMike Kravetz 	 * Allocations for MAP_NORESERVE mappings also need to be
3080d85f69b0SMike Kravetz 	 * checked against any subpool limit.
3081d85f69b0SMike Kravetz 	 */
3082d85f69b0SMike Kravetz 	if (map_chg || avoid_reserve) {
3083d85f69b0SMike Kravetz 		gbl_chg = hugepage_subpool_get_pages(spool, 1);
3084d85f69b0SMike Kravetz 		if (gbl_chg < 0) {
3085feba16e2SMike Kravetz 			vma_end_reservation(h, vma, addr);
308676dcee75SAneesh Kumar K.V 			return ERR_PTR(-ENOSPC);
30875e911373SMike Kravetz 		}
308890d8b7e6SAdam Litke 
3089d85f69b0SMike Kravetz 		/*
3090d85f69b0SMike Kravetz 		 * Even though there was no reservation in the region/reserve
3091d85f69b0SMike Kravetz 		 * map, there could be reservations associated with the
3092d85f69b0SMike Kravetz 		 * subpool that can be used.  This would be indicated if the
3093d85f69b0SMike Kravetz 		 * return value of hugepage_subpool_get_pages() is zero.
3094d85f69b0SMike Kravetz 		 * However, if avoid_reserve is specified we still avoid even
3095d85f69b0SMike Kravetz 		 * the subpool reservations.
3096d85f69b0SMike Kravetz 		 */
3097d85f69b0SMike Kravetz 		if (avoid_reserve)
3098d85f69b0SMike Kravetz 			gbl_chg = 1;
3099d85f69b0SMike Kravetz 	}
3100d85f69b0SMike Kravetz 
310108cf9fafSMina Almasry 	/* If this allocation is not consuming a reservation, charge it now.
310208cf9fafSMina Almasry 	 */
31036501fe5fSMiaohe Lin 	deferred_reserve = map_chg || avoid_reserve;
310408cf9fafSMina Almasry 	if (deferred_reserve) {
310508cf9fafSMina Almasry 		ret = hugetlb_cgroup_charge_cgroup_rsvd(
310608cf9fafSMina Almasry 			idx, pages_per_huge_page(h), &h_cg);
31078f34af6fSJianyu Zhan 		if (ret)
31088f34af6fSJianyu Zhan 			goto out_subpool_put;
310908cf9fafSMina Almasry 	}
311008cf9fafSMina Almasry 
311108cf9fafSMina Almasry 	ret = hugetlb_cgroup_charge_cgroup(idx, pages_per_huge_page(h), &h_cg);
311208cf9fafSMina Almasry 	if (ret)
311308cf9fafSMina Almasry 		goto out_uncharge_cgroup_reservation;
31148f34af6fSJianyu Zhan 
3115db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
3116d85f69b0SMike Kravetz 	/*
3117d85f69b0SMike Kravetz 	 * glb_chg is passed to indicate whether or not a page must be taken
3118d85f69b0SMike Kravetz 	 * from the global free pool (global change).  gbl_chg == 0 indicates
3119d85f69b0SMike Kravetz 	 * a reservation exists for the allocation.
3120d85f69b0SMike Kravetz 	 */
3121ff7d853bSSidhartha Kumar 	folio = dequeue_hugetlb_folio_vma(h, vma, addr, avoid_reserve, gbl_chg);
3122ff7d853bSSidhartha Kumar 	if (!folio) {
3123db71ef79SMike Kravetz 		spin_unlock_irq(&hugetlb_lock);
3124ff7d853bSSidhartha Kumar 		folio = alloc_buddy_hugetlb_folio_with_mpol(h, vma, addr);
3125ff7d853bSSidhartha Kumar 		if (!folio)
31268f34af6fSJianyu Zhan 			goto out_uncharge_cgroup;
312712df140fSRik van Riel 		spin_lock_irq(&hugetlb_lock);
3128a88c7695SNaoya Horiguchi 		if (!avoid_reserve && vma_has_reserves(vma, gbl_chg)) {
3129ff7d853bSSidhartha Kumar 			folio_set_hugetlb_restore_reserve(folio);
3130a88c7695SNaoya Horiguchi 			h->resv_huge_pages--;
3131a88c7695SNaoya Horiguchi 		}
3132ff7d853bSSidhartha Kumar 		list_add(&folio->lru, &h->hugepage_activelist);
3133ff7d853bSSidhartha Kumar 		folio_ref_unfreeze(folio, 1);
313481a6fcaeSJoonsoo Kim 		/* Fall through */
3135a1e78772SMel Gorman 	}
3136ff7d853bSSidhartha Kumar 
3137ff7d853bSSidhartha Kumar 	hugetlb_cgroup_commit_charge(idx, pages_per_huge_page(h), h_cg, folio);
313808cf9fafSMina Almasry 	/* If allocation is not consuming a reservation, also store the
313908cf9fafSMina Almasry 	 * hugetlb_cgroup pointer on the page.
314008cf9fafSMina Almasry 	 */
314108cf9fafSMina Almasry 	if (deferred_reserve) {
314208cf9fafSMina Almasry 		hugetlb_cgroup_commit_charge_rsvd(idx, pages_per_huge_page(h),
3143ff7d853bSSidhartha Kumar 						  h_cg, folio);
314408cf9fafSMina Almasry 	}
314508cf9fafSMina Almasry 
3146db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
3147a1e78772SMel Gorman 
3148ff7d853bSSidhartha Kumar 	hugetlb_set_folio_subpool(folio, spool);
3149a1e78772SMel Gorman 
3150d85f69b0SMike Kravetz 	map_commit = vma_commit_reservation(h, vma, addr);
3151d85f69b0SMike Kravetz 	if (unlikely(map_chg > map_commit)) {
315233039678SMike Kravetz 		/*
315333039678SMike Kravetz 		 * The page was added to the reservation map between
315433039678SMike Kravetz 		 * vma_needs_reservation and vma_commit_reservation.
315533039678SMike Kravetz 		 * This indicates a race with hugetlb_reserve_pages.
315633039678SMike Kravetz 		 * Adjust for the subpool count incremented above AND
315733039678SMike Kravetz 		 * in hugetlb_reserve_pages for the same page.  Also,
315833039678SMike Kravetz 		 * the reservation count added in hugetlb_reserve_pages
315933039678SMike Kravetz 		 * no longer applies.
316033039678SMike Kravetz 		 */
316133039678SMike Kravetz 		long rsv_adjust;
316233039678SMike Kravetz 
316333039678SMike Kravetz 		rsv_adjust = hugepage_subpool_put_pages(spool, 1);
316433039678SMike Kravetz 		hugetlb_acct_memory(h, -rsv_adjust);
3165f6c5d21dSPeter Xu 		if (deferred_reserve) {
3166f6c5d21dSPeter Xu 			spin_lock_irq(&hugetlb_lock);
3167d4ab0316SSidhartha Kumar 			hugetlb_cgroup_uncharge_folio_rsvd(hstate_index(h),
3168d4ab0316SSidhartha Kumar 					pages_per_huge_page(h), folio);
3169f6c5d21dSPeter Xu 			spin_unlock_irq(&hugetlb_lock);
3170f6c5d21dSPeter Xu 		}
317133039678SMike Kravetz 	}
3172d0ce0e47SSidhartha Kumar 	return folio;
31738f34af6fSJianyu Zhan 
31748f34af6fSJianyu Zhan out_uncharge_cgroup:
31758f34af6fSJianyu Zhan 	hugetlb_cgroup_uncharge_cgroup(idx, pages_per_huge_page(h), h_cg);
317608cf9fafSMina Almasry out_uncharge_cgroup_reservation:
317708cf9fafSMina Almasry 	if (deferred_reserve)
317808cf9fafSMina Almasry 		hugetlb_cgroup_uncharge_cgroup_rsvd(idx, pages_per_huge_page(h),
317908cf9fafSMina Almasry 						    h_cg);
31808f34af6fSJianyu Zhan out_subpool_put:
3181d85f69b0SMike Kravetz 	if (map_chg || avoid_reserve)
31828f34af6fSJianyu Zhan 		hugepage_subpool_put_pages(spool, 1);
3183feba16e2SMike Kravetz 	vma_end_reservation(h, vma, addr);
31848f34af6fSJianyu Zhan 	return ERR_PTR(-ENOSPC);
3185b45b5bd6SDavid Gibson }
3186b45b5bd6SDavid Gibson 
3187b5389086SZhenguo Yao int alloc_bootmem_huge_page(struct hstate *h, int nid)
3188e24a1307SAneesh Kumar K.V 	__attribute__ ((weak, alias("__alloc_bootmem_huge_page")));
__alloc_bootmem_huge_page(struct hstate * h,int nid)3189b5389086SZhenguo Yao int __alloc_bootmem_huge_page(struct hstate *h, int nid)
3190aa888a74SAndi Kleen {
3191b5389086SZhenguo Yao 	struct huge_bootmem_page *m = NULL; /* initialize for clang */
3192b2261026SJoonsoo Kim 	int nr_nodes, node;
3193aa888a74SAndi Kleen 
3194b5389086SZhenguo Yao 	/* do node specific alloc */
3195b5389086SZhenguo Yao 	if (nid != NUMA_NO_NODE) {
3196b5389086SZhenguo Yao 		m = memblock_alloc_try_nid_raw(huge_page_size(h), huge_page_size(h),
3197b5389086SZhenguo Yao 				0, MEMBLOCK_ALLOC_ACCESSIBLE, nid);
3198b5389086SZhenguo Yao 		if (!m)
3199b5389086SZhenguo Yao 			return 0;
3200b5389086SZhenguo Yao 		goto found;
3201b5389086SZhenguo Yao 	}
3202b5389086SZhenguo Yao 	/* allocate from next node when distributing huge pages */
3203b2261026SJoonsoo Kim 	for_each_node_mask_to_alloc(h, nr_nodes, node, &node_states[N_MEMORY]) {
3204b5389086SZhenguo Yao 		m = memblock_alloc_try_nid_raw(
32058b89a116SGrygorii Strashko 				huge_page_size(h), huge_page_size(h),
320697ad1087SMike Rapoport 				0, MEMBLOCK_ALLOC_ACCESSIBLE, node);
3207aa888a74SAndi Kleen 		/*
3208aa888a74SAndi Kleen 		 * Use the beginning of the huge page to store the
3209aa888a74SAndi Kleen 		 * huge_bootmem_page struct (until gather_bootmem
3210aa888a74SAndi Kleen 		 * puts them into the mem_map).
3211aa888a74SAndi Kleen 		 */
3212b5389086SZhenguo Yao 		if (!m)
3213b5389086SZhenguo Yao 			return 0;
3214aa888a74SAndi Kleen 		goto found;
3215aa888a74SAndi Kleen 	}
3216aa888a74SAndi Kleen 
3217aa888a74SAndi Kleen found:
3218aa888a74SAndi Kleen 	/* Put them into a private list first because mem_map is not up yet */
3219330d6e48SCannon Matthews 	INIT_LIST_HEAD(&m->list);
3220aa888a74SAndi Kleen 	list_add(&m->list, &huge_boot_pages);
3221aa888a74SAndi Kleen 	m->hstate = h;
3222aa888a74SAndi Kleen 	return 1;
3223aa888a74SAndi Kleen }
3224aa888a74SAndi Kleen 
322548b8d744SMike Kravetz /*
322648b8d744SMike Kravetz  * Put bootmem huge pages into the standard lists after mem_map is up.
322748b8d744SMike Kravetz  * Note: This only applies to gigantic (order > MAX_ORDER) pages.
322848b8d744SMike Kravetz  */
gather_bootmem_prealloc(void)3229aa888a74SAndi Kleen static void __init gather_bootmem_prealloc(void)
3230aa888a74SAndi Kleen {
3231aa888a74SAndi Kleen 	struct huge_bootmem_page *m;
3232aa888a74SAndi Kleen 
3233aa888a74SAndi Kleen 	list_for_each_entry(m, &huge_boot_pages, list) {
323440d18ebfSMike Kravetz 		struct page *page = virt_to_page(m);
32357f325a8dSSidhartha Kumar 		struct folio *folio = page_folio(page);
3236aa888a74SAndi Kleen 		struct hstate *h = m->hstate;
3237ee8f248dSBecky Bruce 
323848b8d744SMike Kravetz 		VM_BUG_ON(!hstate_is_gigantic(h));
3239d1c60955SSidhartha Kumar 		WARN_ON(folio_ref_count(folio) != 1);
3240d1c60955SSidhartha Kumar 		if (prep_compound_gigantic_folio(folio, huge_page_order(h))) {
3241d1c60955SSidhartha Kumar 			WARN_ON(folio_test_reserved(folio));
3242d1c60955SSidhartha Kumar 			prep_new_hugetlb_folio(h, folio, folio_nid(folio));
3243454a00c4SMatthew Wilcox (Oracle) 			free_huge_folio(folio); /* add to the hugepage allocator */
32447118fc29SMike Kravetz 		} else {
3245416d85edSMike Kravetz 			/* VERY unlikely inflated ref count on a tail page */
32467f325a8dSSidhartha Kumar 			free_gigantic_folio(folio, huge_page_order(h));
32477118fc29SMike Kravetz 		}
3248af0fb9dfSMichal Hocko 
3249b0320c7bSRafael Aquini 		/*
325048b8d744SMike Kravetz 		 * We need to restore the 'stolen' pages to totalram_pages
325148b8d744SMike Kravetz 		 * in order to fix confusing memory reports from free(1) and
325248b8d744SMike Kravetz 		 * other side-effects, like CommitLimit going negative.
3253b0320c7bSRafael Aquini 		 */
3254c78a7f36SMiaohe Lin 		adjust_managed_page_count(page, pages_per_huge_page(h));
3255520495feSCannon Matthews 		cond_resched();
3256aa888a74SAndi Kleen 	}
3257aa888a74SAndi Kleen }
hugetlb_hstate_alloc_pages_onenode(struct hstate * h,int nid)3258b5389086SZhenguo Yao static void __init hugetlb_hstate_alloc_pages_onenode(struct hstate *h, int nid)
3259b5389086SZhenguo Yao {
3260b5389086SZhenguo Yao 	unsigned long i;
3261b5389086SZhenguo Yao 	char buf[32];
3262b5389086SZhenguo Yao 
3263b5389086SZhenguo Yao 	for (i = 0; i < h->max_huge_pages_node[nid]; ++i) {
3264b5389086SZhenguo Yao 		if (hstate_is_gigantic(h)) {
3265b5389086SZhenguo Yao 			if (!alloc_bootmem_huge_page(h, nid))
3266b5389086SZhenguo Yao 				break;
3267b5389086SZhenguo Yao 		} else {
326819fc1a7eSSidhartha Kumar 			struct folio *folio;
3269b5389086SZhenguo Yao 			gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
3270b5389086SZhenguo Yao 
327119fc1a7eSSidhartha Kumar 			folio = alloc_fresh_hugetlb_folio(h, gfp_mask, nid,
3272b5389086SZhenguo Yao 					&node_states[N_MEMORY], NULL);
327319fc1a7eSSidhartha Kumar 			if (!folio)
3274b5389086SZhenguo Yao 				break;
3275454a00c4SMatthew Wilcox (Oracle) 			free_huge_folio(folio); /* free it into the hugepage allocator */
3276b5389086SZhenguo Yao 		}
3277b5389086SZhenguo Yao 		cond_resched();
3278b5389086SZhenguo Yao 	}
3279b5389086SZhenguo Yao 	if (i == h->max_huge_pages_node[nid])
3280b5389086SZhenguo Yao 		return;
3281b5389086SZhenguo Yao 
3282b5389086SZhenguo Yao 	string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
3283b5389086SZhenguo Yao 	pr_warn("HugeTLB: allocating %u of page size %s failed node%d.  Only allocated %lu hugepages.\n",
3284b5389086SZhenguo Yao 		h->max_huge_pages_node[nid], buf, nid, i);
3285b5389086SZhenguo Yao 	h->max_huge_pages -= (h->max_huge_pages_node[nid] - i);
3286b5389086SZhenguo Yao 	h->max_huge_pages_node[nid] = i;
3287b5389086SZhenguo Yao }
3288aa888a74SAndi Kleen 
hugetlb_hstate_alloc_pages(struct hstate * h)32898faa8b07SAndi Kleen static void __init hugetlb_hstate_alloc_pages(struct hstate *h)
32901da177e4SLinus Torvalds {
32911da177e4SLinus Torvalds 	unsigned long i;
3292f60858f9SMike Kravetz 	nodemask_t *node_alloc_noretry;
3293b5389086SZhenguo Yao 	bool node_specific_alloc = false;
3294f60858f9SMike Kravetz 
3295b5389086SZhenguo Yao 	/* skip gigantic hugepages allocation if hugetlb_cma enabled */
3296b5389086SZhenguo Yao 	if (hstate_is_gigantic(h) && hugetlb_cma_size) {
3297b5389086SZhenguo Yao 		pr_warn_once("HugeTLB: hugetlb_cma is enabled, skip boot time allocation\n");
3298b5389086SZhenguo Yao 		return;
3299b5389086SZhenguo Yao 	}
3300b5389086SZhenguo Yao 
3301b5389086SZhenguo Yao 	/* do node specific alloc */
33020a7a0f6fSPeng Liu 	for_each_online_node(i) {
3303b5389086SZhenguo Yao 		if (h->max_huge_pages_node[i] > 0) {
3304b5389086SZhenguo Yao 			hugetlb_hstate_alloc_pages_onenode(h, i);
3305b5389086SZhenguo Yao 			node_specific_alloc = true;
3306b5389086SZhenguo Yao 		}
3307b5389086SZhenguo Yao 	}
3308b5389086SZhenguo Yao 
3309b5389086SZhenguo Yao 	if (node_specific_alloc)
3310b5389086SZhenguo Yao 		return;
3311b5389086SZhenguo Yao 
3312b5389086SZhenguo Yao 	/* below will do all node balanced alloc */
3313f60858f9SMike Kravetz 	if (!hstate_is_gigantic(h)) {
3314f60858f9SMike Kravetz 		/*
3315f60858f9SMike Kravetz 		 * Bit mask controlling how hard we retry per-node allocations.
3316f60858f9SMike Kravetz 		 * Ignore errors as lower level routines can deal with
3317f60858f9SMike Kravetz 		 * node_alloc_noretry == NULL.  If this kmalloc fails at boot
3318f60858f9SMike Kravetz 		 * time, we are likely in bigger trouble.
3319f60858f9SMike Kravetz 		 */
3320f60858f9SMike Kravetz 		node_alloc_noretry = kmalloc(sizeof(*node_alloc_noretry),
3321f60858f9SMike Kravetz 						GFP_KERNEL);
3322f60858f9SMike Kravetz 	} else {
3323f60858f9SMike Kravetz 		/* allocations done at boot time */
3324f60858f9SMike Kravetz 		node_alloc_noretry = NULL;
3325f60858f9SMike Kravetz 	}
3326f60858f9SMike Kravetz 
3327f60858f9SMike Kravetz 	/* bit mask controlling how hard we retry per-node allocations */
3328f60858f9SMike Kravetz 	if (node_alloc_noretry)
3329f60858f9SMike Kravetz 		nodes_clear(*node_alloc_noretry);
33301da177e4SLinus Torvalds 
3331e5ff2159SAndi Kleen 	for (i = 0; i < h->max_huge_pages; ++i) {
3332bae7f4aeSLuiz Capitulino 		if (hstate_is_gigantic(h)) {
3333b5389086SZhenguo Yao 			if (!alloc_bootmem_huge_page(h, NUMA_NO_NODE))
3334aa888a74SAndi Kleen 				break;
33350c397daeSMichal Hocko 		} else if (!alloc_pool_huge_page(h,
3336f60858f9SMike Kravetz 					 &node_states[N_MEMORY],
3337f60858f9SMike Kravetz 					 node_alloc_noretry))
33381da177e4SLinus Torvalds 			break;
333969ed779aSDavid Rientjes 		cond_resched();
33401da177e4SLinus Torvalds 	}
3341d715cf80SLiam R. Howlett 	if (i < h->max_huge_pages) {
3342d715cf80SLiam R. Howlett 		char buf[32];
3343d715cf80SLiam R. Howlett 
3344c6247f72SMatthew Wilcox 		string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
3345d715cf80SLiam R. Howlett 		pr_warn("HugeTLB: allocating %lu of page size %s failed.  Only allocated %lu hugepages.\n",
3346d715cf80SLiam R. Howlett 			h->max_huge_pages, buf, i);
33478faa8b07SAndi Kleen 		h->max_huge_pages = i;
3348e5ff2159SAndi Kleen 	}
3349f60858f9SMike Kravetz 	kfree(node_alloc_noretry);
3350d715cf80SLiam R. Howlett }
3351e5ff2159SAndi Kleen 
hugetlb_init_hstates(void)3352e5ff2159SAndi Kleen static void __init hugetlb_init_hstates(void)
3353e5ff2159SAndi Kleen {
335479dfc695SMike Kravetz 	struct hstate *h, *h2;
3355e5ff2159SAndi Kleen 
3356e5ff2159SAndi Kleen 	for_each_hstate(h) {
33578faa8b07SAndi Kleen 		/* oversize hugepages were init'ed in early boot */
3358bae7f4aeSLuiz Capitulino 		if (!hstate_is_gigantic(h))
33598faa8b07SAndi Kleen 			hugetlb_hstate_alloc_pages(h);
336079dfc695SMike Kravetz 
336179dfc695SMike Kravetz 		/*
336279dfc695SMike Kravetz 		 * Set demote order for each hstate.  Note that
336379dfc695SMike Kravetz 		 * h->demote_order is initially 0.
336479dfc695SMike Kravetz 		 * - We can not demote gigantic pages if runtime freeing
336579dfc695SMike Kravetz 		 *   is not supported, so skip this.
3366a01f4390SMike Kravetz 		 * - If CMA allocation is possible, we can not demote
3367a01f4390SMike Kravetz 		 *   HUGETLB_PAGE_ORDER or smaller size pages.
336879dfc695SMike Kravetz 		 */
336979dfc695SMike Kravetz 		if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
337079dfc695SMike Kravetz 			continue;
3371a01f4390SMike Kravetz 		if (hugetlb_cma_size && h->order <= HUGETLB_PAGE_ORDER)
3372a01f4390SMike Kravetz 			continue;
337379dfc695SMike Kravetz 		for_each_hstate(h2) {
337479dfc695SMike Kravetz 			if (h2 == h)
337579dfc695SMike Kravetz 				continue;
337679dfc695SMike Kravetz 			if (h2->order < h->order &&
337779dfc695SMike Kravetz 			    h2->order > h->demote_order)
337879dfc695SMike Kravetz 				h->demote_order = h2->order;
337979dfc695SMike Kravetz 		}
3380e5ff2159SAndi Kleen 	}
3381e5ff2159SAndi Kleen }
3382e5ff2159SAndi Kleen 
report_hugepages(void)3383e5ff2159SAndi Kleen static void __init report_hugepages(void)
3384e5ff2159SAndi Kleen {
3385e5ff2159SAndi Kleen 	struct hstate *h;
3386e5ff2159SAndi Kleen 
3387e5ff2159SAndi Kleen 	for_each_hstate(h) {
33884abd32dbSAndi Kleen 		char buf[32];
3389c6247f72SMatthew Wilcox 
3390c6247f72SMatthew Wilcox 		string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
33916213834cSMuchun Song 		pr_info("HugeTLB: registered %s page size, pre-allocated %ld pages\n",
3392c6247f72SMatthew Wilcox 			buf, h->free_huge_pages);
33936213834cSMuchun Song 		pr_info("HugeTLB: %d KiB vmemmap can be freed for a %s page\n",
33946213834cSMuchun Song 			hugetlb_vmemmap_optimizable_size(h) / SZ_1K, buf);
3395e5ff2159SAndi Kleen 	}
3396e5ff2159SAndi Kleen }
3397e5ff2159SAndi Kleen 
33981da177e4SLinus Torvalds #ifdef CONFIG_HIGHMEM
try_to_free_low(struct hstate * h,unsigned long count,nodemask_t * nodes_allowed)33996ae11b27SLee Schermerhorn static void try_to_free_low(struct hstate *h, unsigned long count,
34006ae11b27SLee Schermerhorn 						nodemask_t *nodes_allowed)
34011da177e4SLinus Torvalds {
34024415cc8dSChristoph Lameter 	int i;
34031121828aSMike Kravetz 	LIST_HEAD(page_list);
34044415cc8dSChristoph Lameter 
34059487ca60SMike Kravetz 	lockdep_assert_held(&hugetlb_lock);
3406bae7f4aeSLuiz Capitulino 	if (hstate_is_gigantic(h))
3407aa888a74SAndi Kleen 		return;
3408aa888a74SAndi Kleen 
34091121828aSMike Kravetz 	/*
34101121828aSMike Kravetz 	 * Collect pages to be freed on a list, and free after dropping lock
34111121828aSMike Kravetz 	 */
34126ae11b27SLee Schermerhorn 	for_each_node_mask(i, *nodes_allowed) {
341310c6ec49SMike Kravetz 		struct page *page, *next;
3414a5516438SAndi Kleen 		struct list_head *freel = &h->hugepage_freelists[i];
3415a5516438SAndi Kleen 		list_for_each_entry_safe(page, next, freel, lru) {
3416a5516438SAndi Kleen 			if (count >= h->nr_huge_pages)
34171121828aSMike Kravetz 				goto out;
34181da177e4SLinus Torvalds 			if (PageHighMem(page))
34191da177e4SLinus Torvalds 				continue;
3420cfd5082bSSidhartha Kumar 			remove_hugetlb_folio(h, page_folio(page), false);
34211121828aSMike Kravetz 			list_add(&page->lru, &page_list);
34221121828aSMike Kravetz 		}
34231121828aSMike Kravetz 	}
34241121828aSMike Kravetz 
34251121828aSMike Kravetz out:
3426db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
342710c6ec49SMike Kravetz 	update_and_free_pages_bulk(h, &page_list);
3428db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
34291da177e4SLinus Torvalds }
34301da177e4SLinus Torvalds #else
try_to_free_low(struct hstate * h,unsigned long count,nodemask_t * nodes_allowed)34316ae11b27SLee Schermerhorn static inline void try_to_free_low(struct hstate *h, unsigned long count,
34326ae11b27SLee Schermerhorn 						nodemask_t *nodes_allowed)
34331da177e4SLinus Torvalds {
34341da177e4SLinus Torvalds }
34351da177e4SLinus Torvalds #endif
34361da177e4SLinus Torvalds 
343720a0307cSWu Fengguang /*
343820a0307cSWu Fengguang  * Increment or decrement surplus_huge_pages.  Keep node-specific counters
343920a0307cSWu Fengguang  * balanced by operating on them in a round-robin fashion.
344020a0307cSWu Fengguang  * Returns 1 if an adjustment was made.
344120a0307cSWu Fengguang  */
adjust_pool_surplus(struct hstate * h,nodemask_t * nodes_allowed,int delta)34426ae11b27SLee Schermerhorn static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed,
34436ae11b27SLee Schermerhorn 				int delta)
344420a0307cSWu Fengguang {
3445b2261026SJoonsoo Kim 	int nr_nodes, node;
344620a0307cSWu Fengguang 
34479487ca60SMike Kravetz 	lockdep_assert_held(&hugetlb_lock);
344820a0307cSWu Fengguang 	VM_BUG_ON(delta != -1 && delta != 1);
344920a0307cSWu Fengguang 
3450e8c5c824SLee Schermerhorn 	if (delta < 0) {
3451b2261026SJoonsoo Kim 		for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
3452b2261026SJoonsoo Kim 			if (h->surplus_huge_pages_node[node])
3453b2261026SJoonsoo Kim 				goto found;
3454b2261026SJoonsoo Kim 		}
3455b2261026SJoonsoo Kim 	} else {
3456b2261026SJoonsoo Kim 		for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
3457b2261026SJoonsoo Kim 			if (h->surplus_huge_pages_node[node] <
3458b2261026SJoonsoo Kim 					h->nr_huge_pages_node[node])
3459b2261026SJoonsoo Kim 				goto found;
3460e8c5c824SLee Schermerhorn 		}
34619a76db09SLee Schermerhorn 	}
3462b2261026SJoonsoo Kim 	return 0;
346320a0307cSWu Fengguang 
3464b2261026SJoonsoo Kim found:
346520a0307cSWu Fengguang 	h->surplus_huge_pages += delta;
3466b2261026SJoonsoo Kim 	h->surplus_huge_pages_node[node] += delta;
3467b2261026SJoonsoo Kim 	return 1;
346820a0307cSWu Fengguang }
346920a0307cSWu Fengguang 
3470a5516438SAndi Kleen #define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages)
set_max_huge_pages(struct hstate * h,unsigned long count,int nid,nodemask_t * nodes_allowed)3471fd875dcaSMike Kravetz static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,
34726ae11b27SLee Schermerhorn 			      nodemask_t *nodes_allowed)
34731da177e4SLinus Torvalds {
34747893d1d5SAdam Litke 	unsigned long min_count, ret;
347510c6ec49SMike Kravetz 	struct page *page;
347610c6ec49SMike Kravetz 	LIST_HEAD(page_list);
3477f60858f9SMike Kravetz 	NODEMASK_ALLOC(nodemask_t, node_alloc_noretry, GFP_KERNEL);
3478f60858f9SMike Kravetz 
3479f60858f9SMike Kravetz 	/*
3480f60858f9SMike Kravetz 	 * Bit mask controlling how hard we retry per-node allocations.
3481f60858f9SMike Kravetz 	 * If we can not allocate the bit mask, do not attempt to allocate
3482f60858f9SMike Kravetz 	 * the requested huge pages.
3483f60858f9SMike Kravetz 	 */
3484f60858f9SMike Kravetz 	if (node_alloc_noretry)
3485f60858f9SMike Kravetz 		nodes_clear(*node_alloc_noretry);
3486f60858f9SMike Kravetz 	else
3487f60858f9SMike Kravetz 		return -ENOMEM;
34881da177e4SLinus Torvalds 
348929383967SMike Kravetz 	/*
349029383967SMike Kravetz 	 * resize_lock mutex prevents concurrent adjustments to number of
349129383967SMike Kravetz 	 * pages in hstate via the proc/sysfs interfaces.
349229383967SMike Kravetz 	 */
349329383967SMike Kravetz 	mutex_lock(&h->resize_lock);
3494b65d4adbSMuchun Song 	flush_free_hpage_work(h);
3495db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
34964eb0716eSAlexandre Ghiti 
34974eb0716eSAlexandre Ghiti 	/*
3498fd875dcaSMike Kravetz 	 * Check for a node specific request.
3499fd875dcaSMike Kravetz 	 * Changing node specific huge page count may require a corresponding
3500fd875dcaSMike Kravetz 	 * change to the global count.  In any case, the passed node mask
3501fd875dcaSMike Kravetz 	 * (nodes_allowed) will restrict alloc/free to the specified node.
3502fd875dcaSMike Kravetz 	 */
3503fd875dcaSMike Kravetz 	if (nid != NUMA_NO_NODE) {
3504fd875dcaSMike Kravetz 		unsigned long old_count = count;
3505fd875dcaSMike Kravetz 
3506fd875dcaSMike Kravetz 		count += h->nr_huge_pages - h->nr_huge_pages_node[nid];
3507fd875dcaSMike Kravetz 		/*
3508fd875dcaSMike Kravetz 		 * User may have specified a large count value which caused the
3509fd875dcaSMike Kravetz 		 * above calculation to overflow.  In this case, they wanted
3510fd875dcaSMike Kravetz 		 * to allocate as many huge pages as possible.  Set count to
3511fd875dcaSMike Kravetz 		 * largest possible value to align with their intention.
3512fd875dcaSMike Kravetz 		 */
3513fd875dcaSMike Kravetz 		if (count < old_count)
3514fd875dcaSMike Kravetz 			count = ULONG_MAX;
3515fd875dcaSMike Kravetz 	}
3516fd875dcaSMike Kravetz 
3517fd875dcaSMike Kravetz 	/*
35184eb0716eSAlexandre Ghiti 	 * Gigantic pages runtime allocation depend on the capability for large
35194eb0716eSAlexandre Ghiti 	 * page range allocation.
35204eb0716eSAlexandre Ghiti 	 * If the system does not provide this feature, return an error when
35214eb0716eSAlexandre Ghiti 	 * the user tries to allocate gigantic pages but let the user free the
35224eb0716eSAlexandre Ghiti 	 * boottime allocated gigantic pages.
35234eb0716eSAlexandre Ghiti 	 */
35244eb0716eSAlexandre Ghiti 	if (hstate_is_gigantic(h) && !IS_ENABLED(CONFIG_CONTIG_ALLOC)) {
35254eb0716eSAlexandre Ghiti 		if (count > persistent_huge_pages(h)) {
3526db71ef79SMike Kravetz 			spin_unlock_irq(&hugetlb_lock);
352729383967SMike Kravetz 			mutex_unlock(&h->resize_lock);
3528f60858f9SMike Kravetz 			NODEMASK_FREE(node_alloc_noretry);
35294eb0716eSAlexandre Ghiti 			return -EINVAL;
35304eb0716eSAlexandre Ghiti 		}
35314eb0716eSAlexandre Ghiti 		/* Fall through to decrease pool */
35324eb0716eSAlexandre Ghiti 	}
3533aa888a74SAndi Kleen 
35347893d1d5SAdam Litke 	/*
35357893d1d5SAdam Litke 	 * Increase the pool size
35367893d1d5SAdam Litke 	 * First take pages out of surplus state.  Then make up the
35377893d1d5SAdam Litke 	 * remaining difference by allocating fresh huge pages.
3538d1c3fb1fSNishanth Aravamudan 	 *
35393a740e8bSSidhartha Kumar 	 * We might race with alloc_surplus_hugetlb_folio() here and be unable
3540d1c3fb1fSNishanth Aravamudan 	 * to convert a surplus huge page to a normal huge page. That is
3541d1c3fb1fSNishanth Aravamudan 	 * not critical, though, it just means the overall size of the
3542d1c3fb1fSNishanth Aravamudan 	 * pool might be one hugepage larger than it needs to be, but
3543d1c3fb1fSNishanth Aravamudan 	 * within all the constraints specified by the sysctls.
35447893d1d5SAdam Litke 	 */
3545a5516438SAndi Kleen 	while (h->surplus_huge_pages && count > persistent_huge_pages(h)) {
35466ae11b27SLee Schermerhorn 		if (!adjust_pool_surplus(h, nodes_allowed, -1))
35477893d1d5SAdam Litke 			break;
35487893d1d5SAdam Litke 	}
35497893d1d5SAdam Litke 
3550a5516438SAndi Kleen 	while (count > persistent_huge_pages(h)) {
35517893d1d5SAdam Litke 		/*
35527893d1d5SAdam Litke 		 * If this allocation races such that we no longer need the
3553454a00c4SMatthew Wilcox (Oracle) 		 * page, free_huge_folio will handle it by freeing the page
35547893d1d5SAdam Litke 		 * and reducing the surplus.
35557893d1d5SAdam Litke 		 */
3556db71ef79SMike Kravetz 		spin_unlock_irq(&hugetlb_lock);
3557649920c6SJia He 
3558649920c6SJia He 		/* yield cpu to avoid soft lockup */
3559649920c6SJia He 		cond_resched();
3560649920c6SJia He 
3561f60858f9SMike Kravetz 		ret = alloc_pool_huge_page(h, nodes_allowed,
3562f60858f9SMike Kravetz 						node_alloc_noretry);
3563db71ef79SMike Kravetz 		spin_lock_irq(&hugetlb_lock);
35647893d1d5SAdam Litke 		if (!ret)
35657893d1d5SAdam Litke 			goto out;
35667893d1d5SAdam Litke 
3567536240f2SMel Gorman 		/* Bail for signals. Probably ctrl-c from user */
3568536240f2SMel Gorman 		if (signal_pending(current))
3569536240f2SMel Gorman 			goto out;
35707893d1d5SAdam Litke 	}
35717893d1d5SAdam Litke 
35727893d1d5SAdam Litke 	/*
35737893d1d5SAdam Litke 	 * Decrease the pool size
35747893d1d5SAdam Litke 	 * First return free pages to the buddy allocator (being careful
35757893d1d5SAdam Litke 	 * to keep enough around to satisfy reservations).  Then place
35767893d1d5SAdam Litke 	 * pages into surplus state as needed so the pool will shrink
35777893d1d5SAdam Litke 	 * to the desired size as pages become free.
3578d1c3fb1fSNishanth Aravamudan 	 *
3579d1c3fb1fSNishanth Aravamudan 	 * By placing pages into the surplus state independent of the
3580d1c3fb1fSNishanth Aravamudan 	 * overcommit value, we are allowing the surplus pool size to
3581d1c3fb1fSNishanth Aravamudan 	 * exceed overcommit. There are few sane options here. Since
35823a740e8bSSidhartha Kumar 	 * alloc_surplus_hugetlb_folio() is checking the global counter,
3583d1c3fb1fSNishanth Aravamudan 	 * though, we'll note that we're not allowed to exceed surplus
3584d1c3fb1fSNishanth Aravamudan 	 * and won't grow the pool anywhere else. Not until one of the
3585d1c3fb1fSNishanth Aravamudan 	 * sysctls are changed, or the surplus pages go out of use.
35867893d1d5SAdam Litke 	 */
3587a5516438SAndi Kleen 	min_count = h->resv_huge_pages + h->nr_huge_pages - h->free_huge_pages;
35886b0c880dSAdam Litke 	min_count = max(count, min_count);
35896ae11b27SLee Schermerhorn 	try_to_free_low(h, min_count, nodes_allowed);
359010c6ec49SMike Kravetz 
359110c6ec49SMike Kravetz 	/*
359210c6ec49SMike Kravetz 	 * Collect pages to be removed on list without dropping lock
359310c6ec49SMike Kravetz 	 */
3594a5516438SAndi Kleen 	while (min_count < persistent_huge_pages(h)) {
359510c6ec49SMike Kravetz 		page = remove_pool_huge_page(h, nodes_allowed, 0);
359610c6ec49SMike Kravetz 		if (!page)
35971da177e4SLinus Torvalds 			break;
359810c6ec49SMike Kravetz 
359910c6ec49SMike Kravetz 		list_add(&page->lru, &page_list);
36001da177e4SLinus Torvalds 	}
360110c6ec49SMike Kravetz 	/* free the pages after dropping lock */
3602db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
360310c6ec49SMike Kravetz 	update_and_free_pages_bulk(h, &page_list);
3604b65d4adbSMuchun Song 	flush_free_hpage_work(h);
3605db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
360610c6ec49SMike Kravetz 
3607a5516438SAndi Kleen 	while (count < persistent_huge_pages(h)) {
36086ae11b27SLee Schermerhorn 		if (!adjust_pool_surplus(h, nodes_allowed, 1))
36097893d1d5SAdam Litke 			break;
36107893d1d5SAdam Litke 	}
36117893d1d5SAdam Litke out:
36124eb0716eSAlexandre Ghiti 	h->max_huge_pages = persistent_huge_pages(h);
3613db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
361429383967SMike Kravetz 	mutex_unlock(&h->resize_lock);
36154eb0716eSAlexandre Ghiti 
3616f60858f9SMike Kravetz 	NODEMASK_FREE(node_alloc_noretry);
3617f60858f9SMike Kravetz 
36184eb0716eSAlexandre Ghiti 	return 0;
36191da177e4SLinus Torvalds }
36201da177e4SLinus Torvalds 
demote_free_hugetlb_folio(struct hstate * h,struct folio * folio)3621bdd7be07SSidhartha Kumar static int demote_free_hugetlb_folio(struct hstate *h, struct folio *folio)
36228531fc6fSMike Kravetz {
3623bdd7be07SSidhartha Kumar 	int i, nid = folio_nid(folio);
36248531fc6fSMike Kravetz 	struct hstate *target_hstate;
362531731452SDoug Berger 	struct page *subpage;
3626bdd7be07SSidhartha Kumar 	struct folio *inner_folio;
36278531fc6fSMike Kravetz 	int rc = 0;
36288531fc6fSMike Kravetz 
36298531fc6fSMike Kravetz 	target_hstate = size_to_hstate(PAGE_SIZE << h->demote_order);
36308531fc6fSMike Kravetz 
3631cfd5082bSSidhartha Kumar 	remove_hugetlb_folio_for_demote(h, folio, false);
36328531fc6fSMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
36338531fc6fSMike Kravetz 
3634bdd7be07SSidhartha Kumar 	rc = hugetlb_vmemmap_restore(h, &folio->page);
36358531fc6fSMike Kravetz 	if (rc) {
3636bdd7be07SSidhartha Kumar 		/* Allocation of vmemmmap failed, we can not demote folio */
36378531fc6fSMike Kravetz 		spin_lock_irq(&hugetlb_lock);
3638bdd7be07SSidhartha Kumar 		folio_ref_unfreeze(folio, 1);
3639bdd7be07SSidhartha Kumar 		add_hugetlb_folio(h, folio, false);
36408531fc6fSMike Kravetz 		return rc;
36418531fc6fSMike Kravetz 	}
36428531fc6fSMike Kravetz 
36438531fc6fSMike Kravetz 	/*
3644911565b8SSidhartha Kumar 	 * Use destroy_compound_hugetlb_folio_for_demote for all huge page
3645bdd7be07SSidhartha Kumar 	 * sizes as it will not ref count folios.
36468531fc6fSMike Kravetz 	 */
3647911565b8SSidhartha Kumar 	destroy_compound_hugetlb_folio_for_demote(folio, huge_page_order(h));
36488531fc6fSMike Kravetz 
36498531fc6fSMike Kravetz 	/*
36508531fc6fSMike Kravetz 	 * Taking target hstate mutex synchronizes with set_max_huge_pages.
36518531fc6fSMike Kravetz 	 * Without the mutex, pages added to target hstate could be marked
36528531fc6fSMike Kravetz 	 * as surplus.
36538531fc6fSMike Kravetz 	 *
36548531fc6fSMike Kravetz 	 * Note that we already hold h->resize_lock.  To prevent deadlock,
36558531fc6fSMike Kravetz 	 * use the convention of always taking larger size hstate mutex first.
36568531fc6fSMike Kravetz 	 */
36578531fc6fSMike Kravetz 	mutex_lock(&target_hstate->resize_lock);
36588531fc6fSMike Kravetz 	for (i = 0; i < pages_per_huge_page(h);
36598531fc6fSMike Kravetz 				i += pages_per_huge_page(target_hstate)) {
3660bdd7be07SSidhartha Kumar 		subpage = folio_page(folio, i);
3661bdd7be07SSidhartha Kumar 		inner_folio = page_folio(subpage);
36628531fc6fSMike Kravetz 		if (hstate_is_gigantic(target_hstate))
3663bdd7be07SSidhartha Kumar 			prep_compound_gigantic_folio_for_demote(inner_folio,
36648531fc6fSMike Kravetz 							target_hstate->order);
36658531fc6fSMike Kravetz 		else
366631731452SDoug Berger 			prep_compound_page(subpage, target_hstate->order);
3667bdd7be07SSidhartha Kumar 		folio_change_private(inner_folio, NULL);
3668bdd7be07SSidhartha Kumar 		prep_new_hugetlb_folio(target_hstate, inner_folio, nid);
3669454a00c4SMatthew Wilcox (Oracle) 		free_huge_folio(inner_folio);
36708531fc6fSMike Kravetz 	}
36718531fc6fSMike Kravetz 	mutex_unlock(&target_hstate->resize_lock);
36728531fc6fSMike Kravetz 
36738531fc6fSMike Kravetz 	spin_lock_irq(&hugetlb_lock);
36748531fc6fSMike Kravetz 
36758531fc6fSMike Kravetz 	/*
36768531fc6fSMike Kravetz 	 * Not absolutely necessary, but for consistency update max_huge_pages
36778531fc6fSMike Kravetz 	 * based on pool changes for the demoted page.
36788531fc6fSMike Kravetz 	 */
36798531fc6fSMike Kravetz 	h->max_huge_pages--;
3680a43a83c7SMiaohe Lin 	target_hstate->max_huge_pages +=
3681a43a83c7SMiaohe Lin 		pages_per_huge_page(h) / pages_per_huge_page(target_hstate);
36828531fc6fSMike Kravetz 
36838531fc6fSMike Kravetz 	return rc;
36848531fc6fSMike Kravetz }
36858531fc6fSMike Kravetz 
demote_pool_huge_page(struct hstate * h,nodemask_t * nodes_allowed)368679dfc695SMike Kravetz static int demote_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed)
368779dfc695SMike Kravetz 	__must_hold(&hugetlb_lock)
368879dfc695SMike Kravetz {
36898531fc6fSMike Kravetz 	int nr_nodes, node;
3690bdd7be07SSidhartha Kumar 	struct folio *folio;
369179dfc695SMike Kravetz 
369279dfc695SMike Kravetz 	lockdep_assert_held(&hugetlb_lock);
369379dfc695SMike Kravetz 
369479dfc695SMike Kravetz 	/* We should never get here if no demote order */
369579dfc695SMike Kravetz 	if (!h->demote_order) {
369679dfc695SMike Kravetz 		pr_warn("HugeTLB: NULL demote order passed to demote_pool_huge_page.\n");
369779dfc695SMike Kravetz 		return -EINVAL;		/* internal error */
369879dfc695SMike Kravetz 	}
369979dfc695SMike Kravetz 
37008531fc6fSMike Kravetz 	for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
3701bdd7be07SSidhartha Kumar 		list_for_each_entry(folio, &h->hugepage_freelists[node], lru) {
3702bdd7be07SSidhartha Kumar 			if (folio_test_hwpoison(folio))
37035a317412SMike Kravetz 				continue;
3704bdd7be07SSidhartha Kumar 			return demote_free_hugetlb_folio(h, folio);
37058531fc6fSMike Kravetz 		}
37068531fc6fSMike Kravetz 	}
37078531fc6fSMike Kravetz 
37085a317412SMike Kravetz 	/*
37095a317412SMike Kravetz 	 * Only way to get here is if all pages on free lists are poisoned.
37105a317412SMike Kravetz 	 * Return -EBUSY so that caller will not retry.
37115a317412SMike Kravetz 	 */
37125a317412SMike Kravetz 	return -EBUSY;
371379dfc695SMike Kravetz }
371479dfc695SMike Kravetz 
3715a3437870SNishanth Aravamudan #define HSTATE_ATTR_RO(_name) \
3716a3437870SNishanth Aravamudan 	static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
3717a3437870SNishanth Aravamudan 
371879dfc695SMike Kravetz #define HSTATE_ATTR_WO(_name) \
371979dfc695SMike Kravetz 	static struct kobj_attribute _name##_attr = __ATTR_WO(_name)
372079dfc695SMike Kravetz 
3721a3437870SNishanth Aravamudan #define HSTATE_ATTR(_name) \
372298bc26acSMiaohe Lin 	static struct kobj_attribute _name##_attr = __ATTR_RW(_name)
3723a3437870SNishanth Aravamudan 
3724a3437870SNishanth Aravamudan static struct kobject *hugepages_kobj;
3725a3437870SNishanth Aravamudan static struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
3726a3437870SNishanth Aravamudan 
37279a305230SLee Schermerhorn static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp);
37289a305230SLee Schermerhorn 
kobj_to_hstate(struct kobject * kobj,int * nidp)37299a305230SLee Schermerhorn static struct hstate *kobj_to_hstate(struct kobject *kobj, int *nidp)
3730a3437870SNishanth Aravamudan {
3731a3437870SNishanth Aravamudan 	int i;
37329a305230SLee Schermerhorn 
3733a3437870SNishanth Aravamudan 	for (i = 0; i < HUGE_MAX_HSTATE; i++)
37349a305230SLee Schermerhorn 		if (hstate_kobjs[i] == kobj) {
37359a305230SLee Schermerhorn 			if (nidp)
37369a305230SLee Schermerhorn 				*nidp = NUMA_NO_NODE;
3737a3437870SNishanth Aravamudan 			return &hstates[i];
37389a305230SLee Schermerhorn 		}
37399a305230SLee Schermerhorn 
37409a305230SLee Schermerhorn 	return kobj_to_node_hstate(kobj, nidp);
3741a3437870SNishanth Aravamudan }
3742a3437870SNishanth Aravamudan 
nr_hugepages_show_common(struct kobject * kobj,struct kobj_attribute * attr,char * buf)374306808b08SLee Schermerhorn static ssize_t nr_hugepages_show_common(struct kobject *kobj,
3744a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
3745a3437870SNishanth Aravamudan {
37469a305230SLee Schermerhorn 	struct hstate *h;
37479a305230SLee Schermerhorn 	unsigned long nr_huge_pages;
37489a305230SLee Schermerhorn 	int nid;
37499a305230SLee Schermerhorn 
37509a305230SLee Schermerhorn 	h = kobj_to_hstate(kobj, &nid);
37519a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE)
37529a305230SLee Schermerhorn 		nr_huge_pages = h->nr_huge_pages;
37539a305230SLee Schermerhorn 	else
37549a305230SLee Schermerhorn 		nr_huge_pages = h->nr_huge_pages_node[nid];
37559a305230SLee Schermerhorn 
3756ae7a927dSJoe Perches 	return sysfs_emit(buf, "%lu\n", nr_huge_pages);
3757a3437870SNishanth Aravamudan }
3758adbe8726SEric B Munson 
__nr_hugepages_store_common(bool obey_mempolicy,struct hstate * h,int nid,unsigned long count,size_t len)3759238d3c13SDavid Rientjes static ssize_t __nr_hugepages_store_common(bool obey_mempolicy,
3760238d3c13SDavid Rientjes 					   struct hstate *h, int nid,
3761238d3c13SDavid Rientjes 					   unsigned long count, size_t len)
3762a3437870SNishanth Aravamudan {
3763a3437870SNishanth Aravamudan 	int err;
37642d0adf7eSOscar Salvador 	nodemask_t nodes_allowed, *n_mask;
3765a3437870SNishanth Aravamudan 
37662d0adf7eSOscar Salvador 	if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
37672d0adf7eSOscar Salvador 		return -EINVAL;
3768adbe8726SEric B Munson 
37699a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE) {
37709a305230SLee Schermerhorn 		/*
37719a305230SLee Schermerhorn 		 * global hstate attribute
37729a305230SLee Schermerhorn 		 */
37739a305230SLee Schermerhorn 		if (!(obey_mempolicy &&
37742d0adf7eSOscar Salvador 				init_nodemask_of_mempolicy(&nodes_allowed)))
37752d0adf7eSOscar Salvador 			n_mask = &node_states[N_MEMORY];
37762d0adf7eSOscar Salvador 		else
37772d0adf7eSOscar Salvador 			n_mask = &nodes_allowed;
37782d0adf7eSOscar Salvador 	} else {
37799a305230SLee Schermerhorn 		/*
3780fd875dcaSMike Kravetz 		 * Node specific request.  count adjustment happens in
3781fd875dcaSMike Kravetz 		 * set_max_huge_pages() after acquiring hugetlb_lock.
37829a305230SLee Schermerhorn 		 */
37832d0adf7eSOscar Salvador 		init_nodemask_of_node(&nodes_allowed, nid);
37842d0adf7eSOscar Salvador 		n_mask = &nodes_allowed;
3785fd875dcaSMike Kravetz 	}
37869a305230SLee Schermerhorn 
37872d0adf7eSOscar Salvador 	err = set_max_huge_pages(h, count, nid, n_mask);
378806808b08SLee Schermerhorn 
37894eb0716eSAlexandre Ghiti 	return err ? err : len;
379006808b08SLee Schermerhorn }
379106808b08SLee Schermerhorn 
nr_hugepages_store_common(bool obey_mempolicy,struct kobject * kobj,const char * buf,size_t len)3792238d3c13SDavid Rientjes static ssize_t nr_hugepages_store_common(bool obey_mempolicy,
3793238d3c13SDavid Rientjes 					 struct kobject *kobj, const char *buf,
3794238d3c13SDavid Rientjes 					 size_t len)
3795238d3c13SDavid Rientjes {
3796238d3c13SDavid Rientjes 	struct hstate *h;
3797238d3c13SDavid Rientjes 	unsigned long count;
3798238d3c13SDavid Rientjes 	int nid;
3799238d3c13SDavid Rientjes 	int err;
3800238d3c13SDavid Rientjes 
3801238d3c13SDavid Rientjes 	err = kstrtoul(buf, 10, &count);
3802238d3c13SDavid Rientjes 	if (err)
3803238d3c13SDavid Rientjes 		return err;
3804238d3c13SDavid Rientjes 
3805238d3c13SDavid Rientjes 	h = kobj_to_hstate(kobj, &nid);
3806238d3c13SDavid Rientjes 	return __nr_hugepages_store_common(obey_mempolicy, h, nid, count, len);
3807238d3c13SDavid Rientjes }
3808238d3c13SDavid Rientjes 
nr_hugepages_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)380906808b08SLee Schermerhorn static ssize_t nr_hugepages_show(struct kobject *kobj,
381006808b08SLee Schermerhorn 				       struct kobj_attribute *attr, char *buf)
381106808b08SLee Schermerhorn {
381206808b08SLee Schermerhorn 	return nr_hugepages_show_common(kobj, attr, buf);
381306808b08SLee Schermerhorn }
381406808b08SLee Schermerhorn 
nr_hugepages_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t len)381506808b08SLee Schermerhorn static ssize_t nr_hugepages_store(struct kobject *kobj,
381606808b08SLee Schermerhorn 	       struct kobj_attribute *attr, const char *buf, size_t len)
381706808b08SLee Schermerhorn {
3818238d3c13SDavid Rientjes 	return nr_hugepages_store_common(false, kobj, buf, len);
3819a3437870SNishanth Aravamudan }
3820a3437870SNishanth Aravamudan HSTATE_ATTR(nr_hugepages);
3821a3437870SNishanth Aravamudan 
382206808b08SLee Schermerhorn #ifdef CONFIG_NUMA
382306808b08SLee Schermerhorn 
382406808b08SLee Schermerhorn /*
382506808b08SLee Schermerhorn  * hstate attribute for optionally mempolicy-based constraint on persistent
382606808b08SLee Schermerhorn  * huge page alloc/free.
382706808b08SLee Schermerhorn  */
nr_hugepages_mempolicy_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)382806808b08SLee Schermerhorn static ssize_t nr_hugepages_mempolicy_show(struct kobject *kobj,
3829ae7a927dSJoe Perches 					   struct kobj_attribute *attr,
3830ae7a927dSJoe Perches 					   char *buf)
383106808b08SLee Schermerhorn {
383206808b08SLee Schermerhorn 	return nr_hugepages_show_common(kobj, attr, buf);
383306808b08SLee Schermerhorn }
383406808b08SLee Schermerhorn 
nr_hugepages_mempolicy_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t len)383506808b08SLee Schermerhorn static ssize_t nr_hugepages_mempolicy_store(struct kobject *kobj,
383606808b08SLee Schermerhorn 	       struct kobj_attribute *attr, const char *buf, size_t len)
383706808b08SLee Schermerhorn {
3838238d3c13SDavid Rientjes 	return nr_hugepages_store_common(true, kobj, buf, len);
383906808b08SLee Schermerhorn }
384006808b08SLee Schermerhorn HSTATE_ATTR(nr_hugepages_mempolicy);
384106808b08SLee Schermerhorn #endif
384206808b08SLee Schermerhorn 
384306808b08SLee Schermerhorn 
nr_overcommit_hugepages_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3844a3437870SNishanth Aravamudan static ssize_t nr_overcommit_hugepages_show(struct kobject *kobj,
3845a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
3846a3437870SNishanth Aravamudan {
38479a305230SLee Schermerhorn 	struct hstate *h = kobj_to_hstate(kobj, NULL);
3848ae7a927dSJoe Perches 	return sysfs_emit(buf, "%lu\n", h->nr_overcommit_huge_pages);
3849a3437870SNishanth Aravamudan }
3850adbe8726SEric B Munson 
nr_overcommit_hugepages_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)3851a3437870SNishanth Aravamudan static ssize_t nr_overcommit_hugepages_store(struct kobject *kobj,
3852a3437870SNishanth Aravamudan 		struct kobj_attribute *attr, const char *buf, size_t count)
3853a3437870SNishanth Aravamudan {
3854a3437870SNishanth Aravamudan 	int err;
3855a3437870SNishanth Aravamudan 	unsigned long input;
38569a305230SLee Schermerhorn 	struct hstate *h = kobj_to_hstate(kobj, NULL);
3857a3437870SNishanth Aravamudan 
3858bae7f4aeSLuiz Capitulino 	if (hstate_is_gigantic(h))
3859adbe8726SEric B Munson 		return -EINVAL;
3860adbe8726SEric B Munson 
38613dbb95f7SJingoo Han 	err = kstrtoul(buf, 10, &input);
3862a3437870SNishanth Aravamudan 	if (err)
386373ae31e5SEric B Munson 		return err;
3864a3437870SNishanth Aravamudan 
3865db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
3866a3437870SNishanth Aravamudan 	h->nr_overcommit_huge_pages = input;
3867db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
3868a3437870SNishanth Aravamudan 
3869a3437870SNishanth Aravamudan 	return count;
3870a3437870SNishanth Aravamudan }
3871a3437870SNishanth Aravamudan HSTATE_ATTR(nr_overcommit_hugepages);
3872a3437870SNishanth Aravamudan 
free_hugepages_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3873a3437870SNishanth Aravamudan static ssize_t free_hugepages_show(struct kobject *kobj,
3874a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
3875a3437870SNishanth Aravamudan {
38769a305230SLee Schermerhorn 	struct hstate *h;
38779a305230SLee Schermerhorn 	unsigned long free_huge_pages;
38789a305230SLee Schermerhorn 	int nid;
38799a305230SLee Schermerhorn 
38809a305230SLee Schermerhorn 	h = kobj_to_hstate(kobj, &nid);
38819a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE)
38829a305230SLee Schermerhorn 		free_huge_pages = h->free_huge_pages;
38839a305230SLee Schermerhorn 	else
38849a305230SLee Schermerhorn 		free_huge_pages = h->free_huge_pages_node[nid];
38859a305230SLee Schermerhorn 
3886ae7a927dSJoe Perches 	return sysfs_emit(buf, "%lu\n", free_huge_pages);
3887a3437870SNishanth Aravamudan }
3888a3437870SNishanth Aravamudan HSTATE_ATTR_RO(free_hugepages);
3889a3437870SNishanth Aravamudan 
resv_hugepages_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3890a3437870SNishanth Aravamudan static ssize_t resv_hugepages_show(struct kobject *kobj,
3891a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
3892a3437870SNishanth Aravamudan {
38939a305230SLee Schermerhorn 	struct hstate *h = kobj_to_hstate(kobj, NULL);
3894ae7a927dSJoe Perches 	return sysfs_emit(buf, "%lu\n", h->resv_huge_pages);
3895a3437870SNishanth Aravamudan }
3896a3437870SNishanth Aravamudan HSTATE_ATTR_RO(resv_hugepages);
3897a3437870SNishanth Aravamudan 
surplus_hugepages_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)3898a3437870SNishanth Aravamudan static ssize_t surplus_hugepages_show(struct kobject *kobj,
3899a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
3900a3437870SNishanth Aravamudan {
39019a305230SLee Schermerhorn 	struct hstate *h;
39029a305230SLee Schermerhorn 	unsigned long surplus_huge_pages;
39039a305230SLee Schermerhorn 	int nid;
39049a305230SLee Schermerhorn 
39059a305230SLee Schermerhorn 	h = kobj_to_hstate(kobj, &nid);
39069a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE)
39079a305230SLee Schermerhorn 		surplus_huge_pages = h->surplus_huge_pages;
39089a305230SLee Schermerhorn 	else
39099a305230SLee Schermerhorn 		surplus_huge_pages = h->surplus_huge_pages_node[nid];
39109a305230SLee Schermerhorn 
3911ae7a927dSJoe Perches 	return sysfs_emit(buf, "%lu\n", surplus_huge_pages);
3912a3437870SNishanth Aravamudan }
3913a3437870SNishanth Aravamudan HSTATE_ATTR_RO(surplus_hugepages);
3914a3437870SNishanth Aravamudan 
demote_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t len)391579dfc695SMike Kravetz static ssize_t demote_store(struct kobject *kobj,
391679dfc695SMike Kravetz 	       struct kobj_attribute *attr, const char *buf, size_t len)
391779dfc695SMike Kravetz {
391879dfc695SMike Kravetz 	unsigned long nr_demote;
391979dfc695SMike Kravetz 	unsigned long nr_available;
392079dfc695SMike Kravetz 	nodemask_t nodes_allowed, *n_mask;
392179dfc695SMike Kravetz 	struct hstate *h;
39228eeda55fSLi zeming 	int err;
392379dfc695SMike Kravetz 	int nid;
392479dfc695SMike Kravetz 
392579dfc695SMike Kravetz 	err = kstrtoul(buf, 10, &nr_demote);
392679dfc695SMike Kravetz 	if (err)
392779dfc695SMike Kravetz 		return err;
392879dfc695SMike Kravetz 	h = kobj_to_hstate(kobj, &nid);
392979dfc695SMike Kravetz 
393079dfc695SMike Kravetz 	if (nid != NUMA_NO_NODE) {
393179dfc695SMike Kravetz 		init_nodemask_of_node(&nodes_allowed, nid);
393279dfc695SMike Kravetz 		n_mask = &nodes_allowed;
393379dfc695SMike Kravetz 	} else {
393479dfc695SMike Kravetz 		n_mask = &node_states[N_MEMORY];
393579dfc695SMike Kravetz 	}
393679dfc695SMike Kravetz 
393779dfc695SMike Kravetz 	/* Synchronize with other sysfs operations modifying huge pages */
393879dfc695SMike Kravetz 	mutex_lock(&h->resize_lock);
393979dfc695SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
394079dfc695SMike Kravetz 
394179dfc695SMike Kravetz 	while (nr_demote) {
394279dfc695SMike Kravetz 		/*
394379dfc695SMike Kravetz 		 * Check for available pages to demote each time thorough the
394479dfc695SMike Kravetz 		 * loop as demote_pool_huge_page will drop hugetlb_lock.
394579dfc695SMike Kravetz 		 */
394679dfc695SMike Kravetz 		if (nid != NUMA_NO_NODE)
394779dfc695SMike Kravetz 			nr_available = h->free_huge_pages_node[nid];
394879dfc695SMike Kravetz 		else
394979dfc695SMike Kravetz 			nr_available = h->free_huge_pages;
395079dfc695SMike Kravetz 		nr_available -= h->resv_huge_pages;
395179dfc695SMike Kravetz 		if (!nr_available)
395279dfc695SMike Kravetz 			break;
395379dfc695SMike Kravetz 
395479dfc695SMike Kravetz 		err = demote_pool_huge_page(h, n_mask);
395579dfc695SMike Kravetz 		if (err)
395679dfc695SMike Kravetz 			break;
395779dfc695SMike Kravetz 
395879dfc695SMike Kravetz 		nr_demote--;
395979dfc695SMike Kravetz 	}
396079dfc695SMike Kravetz 
396179dfc695SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
396279dfc695SMike Kravetz 	mutex_unlock(&h->resize_lock);
396379dfc695SMike Kravetz 
396479dfc695SMike Kravetz 	if (err)
396579dfc695SMike Kravetz 		return err;
396679dfc695SMike Kravetz 	return len;
396779dfc695SMike Kravetz }
396879dfc695SMike Kravetz HSTATE_ATTR_WO(demote);
396979dfc695SMike Kravetz 
demote_size_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)397079dfc695SMike Kravetz static ssize_t demote_size_show(struct kobject *kobj,
397179dfc695SMike Kravetz 					struct kobj_attribute *attr, char *buf)
397279dfc695SMike Kravetz {
397312658abfSMiaohe Lin 	struct hstate *h = kobj_to_hstate(kobj, NULL);
397479dfc695SMike Kravetz 	unsigned long demote_size = (PAGE_SIZE << h->demote_order) / SZ_1K;
397579dfc695SMike Kravetz 
397679dfc695SMike Kravetz 	return sysfs_emit(buf, "%lukB\n", demote_size);
397779dfc695SMike Kravetz }
397879dfc695SMike Kravetz 
demote_size_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)397979dfc695SMike Kravetz static ssize_t demote_size_store(struct kobject *kobj,
398079dfc695SMike Kravetz 					struct kobj_attribute *attr,
398179dfc695SMike Kravetz 					const char *buf, size_t count)
398279dfc695SMike Kravetz {
398379dfc695SMike Kravetz 	struct hstate *h, *demote_hstate;
398479dfc695SMike Kravetz 	unsigned long demote_size;
398579dfc695SMike Kravetz 	unsigned int demote_order;
398679dfc695SMike Kravetz 
398779dfc695SMike Kravetz 	demote_size = (unsigned long)memparse(buf, NULL);
398879dfc695SMike Kravetz 
398979dfc695SMike Kravetz 	demote_hstate = size_to_hstate(demote_size);
399079dfc695SMike Kravetz 	if (!demote_hstate)
399179dfc695SMike Kravetz 		return -EINVAL;
399279dfc695SMike Kravetz 	demote_order = demote_hstate->order;
3993a01f4390SMike Kravetz 	if (demote_order < HUGETLB_PAGE_ORDER)
3994a01f4390SMike Kravetz 		return -EINVAL;
399579dfc695SMike Kravetz 
399679dfc695SMike Kravetz 	/* demote order must be smaller than hstate order */
399712658abfSMiaohe Lin 	h = kobj_to_hstate(kobj, NULL);
399879dfc695SMike Kravetz 	if (demote_order >= h->order)
399979dfc695SMike Kravetz 		return -EINVAL;
400079dfc695SMike Kravetz 
400179dfc695SMike Kravetz 	/* resize_lock synchronizes access to demote size and writes */
400279dfc695SMike Kravetz 	mutex_lock(&h->resize_lock);
400379dfc695SMike Kravetz 	h->demote_order = demote_order;
400479dfc695SMike Kravetz 	mutex_unlock(&h->resize_lock);
400579dfc695SMike Kravetz 
400679dfc695SMike Kravetz 	return count;
400779dfc695SMike Kravetz }
400879dfc695SMike Kravetz HSTATE_ATTR(demote_size);
400979dfc695SMike Kravetz 
4010a3437870SNishanth Aravamudan static struct attribute *hstate_attrs[] = {
4011a3437870SNishanth Aravamudan 	&nr_hugepages_attr.attr,
4012a3437870SNishanth Aravamudan 	&nr_overcommit_hugepages_attr.attr,
4013a3437870SNishanth Aravamudan 	&free_hugepages_attr.attr,
4014a3437870SNishanth Aravamudan 	&resv_hugepages_attr.attr,
4015a3437870SNishanth Aravamudan 	&surplus_hugepages_attr.attr,
401606808b08SLee Schermerhorn #ifdef CONFIG_NUMA
401706808b08SLee Schermerhorn 	&nr_hugepages_mempolicy_attr.attr,
401806808b08SLee Schermerhorn #endif
4019a3437870SNishanth Aravamudan 	NULL,
4020a3437870SNishanth Aravamudan };
4021a3437870SNishanth Aravamudan 
402267e5ed96SArvind Yadav static const struct attribute_group hstate_attr_group = {
4023a3437870SNishanth Aravamudan 	.attrs = hstate_attrs,
4024a3437870SNishanth Aravamudan };
4025a3437870SNishanth Aravamudan 
402679dfc695SMike Kravetz static struct attribute *hstate_demote_attrs[] = {
402779dfc695SMike Kravetz 	&demote_size_attr.attr,
402879dfc695SMike Kravetz 	&demote_attr.attr,
402979dfc695SMike Kravetz 	NULL,
403079dfc695SMike Kravetz };
403179dfc695SMike Kravetz 
403279dfc695SMike Kravetz static const struct attribute_group hstate_demote_attr_group = {
403379dfc695SMike Kravetz 	.attrs = hstate_demote_attrs,
403479dfc695SMike Kravetz };
403579dfc695SMike Kravetz 
hugetlb_sysfs_add_hstate(struct hstate * h,struct kobject * parent,struct kobject ** hstate_kobjs,const struct attribute_group * hstate_attr_group)4036094e9539SJeff Mahoney static int hugetlb_sysfs_add_hstate(struct hstate *h, struct kobject *parent,
40379a305230SLee Schermerhorn 				    struct kobject **hstate_kobjs,
403867e5ed96SArvind Yadav 				    const struct attribute_group *hstate_attr_group)
4039a3437870SNishanth Aravamudan {
4040a3437870SNishanth Aravamudan 	int retval;
4041972dc4deSAneesh Kumar K.V 	int hi = hstate_index(h);
4042a3437870SNishanth Aravamudan 
40439a305230SLee Schermerhorn 	hstate_kobjs[hi] = kobject_create_and_add(h->name, parent);
40449a305230SLee Schermerhorn 	if (!hstate_kobjs[hi])
4045a3437870SNishanth Aravamudan 		return -ENOMEM;
4046a3437870SNishanth Aravamudan 
40479a305230SLee Schermerhorn 	retval = sysfs_create_group(hstate_kobjs[hi], hstate_attr_group);
4048cc2205a6SMiaohe Lin 	if (retval) {
40499a305230SLee Schermerhorn 		kobject_put(hstate_kobjs[hi]);
4050cc2205a6SMiaohe Lin 		hstate_kobjs[hi] = NULL;
40513a6bdda0SMiaohe Lin 		return retval;
4052cc2205a6SMiaohe Lin 	}
4053a3437870SNishanth Aravamudan 
405479dfc695SMike Kravetz 	if (h->demote_order) {
405501088a60SMiaohe Lin 		retval = sysfs_create_group(hstate_kobjs[hi],
405601088a60SMiaohe Lin 					    &hstate_demote_attr_group);
405701088a60SMiaohe Lin 		if (retval) {
405879dfc695SMike Kravetz 			pr_warn("HugeTLB unable to create demote interfaces for %s\n", h->name);
405901088a60SMiaohe Lin 			sysfs_remove_group(hstate_kobjs[hi], hstate_attr_group);
406001088a60SMiaohe Lin 			kobject_put(hstate_kobjs[hi]);
406101088a60SMiaohe Lin 			hstate_kobjs[hi] = NULL;
406201088a60SMiaohe Lin 			return retval;
406301088a60SMiaohe Lin 		}
406479dfc695SMike Kravetz 	}
406579dfc695SMike Kravetz 
406601088a60SMiaohe Lin 	return 0;
4067a3437870SNishanth Aravamudan }
4068a3437870SNishanth Aravamudan 
40699a305230SLee Schermerhorn #ifdef CONFIG_NUMA
4070a4a00b45SMuchun Song static bool hugetlb_sysfs_initialized __ro_after_init;
40719a305230SLee Schermerhorn 
40729a305230SLee Schermerhorn /*
40739a305230SLee Schermerhorn  * node_hstate/s - associate per node hstate attributes, via their kobjects,
407410fbcf4cSKay Sievers  * with node devices in node_devices[] using a parallel array.  The array
407510fbcf4cSKay Sievers  * index of a node device or _hstate == node id.
407610fbcf4cSKay Sievers  * This is here to avoid any static dependency of the node device driver, in
40779a305230SLee Schermerhorn  * the base kernel, on the hugetlb module.
40789a305230SLee Schermerhorn  */
40799a305230SLee Schermerhorn struct node_hstate {
40809a305230SLee Schermerhorn 	struct kobject		*hugepages_kobj;
40819a305230SLee Schermerhorn 	struct kobject		*hstate_kobjs[HUGE_MAX_HSTATE];
40829a305230SLee Schermerhorn };
4083b4e289a6SAlexander Kuleshov static struct node_hstate node_hstates[MAX_NUMNODES];
40849a305230SLee Schermerhorn 
40859a305230SLee Schermerhorn /*
408610fbcf4cSKay Sievers  * A subset of global hstate attributes for node devices
40879a305230SLee Schermerhorn  */
40889a305230SLee Schermerhorn static struct attribute *per_node_hstate_attrs[] = {
40899a305230SLee Schermerhorn 	&nr_hugepages_attr.attr,
40909a305230SLee Schermerhorn 	&free_hugepages_attr.attr,
40919a305230SLee Schermerhorn 	&surplus_hugepages_attr.attr,
40929a305230SLee Schermerhorn 	NULL,
40939a305230SLee Schermerhorn };
40949a305230SLee Schermerhorn 
409567e5ed96SArvind Yadav static const struct attribute_group per_node_hstate_attr_group = {
40969a305230SLee Schermerhorn 	.attrs = per_node_hstate_attrs,
40979a305230SLee Schermerhorn };
40989a305230SLee Schermerhorn 
40999a305230SLee Schermerhorn /*
410010fbcf4cSKay Sievers  * kobj_to_node_hstate - lookup global hstate for node device hstate attr kobj.
41019a305230SLee Schermerhorn  * Returns node id via non-NULL nidp.
41029a305230SLee Schermerhorn  */
kobj_to_node_hstate(struct kobject * kobj,int * nidp)41039a305230SLee Schermerhorn static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
41049a305230SLee Schermerhorn {
41059a305230SLee Schermerhorn 	int nid;
41069a305230SLee Schermerhorn 
41079a305230SLee Schermerhorn 	for (nid = 0; nid < nr_node_ids; nid++) {
41089a305230SLee Schermerhorn 		struct node_hstate *nhs = &node_hstates[nid];
41099a305230SLee Schermerhorn 		int i;
41109a305230SLee Schermerhorn 		for (i = 0; i < HUGE_MAX_HSTATE; i++)
41119a305230SLee Schermerhorn 			if (nhs->hstate_kobjs[i] == kobj) {
41129a305230SLee Schermerhorn 				if (nidp)
41139a305230SLee Schermerhorn 					*nidp = nid;
41149a305230SLee Schermerhorn 				return &hstates[i];
41159a305230SLee Schermerhorn 			}
41169a305230SLee Schermerhorn 	}
41179a305230SLee Schermerhorn 
41189a305230SLee Schermerhorn 	BUG();
41199a305230SLee Schermerhorn 	return NULL;
41209a305230SLee Schermerhorn }
41219a305230SLee Schermerhorn 
41229a305230SLee Schermerhorn /*
412310fbcf4cSKay Sievers  * Unregister hstate attributes from a single node device.
41249a305230SLee Schermerhorn  * No-op if no hstate attributes attached.
41259a305230SLee Schermerhorn  */
hugetlb_unregister_node(struct node * node)4126a4a00b45SMuchun Song void hugetlb_unregister_node(struct node *node)
41279a305230SLee Schermerhorn {
41289a305230SLee Schermerhorn 	struct hstate *h;
412910fbcf4cSKay Sievers 	struct node_hstate *nhs = &node_hstates[node->dev.id];
41309a305230SLee Schermerhorn 
41319a305230SLee Schermerhorn 	if (!nhs->hugepages_kobj)
41329b5e5d0fSLee Schermerhorn 		return;		/* no hstate attributes */
41339a305230SLee Schermerhorn 
4134972dc4deSAneesh Kumar K.V 	for_each_hstate(h) {
4135972dc4deSAneesh Kumar K.V 		int idx = hstate_index(h);
413601088a60SMiaohe Lin 		struct kobject *hstate_kobj = nhs->hstate_kobjs[idx];
413701088a60SMiaohe Lin 
413801088a60SMiaohe Lin 		if (!hstate_kobj)
413901088a60SMiaohe Lin 			continue;
414001088a60SMiaohe Lin 		if (h->demote_order)
414101088a60SMiaohe Lin 			sysfs_remove_group(hstate_kobj, &hstate_demote_attr_group);
414201088a60SMiaohe Lin 		sysfs_remove_group(hstate_kobj, &per_node_hstate_attr_group);
414301088a60SMiaohe Lin 		kobject_put(hstate_kobj);
4144972dc4deSAneesh Kumar K.V 		nhs->hstate_kobjs[idx] = NULL;
4145972dc4deSAneesh Kumar K.V 	}
41469a305230SLee Schermerhorn 
41479a305230SLee Schermerhorn 	kobject_put(nhs->hugepages_kobj);
41489a305230SLee Schermerhorn 	nhs->hugepages_kobj = NULL;
41499a305230SLee Schermerhorn }
41509a305230SLee Schermerhorn 
41519a305230SLee Schermerhorn 
41529a305230SLee Schermerhorn /*
415310fbcf4cSKay Sievers  * Register hstate attributes for a single node device.
41549a305230SLee Schermerhorn  * No-op if attributes already registered.
41559a305230SLee Schermerhorn  */
hugetlb_register_node(struct node * node)4156a4a00b45SMuchun Song void hugetlb_register_node(struct node *node)
41579a305230SLee Schermerhorn {
41589a305230SLee Schermerhorn 	struct hstate *h;
415910fbcf4cSKay Sievers 	struct node_hstate *nhs = &node_hstates[node->dev.id];
41609a305230SLee Schermerhorn 	int err;
41619a305230SLee Schermerhorn 
4162a4a00b45SMuchun Song 	if (!hugetlb_sysfs_initialized)
4163a4a00b45SMuchun Song 		return;
4164a4a00b45SMuchun Song 
41659a305230SLee Schermerhorn 	if (nhs->hugepages_kobj)
41669a305230SLee Schermerhorn 		return;		/* already allocated */
41679a305230SLee Schermerhorn 
41689a305230SLee Schermerhorn 	nhs->hugepages_kobj = kobject_create_and_add("hugepages",
416910fbcf4cSKay Sievers 							&node->dev.kobj);
41709a305230SLee Schermerhorn 	if (!nhs->hugepages_kobj)
41719a305230SLee Schermerhorn 		return;
41729a305230SLee Schermerhorn 
41739a305230SLee Schermerhorn 	for_each_hstate(h) {
41749a305230SLee Schermerhorn 		err = hugetlb_sysfs_add_hstate(h, nhs->hugepages_kobj,
41759a305230SLee Schermerhorn 						nhs->hstate_kobjs,
41769a305230SLee Schermerhorn 						&per_node_hstate_attr_group);
41779a305230SLee Schermerhorn 		if (err) {
4178282f4214SMike Kravetz 			pr_err("HugeTLB: Unable to add hstate %s for node %d\n",
417910fbcf4cSKay Sievers 				h->name, node->dev.id);
41809a305230SLee Schermerhorn 			hugetlb_unregister_node(node);
41819a305230SLee Schermerhorn 			break;
41829a305230SLee Schermerhorn 		}
41839a305230SLee Schermerhorn 	}
41849a305230SLee Schermerhorn }
41859a305230SLee Schermerhorn 
41869a305230SLee Schermerhorn /*
41879b5e5d0fSLee Schermerhorn  * hugetlb init time:  register hstate attributes for all registered node
418810fbcf4cSKay Sievers  * devices of nodes that have memory.  All on-line nodes should have
418910fbcf4cSKay Sievers  * registered their associated device by this time.
41909a305230SLee Schermerhorn  */
hugetlb_register_all_nodes(void)41917d9ca000SLuiz Capitulino static void __init hugetlb_register_all_nodes(void)
41929a305230SLee Schermerhorn {
41939a305230SLee Schermerhorn 	int nid;
41949a305230SLee Schermerhorn 
4195a4a00b45SMuchun Song 	for_each_online_node(nid)
4196b958d4d0SMuchun Song 		hugetlb_register_node(node_devices[nid]);
41979a305230SLee Schermerhorn }
41989a305230SLee Schermerhorn #else	/* !CONFIG_NUMA */
41999a305230SLee Schermerhorn 
kobj_to_node_hstate(struct kobject * kobj,int * nidp)42009a305230SLee Schermerhorn static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
42019a305230SLee Schermerhorn {
42029a305230SLee Schermerhorn 	BUG();
42039a305230SLee Schermerhorn 	if (nidp)
42049a305230SLee Schermerhorn 		*nidp = -1;
42059a305230SLee Schermerhorn 	return NULL;
42069a305230SLee Schermerhorn }
42079a305230SLee Schermerhorn 
hugetlb_register_all_nodes(void)42089a305230SLee Schermerhorn static void hugetlb_register_all_nodes(void) { }
42099a305230SLee Schermerhorn 
42109a305230SLee Schermerhorn #endif
42119a305230SLee Schermerhorn 
4212263b8998SMiaohe Lin #ifdef CONFIG_CMA
4213263b8998SMiaohe Lin static void __init hugetlb_cma_check(void);
4214263b8998SMiaohe Lin #else
hugetlb_cma_check(void)4215263b8998SMiaohe Lin static inline __init void hugetlb_cma_check(void)
4216263b8998SMiaohe Lin {
4217263b8998SMiaohe Lin }
4218263b8998SMiaohe Lin #endif
4219263b8998SMiaohe Lin 
hugetlb_sysfs_init(void)4220a4a00b45SMuchun Song static void __init hugetlb_sysfs_init(void)
4221a4a00b45SMuchun Song {
4222a4a00b45SMuchun Song 	struct hstate *h;
4223a4a00b45SMuchun Song 	int err;
4224a4a00b45SMuchun Song 
4225a4a00b45SMuchun Song 	hugepages_kobj = kobject_create_and_add("hugepages", mm_kobj);
4226a4a00b45SMuchun Song 	if (!hugepages_kobj)
4227a4a00b45SMuchun Song 		return;
4228a4a00b45SMuchun Song 
4229a4a00b45SMuchun Song 	for_each_hstate(h) {
4230a4a00b45SMuchun Song 		err = hugetlb_sysfs_add_hstate(h, hugepages_kobj,
4231a4a00b45SMuchun Song 					 hstate_kobjs, &hstate_attr_group);
4232a4a00b45SMuchun Song 		if (err)
4233a4a00b45SMuchun Song 			pr_err("HugeTLB: Unable to add hstate %s", h->name);
4234a4a00b45SMuchun Song 	}
4235a4a00b45SMuchun Song 
4236a4a00b45SMuchun Song #ifdef CONFIG_NUMA
4237a4a00b45SMuchun Song 	hugetlb_sysfs_initialized = true;
4238a4a00b45SMuchun Song #endif
4239a4a00b45SMuchun Song 	hugetlb_register_all_nodes();
4240a4a00b45SMuchun Song }
4241a4a00b45SMuchun Song 
4242962de548SKefeng Wang #ifdef CONFIG_SYSCTL
4243962de548SKefeng Wang static void hugetlb_sysctl_init(void);
4244962de548SKefeng Wang #else
hugetlb_sysctl_init(void)4245962de548SKefeng Wang static inline void hugetlb_sysctl_init(void) { }
4246962de548SKefeng Wang #endif
4247962de548SKefeng Wang 
hugetlb_init(void)4248a3437870SNishanth Aravamudan static int __init hugetlb_init(void)
4249a3437870SNishanth Aravamudan {
42508382d914SDavidlohr Bueso 	int i;
42518382d914SDavidlohr Bueso 
4252d6995da3SMike Kravetz 	BUILD_BUG_ON(sizeof_field(struct page, private) * BITS_PER_BYTE <
4253d6995da3SMike Kravetz 			__NR_HPAGEFLAGS);
4254d6995da3SMike Kravetz 
4255c2833a5bSMike Kravetz 	if (!hugepages_supported()) {
4256c2833a5bSMike Kravetz 		if (hugetlb_max_hstate || default_hstate_max_huge_pages)
4257c2833a5bSMike Kravetz 			pr_warn("HugeTLB: huge pages not supported, ignoring associated command-line parameters\n");
42580ef89d25SBenjamin Herrenschmidt 		return 0;
4259d715cf80SLiam R. Howlett 	}
4260d715cf80SLiam R. Howlett 
4261282f4214SMike Kravetz 	/*
4262282f4214SMike Kravetz 	 * Make sure HPAGE_SIZE (HUGETLB_PAGE_ORDER) hstate exists.  Some
4263282f4214SMike Kravetz 	 * architectures depend on setup being done here.
4264282f4214SMike Kravetz 	 */
4265a3437870SNishanth Aravamudan 	hugetlb_add_hstate(HUGETLB_PAGE_ORDER);
4266282f4214SMike Kravetz 	if (!parsed_default_hugepagesz) {
4267282f4214SMike Kravetz 		/*
4268282f4214SMike Kravetz 		 * If we did not parse a default huge page size, set
4269282f4214SMike Kravetz 		 * default_hstate_idx to HPAGE_SIZE hstate. And, if the
4270282f4214SMike Kravetz 		 * number of huge pages for this default size was implicitly
4271282f4214SMike Kravetz 		 * specified, set that here as well.
4272282f4214SMike Kravetz 		 * Note that the implicit setting will overwrite an explicit
4273282f4214SMike Kravetz 		 * setting.  A warning will be printed in this case.
4274282f4214SMike Kravetz 		 */
4275282f4214SMike Kravetz 		default_hstate_idx = hstate_index(size_to_hstate(HPAGE_SIZE));
4276f8b74815SVaishali Thakkar 		if (default_hstate_max_huge_pages) {
4277282f4214SMike Kravetz 			if (default_hstate.max_huge_pages) {
4278282f4214SMike Kravetz 				char buf[32];
4279282f4214SMike Kravetz 
4280282f4214SMike Kravetz 				string_get_size(huge_page_size(&default_hstate),
4281282f4214SMike Kravetz 					1, STRING_UNITS_2, buf, 32);
4282282f4214SMike Kravetz 				pr_warn("HugeTLB: Ignoring hugepages=%lu associated with %s page size\n",
4283282f4214SMike Kravetz 					default_hstate.max_huge_pages, buf);
4284282f4214SMike Kravetz 				pr_warn("HugeTLB: Using hugepages=%lu for number of default huge pages\n",
4285282f4214SMike Kravetz 					default_hstate_max_huge_pages);
4286282f4214SMike Kravetz 			}
4287282f4214SMike Kravetz 			default_hstate.max_huge_pages =
4288282f4214SMike Kravetz 				default_hstate_max_huge_pages;
4289b5389086SZhenguo Yao 
42900a7a0f6fSPeng Liu 			for_each_online_node(i)
4291b5389086SZhenguo Yao 				default_hstate.max_huge_pages_node[i] =
4292b5389086SZhenguo Yao 					default_hugepages_in_node[i];
4293282f4214SMike Kravetz 		}
4294f8b74815SVaishali Thakkar 	}
4295a3437870SNishanth Aravamudan 
4296cf11e85fSRoman Gushchin 	hugetlb_cma_check();
4297a3437870SNishanth Aravamudan 	hugetlb_init_hstates();
4298aa888a74SAndi Kleen 	gather_bootmem_prealloc();
4299a3437870SNishanth Aravamudan 	report_hugepages();
4300a3437870SNishanth Aravamudan 
4301a3437870SNishanth Aravamudan 	hugetlb_sysfs_init();
43027179e7bfSJianguo Wu 	hugetlb_cgroup_file_init();
4303962de548SKefeng Wang 	hugetlb_sysctl_init();
43049a305230SLee Schermerhorn 
43058382d914SDavidlohr Bueso #ifdef CONFIG_SMP
43068382d914SDavidlohr Bueso 	num_fault_mutexes = roundup_pow_of_two(8 * num_possible_cpus());
43078382d914SDavidlohr Bueso #else
43088382d914SDavidlohr Bueso 	num_fault_mutexes = 1;
43098382d914SDavidlohr Bueso #endif
4310c672c7f2SMike Kravetz 	hugetlb_fault_mutex_table =
43116da2ec56SKees Cook 		kmalloc_array(num_fault_mutexes, sizeof(struct mutex),
43126da2ec56SKees Cook 			      GFP_KERNEL);
4313c672c7f2SMike Kravetz 	BUG_ON(!hugetlb_fault_mutex_table);
43148382d914SDavidlohr Bueso 
43158382d914SDavidlohr Bueso 	for (i = 0; i < num_fault_mutexes; i++)
4316c672c7f2SMike Kravetz 		mutex_init(&hugetlb_fault_mutex_table[i]);
4317a3437870SNishanth Aravamudan 	return 0;
4318a3437870SNishanth Aravamudan }
43193e89e1c5SPaul Gortmaker subsys_initcall(hugetlb_init);
4320a3437870SNishanth Aravamudan 
4321ae94da89SMike Kravetz /* Overwritten by architectures with more huge page sizes */
__init(weak)4322ae94da89SMike Kravetz bool __init __attribute((weak)) arch_hugetlb_valid_size(unsigned long size)
43239fee021dSVaishali Thakkar {
4324ae94da89SMike Kravetz 	return size == HPAGE_SIZE;
43259fee021dSVaishali Thakkar }
43269fee021dSVaishali Thakkar 
hugetlb_add_hstate(unsigned int order)4327d00181b9SKirill A. Shutemov void __init hugetlb_add_hstate(unsigned int order)
4328a3437870SNishanth Aravamudan {
4329a3437870SNishanth Aravamudan 	struct hstate *h;
43308faa8b07SAndi Kleen 	unsigned long i;
43318faa8b07SAndi Kleen 
4332a3437870SNishanth Aravamudan 	if (size_to_hstate(PAGE_SIZE << order)) {
4333a3437870SNishanth Aravamudan 		return;
4334a3437870SNishanth Aravamudan 	}
433547d38344SAneesh Kumar K.V 	BUG_ON(hugetlb_max_hstate >= HUGE_MAX_HSTATE);
4336a3437870SNishanth Aravamudan 	BUG_ON(order == 0);
433747d38344SAneesh Kumar K.V 	h = &hstates[hugetlb_max_hstate++];
433899a49b67SMiaohe Lin 	__mutex_init(&h->resize_lock, "resize mutex", &h->resize_key);
4339a3437870SNishanth Aravamudan 	h->order = order;
4340aca78307SMiaohe Lin 	h->mask = ~(huge_page_size(h) - 1);
43418faa8b07SAndi Kleen 	for (i = 0; i < MAX_NUMNODES; ++i)
43428faa8b07SAndi Kleen 		INIT_LIST_HEAD(&h->hugepage_freelists[i]);
43430edaecfaSAneesh Kumar K.V 	INIT_LIST_HEAD(&h->hugepage_activelist);
434454f18d35SAndrew Morton 	h->next_nid_to_alloc = first_memory_node;
434554f18d35SAndrew Morton 	h->next_nid_to_free = first_memory_node;
4346a3437870SNishanth Aravamudan 	snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB",
4347c2c3a60aSMiaohe Lin 					huge_page_size(h)/SZ_1K);
43488faa8b07SAndi Kleen 
4349a3437870SNishanth Aravamudan 	parsed_hstate = h;
4350a3437870SNishanth Aravamudan }
4351a3437870SNishanth Aravamudan 
hugetlb_node_alloc_supported(void)4352b5389086SZhenguo Yao bool __init __weak hugetlb_node_alloc_supported(void)
4353b5389086SZhenguo Yao {
4354b5389086SZhenguo Yao 	return true;
4355b5389086SZhenguo Yao }
4356f87442f4SPeng Liu 
hugepages_clear_pages_in_node(void)4357f87442f4SPeng Liu static void __init hugepages_clear_pages_in_node(void)
4358f87442f4SPeng Liu {
4359f87442f4SPeng Liu 	if (!hugetlb_max_hstate) {
4360f87442f4SPeng Liu 		default_hstate_max_huge_pages = 0;
4361f87442f4SPeng Liu 		memset(default_hugepages_in_node, 0,
436210395680SMiaohe Lin 			sizeof(default_hugepages_in_node));
4363f87442f4SPeng Liu 	} else {
4364f87442f4SPeng Liu 		parsed_hstate->max_huge_pages = 0;
4365f87442f4SPeng Liu 		memset(parsed_hstate->max_huge_pages_node, 0,
436610395680SMiaohe Lin 			sizeof(parsed_hstate->max_huge_pages_node));
4367f87442f4SPeng Liu 	}
4368f87442f4SPeng Liu }
4369f87442f4SPeng Liu 
4370282f4214SMike Kravetz /*
4371282f4214SMike Kravetz  * hugepages command line processing
4372282f4214SMike Kravetz  * hugepages normally follows a valid hugepagsz or default_hugepagsz
4373282f4214SMike Kravetz  * specification.  If not, ignore the hugepages value.  hugepages can also
4374282f4214SMike Kravetz  * be the first huge page command line  option in which case it implicitly
4375282f4214SMike Kravetz  * specifies the number of huge pages for the default size.
4376282f4214SMike Kravetz  */
hugepages_setup(char * s)4377282f4214SMike Kravetz static int __init hugepages_setup(char *s)
4378a3437870SNishanth Aravamudan {
4379a3437870SNishanth Aravamudan 	unsigned long *mhp;
43808faa8b07SAndi Kleen 	static unsigned long *last_mhp;
4381b5389086SZhenguo Yao 	int node = NUMA_NO_NODE;
4382b5389086SZhenguo Yao 	int count;
4383b5389086SZhenguo Yao 	unsigned long tmp;
4384b5389086SZhenguo Yao 	char *p = s;
4385a3437870SNishanth Aravamudan 
43869fee021dSVaishali Thakkar 	if (!parsed_valid_hugepagesz) {
4387282f4214SMike Kravetz 		pr_warn("HugeTLB: hugepages=%s does not follow a valid hugepagesz, ignoring\n", s);
43889fee021dSVaishali Thakkar 		parsed_valid_hugepagesz = true;
4389f81f6e4bSPeng Liu 		return 1;
43909fee021dSVaishali Thakkar 	}
4391282f4214SMike Kravetz 
4392a3437870SNishanth Aravamudan 	/*
4393282f4214SMike Kravetz 	 * !hugetlb_max_hstate means we haven't parsed a hugepagesz= parameter
4394282f4214SMike Kravetz 	 * yet, so this hugepages= parameter goes to the "default hstate".
4395282f4214SMike Kravetz 	 * Otherwise, it goes with the previously parsed hugepagesz or
4396282f4214SMike Kravetz 	 * default_hugepagesz.
4397a3437870SNishanth Aravamudan 	 */
43989fee021dSVaishali Thakkar 	else if (!hugetlb_max_hstate)
4399a3437870SNishanth Aravamudan 		mhp = &default_hstate_max_huge_pages;
4400a3437870SNishanth Aravamudan 	else
4401a3437870SNishanth Aravamudan 		mhp = &parsed_hstate->max_huge_pages;
4402a3437870SNishanth Aravamudan 
44038faa8b07SAndi Kleen 	if (mhp == last_mhp) {
4404282f4214SMike Kravetz 		pr_warn("HugeTLB: hugepages= specified twice without interleaving hugepagesz=, ignoring hugepages=%s\n", s);
4405f81f6e4bSPeng Liu 		return 1;
44068faa8b07SAndi Kleen 	}
44078faa8b07SAndi Kleen 
4408b5389086SZhenguo Yao 	while (*p) {
4409b5389086SZhenguo Yao 		count = 0;
4410b5389086SZhenguo Yao 		if (sscanf(p, "%lu%n", &tmp, &count) != 1)
4411b5389086SZhenguo Yao 			goto invalid;
4412b5389086SZhenguo Yao 		/* Parameter is node format */
4413b5389086SZhenguo Yao 		if (p[count] == ':') {
4414b5389086SZhenguo Yao 			if (!hugetlb_node_alloc_supported()) {
4415b5389086SZhenguo Yao 				pr_warn("HugeTLB: architecture can't support node specific alloc, ignoring!\n");
4416f81f6e4bSPeng Liu 				return 1;
4417b5389086SZhenguo Yao 			}
44180a7a0f6fSPeng Liu 			if (tmp >= MAX_NUMNODES || !node_online(tmp))
4419e79ce983SLiu Yuntao 				goto invalid;
44200a7a0f6fSPeng Liu 			node = array_index_nospec(tmp, MAX_NUMNODES);
4421b5389086SZhenguo Yao 			p += count + 1;
4422b5389086SZhenguo Yao 			/* Parse hugepages */
4423b5389086SZhenguo Yao 			if (sscanf(p, "%lu%n", &tmp, &count) != 1)
4424b5389086SZhenguo Yao 				goto invalid;
4425b5389086SZhenguo Yao 			if (!hugetlb_max_hstate)
4426b5389086SZhenguo Yao 				default_hugepages_in_node[node] = tmp;
4427b5389086SZhenguo Yao 			else
4428b5389086SZhenguo Yao 				parsed_hstate->max_huge_pages_node[node] = tmp;
4429b5389086SZhenguo Yao 			*mhp += tmp;
4430b5389086SZhenguo Yao 			/* Go to parse next node*/
4431b5389086SZhenguo Yao 			if (p[count] == ',')
4432b5389086SZhenguo Yao 				p += count + 1;
4433b5389086SZhenguo Yao 			else
4434b5389086SZhenguo Yao 				break;
4435b5389086SZhenguo Yao 		} else {
4436b5389086SZhenguo Yao 			if (p != s)
4437b5389086SZhenguo Yao 				goto invalid;
4438b5389086SZhenguo Yao 			*mhp = tmp;
4439b5389086SZhenguo Yao 			break;
4440b5389086SZhenguo Yao 		}
4441b5389086SZhenguo Yao 	}
4442a3437870SNishanth Aravamudan 
44438faa8b07SAndi Kleen 	/*
44448faa8b07SAndi Kleen 	 * Global state is always initialized later in hugetlb_init.
444504adbc3fSMiaohe Lin 	 * But we need to allocate gigantic hstates here early to still
44468faa8b07SAndi Kleen 	 * use the bootmem allocator.
44478faa8b07SAndi Kleen 	 */
444804adbc3fSMiaohe Lin 	if (hugetlb_max_hstate && hstate_is_gigantic(parsed_hstate))
44498faa8b07SAndi Kleen 		hugetlb_hstate_alloc_pages(parsed_hstate);
44508faa8b07SAndi Kleen 
44518faa8b07SAndi Kleen 	last_mhp = mhp;
44528faa8b07SAndi Kleen 
4453a3437870SNishanth Aravamudan 	return 1;
4454b5389086SZhenguo Yao 
4455b5389086SZhenguo Yao invalid:
4456b5389086SZhenguo Yao 	pr_warn("HugeTLB: Invalid hugepages parameter %s\n", p);
4457f87442f4SPeng Liu 	hugepages_clear_pages_in_node();
4458f81f6e4bSPeng Liu 	return 1;
4459a3437870SNishanth Aravamudan }
4460282f4214SMike Kravetz __setup("hugepages=", hugepages_setup);
4461e11bfbfcSNick Piggin 
4462282f4214SMike Kravetz /*
4463282f4214SMike Kravetz  * hugepagesz command line processing
4464282f4214SMike Kravetz  * A specific huge page size can only be specified once with hugepagesz.
4465282f4214SMike Kravetz  * hugepagesz is followed by hugepages on the command line.  The global
4466282f4214SMike Kravetz  * variable 'parsed_valid_hugepagesz' is used to determine if prior
4467282f4214SMike Kravetz  * hugepagesz argument was valid.
4468282f4214SMike Kravetz  */
hugepagesz_setup(char * s)4469359f2544SMike Kravetz static int __init hugepagesz_setup(char *s)
4470e11bfbfcSNick Piggin {
4471359f2544SMike Kravetz 	unsigned long size;
4472282f4214SMike Kravetz 	struct hstate *h;
4473282f4214SMike Kravetz 
4474282f4214SMike Kravetz 	parsed_valid_hugepagesz = false;
4475359f2544SMike Kravetz 	size = (unsigned long)memparse(s, NULL);
4476359f2544SMike Kravetz 
4477359f2544SMike Kravetz 	if (!arch_hugetlb_valid_size(size)) {
4478282f4214SMike Kravetz 		pr_err("HugeTLB: unsupported hugepagesz=%s\n", s);
4479f81f6e4bSPeng Liu 		return 1;
4480359f2544SMike Kravetz 	}
4481359f2544SMike Kravetz 
4482282f4214SMike Kravetz 	h = size_to_hstate(size);
4483282f4214SMike Kravetz 	if (h) {
4484282f4214SMike Kravetz 		/*
4485282f4214SMike Kravetz 		 * hstate for this size already exists.  This is normally
4486282f4214SMike Kravetz 		 * an error, but is allowed if the existing hstate is the
4487282f4214SMike Kravetz 		 * default hstate.  More specifically, it is only allowed if
4488282f4214SMike Kravetz 		 * the number of huge pages for the default hstate was not
4489282f4214SMike Kravetz 		 * previously specified.
4490282f4214SMike Kravetz 		 */
4491282f4214SMike Kravetz 		if (!parsed_default_hugepagesz ||  h != &default_hstate ||
4492282f4214SMike Kravetz 		    default_hstate.max_huge_pages) {
4493282f4214SMike Kravetz 			pr_warn("HugeTLB: hugepagesz=%s specified twice, ignoring\n", s);
4494f81f6e4bSPeng Liu 			return 1;
449538237830SMike Kravetz 		}
449638237830SMike Kravetz 
4497282f4214SMike Kravetz 		/*
4498282f4214SMike Kravetz 		 * No need to call hugetlb_add_hstate() as hstate already
4499282f4214SMike Kravetz 		 * exists.  But, do set parsed_hstate so that a following
4500282f4214SMike Kravetz 		 * hugepages= parameter will be applied to this hstate.
4501282f4214SMike Kravetz 		 */
4502282f4214SMike Kravetz 		parsed_hstate = h;
4503282f4214SMike Kravetz 		parsed_valid_hugepagesz = true;
4504e11bfbfcSNick Piggin 		return 1;
4505e11bfbfcSNick Piggin 	}
4506282f4214SMike Kravetz 
4507359f2544SMike Kravetz 	hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
4508282f4214SMike Kravetz 	parsed_valid_hugepagesz = true;
4509359f2544SMike Kravetz 	return 1;
4510359f2544SMike Kravetz }
4511359f2544SMike Kravetz __setup("hugepagesz=", hugepagesz_setup);
4512359f2544SMike Kravetz 
4513282f4214SMike Kravetz /*
4514282f4214SMike Kravetz  * default_hugepagesz command line input
4515282f4214SMike Kravetz  * Only one instance of default_hugepagesz allowed on command line.
4516282f4214SMike Kravetz  */
default_hugepagesz_setup(char * s)4517ae94da89SMike Kravetz static int __init default_hugepagesz_setup(char *s)
4518e11bfbfcSNick Piggin {
4519ae94da89SMike Kravetz 	unsigned long size;
4520b5389086SZhenguo Yao 	int i;
4521ae94da89SMike Kravetz 
4522282f4214SMike Kravetz 	parsed_valid_hugepagesz = false;
4523282f4214SMike Kravetz 	if (parsed_default_hugepagesz) {
4524282f4214SMike Kravetz 		pr_err("HugeTLB: default_hugepagesz previously specified, ignoring %s\n", s);
4525f81f6e4bSPeng Liu 		return 1;
4526282f4214SMike Kravetz 	}
4527282f4214SMike Kravetz 
4528282f4214SMike Kravetz 	size = (unsigned long)memparse(s, NULL);
4529282f4214SMike Kravetz 
4530282f4214SMike Kravetz 	if (!arch_hugetlb_valid_size(size)) {
4531282f4214SMike Kravetz 		pr_err("HugeTLB: unsupported default_hugepagesz=%s\n", s);
4532f81f6e4bSPeng Liu 		return 1;
4533282f4214SMike Kravetz 	}
4534282f4214SMike Kravetz 
4535282f4214SMike Kravetz 	hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
4536282f4214SMike Kravetz 	parsed_valid_hugepagesz = true;
4537282f4214SMike Kravetz 	parsed_default_hugepagesz = true;
4538282f4214SMike Kravetz 	default_hstate_idx = hstate_index(size_to_hstate(size));
4539282f4214SMike Kravetz 
4540282f4214SMike Kravetz 	/*
4541282f4214SMike Kravetz 	 * The number of default huge pages (for this size) could have been
4542282f4214SMike Kravetz 	 * specified as the first hugetlb parameter: hugepages=X.  If so,
4543282f4214SMike Kravetz 	 * then default_hstate_max_huge_pages is set.  If the default huge
454423baf831SKirill A. Shutemov 	 * page size is gigantic (> MAX_ORDER), then the pages must be
4545282f4214SMike Kravetz 	 * allocated here from bootmem allocator.
4546282f4214SMike Kravetz 	 */
4547282f4214SMike Kravetz 	if (default_hstate_max_huge_pages) {
4548282f4214SMike Kravetz 		default_hstate.max_huge_pages = default_hstate_max_huge_pages;
45490a7a0f6fSPeng Liu 		for_each_online_node(i)
4550b5389086SZhenguo Yao 			default_hstate.max_huge_pages_node[i] =
4551b5389086SZhenguo Yao 				default_hugepages_in_node[i];
4552282f4214SMike Kravetz 		if (hstate_is_gigantic(&default_hstate))
4553282f4214SMike Kravetz 			hugetlb_hstate_alloc_pages(&default_hstate);
4554282f4214SMike Kravetz 		default_hstate_max_huge_pages = 0;
4555282f4214SMike Kravetz 	}
4556282f4214SMike Kravetz 
4557e11bfbfcSNick Piggin 	return 1;
4558e11bfbfcSNick Piggin }
4559ae94da89SMike Kravetz __setup("default_hugepagesz=", default_hugepagesz_setup);
4560a3437870SNishanth Aravamudan 
allowed_mems_nr(struct hstate * h)45618ca39e68SMuchun Song static unsigned int allowed_mems_nr(struct hstate *h)
45628a213460SNishanth Aravamudan {
45638a213460SNishanth Aravamudan 	int node;
45648a213460SNishanth Aravamudan 	unsigned int nr = 0;
4565d2226ebdSFeng Tang 	nodemask_t *mbind_nodemask;
45668ca39e68SMuchun Song 	unsigned int *array = h->free_huge_pages_node;
45678ca39e68SMuchun Song 	gfp_t gfp_mask = htlb_alloc_mask(h);
45688a213460SNishanth Aravamudan 
4569d2226ebdSFeng Tang 	mbind_nodemask = policy_mbind_nodemask(gfp_mask);
45708ca39e68SMuchun Song 	for_each_node_mask(node, cpuset_current_mems_allowed) {
4571d2226ebdSFeng Tang 		if (!mbind_nodemask || node_isset(node, *mbind_nodemask))
45728a213460SNishanth Aravamudan 			nr += array[node];
45738ca39e68SMuchun Song 	}
45748a213460SNishanth Aravamudan 
45758a213460SNishanth Aravamudan 	return nr;
45768a213460SNishanth Aravamudan }
45778a213460SNishanth Aravamudan 
45788a213460SNishanth Aravamudan #ifdef CONFIG_SYSCTL
proc_hugetlb_doulongvec_minmax(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos,unsigned long * out)457917743798SMuchun Song static int proc_hugetlb_doulongvec_minmax(struct ctl_table *table, int write,
458017743798SMuchun Song 					  void *buffer, size_t *length,
458117743798SMuchun Song 					  loff_t *ppos, unsigned long *out)
458217743798SMuchun Song {
458317743798SMuchun Song 	struct ctl_table dup_table;
458417743798SMuchun Song 
458517743798SMuchun Song 	/*
458617743798SMuchun Song 	 * In order to avoid races with __do_proc_doulongvec_minmax(), we
458717743798SMuchun Song 	 * can duplicate the @table and alter the duplicate of it.
458817743798SMuchun Song 	 */
458917743798SMuchun Song 	dup_table = *table;
459017743798SMuchun Song 	dup_table.data = out;
459117743798SMuchun Song 
459217743798SMuchun Song 	return proc_doulongvec_minmax(&dup_table, write, buffer, length, ppos);
459317743798SMuchun Song }
459417743798SMuchun Song 
hugetlb_sysctl_handler_common(bool obey_mempolicy,struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)459506808b08SLee Schermerhorn static int hugetlb_sysctl_handler_common(bool obey_mempolicy,
459606808b08SLee Schermerhorn 			 struct ctl_table *table, int write,
459732927393SChristoph Hellwig 			 void *buffer, size_t *length, loff_t *ppos)
45981da177e4SLinus Torvalds {
4599e5ff2159SAndi Kleen 	struct hstate *h = &default_hstate;
4600238d3c13SDavid Rientjes 	unsigned long tmp = h->max_huge_pages;
460108d4a246SMichal Hocko 	int ret;
4602e5ff2159SAndi Kleen 
4603457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
460486613628SJan Stancek 		return -EOPNOTSUPP;
4605457c1b27SNishanth Aravamudan 
460617743798SMuchun Song 	ret = proc_hugetlb_doulongvec_minmax(table, write, buffer, length, ppos,
460717743798SMuchun Song 					     &tmp);
460808d4a246SMichal Hocko 	if (ret)
460908d4a246SMichal Hocko 		goto out;
4610e5ff2159SAndi Kleen 
4611238d3c13SDavid Rientjes 	if (write)
4612238d3c13SDavid Rientjes 		ret = __nr_hugepages_store_common(obey_mempolicy, h,
4613238d3c13SDavid Rientjes 						  NUMA_NO_NODE, tmp, *length);
461408d4a246SMichal Hocko out:
461508d4a246SMichal Hocko 	return ret;
46161da177e4SLinus Torvalds }
4617396faf03SMel Gorman 
hugetlb_sysctl_handler(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)4618962de548SKefeng Wang static int hugetlb_sysctl_handler(struct ctl_table *table, int write,
461932927393SChristoph Hellwig 			  void *buffer, size_t *length, loff_t *ppos)
462006808b08SLee Schermerhorn {
462106808b08SLee Schermerhorn 
462206808b08SLee Schermerhorn 	return hugetlb_sysctl_handler_common(false, table, write,
462306808b08SLee Schermerhorn 							buffer, length, ppos);
462406808b08SLee Schermerhorn }
462506808b08SLee Schermerhorn 
462606808b08SLee Schermerhorn #ifdef CONFIG_NUMA
hugetlb_mempolicy_sysctl_handler(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)4627962de548SKefeng Wang static int hugetlb_mempolicy_sysctl_handler(struct ctl_table *table, int write,
462832927393SChristoph Hellwig 			  void *buffer, size_t *length, loff_t *ppos)
462906808b08SLee Schermerhorn {
463006808b08SLee Schermerhorn 	return hugetlb_sysctl_handler_common(true, table, write,
463106808b08SLee Schermerhorn 							buffer, length, ppos);
463206808b08SLee Schermerhorn }
463306808b08SLee Schermerhorn #endif /* CONFIG_NUMA */
463406808b08SLee Schermerhorn 
hugetlb_overcommit_handler(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)4635962de548SKefeng Wang static int hugetlb_overcommit_handler(struct ctl_table *table, int write,
463632927393SChristoph Hellwig 		void *buffer, size_t *length, loff_t *ppos)
4637a3d0c6aaSNishanth Aravamudan {
4638a5516438SAndi Kleen 	struct hstate *h = &default_hstate;
4639e5ff2159SAndi Kleen 	unsigned long tmp;
464008d4a246SMichal Hocko 	int ret;
4641e5ff2159SAndi Kleen 
4642457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
464386613628SJan Stancek 		return -EOPNOTSUPP;
4644457c1b27SNishanth Aravamudan 
4645e5ff2159SAndi Kleen 	tmp = h->nr_overcommit_huge_pages;
4646e5ff2159SAndi Kleen 
4647bae7f4aeSLuiz Capitulino 	if (write && hstate_is_gigantic(h))
4648adbe8726SEric B Munson 		return -EINVAL;
4649adbe8726SEric B Munson 
465017743798SMuchun Song 	ret = proc_hugetlb_doulongvec_minmax(table, write, buffer, length, ppos,
465117743798SMuchun Song 					     &tmp);
465208d4a246SMichal Hocko 	if (ret)
465308d4a246SMichal Hocko 		goto out;
4654e5ff2159SAndi Kleen 
4655e5ff2159SAndi Kleen 	if (write) {
4656db71ef79SMike Kravetz 		spin_lock_irq(&hugetlb_lock);
4657e5ff2159SAndi Kleen 		h->nr_overcommit_huge_pages = tmp;
4658db71ef79SMike Kravetz 		spin_unlock_irq(&hugetlb_lock);
4659e5ff2159SAndi Kleen 	}
466008d4a246SMichal Hocko out:
466108d4a246SMichal Hocko 	return ret;
4662a3d0c6aaSNishanth Aravamudan }
4663a3d0c6aaSNishanth Aravamudan 
4664962de548SKefeng Wang static struct ctl_table hugetlb_table[] = {
4665962de548SKefeng Wang 	{
4666962de548SKefeng Wang 		.procname	= "nr_hugepages",
4667962de548SKefeng Wang 		.data		= NULL,
4668962de548SKefeng Wang 		.maxlen		= sizeof(unsigned long),
4669962de548SKefeng Wang 		.mode		= 0644,
4670962de548SKefeng Wang 		.proc_handler	= hugetlb_sysctl_handler,
4671962de548SKefeng Wang 	},
4672962de548SKefeng Wang #ifdef CONFIG_NUMA
4673962de548SKefeng Wang 	{
4674962de548SKefeng Wang 		.procname       = "nr_hugepages_mempolicy",
4675962de548SKefeng Wang 		.data           = NULL,
4676962de548SKefeng Wang 		.maxlen         = sizeof(unsigned long),
4677962de548SKefeng Wang 		.mode           = 0644,
4678962de548SKefeng Wang 		.proc_handler   = &hugetlb_mempolicy_sysctl_handler,
4679962de548SKefeng Wang 	},
4680962de548SKefeng Wang #endif
4681962de548SKefeng Wang 	{
4682962de548SKefeng Wang 		.procname	= "hugetlb_shm_group",
4683962de548SKefeng Wang 		.data		= &sysctl_hugetlb_shm_group,
4684962de548SKefeng Wang 		.maxlen		= sizeof(gid_t),
4685962de548SKefeng Wang 		.mode		= 0644,
4686962de548SKefeng Wang 		.proc_handler	= proc_dointvec,
4687962de548SKefeng Wang 	},
4688962de548SKefeng Wang 	{
4689962de548SKefeng Wang 		.procname	= "nr_overcommit_hugepages",
4690962de548SKefeng Wang 		.data		= NULL,
4691962de548SKefeng Wang 		.maxlen		= sizeof(unsigned long),
4692962de548SKefeng Wang 		.mode		= 0644,
4693962de548SKefeng Wang 		.proc_handler	= hugetlb_overcommit_handler,
4694962de548SKefeng Wang 	},
4695962de548SKefeng Wang 	{ }
4696962de548SKefeng Wang };
4697962de548SKefeng Wang 
hugetlb_sysctl_init(void)4698962de548SKefeng Wang static void hugetlb_sysctl_init(void)
4699962de548SKefeng Wang {
4700962de548SKefeng Wang 	register_sysctl_init("vm", hugetlb_table);
4701962de548SKefeng Wang }
47021da177e4SLinus Torvalds #endif /* CONFIG_SYSCTL */
47031da177e4SLinus Torvalds 
hugetlb_report_meminfo(struct seq_file * m)4704e1759c21SAlexey Dobriyan void hugetlb_report_meminfo(struct seq_file *m)
47051da177e4SLinus Torvalds {
4706fcb2b0c5SRoman Gushchin 	struct hstate *h;
4707fcb2b0c5SRoman Gushchin 	unsigned long total = 0;
4708fcb2b0c5SRoman Gushchin 
4709457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
4710457c1b27SNishanth Aravamudan 		return;
4711fcb2b0c5SRoman Gushchin 
4712fcb2b0c5SRoman Gushchin 	for_each_hstate(h) {
4713fcb2b0c5SRoman Gushchin 		unsigned long count = h->nr_huge_pages;
4714fcb2b0c5SRoman Gushchin 
4715aca78307SMiaohe Lin 		total += huge_page_size(h) * count;
4716fcb2b0c5SRoman Gushchin 
4717fcb2b0c5SRoman Gushchin 		if (h == &default_hstate)
4718e1759c21SAlexey Dobriyan 			seq_printf(m,
47191da177e4SLinus Torvalds 				   "HugePages_Total:   %5lu\n"
47201da177e4SLinus Torvalds 				   "HugePages_Free:    %5lu\n"
4721b45b5bd6SDavid Gibson 				   "HugePages_Rsvd:    %5lu\n"
47227893d1d5SAdam Litke 				   "HugePages_Surp:    %5lu\n"
47234f98a2feSRik van Riel 				   "Hugepagesize:   %8lu kB\n",
4724fcb2b0c5SRoman Gushchin 				   count,
4725a5516438SAndi Kleen 				   h->free_huge_pages,
4726a5516438SAndi Kleen 				   h->resv_huge_pages,
4727a5516438SAndi Kleen 				   h->surplus_huge_pages,
4728aca78307SMiaohe Lin 				   huge_page_size(h) / SZ_1K);
4729fcb2b0c5SRoman Gushchin 	}
4730fcb2b0c5SRoman Gushchin 
4731aca78307SMiaohe Lin 	seq_printf(m, "Hugetlb:        %8lu kB\n", total / SZ_1K);
47321da177e4SLinus Torvalds }
47331da177e4SLinus Torvalds 
hugetlb_report_node_meminfo(char * buf,int len,int nid)47347981593bSJoe Perches int hugetlb_report_node_meminfo(char *buf, int len, int nid)
47351da177e4SLinus Torvalds {
4736a5516438SAndi Kleen 	struct hstate *h = &default_hstate;
47377981593bSJoe Perches 
4738457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
4739457c1b27SNishanth Aravamudan 		return 0;
47407981593bSJoe Perches 
47417981593bSJoe Perches 	return sysfs_emit_at(buf, len,
47421da177e4SLinus Torvalds 			     "Node %d HugePages_Total: %5u\n"
4743a1de0919SNishanth Aravamudan 			     "Node %d HugePages_Free:  %5u\n"
4744a1de0919SNishanth Aravamudan 			     "Node %d HugePages_Surp:  %5u\n",
4745a5516438SAndi Kleen 			     nid, h->nr_huge_pages_node[nid],
4746a5516438SAndi Kleen 			     nid, h->free_huge_pages_node[nid],
4747a5516438SAndi Kleen 			     nid, h->surplus_huge_pages_node[nid]);
47481da177e4SLinus Torvalds }
47491da177e4SLinus Torvalds 
hugetlb_show_meminfo_node(int nid)4750dcadcf1cSGang Li void hugetlb_show_meminfo_node(int nid)
4751949f7ec5SDavid Rientjes {
4752949f7ec5SDavid Rientjes 	struct hstate *h;
4753949f7ec5SDavid Rientjes 
4754457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
4755457c1b27SNishanth Aravamudan 		return;
4756457c1b27SNishanth Aravamudan 
4757949f7ec5SDavid Rientjes 	for_each_hstate(h)
4758dcadcf1cSGang Li 		printk("Node %d hugepages_total=%u hugepages_free=%u hugepages_surp=%u hugepages_size=%lukB\n",
4759949f7ec5SDavid Rientjes 			nid,
4760949f7ec5SDavid Rientjes 			h->nr_huge_pages_node[nid],
4761949f7ec5SDavid Rientjes 			h->free_huge_pages_node[nid],
4762949f7ec5SDavid Rientjes 			h->surplus_huge_pages_node[nid],
4763aca78307SMiaohe Lin 			huge_page_size(h) / SZ_1K);
4764949f7ec5SDavid Rientjes }
4765949f7ec5SDavid Rientjes 
hugetlb_report_usage(struct seq_file * m,struct mm_struct * mm)47665d317b2bSNaoya Horiguchi void hugetlb_report_usage(struct seq_file *m, struct mm_struct *mm)
47675d317b2bSNaoya Horiguchi {
47685d317b2bSNaoya Horiguchi 	seq_printf(m, "HugetlbPages:\t%8lu kB\n",
47696c1aa2d3SZhangPeng 		   K(atomic_long_read(&mm->hugetlb_usage)));
47705d317b2bSNaoya Horiguchi }
47715d317b2bSNaoya Horiguchi 
47721da177e4SLinus Torvalds /* Return the number pages of memory we physically have, in PAGE_SIZE units. */
hugetlb_total_pages(void)47731da177e4SLinus Torvalds unsigned long hugetlb_total_pages(void)
47741da177e4SLinus Torvalds {
4775d0028588SWanpeng Li 	struct hstate *h;
4776d0028588SWanpeng Li 	unsigned long nr_total_pages = 0;
4777d0028588SWanpeng Li 
4778d0028588SWanpeng Li 	for_each_hstate(h)
4779d0028588SWanpeng Li 		nr_total_pages += h->nr_huge_pages * pages_per_huge_page(h);
4780d0028588SWanpeng Li 	return nr_total_pages;
47811da177e4SLinus Torvalds }
47821da177e4SLinus Torvalds 
hugetlb_acct_memory(struct hstate * h,long delta)4783a5516438SAndi Kleen static int hugetlb_acct_memory(struct hstate *h, long delta)
4784fc1b8a73SMel Gorman {
4785fc1b8a73SMel Gorman 	int ret = -ENOMEM;
4786fc1b8a73SMel Gorman 
47870aa7f354SMiaohe Lin 	if (!delta)
47880aa7f354SMiaohe Lin 		return 0;
47890aa7f354SMiaohe Lin 
4790db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
4791fc1b8a73SMel Gorman 	/*
4792fc1b8a73SMel Gorman 	 * When cpuset is configured, it breaks the strict hugetlb page
4793fc1b8a73SMel Gorman 	 * reservation as the accounting is done on a global variable. Such
4794fc1b8a73SMel Gorman 	 * reservation is completely rubbish in the presence of cpuset because
4795fc1b8a73SMel Gorman 	 * the reservation is not checked against page availability for the
4796fc1b8a73SMel Gorman 	 * current cpuset. Application can still potentially OOM'ed by kernel
4797fc1b8a73SMel Gorman 	 * with lack of free htlb page in cpuset that the task is in.
4798fc1b8a73SMel Gorman 	 * Attempt to enforce strict accounting with cpuset is almost
4799fc1b8a73SMel Gorman 	 * impossible (or too ugly) because cpuset is too fluid that
4800fc1b8a73SMel Gorman 	 * task or memory node can be dynamically moved between cpusets.
4801fc1b8a73SMel Gorman 	 *
4802fc1b8a73SMel Gorman 	 * The change of semantics for shared hugetlb mapping with cpuset is
4803fc1b8a73SMel Gorman 	 * undesirable. However, in order to preserve some of the semantics,
4804fc1b8a73SMel Gorman 	 * we fall back to check against current free page availability as
4805fc1b8a73SMel Gorman 	 * a best attempt and hopefully to minimize the impact of changing
4806fc1b8a73SMel Gorman 	 * semantics that cpuset has.
48078ca39e68SMuchun Song 	 *
48088ca39e68SMuchun Song 	 * Apart from cpuset, we also have memory policy mechanism that
48098ca39e68SMuchun Song 	 * also determines from which node the kernel will allocate memory
48108ca39e68SMuchun Song 	 * in a NUMA system. So similar to cpuset, we also should consider
48118ca39e68SMuchun Song 	 * the memory policy of the current task. Similar to the description
48128ca39e68SMuchun Song 	 * above.
4813fc1b8a73SMel Gorman 	 */
4814fc1b8a73SMel Gorman 	if (delta > 0) {
4815a5516438SAndi Kleen 		if (gather_surplus_pages(h, delta) < 0)
4816fc1b8a73SMel Gorman 			goto out;
4817fc1b8a73SMel Gorman 
48188ca39e68SMuchun Song 		if (delta > allowed_mems_nr(h)) {
4819a5516438SAndi Kleen 			return_unused_surplus_pages(h, delta);
4820fc1b8a73SMel Gorman 			goto out;
4821fc1b8a73SMel Gorman 		}
4822fc1b8a73SMel Gorman 	}
4823fc1b8a73SMel Gorman 
4824fc1b8a73SMel Gorman 	ret = 0;
4825fc1b8a73SMel Gorman 	if (delta < 0)
4826a5516438SAndi Kleen 		return_unused_surplus_pages(h, (unsigned long) -delta);
4827fc1b8a73SMel Gorman 
4828fc1b8a73SMel Gorman out:
4829db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
4830fc1b8a73SMel Gorman 	return ret;
4831fc1b8a73SMel Gorman }
4832fc1b8a73SMel Gorman 
hugetlb_vm_op_open(struct vm_area_struct * vma)483384afd99bSAndy Whitcroft static void hugetlb_vm_op_open(struct vm_area_struct *vma)
483484afd99bSAndy Whitcroft {
4835f522c3acSJoonsoo Kim 	struct resv_map *resv = vma_resv_map(vma);
483684afd99bSAndy Whitcroft 
483784afd99bSAndy Whitcroft 	/*
4838612b8a31SMike Kravetz 	 * HPAGE_RESV_OWNER indicates a private mapping.
483984afd99bSAndy Whitcroft 	 * This new VMA should share its siblings reservation map if present.
484084afd99bSAndy Whitcroft 	 * The VMA will only ever have a valid reservation map pointer where
484184afd99bSAndy Whitcroft 	 * it is being copied for another still existing VMA.  As that VMA
484225985edcSLucas De Marchi 	 * has a reference to the reservation map it cannot disappear until
484384afd99bSAndy Whitcroft 	 * after this open call completes.  It is therefore safe to take a
484484afd99bSAndy Whitcroft 	 * new reference here without additional locking.
484584afd99bSAndy Whitcroft 	 */
484609a26e83SMike Kravetz 	if (resv && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
484709a26e83SMike Kravetz 		resv_map_dup_hugetlb_cgroup_uncharge_info(resv);
4848f522c3acSJoonsoo Kim 		kref_get(&resv->refs);
484984afd99bSAndy Whitcroft 	}
48508d9bfb26SMike Kravetz 
4851131a79b4SMike Kravetz 	/*
4852131a79b4SMike Kravetz 	 * vma_lock structure for sharable mappings is vma specific.
4853612b8a31SMike Kravetz 	 * Clear old pointer (if copied via vm_area_dup) and allocate
4854612b8a31SMike Kravetz 	 * new structure.  Before clearing, make sure vma_lock is not
4855612b8a31SMike Kravetz 	 * for this vma.
4856131a79b4SMike Kravetz 	 */
4857131a79b4SMike Kravetz 	if (vma->vm_flags & VM_MAYSHARE) {
4858612b8a31SMike Kravetz 		struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
4859612b8a31SMike Kravetz 
4860612b8a31SMike Kravetz 		if (vma_lock) {
4861612b8a31SMike Kravetz 			if (vma_lock->vma != vma) {
4862131a79b4SMike Kravetz 				vma->vm_private_data = NULL;
48638d9bfb26SMike Kravetz 				hugetlb_vma_lock_alloc(vma);
4864612b8a31SMike Kravetz 			} else
4865612b8a31SMike Kravetz 				pr_warn("HugeTLB: vma_lock already exists in %s.\n", __func__);
4866612b8a31SMike Kravetz 		} else
4867612b8a31SMike Kravetz 			hugetlb_vma_lock_alloc(vma);
486809a26e83SMike Kravetz 	}
4869131a79b4SMike Kravetz }
487084afd99bSAndy Whitcroft 
hugetlb_vm_op_close(struct vm_area_struct * vma)4871a1e78772SMel Gorman static void hugetlb_vm_op_close(struct vm_area_struct *vma)
4872a1e78772SMel Gorman {
4873a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
48748d9bfb26SMike Kravetz 	struct resv_map *resv;
487590481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_vma(vma);
48764e35f483SJoonsoo Kim 	unsigned long reserve, start, end;
48771c5ecae3SMike Kravetz 	long gbl_reserve;
487884afd99bSAndy Whitcroft 
48798d9bfb26SMike Kravetz 	hugetlb_vma_lock_free(vma);
48808d9bfb26SMike Kravetz 
48818d9bfb26SMike Kravetz 	resv = vma_resv_map(vma);
48824e35f483SJoonsoo Kim 	if (!resv || !is_vma_resv_set(vma, HPAGE_RESV_OWNER))
48834e35f483SJoonsoo Kim 		return;
48844e35f483SJoonsoo Kim 
4885a5516438SAndi Kleen 	start = vma_hugecache_offset(h, vma, vma->vm_start);
4886a5516438SAndi Kleen 	end = vma_hugecache_offset(h, vma, vma->vm_end);
488784afd99bSAndy Whitcroft 
48884e35f483SJoonsoo Kim 	reserve = (end - start) - region_count(resv, start, end);
4889e9fe92aeSMina Almasry 	hugetlb_cgroup_uncharge_counter(resv, start, end);
48907251ff78SAdam Litke 	if (reserve) {
48911c5ecae3SMike Kravetz 		/*
48921c5ecae3SMike Kravetz 		 * Decrement reserve counts.  The global reserve count may be
48931c5ecae3SMike Kravetz 		 * adjusted if the subpool has a minimum size.
48941c5ecae3SMike Kravetz 		 */
48951c5ecae3SMike Kravetz 		gbl_reserve = hugepage_subpool_put_pages(spool, reserve);
48961c5ecae3SMike Kravetz 		hugetlb_acct_memory(h, -gbl_reserve);
48977251ff78SAdam Litke 	}
4898e9fe92aeSMina Almasry 
4899e9fe92aeSMina Almasry 	kref_put(&resv->refs, resv_map_release);
4900a1e78772SMel Gorman }
4901a1e78772SMel Gorman 
hugetlb_vm_op_split(struct vm_area_struct * vma,unsigned long addr)490231383c68SDan Williams static int hugetlb_vm_op_split(struct vm_area_struct *vma, unsigned long addr)
490331383c68SDan Williams {
490431383c68SDan Williams 	if (addr & ~(huge_page_mask(hstate_vma(vma))))
490531383c68SDan Williams 		return -EINVAL;
4906b30c14cdSJames Houghton 
4907b30c14cdSJames Houghton 	/*
4908b30c14cdSJames Houghton 	 * PMD sharing is only possible for PUD_SIZE-aligned address ranges
4909b30c14cdSJames Houghton 	 * in HugeTLB VMAs. If we will lose PUD_SIZE alignment due to this
4910b30c14cdSJames Houghton 	 * split, unshare PMDs in the PUD_SIZE interval surrounding addr now.
4911b30c14cdSJames Houghton 	 */
4912b30c14cdSJames Houghton 	if (addr & ~PUD_MASK) {
4913b30c14cdSJames Houghton 		/*
4914b30c14cdSJames Houghton 		 * hugetlb_vm_op_split is called right before we attempt to
4915b30c14cdSJames Houghton 		 * split the VMA. We will need to unshare PMDs in the old and
4916b30c14cdSJames Houghton 		 * new VMAs, so let's unshare before we split.
4917b30c14cdSJames Houghton 		 */
4918b30c14cdSJames Houghton 		unsigned long floor = addr & PUD_MASK;
4919b30c14cdSJames Houghton 		unsigned long ceil = floor + PUD_SIZE;
4920b30c14cdSJames Houghton 
4921b30c14cdSJames Houghton 		if (floor >= vma->vm_start && ceil <= vma->vm_end)
4922b30c14cdSJames Houghton 			hugetlb_unshare_pmds(vma, floor, ceil);
4923b30c14cdSJames Houghton 	}
4924b30c14cdSJames Houghton 
492531383c68SDan Williams 	return 0;
492631383c68SDan Williams }
492731383c68SDan Williams 
hugetlb_vm_op_pagesize(struct vm_area_struct * vma)492805ea8860SDan Williams static unsigned long hugetlb_vm_op_pagesize(struct vm_area_struct *vma)
492905ea8860SDan Williams {
4930aca78307SMiaohe Lin 	return huge_page_size(hstate_vma(vma));
493105ea8860SDan Williams }
493205ea8860SDan Williams 
49331da177e4SLinus Torvalds /*
49341da177e4SLinus Torvalds  * We cannot handle pagefaults against hugetlb pages at all.  They cause
49351da177e4SLinus Torvalds  * handle_mm_fault() to try to instantiate regular-sized pages in the
49366c26d310SMiaohe Lin  * hugepage VMA.  do_page_fault() is supposed to trap this, so BUG is we get
49371da177e4SLinus Torvalds  * this far.
49381da177e4SLinus Torvalds  */
hugetlb_vm_op_fault(struct vm_fault * vmf)4939b3ec9f33SSouptick Joarder static vm_fault_t hugetlb_vm_op_fault(struct vm_fault *vmf)
49401da177e4SLinus Torvalds {
49411da177e4SLinus Torvalds 	BUG();
4942d0217ac0SNick Piggin 	return 0;
49431da177e4SLinus Torvalds }
49441da177e4SLinus Torvalds 
4945eec3636aSJane Chu /*
4946eec3636aSJane Chu  * When a new function is introduced to vm_operations_struct and added
4947eec3636aSJane Chu  * to hugetlb_vm_ops, please consider adding the function to shm_vm_ops.
4948eec3636aSJane Chu  * This is because under System V memory model, mappings created via
4949eec3636aSJane Chu  * shmget/shmat with "huge page" specified are backed by hugetlbfs files,
4950eec3636aSJane Chu  * their original vm_ops are overwritten with shm_vm_ops.
4951eec3636aSJane Chu  */
4952f0f37e2fSAlexey Dobriyan const struct vm_operations_struct hugetlb_vm_ops = {
4953d0217ac0SNick Piggin 	.fault = hugetlb_vm_op_fault,
495484afd99bSAndy Whitcroft 	.open = hugetlb_vm_op_open,
4955a1e78772SMel Gorman 	.close = hugetlb_vm_op_close,
4956dd3b614fSDmitry Safonov 	.may_split = hugetlb_vm_op_split,
495705ea8860SDan Williams 	.pagesize = hugetlb_vm_op_pagesize,
49581da177e4SLinus Torvalds };
49591da177e4SLinus Torvalds 
make_huge_pte(struct vm_area_struct * vma,struct page * page,int writable)49601e8f889bSDavid Gibson static pte_t make_huge_pte(struct vm_area_struct *vma, struct page *page,
49611e8f889bSDavid Gibson 				int writable)
496263551ae0SDavid Gibson {
496363551ae0SDavid Gibson 	pte_t entry;
496479c1c594SChristophe Leroy 	unsigned int shift = huge_page_shift(hstate_vma(vma));
496563551ae0SDavid Gibson 
49661e8f889bSDavid Gibson 	if (writable) {
4967106c992aSGerald Schaefer 		entry = huge_pte_mkwrite(huge_pte_mkdirty(mk_huge_pte(page,
4968106c992aSGerald Schaefer 					 vma->vm_page_prot)));
496963551ae0SDavid Gibson 	} else {
4970106c992aSGerald Schaefer 		entry = huge_pte_wrprotect(mk_huge_pte(page,
4971106c992aSGerald Schaefer 					   vma->vm_page_prot));
497263551ae0SDavid Gibson 	}
497363551ae0SDavid Gibson 	entry = pte_mkyoung(entry);
497479c1c594SChristophe Leroy 	entry = arch_make_huge_pte(entry, shift, vma->vm_flags);
497563551ae0SDavid Gibson 
497663551ae0SDavid Gibson 	return entry;
497763551ae0SDavid Gibson }
497863551ae0SDavid Gibson 
set_huge_ptep_writable(struct vm_area_struct * vma,unsigned long address,pte_t * ptep)49791e8f889bSDavid Gibson static void set_huge_ptep_writable(struct vm_area_struct *vma,
49801e8f889bSDavid Gibson 				   unsigned long address, pte_t *ptep)
49811e8f889bSDavid Gibson {
49821e8f889bSDavid Gibson 	pte_t entry;
49831e8f889bSDavid Gibson 
4984106c992aSGerald Schaefer 	entry = huge_pte_mkwrite(huge_pte_mkdirty(huge_ptep_get(ptep)));
498532f84528SChris Forbes 	if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1))
49864b3073e1SRussell King 		update_mmu_cache(vma, address, ptep);
49871e8f889bSDavid Gibson }
49881e8f889bSDavid Gibson 
is_hugetlb_entry_migration(pte_t pte)4989d5ed7444SAneesh Kumar K.V bool is_hugetlb_entry_migration(pte_t pte)
49904a705fefSNaoya Horiguchi {
49914a705fefSNaoya Horiguchi 	swp_entry_t swp;
49924a705fefSNaoya Horiguchi 
49934a705fefSNaoya Horiguchi 	if (huge_pte_none(pte) || pte_present(pte))
4994d5ed7444SAneesh Kumar K.V 		return false;
49954a705fefSNaoya Horiguchi 	swp = pte_to_swp_entry(pte);
4996d79d176aSBaoquan He 	if (is_migration_entry(swp))
4997d5ed7444SAneesh Kumar K.V 		return true;
49984a705fefSNaoya Horiguchi 	else
4999d5ed7444SAneesh Kumar K.V 		return false;
50004a705fefSNaoya Horiguchi }
50014a705fefSNaoya Horiguchi 
is_hugetlb_entry_hwpoisoned(pte_t pte)50023e5c3600SBaoquan He static bool is_hugetlb_entry_hwpoisoned(pte_t pte)
50034a705fefSNaoya Horiguchi {
50044a705fefSNaoya Horiguchi 	swp_entry_t swp;
50054a705fefSNaoya Horiguchi 
50064a705fefSNaoya Horiguchi 	if (huge_pte_none(pte) || pte_present(pte))
50073e5c3600SBaoquan He 		return false;
50084a705fefSNaoya Horiguchi 	swp = pte_to_swp_entry(pte);
5009d79d176aSBaoquan He 	if (is_hwpoison_entry(swp))
50103e5c3600SBaoquan He 		return true;
50114a705fefSNaoya Horiguchi 	else
50123e5c3600SBaoquan He 		return false;
50134a705fefSNaoya Horiguchi }
50141e8f889bSDavid Gibson 
50154eae4efaSPeter Xu static void
hugetlb_install_folio(struct vm_area_struct * vma,pte_t * ptep,unsigned long addr,struct folio * new_folio,pte_t old,unsigned long sz)5016ea4c353dSSidhartha Kumar hugetlb_install_folio(struct vm_area_struct *vma, pte_t *ptep, unsigned long addr,
5017935d4f0cSRyan Roberts 		      struct folio *new_folio, pte_t old, unsigned long sz)
50184eae4efaSPeter Xu {
50195a2f8d22SPeter Xu 	pte_t newpte = make_huge_pte(vma, &new_folio->page, 1);
50205a2f8d22SPeter Xu 
5021ea4c353dSSidhartha Kumar 	__folio_mark_uptodate(new_folio);
5022d0ce0e47SSidhartha Kumar 	hugepage_add_new_anon_rmap(new_folio, vma, addr);
50235a2f8d22SPeter Xu 	if (userfaultfd_wp(vma) && huge_pte_uffd_wp(old))
50245a2f8d22SPeter Xu 		newpte = huge_pte_mkuffd_wp(newpte);
5025935d4f0cSRyan Roberts 	set_huge_pte_at(vma->vm_mm, addr, ptep, newpte, sz);
50264eae4efaSPeter Xu 	hugetlb_count_add(pages_per_huge_page(hstate_vma(vma)), vma->vm_mm);
5027ea4c353dSSidhartha Kumar 	folio_set_hugetlb_migratable(new_folio);
50284eae4efaSPeter Xu }
50294eae4efaSPeter Xu 
copy_hugetlb_page_range(struct mm_struct * dst,struct mm_struct * src,struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma)503063551ae0SDavid Gibson int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src,
5031bc70fbf2SPeter Xu 			    struct vm_area_struct *dst_vma,
5032bc70fbf2SPeter Xu 			    struct vm_area_struct *src_vma)
503363551ae0SDavid Gibson {
50343aa4ed80SMiaohe Lin 	pte_t *src_pte, *dst_pte, entry;
5035ad27ce20SZhangPeng 	struct folio *pte_folio;
50361c59827dSHugh Dickins 	unsigned long addr;
5037bc70fbf2SPeter Xu 	bool cow = is_cow_mapping(src_vma->vm_flags);
5038bc70fbf2SPeter Xu 	struct hstate *h = hstate_vma(src_vma);
5039a5516438SAndi Kleen 	unsigned long sz = huge_page_size(h);
50404eae4efaSPeter Xu 	unsigned long npages = pages_per_huge_page(h);
5041ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
5042e95a9851SMike Kravetz 	unsigned long last_addr_mask;
5043e8569dd2SAndreas Sandberg 	int ret = 0;
50441e8f889bSDavid Gibson 
5045ac46d4f3SJérôme Glisse 	if (cow) {
50467d4a8be0SAlistair Popple 		mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, src,
5047bc70fbf2SPeter Xu 					src_vma->vm_start,
5048bc70fbf2SPeter Xu 					src_vma->vm_end);
5049ac46d4f3SJérôme Glisse 		mmu_notifier_invalidate_range_start(&range);
5050e727bfd5SSuren Baghdasaryan 		vma_assert_write_locked(src_vma);
5051623a1ddfSDavid Hildenbrand 		raw_write_seqcount_begin(&src->write_protect_seq);
505240549ba8SMike Kravetz 	} else {
505340549ba8SMike Kravetz 		/*
505440549ba8SMike Kravetz 		 * For shared mappings the vma lock must be held before
50559c67a207SPeter Xu 		 * calling hugetlb_walk() in the src vma. Otherwise, the
505640549ba8SMike Kravetz 		 * returned ptep could go away if part of a shared pmd and
505740549ba8SMike Kravetz 		 * another thread calls huge_pmd_unshare.
505840549ba8SMike Kravetz 		 */
505940549ba8SMike Kravetz 		hugetlb_vma_lock_read(src_vma);
5060ac46d4f3SJérôme Glisse 	}
5061e8569dd2SAndreas Sandberg 
5062e95a9851SMike Kravetz 	last_addr_mask = hugetlb_mask_last_page(h);
5063bc70fbf2SPeter Xu 	for (addr = src_vma->vm_start; addr < src_vma->vm_end; addr += sz) {
5064cb900f41SKirill A. Shutemov 		spinlock_t *src_ptl, *dst_ptl;
50659c67a207SPeter Xu 		src_pte = hugetlb_walk(src_vma, addr, sz);
5066e95a9851SMike Kravetz 		if (!src_pte) {
5067e95a9851SMike Kravetz 			addr |= last_addr_mask;
5068c74df32cSHugh Dickins 			continue;
5069e95a9851SMike Kravetz 		}
5070bc70fbf2SPeter Xu 		dst_pte = huge_pte_alloc(dst, dst_vma, addr, sz);
5071e8569dd2SAndreas Sandberg 		if (!dst_pte) {
5072e8569dd2SAndreas Sandberg 			ret = -ENOMEM;
5073e8569dd2SAndreas Sandberg 			break;
5074e8569dd2SAndreas Sandberg 		}
5075c5c99429SLarry Woodman 
50765e41540cSMike Kravetz 		/*
50775e41540cSMike Kravetz 		 * If the pagetables are shared don't copy or take references.
50785e41540cSMike Kravetz 		 *
50793aa4ed80SMiaohe Lin 		 * dst_pte == src_pte is the common case of src/dest sharing.
50805e41540cSMike Kravetz 		 * However, src could have 'unshared' and dst shares with
50813aa4ed80SMiaohe Lin 		 * another vma. So page_count of ptep page is checked instead
50823aa4ed80SMiaohe Lin 		 * to reliably determine whether pte is shared.
50835e41540cSMike Kravetz 		 */
50843aa4ed80SMiaohe Lin 		if (page_count(virt_to_page(dst_pte)) > 1) {
5085e95a9851SMike Kravetz 			addr |= last_addr_mask;
5086c5c99429SLarry Woodman 			continue;
5087e95a9851SMike Kravetz 		}
5088c5c99429SLarry Woodman 
5089cb900f41SKirill A. Shutemov 		dst_ptl = huge_pte_lock(h, dst, dst_pte);
5090cb900f41SKirill A. Shutemov 		src_ptl = huge_pte_lockptr(h, src, src_pte);
5091cb900f41SKirill A. Shutemov 		spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
50924a705fefSNaoya Horiguchi 		entry = huge_ptep_get(src_pte);
50934eae4efaSPeter Xu again:
50943aa4ed80SMiaohe Lin 		if (huge_pte_none(entry)) {
50955e41540cSMike Kravetz 			/*
50963aa4ed80SMiaohe Lin 			 * Skip if src entry none.
50975e41540cSMike Kravetz 			 */
50984a705fefSNaoya Horiguchi 			;
5099c2cb0dccSNaoya Horiguchi 		} else if (unlikely(is_hugetlb_entry_hwpoisoned(entry))) {
51005a2f8d22SPeter Xu 			if (!userfaultfd_wp(dst_vma))
5101c2cb0dccSNaoya Horiguchi 				entry = huge_pte_clear_uffd_wp(entry);
5102935d4f0cSRyan Roberts 			set_huge_pte_at(dst, addr, dst_pte, entry, sz);
5103c2cb0dccSNaoya Horiguchi 		} else if (unlikely(is_hugetlb_entry_migration(entry))) {
51044a705fefSNaoya Horiguchi 			swp_entry_t swp_entry = pte_to_swp_entry(entry);
51055a2f8d22SPeter Xu 			bool uffd_wp = pte_swp_uffd_wp(entry);
51064a705fefSNaoya Horiguchi 
51076c287605SDavid Hildenbrand 			if (!is_readable_migration_entry(swp_entry) && cow) {
51084a705fefSNaoya Horiguchi 				/*
51094a705fefSNaoya Horiguchi 				 * COW mappings require pages in both
51104a705fefSNaoya Horiguchi 				 * parent and child to be set to read.
51114a705fefSNaoya Horiguchi 				 */
51124dd845b5SAlistair Popple 				swp_entry = make_readable_migration_entry(
51134dd845b5SAlistair Popple 							swp_offset(swp_entry));
51144a705fefSNaoya Horiguchi 				entry = swp_entry_to_pte(swp_entry);
5115bc70fbf2SPeter Xu 				if (userfaultfd_wp(src_vma) && uffd_wp)
51165a2f8d22SPeter Xu 					entry = pte_swp_mkuffd_wp(entry);
5117935d4f0cSRyan Roberts 				set_huge_pte_at(src, addr, src_pte, entry, sz);
51184a705fefSNaoya Horiguchi 			}
51195a2f8d22SPeter Xu 			if (!userfaultfd_wp(dst_vma))
5120bc70fbf2SPeter Xu 				entry = huge_pte_clear_uffd_wp(entry);
5121935d4f0cSRyan Roberts 			set_huge_pte_at(dst, addr, dst_pte, entry, sz);
5122bc70fbf2SPeter Xu 		} else if (unlikely(is_pte_marker(entry))) {
5123af19487fSAxel Rasmussen 			pte_marker marker = copy_pte_marker(
5124af19487fSAxel Rasmussen 				pte_to_swp_entry(entry), dst_vma);
5125af19487fSAxel Rasmussen 
5126af19487fSAxel Rasmussen 			if (marker)
5127af19487fSAxel Rasmussen 				set_huge_pte_at(dst, addr, dst_pte,
5128935d4f0cSRyan Roberts 						make_pte_marker(marker), sz);
51294a705fefSNaoya Horiguchi 		} else {
51304eae4efaSPeter Xu 			entry = huge_ptep_get(src_pte);
5131ad27ce20SZhangPeng 			pte_folio = page_folio(pte_page(entry));
5132ad27ce20SZhangPeng 			folio_get(pte_folio);
51334eae4efaSPeter Xu 
51344eae4efaSPeter Xu 			/*
5135fb3d824dSDavid Hildenbrand 			 * Failing to duplicate the anon rmap is a rare case
5136fb3d824dSDavid Hildenbrand 			 * where we see pinned hugetlb pages while they're
5137fb3d824dSDavid Hildenbrand 			 * prone to COW. We need to do the COW earlier during
5138fb3d824dSDavid Hildenbrand 			 * fork.
51394eae4efaSPeter Xu 			 *
51404eae4efaSPeter Xu 			 * When pre-allocating the page or copying data, we
51414eae4efaSPeter Xu 			 * need to be without the pgtable locks since we could
51424eae4efaSPeter Xu 			 * sleep during the process.
51434eae4efaSPeter Xu 			 */
5144ad27ce20SZhangPeng 			if (!folio_test_anon(pte_folio)) {
5145ad27ce20SZhangPeng 				page_dup_file_rmap(&pte_folio->page, true);
5146ad27ce20SZhangPeng 			} else if (page_try_dup_anon_rmap(&pte_folio->page,
5147ad27ce20SZhangPeng 							  true, src_vma)) {
51484eae4efaSPeter Xu 				pte_t src_pte_old = entry;
5149d0ce0e47SSidhartha Kumar 				struct folio *new_folio;
51504eae4efaSPeter Xu 
51514eae4efaSPeter Xu 				spin_unlock(src_ptl);
51524eae4efaSPeter Xu 				spin_unlock(dst_ptl);
51534eae4efaSPeter Xu 				/* Do not use reserve as it's private owned */
5154d0ce0e47SSidhartha Kumar 				new_folio = alloc_hugetlb_folio(dst_vma, addr, 1);
5155d0ce0e47SSidhartha Kumar 				if (IS_ERR(new_folio)) {
5156ad27ce20SZhangPeng 					folio_put(pte_folio);
5157d0ce0e47SSidhartha Kumar 					ret = PTR_ERR(new_folio);
51584eae4efaSPeter Xu 					break;
51594eae4efaSPeter Xu 				}
51601cb9dc4bSLiu Shixin 				ret = copy_user_large_folio(new_folio,
5161ad27ce20SZhangPeng 							    pte_folio,
5162c0e8150eSZhangPeng 							    addr, dst_vma);
5163ad27ce20SZhangPeng 				folio_put(pte_folio);
51641cb9dc4bSLiu Shixin 				if (ret) {
51651cb9dc4bSLiu Shixin 					folio_put(new_folio);
51661cb9dc4bSLiu Shixin 					break;
51671cb9dc4bSLiu Shixin 				}
51684eae4efaSPeter Xu 
5169d0ce0e47SSidhartha Kumar 				/* Install the new hugetlb folio if src pte stable */
51704eae4efaSPeter Xu 				dst_ptl = huge_pte_lock(h, dst, dst_pte);
51714eae4efaSPeter Xu 				src_ptl = huge_pte_lockptr(h, src, src_pte);
51724eae4efaSPeter Xu 				spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
51734eae4efaSPeter Xu 				entry = huge_ptep_get(src_pte);
51744eae4efaSPeter Xu 				if (!pte_same(src_pte_old, entry)) {
5175bc70fbf2SPeter Xu 					restore_reserve_on_error(h, dst_vma, addr,
5176d2d7bb44SSidhartha Kumar 								new_folio);
5177d0ce0e47SSidhartha Kumar 					folio_put(new_folio);
51783aa4ed80SMiaohe Lin 					/* huge_ptep of dst_pte won't change as in child */
51794eae4efaSPeter Xu 					goto again;
51804eae4efaSPeter Xu 				}
51815a2f8d22SPeter Xu 				hugetlb_install_folio(dst_vma, dst_pte, addr,
5182935d4f0cSRyan Roberts 						      new_folio, src_pte_old, sz);
51834eae4efaSPeter Xu 				spin_unlock(src_ptl);
51844eae4efaSPeter Xu 				spin_unlock(dst_ptl);
51854eae4efaSPeter Xu 				continue;
51864eae4efaSPeter Xu 			}
51874eae4efaSPeter Xu 
518834ee645eSJoerg Roedel 			if (cow) {
51890f10851eSJérôme Glisse 				/*
51900f10851eSJérôme Glisse 				 * No need to notify as we are downgrading page
51910f10851eSJérôme Glisse 				 * table protection not changing it to point
51920f10851eSJérôme Glisse 				 * to a new page.
51930f10851eSJérôme Glisse 				 *
5194ee65728eSMike Rapoport 				 * See Documentation/mm/mmu_notifier.rst
51950f10851eSJérôme Glisse 				 */
51967f2e9525SGerald Schaefer 				huge_ptep_set_wrprotect(src, addr, src_pte);
519784894e1cSPeter Xu 				entry = huge_pte_wrprotect(entry);
519834ee645eSJoerg Roedel 			}
51994eae4efaSPeter Xu 
52005a2f8d22SPeter Xu 			if (!userfaultfd_wp(dst_vma))
52015a2f8d22SPeter Xu 				entry = huge_pte_clear_uffd_wp(entry);
52025a2f8d22SPeter Xu 
5203935d4f0cSRyan Roberts 			set_huge_pte_at(dst, addr, dst_pte, entry, sz);
52044eae4efaSPeter Xu 			hugetlb_count_add(npages, dst);
52051c59827dSHugh Dickins 		}
5206cb900f41SKirill A. Shutemov 		spin_unlock(src_ptl);
5207cb900f41SKirill A. Shutemov 		spin_unlock(dst_ptl);
520863551ae0SDavid Gibson 	}
520963551ae0SDavid Gibson 
5210623a1ddfSDavid Hildenbrand 	if (cow) {
5211623a1ddfSDavid Hildenbrand 		raw_write_seqcount_end(&src->write_protect_seq);
5212ac46d4f3SJérôme Glisse 		mmu_notifier_invalidate_range_end(&range);
521340549ba8SMike Kravetz 	} else {
521440549ba8SMike Kravetz 		hugetlb_vma_unlock_read(src_vma);
5215623a1ddfSDavid Hildenbrand 	}
5216e8569dd2SAndreas Sandberg 
5217e8569dd2SAndreas Sandberg 	return ret;
521863551ae0SDavid Gibson }
521963551ae0SDavid Gibson 
move_huge_pte(struct vm_area_struct * vma,unsigned long old_addr,unsigned long new_addr,pte_t * src_pte,pte_t * dst_pte,unsigned long sz)5220550a7d60SMina Almasry static void move_huge_pte(struct vm_area_struct *vma, unsigned long old_addr,
5221935d4f0cSRyan Roberts 			  unsigned long new_addr, pte_t *src_pte, pte_t *dst_pte,
5222935d4f0cSRyan Roberts 			  unsigned long sz)
5223550a7d60SMina Almasry {
5224550a7d60SMina Almasry 	struct hstate *h = hstate_vma(vma);
5225550a7d60SMina Almasry 	struct mm_struct *mm = vma->vm_mm;
5226550a7d60SMina Almasry 	spinlock_t *src_ptl, *dst_ptl;
5227db110a99SAneesh Kumar K.V 	pte_t pte;
5228550a7d60SMina Almasry 
5229550a7d60SMina Almasry 	dst_ptl = huge_pte_lock(h, mm, dst_pte);
5230550a7d60SMina Almasry 	src_ptl = huge_pte_lockptr(h, mm, src_pte);
5231550a7d60SMina Almasry 
5232550a7d60SMina Almasry 	/*
5233550a7d60SMina Almasry 	 * We don't have to worry about the ordering of src and dst ptlocks
52348651a137SLorenzo Stoakes 	 * because exclusive mmap_lock (or the i_mmap_lock) prevents deadlock.
5235550a7d60SMina Almasry 	 */
5236550a7d60SMina Almasry 	if (src_ptl != dst_ptl)
5237550a7d60SMina Almasry 		spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
5238550a7d60SMina Almasry 
5239*c04035ceSRyan Roberts 	pte = huge_ptep_get_and_clear(mm, old_addr, src_pte, sz);
5240935d4f0cSRyan Roberts 	set_huge_pte_at(mm, new_addr, dst_pte, pte, sz);
5241550a7d60SMina Almasry 
5242550a7d60SMina Almasry 	if (src_ptl != dst_ptl)
5243550a7d60SMina Almasry 		spin_unlock(src_ptl);
5244550a7d60SMina Almasry 	spin_unlock(dst_ptl);
5245550a7d60SMina Almasry }
5246550a7d60SMina Almasry 
move_hugetlb_page_tables(struct vm_area_struct * vma,struct vm_area_struct * new_vma,unsigned long old_addr,unsigned long new_addr,unsigned long len)5247550a7d60SMina Almasry int move_hugetlb_page_tables(struct vm_area_struct *vma,
5248550a7d60SMina Almasry 			     struct vm_area_struct *new_vma,
5249550a7d60SMina Almasry 			     unsigned long old_addr, unsigned long new_addr,
5250550a7d60SMina Almasry 			     unsigned long len)
5251550a7d60SMina Almasry {
5252550a7d60SMina Almasry 	struct hstate *h = hstate_vma(vma);
5253550a7d60SMina Almasry 	struct address_space *mapping = vma->vm_file->f_mapping;
5254550a7d60SMina Almasry 	unsigned long sz = huge_page_size(h);
5255550a7d60SMina Almasry 	struct mm_struct *mm = vma->vm_mm;
5256550a7d60SMina Almasry 	unsigned long old_end = old_addr + len;
5257e95a9851SMike Kravetz 	unsigned long last_addr_mask;
5258550a7d60SMina Almasry 	pte_t *src_pte, *dst_pte;
5259550a7d60SMina Almasry 	struct mmu_notifier_range range;
52603d0b95cdSBaolin Wang 	bool shared_pmd = false;
5261550a7d60SMina Almasry 
52627d4a8be0SAlistair Popple 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, old_addr,
5263550a7d60SMina Almasry 				old_end);
5264550a7d60SMina Almasry 	adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
52653d0b95cdSBaolin Wang 	/*
52663d0b95cdSBaolin Wang 	 * In case of shared PMDs, we should cover the maximum possible
52673d0b95cdSBaolin Wang 	 * range.
52683d0b95cdSBaolin Wang 	 */
52693d0b95cdSBaolin Wang 	flush_cache_range(vma, range.start, range.end);
52703d0b95cdSBaolin Wang 
5271550a7d60SMina Almasry 	mmu_notifier_invalidate_range_start(&range);
5272e95a9851SMike Kravetz 	last_addr_mask = hugetlb_mask_last_page(h);
5273550a7d60SMina Almasry 	/* Prevent race with file truncation */
527440549ba8SMike Kravetz 	hugetlb_vma_lock_write(vma);
5275550a7d60SMina Almasry 	i_mmap_lock_write(mapping);
5276550a7d60SMina Almasry 	for (; old_addr < old_end; old_addr += sz, new_addr += sz) {
52779c67a207SPeter Xu 		src_pte = hugetlb_walk(vma, old_addr, sz);
5278e95a9851SMike Kravetz 		if (!src_pte) {
5279e95a9851SMike Kravetz 			old_addr |= last_addr_mask;
5280e95a9851SMike Kravetz 			new_addr |= last_addr_mask;
5281550a7d60SMina Almasry 			continue;
5282e95a9851SMike Kravetz 		}
5283550a7d60SMina Almasry 		if (huge_pte_none(huge_ptep_get(src_pte)))
5284550a7d60SMina Almasry 			continue;
5285550a7d60SMina Almasry 
52864ddb4d91SMike Kravetz 		if (huge_pmd_unshare(mm, vma, old_addr, src_pte)) {
52873d0b95cdSBaolin Wang 			shared_pmd = true;
52884ddb4d91SMike Kravetz 			old_addr |= last_addr_mask;
52894ddb4d91SMike Kravetz 			new_addr |= last_addr_mask;
5290550a7d60SMina Almasry 			continue;
52913d0b95cdSBaolin Wang 		}
5292550a7d60SMina Almasry 
5293550a7d60SMina Almasry 		dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz);
5294550a7d60SMina Almasry 		if (!dst_pte)
5295550a7d60SMina Almasry 			break;
5296550a7d60SMina Almasry 
5297935d4f0cSRyan Roberts 		move_huge_pte(vma, old_addr, new_addr, src_pte, dst_pte, sz);
5298550a7d60SMina Almasry 	}
52993d0b95cdSBaolin Wang 
53003d0b95cdSBaolin Wang 	if (shared_pmd)
5301f720b471SKefeng Wang 		flush_hugetlb_tlb_range(vma, range.start, range.end);
53023d0b95cdSBaolin Wang 	else
5303f720b471SKefeng Wang 		flush_hugetlb_tlb_range(vma, old_end - len, old_end);
5304550a7d60SMina Almasry 	mmu_notifier_invalidate_range_end(&range);
530513e4ad2cSNadav Amit 	i_mmap_unlock_write(mapping);
530640549ba8SMike Kravetz 	hugetlb_vma_unlock_write(vma);
5307550a7d60SMina Almasry 
5308550a7d60SMina Almasry 	return len + old_addr - old_end;
5309550a7d60SMina Almasry }
5310550a7d60SMina Almasry 
__unmap_hugepage_range(struct mmu_gather * tlb,struct vm_area_struct * vma,unsigned long start,unsigned long end,struct page * ref_page,zap_flags_t zap_flags)53112820b0f0SRik van Riel void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
531224669e58SAneesh Kumar K.V 			    unsigned long start, unsigned long end,
531305e90bd0SPeter Xu 			    struct page *ref_page, zap_flags_t zap_flags)
531463551ae0SDavid Gibson {
531563551ae0SDavid Gibson 	struct mm_struct *mm = vma->vm_mm;
531663551ae0SDavid Gibson 	unsigned long address;
5317c7546f8fSDavid Gibson 	pte_t *ptep;
531863551ae0SDavid Gibson 	pte_t pte;
5319cb900f41SKirill A. Shutemov 	spinlock_t *ptl;
532063551ae0SDavid Gibson 	struct page *page;
5321a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
5322a5516438SAndi Kleen 	unsigned long sz = huge_page_size(h);
5323e95a9851SMike Kravetz 	unsigned long last_addr_mask;
5324a4a118f2SNadav Amit 	bool force_flush = false;
5325a5516438SAndi Kleen 
532663551ae0SDavid Gibson 	WARN_ON(!is_vm_hugetlb_page(vma));
5327a5516438SAndi Kleen 	BUG_ON(start & ~huge_page_mask(h));
5328a5516438SAndi Kleen 	BUG_ON(end & ~huge_page_mask(h));
532963551ae0SDavid Gibson 
533007e32661SAneesh Kumar K.V 	/*
533107e32661SAneesh Kumar K.V 	 * This is a hugetlb vma, all the pte entries should point
533207e32661SAneesh Kumar K.V 	 * to huge page.
533307e32661SAneesh Kumar K.V 	 */
5334ed6a7935SPeter Zijlstra 	tlb_change_page_size(tlb, sz);
533524669e58SAneesh Kumar K.V 	tlb_start_vma(tlb, vma);
5336dff11abeSMike Kravetz 
5337e95a9851SMike Kravetz 	last_addr_mask = hugetlb_mask_last_page(h);
5338569f48b8SHillf Danton 	address = start;
5339569f48b8SHillf Danton 	for (; address < end; address += sz) {
53409c67a207SPeter Xu 		ptep = hugetlb_walk(vma, address, sz);
5341e95a9851SMike Kravetz 		if (!ptep) {
5342e95a9851SMike Kravetz 			address |= last_addr_mask;
5343c7546f8fSDavid Gibson 			continue;
5344e95a9851SMike Kravetz 		}
5345c7546f8fSDavid Gibson 
5346cb900f41SKirill A. Shutemov 		ptl = huge_pte_lock(h, mm, ptep);
53474ddb4d91SMike Kravetz 		if (huge_pmd_unshare(mm, vma, address, ptep)) {
534831d49da5SAneesh Kumar K.V 			spin_unlock(ptl);
5349a4a118f2SNadav Amit 			tlb_flush_pmd_range(tlb, address & PUD_MASK, PUD_SIZE);
5350a4a118f2SNadav Amit 			force_flush = true;
53514ddb4d91SMike Kravetz 			address |= last_addr_mask;
535231d49da5SAneesh Kumar K.V 			continue;
535331d49da5SAneesh Kumar K.V 		}
535439dde65cSChen, Kenneth W 
53556629326bSHillf Danton 		pte = huge_ptep_get(ptep);
535631d49da5SAneesh Kumar K.V 		if (huge_pte_none(pte)) {
535731d49da5SAneesh Kumar K.V 			spin_unlock(ptl);
535831d49da5SAneesh Kumar K.V 			continue;
535931d49da5SAneesh Kumar K.V 		}
53606629326bSHillf Danton 
53616629326bSHillf Danton 		/*
53629fbc1f63SNaoya Horiguchi 		 * Migrating hugepage or HWPoisoned hugepage is already
53639fbc1f63SNaoya Horiguchi 		 * unmapped and its refcount is dropped, so just clear pte here.
53646629326bSHillf Danton 		 */
53659fbc1f63SNaoya Horiguchi 		if (unlikely(!pte_present(pte))) {
536605e90bd0SPeter Xu 			/*
536705e90bd0SPeter Xu 			 * If the pte was wr-protected by uffd-wp in any of the
536805e90bd0SPeter Xu 			 * swap forms, meanwhile the caller does not want to
536905e90bd0SPeter Xu 			 * drop the uffd-wp bit in this zap, then replace the
537005e90bd0SPeter Xu 			 * pte with a marker.
537105e90bd0SPeter Xu 			 */
537205e90bd0SPeter Xu 			if (pte_swp_uffd_wp_any(pte) &&
537305e90bd0SPeter Xu 			    !(zap_flags & ZAP_FLAG_DROP_MARKER))
537405e90bd0SPeter Xu 				set_huge_pte_at(mm, address, ptep,
5375935d4f0cSRyan Roberts 						make_pte_marker(PTE_MARKER_UFFD_WP),
5376935d4f0cSRyan Roberts 						sz);
537705e90bd0SPeter Xu 			else
53789386fac3SPunit Agrawal 				huge_pte_clear(mm, address, ptep, sz);
537931d49da5SAneesh Kumar K.V 			spin_unlock(ptl);
538031d49da5SAneesh Kumar K.V 			continue;
53818c4894c6SNaoya Horiguchi 		}
53826629326bSHillf Danton 
53836629326bSHillf Danton 		page = pte_page(pte);
538404f2cbe3SMel Gorman 		/*
538504f2cbe3SMel Gorman 		 * If a reference page is supplied, it is because a specific
538604f2cbe3SMel Gorman 		 * page is being unmapped, not a range. Ensure the page we
538704f2cbe3SMel Gorman 		 * are about to unmap is the actual page of interest.
538804f2cbe3SMel Gorman 		 */
538904f2cbe3SMel Gorman 		if (ref_page) {
539031d49da5SAneesh Kumar K.V 			if (page != ref_page) {
539131d49da5SAneesh Kumar K.V 				spin_unlock(ptl);
539231d49da5SAneesh Kumar K.V 				continue;
539331d49da5SAneesh Kumar K.V 			}
539404f2cbe3SMel Gorman 			/*
539504f2cbe3SMel Gorman 			 * Mark the VMA as having unmapped its page so that
539604f2cbe3SMel Gorman 			 * future faults in this VMA will fail rather than
539704f2cbe3SMel Gorman 			 * looking like data was lost
539804f2cbe3SMel Gorman 			 */
539904f2cbe3SMel Gorman 			set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED);
540004f2cbe3SMel Gorman 		}
540104f2cbe3SMel Gorman 
5402*c04035ceSRyan Roberts 		pte = huge_ptep_get_and_clear(mm, address, ptep, sz);
5403b528e4b6SAneesh Kumar K.V 		tlb_remove_huge_tlb_entry(h, tlb, ptep, address);
5404106c992aSGerald Schaefer 		if (huge_pte_dirty(pte))
54056649a386SKen Chen 			set_page_dirty(page);
540605e90bd0SPeter Xu 		/* Leave a uffd-wp pte marker if needed */
540705e90bd0SPeter Xu 		if (huge_pte_uffd_wp(pte) &&
540805e90bd0SPeter Xu 		    !(zap_flags & ZAP_FLAG_DROP_MARKER))
540905e90bd0SPeter Xu 			set_huge_pte_at(mm, address, ptep,
5410935d4f0cSRyan Roberts 					make_pte_marker(PTE_MARKER_UFFD_WP),
5411935d4f0cSRyan Roberts 					sz);
54125d317b2bSNaoya Horiguchi 		hugetlb_count_sub(pages_per_huge_page(h), mm);
5413cea86fe2SHugh Dickins 		page_remove_rmap(page, vma, true);
541431d49da5SAneesh Kumar K.V 
5415cb900f41SKirill A. Shutemov 		spin_unlock(ptl);
5416e77b0852SAneesh Kumar K.V 		tlb_remove_page_size(tlb, page, huge_page_size(h));
541724669e58SAneesh Kumar K.V 		/*
541831d49da5SAneesh Kumar K.V 		 * Bail out after unmapping reference page if supplied
541924669e58SAneesh Kumar K.V 		 */
542031d49da5SAneesh Kumar K.V 		if (ref_page)
542131d49da5SAneesh Kumar K.V 			break;
5422fe1668aeSChen, Kenneth W 	}
542324669e58SAneesh Kumar K.V 	tlb_end_vma(tlb, vma);
5424a4a118f2SNadav Amit 
5425a4a118f2SNadav Amit 	/*
5426a4a118f2SNadav Amit 	 * If we unshared PMDs, the TLB flush was not recorded in mmu_gather. We
5427a4a118f2SNadav Amit 	 * could defer the flush until now, since by holding i_mmap_rwsem we
5428a4a118f2SNadav Amit 	 * guaranteed that the last refernece would not be dropped. But we must
5429a4a118f2SNadav Amit 	 * do the flushing before we return, as otherwise i_mmap_rwsem will be
5430a4a118f2SNadav Amit 	 * dropped and the last reference to the shared PMDs page might be
5431a4a118f2SNadav Amit 	 * dropped as well.
5432a4a118f2SNadav Amit 	 *
5433a4a118f2SNadav Amit 	 * In theory we could defer the freeing of the PMD pages as well, but
5434a4a118f2SNadav Amit 	 * huge_pmd_unshare() relies on the exact page_count for the PMD page to
5435a4a118f2SNadav Amit 	 * detect sharing, so we cannot defer the release of the page either.
5436a4a118f2SNadav Amit 	 * Instead, do flush now.
5437a4a118f2SNadav Amit 	 */
5438a4a118f2SNadav Amit 	if (force_flush)
5439a4a118f2SNadav Amit 		tlb_flush_mmu_tlbonly(tlb);
54401da177e4SLinus Torvalds }
544163551ae0SDavid Gibson 
__hugetlb_zap_begin(struct vm_area_struct * vma,unsigned long * start,unsigned long * end)54422820b0f0SRik van Riel void __hugetlb_zap_begin(struct vm_area_struct *vma,
54432820b0f0SRik van Riel 			 unsigned long *start, unsigned long *end)
5444d833352aSMel Gorman {
54452820b0f0SRik van Riel 	if (!vma->vm_file)	/* hugetlbfs_file_mmap error */
54462820b0f0SRik van Riel 		return;
5447131a79b4SMike Kravetz 
54482820b0f0SRik van Riel 	adjust_range_if_pmd_sharing_possible(vma, start, end);
54492820b0f0SRik van Riel 	hugetlb_vma_lock_write(vma);
54502820b0f0SRik van Riel 	if (vma->vm_file)
54512820b0f0SRik van Riel 		i_mmap_lock_write(vma->vm_file->f_mapping);
54522820b0f0SRik van Riel }
54532820b0f0SRik van Riel 
__hugetlb_zap_end(struct vm_area_struct * vma,struct zap_details * details)54542820b0f0SRik van Riel void __hugetlb_zap_end(struct vm_area_struct *vma,
54552820b0f0SRik van Riel 		       struct zap_details *details)
54562820b0f0SRik van Riel {
54572820b0f0SRik van Riel 	zap_flags_t zap_flags = details ? details->zap_flags : 0;
54582820b0f0SRik van Riel 
54592820b0f0SRik van Riel 	if (!vma->vm_file)	/* hugetlbfs_file_mmap error */
54602820b0f0SRik van Riel 		return;
5461d833352aSMel Gorman 
546204ada095SMike Kravetz 	if (zap_flags & ZAP_FLAG_UNMAP) {	/* final unmap */
5463d833352aSMel Gorman 		/*
546404ada095SMike Kravetz 		 * Unlock and free the vma lock before releasing i_mmap_rwsem.
546504ada095SMike Kravetz 		 * When the vma_lock is freed, this makes the vma ineligible
546604ada095SMike Kravetz 		 * for pmd sharing.  And, i_mmap_rwsem is required to set up
546704ada095SMike Kravetz 		 * pmd sharing.  This is important as page tables for this
546804ada095SMike Kravetz 		 * unmapped range will be asynchrously deleted.  If the page
546904ada095SMike Kravetz 		 * tables are shared, there will be issues when accessed by
547004ada095SMike Kravetz 		 * someone else.
5471d833352aSMel Gorman 		 */
5472ecfbd733SMike Kravetz 		__hugetlb_vma_unlock_write_free(vma);
547304ada095SMike Kravetz 	} else {
547404ada095SMike Kravetz 		hugetlb_vma_unlock_write(vma);
547504ada095SMike Kravetz 	}
54762820b0f0SRik van Riel 
54772820b0f0SRik van Riel 	if (vma->vm_file)
54782820b0f0SRik van Riel 		i_mmap_unlock_write(vma->vm_file->f_mapping);
5479d833352aSMel Gorman }
5480d833352aSMel Gorman 
unmap_hugepage_range(struct vm_area_struct * vma,unsigned long start,unsigned long end,struct page * ref_page,zap_flags_t zap_flags)5481502717f4SChen, Kenneth W void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
548205e90bd0SPeter Xu 			  unsigned long end, struct page *ref_page,
548305e90bd0SPeter Xu 			  zap_flags_t zap_flags)
5484502717f4SChen, Kenneth W {
5485369258ceSMike Kravetz 	struct mmu_notifier_range range;
548624669e58SAneesh Kumar K.V 	struct mmu_gather tlb;
5487dff11abeSMike Kravetz 
54887d4a8be0SAlistair Popple 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
5489369258ceSMike Kravetz 				start, end);
5490369258ceSMike Kravetz 	adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
5491369258ceSMike Kravetz 	mmu_notifier_invalidate_range_start(&range);
5492a72afd87SWill Deacon 	tlb_gather_mmu(&tlb, vma->vm_mm);
5493369258ceSMike Kravetz 
549405e90bd0SPeter Xu 	__unmap_hugepage_range(&tlb, vma, start, end, ref_page, zap_flags);
5495369258ceSMike Kravetz 
5496369258ceSMike Kravetz 	mmu_notifier_invalidate_range_end(&range);
5497ae8eba8bSWill Deacon 	tlb_finish_mmu(&tlb);
5498502717f4SChen, Kenneth W }
5499502717f4SChen, Kenneth W 
550004f2cbe3SMel Gorman /*
550104f2cbe3SMel Gorman  * This is called when the original mapper is failing to COW a MAP_PRIVATE
5502578b7725SZhiyuan Dai  * mapping it owns the reserve page for. The intention is to unmap the page
550304f2cbe3SMel Gorman  * from other VMAs and let the children be SIGKILLed if they are faulting the
550404f2cbe3SMel Gorman  * same region.
550504f2cbe3SMel Gorman  */
unmap_ref_private(struct mm_struct * mm,struct vm_area_struct * vma,struct page * page,unsigned long address)55062f4612afSDavidlohr Bueso static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,
55072a4b3dedSHarvey Harrison 			      struct page *page, unsigned long address)
550804f2cbe3SMel Gorman {
55097526674dSAdam Litke 	struct hstate *h = hstate_vma(vma);
551004f2cbe3SMel Gorman 	struct vm_area_struct *iter_vma;
551104f2cbe3SMel Gorman 	struct address_space *mapping;
551204f2cbe3SMel Gorman 	pgoff_t pgoff;
551304f2cbe3SMel Gorman 
551404f2cbe3SMel Gorman 	/*
551504f2cbe3SMel Gorman 	 * vm_pgoff is in PAGE_SIZE units, hence the different calculation
551604f2cbe3SMel Gorman 	 * from page cache lookup which is in HPAGE_SIZE units.
551704f2cbe3SMel Gorman 	 */
55187526674dSAdam Litke 	address = address & huge_page_mask(h);
551936e4f20aSMichal Hocko 	pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) +
552036e4f20aSMichal Hocko 			vma->vm_pgoff;
552193c76a3dSAl Viro 	mapping = vma->vm_file->f_mapping;
552204f2cbe3SMel Gorman 
55234eb2b1dcSMel Gorman 	/*
55244eb2b1dcSMel Gorman 	 * Take the mapping lock for the duration of the table walk. As
55254eb2b1dcSMel Gorman 	 * this mapping should be shared between all the VMAs,
55264eb2b1dcSMel Gorman 	 * __unmap_hugepage_range() is called as the lock is already held
55274eb2b1dcSMel Gorman 	 */
552883cde9e8SDavidlohr Bueso 	i_mmap_lock_write(mapping);
55296b2dbba8SMichel Lespinasse 	vma_interval_tree_foreach(iter_vma, &mapping->i_mmap, pgoff, pgoff) {
553004f2cbe3SMel Gorman 		/* Do not unmap the current VMA */
553104f2cbe3SMel Gorman 		if (iter_vma == vma)
553204f2cbe3SMel Gorman 			continue;
553304f2cbe3SMel Gorman 
553404f2cbe3SMel Gorman 		/*
55352f84a899SMel Gorman 		 * Shared VMAs have their own reserves and do not affect
55362f84a899SMel Gorman 		 * MAP_PRIVATE accounting but it is possible that a shared
55372f84a899SMel Gorman 		 * VMA is using the same page so check and skip such VMAs.
55382f84a899SMel Gorman 		 */
55392f84a899SMel Gorman 		if (iter_vma->vm_flags & VM_MAYSHARE)
55402f84a899SMel Gorman 			continue;
55412f84a899SMel Gorman 
55422f84a899SMel Gorman 		/*
554304f2cbe3SMel Gorman 		 * Unmap the page from other VMAs without their own reserves.
554404f2cbe3SMel Gorman 		 * They get marked to be SIGKILLed if they fault in these
554504f2cbe3SMel Gorman 		 * areas. This is because a future no-page fault on this VMA
554604f2cbe3SMel Gorman 		 * could insert a zeroed page instead of the data existing
554704f2cbe3SMel Gorman 		 * from the time of fork. This would look like data corruption
554804f2cbe3SMel Gorman 		 */
554904f2cbe3SMel Gorman 		if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER))
555024669e58SAneesh Kumar K.V 			unmap_hugepage_range(iter_vma, address,
555105e90bd0SPeter Xu 					     address + huge_page_size(h), page, 0);
555204f2cbe3SMel Gorman 	}
555383cde9e8SDavidlohr Bueso 	i_mmap_unlock_write(mapping);
555404f2cbe3SMel Gorman }
555504f2cbe3SMel Gorman 
55560fe6e20bSNaoya Horiguchi /*
5557c89357e2SDavid Hildenbrand  * hugetlb_wp() should be called with page lock of the original hugepage held.
5558aa6d2e8cSBaolin Wang  * Called with hugetlb_fault_mutex_table held and pte_page locked so we
5559ef009b25SMichal Hocko  * cannot race with other handlers or page migration.
5560ef009b25SMichal Hocko  * Keep the pte_same checks anyway to make transition from the mutex easier.
55610fe6e20bSNaoya Horiguchi  */
hugetlb_wp(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long address,pte_t * ptep,unsigned int flags,struct folio * pagecache_folio,spinlock_t * ptl)5562c89357e2SDavid Hildenbrand static vm_fault_t hugetlb_wp(struct mm_struct *mm, struct vm_area_struct *vma,
5563c89357e2SDavid Hildenbrand 		       unsigned long address, pte_t *ptep, unsigned int flags,
5564371607a3SSidhartha Kumar 		       struct folio *pagecache_folio, spinlock_t *ptl)
55651e8f889bSDavid Gibson {
5566c89357e2SDavid Hildenbrand 	const bool unshare = flags & FAULT_FLAG_UNSHARE;
556760d5b473SPeter Xu 	pte_t pte = huge_ptep_get(ptep);
5568a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
5569959a78b6SZhangPeng 	struct folio *old_folio;
5570d0ce0e47SSidhartha Kumar 	struct folio *new_folio;
55712b740303SSouptick Joarder 	int outside_reserve = 0;
55722b740303SSouptick Joarder 	vm_fault_t ret = 0;
5573974e6d66SHuang Ying 	unsigned long haddr = address & huge_page_mask(h);
5574ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
55751e8f889bSDavid Gibson 
55761d8d1464SDavid Hildenbrand 	/*
557760d5b473SPeter Xu 	 * Never handle CoW for uffd-wp protected pages.  It should be only
557860d5b473SPeter Xu 	 * handled when the uffd-wp protection is removed.
557960d5b473SPeter Xu 	 *
558060d5b473SPeter Xu 	 * Note that only the CoW optimization path (in hugetlb_no_page())
558160d5b473SPeter Xu 	 * can trigger this, because hugetlb_fault() will always resolve
558260d5b473SPeter Xu 	 * uffd-wp bit first.
558360d5b473SPeter Xu 	 */
558460d5b473SPeter Xu 	if (!unshare && huge_pte_uffd_wp(pte))
558560d5b473SPeter Xu 		return 0;
558660d5b473SPeter Xu 
558760d5b473SPeter Xu 	/*
55881d8d1464SDavid Hildenbrand 	 * hugetlb does not support FOLL_FORCE-style write faults that keep the
55891d8d1464SDavid Hildenbrand 	 * PTE mapped R/O such as maybe_mkwrite() would do.
55901d8d1464SDavid Hildenbrand 	 */
55911d8d1464SDavid Hildenbrand 	if (WARN_ON_ONCE(!unshare && !(vma->vm_flags & VM_WRITE)))
55921d8d1464SDavid Hildenbrand 		return VM_FAULT_SIGSEGV;
55931d8d1464SDavid Hildenbrand 
55941d8d1464SDavid Hildenbrand 	/* Let's take out MAP_SHARED mappings first. */
55951d8d1464SDavid Hildenbrand 	if (vma->vm_flags & VM_MAYSHARE) {
55961d8d1464SDavid Hildenbrand 		set_huge_ptep_writable(vma, haddr, ptep);
55971d8d1464SDavid Hildenbrand 		return 0;
55981d8d1464SDavid Hildenbrand 	}
55991d8d1464SDavid Hildenbrand 
5600959a78b6SZhangPeng 	old_folio = page_folio(pte_page(pte));
56011e8f889bSDavid Gibson 
5602662ce1dcSYang Yang 	delayacct_wpcopy_start();
5603662ce1dcSYang Yang 
560404f2cbe3SMel Gorman retry_avoidcopy:
5605c89357e2SDavid Hildenbrand 	/*
5606c89357e2SDavid Hildenbrand 	 * If no-one else is actually using this page, we're the exclusive
5607c89357e2SDavid Hildenbrand 	 * owner and can reuse this page.
5608c89357e2SDavid Hildenbrand 	 */
5609959a78b6SZhangPeng 	if (folio_mapcount(old_folio) == 1 && folio_test_anon(old_folio)) {
5610959a78b6SZhangPeng 		if (!PageAnonExclusive(&old_folio->page))
5611959a78b6SZhangPeng 			page_move_anon_rmap(&old_folio->page, vma);
5612c89357e2SDavid Hildenbrand 		if (likely(!unshare))
56135b7a1d40SHuang Ying 			set_huge_ptep_writable(vma, haddr, ptep);
5614662ce1dcSYang Yang 
5615662ce1dcSYang Yang 		delayacct_wpcopy_end();
561683c54070SNick Piggin 		return 0;
56171e8f889bSDavid Gibson 	}
5618959a78b6SZhangPeng 	VM_BUG_ON_PAGE(folio_test_anon(old_folio) &&
5619959a78b6SZhangPeng 		       PageAnonExclusive(&old_folio->page), &old_folio->page);
56201e8f889bSDavid Gibson 
562104f2cbe3SMel Gorman 	/*
562204f2cbe3SMel Gorman 	 * If the process that created a MAP_PRIVATE mapping is about to
562304f2cbe3SMel Gorman 	 * perform a COW due to a shared page count, attempt to satisfy
562404f2cbe3SMel Gorman 	 * the allocation without using the existing reserves. The pagecache
562504f2cbe3SMel Gorman 	 * page is used to determine if the reserve at this address was
562604f2cbe3SMel Gorman 	 * consumed or not. If reserves were used, a partial faulted mapping
562704f2cbe3SMel Gorman 	 * at the time of fork() could consume its reserves on COW instead
562804f2cbe3SMel Gorman 	 * of the full address range.
562904f2cbe3SMel Gorman 	 */
56305944d011SJoonsoo Kim 	if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) &&
5631959a78b6SZhangPeng 			old_folio != pagecache_folio)
563204f2cbe3SMel Gorman 		outside_reserve = 1;
563304f2cbe3SMel Gorman 
5634959a78b6SZhangPeng 	folio_get(old_folio);
5635b76c8cfbSLarry Woodman 
5636ad4404a2SDavidlohr Bueso 	/*
5637ad4404a2SDavidlohr Bueso 	 * Drop page table lock as buddy allocator may be called. It will
5638ad4404a2SDavidlohr Bueso 	 * be acquired again before returning to the caller, as expected.
5639ad4404a2SDavidlohr Bueso 	 */
5640cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
5641d0ce0e47SSidhartha Kumar 	new_folio = alloc_hugetlb_folio(vma, haddr, outside_reserve);
56421e8f889bSDavid Gibson 
5643d0ce0e47SSidhartha Kumar 	if (IS_ERR(new_folio)) {
564404f2cbe3SMel Gorman 		/*
564504f2cbe3SMel Gorman 		 * If a process owning a MAP_PRIVATE mapping fails to COW,
564604f2cbe3SMel Gorman 		 * it is due to references held by a child and an insufficient
564704f2cbe3SMel Gorman 		 * huge page pool. To guarantee the original mappers
564804f2cbe3SMel Gorman 		 * reliability, unmap the page from child processes. The child
564904f2cbe3SMel Gorman 		 * may get SIGKILLed if it later faults.
565004f2cbe3SMel Gorman 		 */
565104f2cbe3SMel Gorman 		if (outside_reserve) {
565240549ba8SMike Kravetz 			struct address_space *mapping = vma->vm_file->f_mapping;
565340549ba8SMike Kravetz 			pgoff_t idx;
565440549ba8SMike Kravetz 			u32 hash;
565540549ba8SMike Kravetz 
5656959a78b6SZhangPeng 			folio_put(old_folio);
565740549ba8SMike Kravetz 			/*
565840549ba8SMike Kravetz 			 * Drop hugetlb_fault_mutex and vma_lock before
565940549ba8SMike Kravetz 			 * unmapping.  unmapping needs to hold vma_lock
566040549ba8SMike Kravetz 			 * in write mode.  Dropping vma_lock in read mode
566140549ba8SMike Kravetz 			 * here is OK as COW mappings do not interact with
566240549ba8SMike Kravetz 			 * PMD sharing.
566340549ba8SMike Kravetz 			 *
566440549ba8SMike Kravetz 			 * Reacquire both after unmap operation.
566540549ba8SMike Kravetz 			 */
566640549ba8SMike Kravetz 			idx = vma_hugecache_offset(h, vma, haddr);
566740549ba8SMike Kravetz 			hash = hugetlb_fault_mutex_hash(mapping, idx);
566840549ba8SMike Kravetz 			hugetlb_vma_unlock_read(vma);
566940549ba8SMike Kravetz 			mutex_unlock(&hugetlb_fault_mutex_table[hash]);
567040549ba8SMike Kravetz 
5671959a78b6SZhangPeng 			unmap_ref_private(mm, vma, &old_folio->page, haddr);
567240549ba8SMike Kravetz 
567340549ba8SMike Kravetz 			mutex_lock(&hugetlb_fault_mutex_table[hash]);
567440549ba8SMike Kravetz 			hugetlb_vma_lock_read(vma);
5675cb900f41SKirill A. Shutemov 			spin_lock(ptl);
56769c67a207SPeter Xu 			ptep = hugetlb_walk(vma, haddr, huge_page_size(h));
5677a9af0c5dSNaoya Horiguchi 			if (likely(ptep &&
5678a9af0c5dSNaoya Horiguchi 				   pte_same(huge_ptep_get(ptep), pte)))
567904f2cbe3SMel Gorman 				goto retry_avoidcopy;
5680a734bcc8SHillf Danton 			/*
5681cb900f41SKirill A. Shutemov 			 * race occurs while re-acquiring page table
5682cb900f41SKirill A. Shutemov 			 * lock, and our job is done.
5683a734bcc8SHillf Danton 			 */
5684662ce1dcSYang Yang 			delayacct_wpcopy_end();
5685a734bcc8SHillf Danton 			return 0;
568604f2cbe3SMel Gorman 		}
568704f2cbe3SMel Gorman 
5688d0ce0e47SSidhartha Kumar 		ret = vmf_error(PTR_ERR(new_folio));
5689ad4404a2SDavidlohr Bueso 		goto out_release_old;
56901e8f889bSDavid Gibson 	}
56911e8f889bSDavid Gibson 
56920fe6e20bSNaoya Horiguchi 	/*
56930fe6e20bSNaoya Horiguchi 	 * When the original hugepage is shared one, it does not have
56940fe6e20bSNaoya Horiguchi 	 * anon_vma prepared.
56950fe6e20bSNaoya Horiguchi 	 */
569644e2aa93SDean Nelson 	if (unlikely(anon_vma_prepare(vma))) {
5697ad4404a2SDavidlohr Bueso 		ret = VM_FAULT_OOM;
5698ad4404a2SDavidlohr Bueso 		goto out_release_all;
569944e2aa93SDean Nelson 	}
57000fe6e20bSNaoya Horiguchi 
5701959a78b6SZhangPeng 	if (copy_user_large_folio(new_folio, old_folio, address, vma)) {
57021cb9dc4bSLiu Shixin 		ret = VM_FAULT_HWPOISON_LARGE;
57031cb9dc4bSLiu Shixin 		goto out_release_all;
57041cb9dc4bSLiu Shixin 	}
5705d0ce0e47SSidhartha Kumar 	__folio_mark_uptodate(new_folio);
57061e8f889bSDavid Gibson 
57077d4a8be0SAlistair Popple 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, haddr,
57086f4f13e8SJérôme Glisse 				haddr + huge_page_size(h));
5709ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
5710ad4404a2SDavidlohr Bueso 
5711b76c8cfbSLarry Woodman 	/*
5712cb900f41SKirill A. Shutemov 	 * Retake the page table lock to check for racing updates
5713b76c8cfbSLarry Woodman 	 * before the page tables are altered
5714b76c8cfbSLarry Woodman 	 */
5715cb900f41SKirill A. Shutemov 	spin_lock(ptl);
57169c67a207SPeter Xu 	ptep = hugetlb_walk(vma, haddr, huge_page_size(h));
5717a9af0c5dSNaoya Horiguchi 	if (likely(ptep && pte_same(huge_ptep_get(ptep), pte))) {
57180f230bc2SPeter Xu 		pte_t newpte = make_huge_pte(vma, &new_folio->page, !unshare);
57190f230bc2SPeter Xu 
5720c89357e2SDavid Hildenbrand 		/* Break COW or unshare */
57215b7a1d40SHuang Ying 		huge_ptep_clear_flush(vma, haddr, ptep);
5722959a78b6SZhangPeng 		page_remove_rmap(&old_folio->page, vma, true);
5723d0ce0e47SSidhartha Kumar 		hugepage_add_new_anon_rmap(new_folio, vma, haddr);
57240f230bc2SPeter Xu 		if (huge_pte_uffd_wp(pte))
57250f230bc2SPeter Xu 			newpte = huge_pte_mkuffd_wp(newpte);
5726935d4f0cSRyan Roberts 		set_huge_pte_at(mm, haddr, ptep, newpte, huge_page_size(h));
5727d0ce0e47SSidhartha Kumar 		folio_set_hugetlb_migratable(new_folio);
57281e8f889bSDavid Gibson 		/* Make the old page be freed below */
5729959a78b6SZhangPeng 		new_folio = old_folio;
57301e8f889bSDavid Gibson 	}
5731cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
5732ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
5733ad4404a2SDavidlohr Bueso out_release_all:
5734c89357e2SDavid Hildenbrand 	/*
5735c89357e2SDavid Hildenbrand 	 * No restore in case of successful pagetable update (Break COW or
5736c89357e2SDavid Hildenbrand 	 * unshare)
5737c89357e2SDavid Hildenbrand 	 */
5738959a78b6SZhangPeng 	if (new_folio != old_folio)
5739d2d7bb44SSidhartha Kumar 		restore_reserve_on_error(h, vma, haddr, new_folio);
5740d0ce0e47SSidhartha Kumar 	folio_put(new_folio);
5741ad4404a2SDavidlohr Bueso out_release_old:
5742959a78b6SZhangPeng 	folio_put(old_folio);
57438312034fSJoonsoo Kim 
5744ad4404a2SDavidlohr Bueso 	spin_lock(ptl); /* Caller expects lock to be held */
5745662ce1dcSYang Yang 
5746662ce1dcSYang Yang 	delayacct_wpcopy_end();
5747ad4404a2SDavidlohr Bueso 	return ret;
57481e8f889bSDavid Gibson }
57491e8f889bSDavid Gibson 
57503ae77f43SHugh Dickins /*
57513ae77f43SHugh Dickins  * Return whether there is a pagecache page to back given address within VMA.
57523ae77f43SHugh Dickins  */
hugetlbfs_pagecache_present(struct hstate * h,struct vm_area_struct * vma,unsigned long address)57533ae77f43SHugh Dickins static bool hugetlbfs_pagecache_present(struct hstate *h,
57542a15efc9SHugh Dickins 			struct vm_area_struct *vma, unsigned long address)
57552a15efc9SHugh Dickins {
575691a2fb95SSidhartha Kumar 	struct address_space *mapping = vma->vm_file->f_mapping;
575791a2fb95SSidhartha Kumar 	pgoff_t idx = vma_hugecache_offset(h, vma, address);
5758fd4aed8dSMike Kravetz 	struct folio *folio;
57592a15efc9SHugh Dickins 
5760fd4aed8dSMike Kravetz 	folio = filemap_get_folio(mapping, idx);
5761fd4aed8dSMike Kravetz 	if (IS_ERR(folio))
5762fd4aed8dSMike Kravetz 		return false;
5763fd4aed8dSMike Kravetz 	folio_put(folio);
5764fd4aed8dSMike Kravetz 	return true;
57652a15efc9SHugh Dickins }
57662a15efc9SHugh Dickins 
hugetlb_add_to_page_cache(struct folio * folio,struct address_space * mapping,pgoff_t idx)57679b91c0e2SSidhartha Kumar int hugetlb_add_to_page_cache(struct folio *folio, struct address_space *mapping,
5768ab76ad54SMike Kravetz 			   pgoff_t idx)
5769ab76ad54SMike Kravetz {
5770ab76ad54SMike Kravetz 	struct inode *inode = mapping->host;
5771ab76ad54SMike Kravetz 	struct hstate *h = hstate_inode(inode);
5772d9ef44deSMatthew Wilcox (Oracle) 	int err;
5773ab76ad54SMike Kravetz 
5774d9ef44deSMatthew Wilcox (Oracle) 	__folio_set_locked(folio);
5775d9ef44deSMatthew Wilcox (Oracle) 	err = __filemap_add_folio(mapping, folio, idx, GFP_KERNEL, NULL);
5776d9ef44deSMatthew Wilcox (Oracle) 
5777d9ef44deSMatthew Wilcox (Oracle) 	if (unlikely(err)) {
5778d9ef44deSMatthew Wilcox (Oracle) 		__folio_clear_locked(folio);
5779ab76ad54SMike Kravetz 		return err;
5780d9ef44deSMatthew Wilcox (Oracle) 	}
57819b91c0e2SSidhartha Kumar 	folio_clear_hugetlb_restore_reserve(folio);
5782ab76ad54SMike Kravetz 
578322146c3cSMike Kravetz 	/*
5784d9ef44deSMatthew Wilcox (Oracle) 	 * mark folio dirty so that it will not be removed from cache/file
578522146c3cSMike Kravetz 	 * by non-hugetlbfs specific code paths.
578622146c3cSMike Kravetz 	 */
5787d9ef44deSMatthew Wilcox (Oracle) 	folio_mark_dirty(folio);
578822146c3cSMike Kravetz 
5789ab76ad54SMike Kravetz 	spin_lock(&inode->i_lock);
5790ab76ad54SMike Kravetz 	inode->i_blocks += blocks_per_huge_page(h);
5791ab76ad54SMike Kravetz 	spin_unlock(&inode->i_lock);
5792ab76ad54SMike Kravetz 	return 0;
5793ab76ad54SMike Kravetz }
5794ab76ad54SMike Kravetz 
hugetlb_handle_userfault(struct vm_area_struct * vma,struct address_space * mapping,pgoff_t idx,unsigned int flags,unsigned long haddr,unsigned long addr,unsigned long reason)57957677f7fdSAxel Rasmussen static inline vm_fault_t hugetlb_handle_userfault(struct vm_area_struct *vma,
57967677f7fdSAxel Rasmussen 						  struct address_space *mapping,
57977677f7fdSAxel Rasmussen 						  pgoff_t idx,
57987677f7fdSAxel Rasmussen 						  unsigned int flags,
57997677f7fdSAxel Rasmussen 						  unsigned long haddr,
5800824ddc60SNadav Amit 						  unsigned long addr,
58017677f7fdSAxel Rasmussen 						  unsigned long reason)
58027677f7fdSAxel Rasmussen {
58037677f7fdSAxel Rasmussen 	u32 hash;
58047677f7fdSAxel Rasmussen 	struct vm_fault vmf = {
58057677f7fdSAxel Rasmussen 		.vma = vma,
58067677f7fdSAxel Rasmussen 		.address = haddr,
5807824ddc60SNadav Amit 		.real_address = addr,
58087677f7fdSAxel Rasmussen 		.flags = flags,
58097677f7fdSAxel Rasmussen 
58107677f7fdSAxel Rasmussen 		/*
58117677f7fdSAxel Rasmussen 		 * Hard to debug if it ends up being
58127677f7fdSAxel Rasmussen 		 * used by a callee that assumes
58137677f7fdSAxel Rasmussen 		 * something about the other
58147677f7fdSAxel Rasmussen 		 * uninitialized fields... same as in
58157677f7fdSAxel Rasmussen 		 * memory.c
58167677f7fdSAxel Rasmussen 		 */
58177677f7fdSAxel Rasmussen 	};
58187677f7fdSAxel Rasmussen 
58197677f7fdSAxel Rasmussen 	/*
5820958f32ceSLiu Shixin 	 * vma_lock and hugetlb_fault_mutex must be dropped before handling
5821958f32ceSLiu Shixin 	 * userfault. Also mmap_lock could be dropped due to handling
5822958f32ceSLiu Shixin 	 * userfault, any vma operation should be careful from here.
58237677f7fdSAxel Rasmussen 	 */
582440549ba8SMike Kravetz 	hugetlb_vma_unlock_read(vma);
58257677f7fdSAxel Rasmussen 	hash = hugetlb_fault_mutex_hash(mapping, idx);
58267677f7fdSAxel Rasmussen 	mutex_unlock(&hugetlb_fault_mutex_table[hash]);
5827958f32ceSLiu Shixin 	return handle_userfault(&vmf, reason);
58287677f7fdSAxel Rasmussen }
58297677f7fdSAxel Rasmussen 
58302ea7ff1eSPeter Xu /*
58312ea7ff1eSPeter Xu  * Recheck pte with pgtable lock.  Returns true if pte didn't change, or
58322ea7ff1eSPeter Xu  * false if pte changed or is changing.
58332ea7ff1eSPeter Xu  */
hugetlb_pte_stable(struct hstate * h,struct mm_struct * mm,pte_t * ptep,pte_t old_pte)58342ea7ff1eSPeter Xu static bool hugetlb_pte_stable(struct hstate *h, struct mm_struct *mm,
58352ea7ff1eSPeter Xu 			       pte_t *ptep, pte_t old_pte)
58362ea7ff1eSPeter Xu {
58372ea7ff1eSPeter Xu 	spinlock_t *ptl;
58382ea7ff1eSPeter Xu 	bool same;
58392ea7ff1eSPeter Xu 
58402ea7ff1eSPeter Xu 	ptl = huge_pte_lock(h, mm, ptep);
58412ea7ff1eSPeter Xu 	same = pte_same(huge_ptep_get(ptep), old_pte);
58422ea7ff1eSPeter Xu 	spin_unlock(ptl);
58432ea7ff1eSPeter Xu 
58442ea7ff1eSPeter Xu 	return same;
58452ea7ff1eSPeter Xu }
58462ea7ff1eSPeter Xu 
hugetlb_no_page(struct mm_struct * mm,struct vm_area_struct * vma,struct address_space * mapping,pgoff_t idx,unsigned long address,pte_t * ptep,pte_t old_pte,unsigned int flags)58472b740303SSouptick Joarder static vm_fault_t hugetlb_no_page(struct mm_struct *mm,
58482b740303SSouptick Joarder 			struct vm_area_struct *vma,
58498382d914SDavidlohr Bueso 			struct address_space *mapping, pgoff_t idx,
5850c64e912cSPeter Xu 			unsigned long address, pte_t *ptep,
5851c64e912cSPeter Xu 			pte_t old_pte, unsigned int flags)
5852ac9b9c66SHugh Dickins {
5853a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
58542b740303SSouptick Joarder 	vm_fault_t ret = VM_FAULT_SIGBUS;
5855409eb8c2SHillf Danton 	int anon_rmap = 0;
58564c887265SAdam Litke 	unsigned long size;
5857d0ce0e47SSidhartha Kumar 	struct folio *folio;
58581e8f889bSDavid Gibson 	pte_t new_pte;
5859cb900f41SKirill A. Shutemov 	spinlock_t *ptl;
5860285b8dcaSHuang Ying 	unsigned long haddr = address & huge_page_mask(h);
5861d0ce0e47SSidhartha Kumar 	bool new_folio, new_pagecache_folio = false;
5862958f32ceSLiu Shixin 	u32 hash = hugetlb_fault_mutex_hash(mapping, idx);
58634c887265SAdam Litke 
586404f2cbe3SMel Gorman 	/*
586504f2cbe3SMel Gorman 	 * Currently, we are forced to kill the process in the event the
586604f2cbe3SMel Gorman 	 * original mapper has unmapped pages from the child due to a failed
5867c89357e2SDavid Hildenbrand 	 * COW/unsharing. Warn that such a situation has occurred as it may not
5868c89357e2SDavid Hildenbrand 	 * be obvious.
586904f2cbe3SMel Gorman 	 */
587004f2cbe3SMel Gorman 	if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) {
5871910154d5SGeoffrey Thomas 		pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n",
587204f2cbe3SMel Gorman 			   current->pid);
5873958f32ceSLiu Shixin 		goto out;
587404f2cbe3SMel Gorman 	}
587504f2cbe3SMel Gorman 
58764c887265SAdam Litke 	/*
5877188a3972SMike Kravetz 	 * Use page lock to guard against racing truncation
5878188a3972SMike Kravetz 	 * before we get page_table_lock.
58794c887265SAdam Litke 	 */
5880d0ce0e47SSidhartha Kumar 	new_folio = false;
5881d0ce0e47SSidhartha Kumar 	folio = filemap_lock_folio(mapping, idx);
588266dabbb6SChristoph Hellwig 	if (IS_ERR(folio)) {
5883188a3972SMike Kravetz 		size = i_size_read(mapping->host) >> huge_page_shift(h);
5884188a3972SMike Kravetz 		if (idx >= size)
5885188a3972SMike Kravetz 			goto out;
58867677f7fdSAxel Rasmussen 		/* Check for page in userfault range */
58872ea7ff1eSPeter Xu 		if (userfaultfd_missing(vma)) {
58882ea7ff1eSPeter Xu 			/*
58892ea7ff1eSPeter Xu 			 * Since hugetlb_no_page() was examining pte
58902ea7ff1eSPeter Xu 			 * without pgtable lock, we need to re-test under
58912ea7ff1eSPeter Xu 			 * lock because the pte may not be stable and could
58922ea7ff1eSPeter Xu 			 * have changed from under us.  Try to detect
58932ea7ff1eSPeter Xu 			 * either changed or during-changing ptes and retry
58942ea7ff1eSPeter Xu 			 * properly when needed.
58952ea7ff1eSPeter Xu 			 *
58962ea7ff1eSPeter Xu 			 * Note that userfaultfd is actually fine with
58972ea7ff1eSPeter Xu 			 * false positives (e.g. caused by pte changed),
58982ea7ff1eSPeter Xu 			 * but not wrong logical events (e.g. caused by
58992ea7ff1eSPeter Xu 			 * reading a pte during changing).  The latter can
59002ea7ff1eSPeter Xu 			 * confuse the userspace, so the strictness is very
59012ea7ff1eSPeter Xu 			 * much preferred.  E.g., MISSING event should
59022ea7ff1eSPeter Xu 			 * never happen on the page after UFFDIO_COPY has
59032ea7ff1eSPeter Xu 			 * correctly installed the page and returned.
59042ea7ff1eSPeter Xu 			 */
59052ea7ff1eSPeter Xu 			if (!hugetlb_pte_stable(h, mm, ptep, old_pte)) {
59062ea7ff1eSPeter Xu 				ret = 0;
59072ea7ff1eSPeter Xu 				goto out;
59082ea7ff1eSPeter Xu 			}
59092ea7ff1eSPeter Xu 
59102ea7ff1eSPeter Xu 			return hugetlb_handle_userfault(vma, mapping, idx, flags,
59112ea7ff1eSPeter Xu 							haddr, address,
59127677f7fdSAxel Rasmussen 							VM_UFFD_MISSING);
59132ea7ff1eSPeter Xu 		}
59141a1aad8aSMike Kravetz 
5915d0ce0e47SSidhartha Kumar 		folio = alloc_hugetlb_folio(vma, haddr, 0);
5916d0ce0e47SSidhartha Kumar 		if (IS_ERR(folio)) {
59174643d67eSMike Kravetz 			/*
59184643d67eSMike Kravetz 			 * Returning error will result in faulting task being
59194643d67eSMike Kravetz 			 * sent SIGBUS.  The hugetlb fault mutex prevents two
59204643d67eSMike Kravetz 			 * tasks from racing to fault in the same page which
59214643d67eSMike Kravetz 			 * could result in false unable to allocate errors.
59224643d67eSMike Kravetz 			 * Page migration does not take the fault mutex, but
59234643d67eSMike Kravetz 			 * does a clear then write of pte's under page table
59244643d67eSMike Kravetz 			 * lock.  Page fault code could race with migration,
59254643d67eSMike Kravetz 			 * notice the clear pte and try to allocate a page
59264643d67eSMike Kravetz 			 * here.  Before returning error, get ptl and make
59274643d67eSMike Kravetz 			 * sure there really is no pte entry.
59284643d67eSMike Kravetz 			 */
5929f9bf6c03SPeter Xu 			if (hugetlb_pte_stable(h, mm, ptep, old_pte))
5930d0ce0e47SSidhartha Kumar 				ret = vmf_error(PTR_ERR(folio));
5931f9bf6c03SPeter Xu 			else
5932f9bf6c03SPeter Xu 				ret = 0;
59336bda666aSChristoph Lameter 			goto out;
59346bda666aSChristoph Lameter 		}
5935d0ce0e47SSidhartha Kumar 		clear_huge_page(&folio->page, address, pages_per_huge_page(h));
5936d0ce0e47SSidhartha Kumar 		__folio_mark_uptodate(folio);
5937d0ce0e47SSidhartha Kumar 		new_folio = true;
5938ac9b9c66SHugh Dickins 
5939f83a275dSMel Gorman 		if (vma->vm_flags & VM_MAYSHARE) {
59409b91c0e2SSidhartha Kumar 			int err = hugetlb_add_to_page_cache(folio, mapping, idx);
59416bda666aSChristoph Lameter 			if (err) {
59423a5497a2SMiaohe Lin 				/*
59433a5497a2SMiaohe Lin 				 * err can't be -EEXIST which implies someone
59443a5497a2SMiaohe Lin 				 * else consumed the reservation since hugetlb
59453a5497a2SMiaohe Lin 				 * fault mutex is held when add a hugetlb page
59463a5497a2SMiaohe Lin 				 * to the page cache. So it's safe to call
59473a5497a2SMiaohe Lin 				 * restore_reserve_on_error() here.
59483a5497a2SMiaohe Lin 				 */
5949d2d7bb44SSidhartha Kumar 				restore_reserve_on_error(h, vma, haddr, folio);
5950d0ce0e47SSidhartha Kumar 				folio_put(folio);
59516bda666aSChristoph Lameter 				goto out;
59526bda666aSChristoph Lameter 			}
5953d0ce0e47SSidhartha Kumar 			new_pagecache_folio = true;
595423be7468SMel Gorman 		} else {
5955d0ce0e47SSidhartha Kumar 			folio_lock(folio);
59560fe6e20bSNaoya Horiguchi 			if (unlikely(anon_vma_prepare(vma))) {
59570fe6e20bSNaoya Horiguchi 				ret = VM_FAULT_OOM;
59580fe6e20bSNaoya Horiguchi 				goto backout_unlocked;
595923be7468SMel Gorman 			}
5960409eb8c2SHillf Danton 			anon_rmap = 1;
59610fe6e20bSNaoya Horiguchi 		}
59620fe6e20bSNaoya Horiguchi 	} else {
596357303d80SAndy Whitcroft 		/*
5964998b4382SNaoya Horiguchi 		 * If memory error occurs between mmap() and fault, some process
5965998b4382SNaoya Horiguchi 		 * don't have hwpoisoned swap entry for errored virtual address.
5966998b4382SNaoya Horiguchi 		 * So we need to block hugepage fault by PG_hwpoison bit check.
5967fd6a03edSNaoya Horiguchi 		 */
5968d0ce0e47SSidhartha Kumar 		if (unlikely(folio_test_hwpoison(folio))) {
59690eb98f15SMiaohe Lin 			ret = VM_FAULT_HWPOISON_LARGE |
5970972dc4deSAneesh Kumar K.V 				VM_FAULT_SET_HINDEX(hstate_index(h));
5971fd6a03edSNaoya Horiguchi 			goto backout_unlocked;
59726bda666aSChristoph Lameter 		}
59737677f7fdSAxel Rasmussen 
59747677f7fdSAxel Rasmussen 		/* Check for page in userfault range. */
59757677f7fdSAxel Rasmussen 		if (userfaultfd_minor(vma)) {
5976d0ce0e47SSidhartha Kumar 			folio_unlock(folio);
5977d0ce0e47SSidhartha Kumar 			folio_put(folio);
59782ea7ff1eSPeter Xu 			/* See comment in userfaultfd_missing() block above */
59792ea7ff1eSPeter Xu 			if (!hugetlb_pte_stable(h, mm, ptep, old_pte)) {
59802ea7ff1eSPeter Xu 				ret = 0;
59812ea7ff1eSPeter Xu 				goto out;
59822ea7ff1eSPeter Xu 			}
59832ea7ff1eSPeter Xu 			return hugetlb_handle_userfault(vma, mapping, idx, flags,
59842ea7ff1eSPeter Xu 							haddr, address,
59857677f7fdSAxel Rasmussen 							VM_UFFD_MINOR);
59867677f7fdSAxel Rasmussen 		}
5987998b4382SNaoya Horiguchi 	}
59881e8f889bSDavid Gibson 
598957303d80SAndy Whitcroft 	/*
599057303d80SAndy Whitcroft 	 * If we are going to COW a private mapping later, we examine the
599157303d80SAndy Whitcroft 	 * pending reservations for this page now. This will ensure that
599257303d80SAndy Whitcroft 	 * any allocations necessary to record that reservation occur outside
599357303d80SAndy Whitcroft 	 * the spinlock.
599457303d80SAndy Whitcroft 	 */
59955e911373SMike Kravetz 	if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
5996285b8dcaSHuang Ying 		if (vma_needs_reservation(h, vma, haddr) < 0) {
59972b26736cSAndy Whitcroft 			ret = VM_FAULT_OOM;
59982b26736cSAndy Whitcroft 			goto backout_unlocked;
59992b26736cSAndy Whitcroft 		}
60005e911373SMike Kravetz 		/* Just decrements count, does not deallocate */
6001285b8dcaSHuang Ying 		vma_end_reservation(h, vma, haddr);
60025e911373SMike Kravetz 	}
600357303d80SAndy Whitcroft 
60048bea8052SAneesh Kumar K.V 	ptl = huge_pte_lock(h, mm, ptep);
600583c54070SNick Piggin 	ret = 0;
6006c64e912cSPeter Xu 	/* If pte changed from under us, retry */
6007c64e912cSPeter Xu 	if (!pte_same(huge_ptep_get(ptep), old_pte))
60084c887265SAdam Litke 		goto backout;
60094c887265SAdam Litke 
60104781593dSPeter Xu 	if (anon_rmap)
6011d0ce0e47SSidhartha Kumar 		hugepage_add_new_anon_rmap(folio, vma, haddr);
60124781593dSPeter Xu 	else
6013d0ce0e47SSidhartha Kumar 		page_dup_file_rmap(&folio->page, true);
6014d0ce0e47SSidhartha Kumar 	new_pte = make_huge_pte(vma, &folio->page, ((vma->vm_flags & VM_WRITE)
60151e8f889bSDavid Gibson 				&& (vma->vm_flags & VM_SHARED)));
6016c64e912cSPeter Xu 	/*
6017c64e912cSPeter Xu 	 * If this pte was previously wr-protected, keep it wr-protected even
6018c64e912cSPeter Xu 	 * if populated.
6019c64e912cSPeter Xu 	 */
6020c64e912cSPeter Xu 	if (unlikely(pte_marker_uffd_wp(old_pte)))
6021f1eb1bacSPeter Xu 		new_pte = huge_pte_mkuffd_wp(new_pte);
6022935d4f0cSRyan Roberts 	set_huge_pte_at(mm, haddr, ptep, new_pte, huge_page_size(h));
60231e8f889bSDavid Gibson 
60245d317b2bSNaoya Horiguchi 	hugetlb_count_add(pages_per_huge_page(h), mm);
6025788c7df4SHugh Dickins 	if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
60261e8f889bSDavid Gibson 		/* Optimization, do the COW without a second fault */
6027371607a3SSidhartha Kumar 		ret = hugetlb_wp(mm, vma, address, ptep, flags, folio, ptl);
60281e8f889bSDavid Gibson 	}
60291e8f889bSDavid Gibson 
6030cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
6031cb6acd01SMike Kravetz 
6032cb6acd01SMike Kravetz 	/*
6033d0ce0e47SSidhartha Kumar 	 * Only set hugetlb_migratable in newly allocated pages.  Existing pages
6034d0ce0e47SSidhartha Kumar 	 * found in the pagecache may not have hugetlb_migratable if they have
60358f251a3dSMike Kravetz 	 * been isolated for migration.
6036cb6acd01SMike Kravetz 	 */
6037d0ce0e47SSidhartha Kumar 	if (new_folio)
6038d0ce0e47SSidhartha Kumar 		folio_set_hugetlb_migratable(folio);
6039cb6acd01SMike Kravetz 
6040d0ce0e47SSidhartha Kumar 	folio_unlock(folio);
60414c887265SAdam Litke out:
6042958f32ceSLiu Shixin 	hugetlb_vma_unlock_read(vma);
6043958f32ceSLiu Shixin 	mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6044ac9b9c66SHugh Dickins 	return ret;
60454c887265SAdam Litke 
60464c887265SAdam Litke backout:
6047cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
60482b26736cSAndy Whitcroft backout_unlocked:
6049d0ce0e47SSidhartha Kumar 	if (new_folio && !new_pagecache_folio)
6050d2d7bb44SSidhartha Kumar 		restore_reserve_on_error(h, vma, haddr, folio);
6051fa27759aSMike Kravetz 
6052d0ce0e47SSidhartha Kumar 	folio_unlock(folio);
6053d0ce0e47SSidhartha Kumar 	folio_put(folio);
60544c887265SAdam Litke 	goto out;
6055ac9b9c66SHugh Dickins }
6056ac9b9c66SHugh Dickins 
60578382d914SDavidlohr Bueso #ifdef CONFIG_SMP
hugetlb_fault_mutex_hash(struct address_space * mapping,pgoff_t idx)6058188b04a7SWei Yang u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
60598382d914SDavidlohr Bueso {
60608382d914SDavidlohr Bueso 	unsigned long key[2];
60618382d914SDavidlohr Bueso 	u32 hash;
60628382d914SDavidlohr Bueso 
60638382d914SDavidlohr Bueso 	key[0] = (unsigned long) mapping;
60648382d914SDavidlohr Bueso 	key[1] = idx;
60658382d914SDavidlohr Bueso 
606655254636SMike Kravetz 	hash = jhash2((u32 *)&key, sizeof(key)/(sizeof(u32)), 0);
60678382d914SDavidlohr Bueso 
60688382d914SDavidlohr Bueso 	return hash & (num_fault_mutexes - 1);
60698382d914SDavidlohr Bueso }
60708382d914SDavidlohr Bueso #else
60718382d914SDavidlohr Bueso /*
60726c26d310SMiaohe Lin  * For uniprocessor systems we always use a single mutex, so just
60738382d914SDavidlohr Bueso  * return 0 and avoid the hashing overhead.
60748382d914SDavidlohr Bueso  */
hugetlb_fault_mutex_hash(struct address_space * mapping,pgoff_t idx)6075188b04a7SWei Yang u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
60768382d914SDavidlohr Bueso {
60778382d914SDavidlohr Bueso 	return 0;
60788382d914SDavidlohr Bueso }
60798382d914SDavidlohr Bueso #endif
60808382d914SDavidlohr Bueso 
hugetlb_fault(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long address,unsigned int flags)60812b740303SSouptick Joarder vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,
6082788c7df4SHugh Dickins 			unsigned long address, unsigned int flags)
608386e5216fSAdam Litke {
60848382d914SDavidlohr Bueso 	pte_t *ptep, entry;
6085cb900f41SKirill A. Shutemov 	spinlock_t *ptl;
60862b740303SSouptick Joarder 	vm_fault_t ret;
60878382d914SDavidlohr Bueso 	u32 hash;
60888382d914SDavidlohr Bueso 	pgoff_t idx;
6089061e62e8SZhangPeng 	struct folio *folio = NULL;
6090371607a3SSidhartha Kumar 	struct folio *pagecache_folio = NULL;
6091a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
60928382d914SDavidlohr Bueso 	struct address_space *mapping;
60930f792cf9SNaoya Horiguchi 	int need_wait_lock = 0;
6094285b8dcaSHuang Ying 	unsigned long haddr = address & huge_page_mask(h);
609586e5216fSAdam Litke 
60964ec31152SMatthew Wilcox (Oracle) 	/* TODO: Handle faults under the VMA lock */
60974ec31152SMatthew Wilcox (Oracle) 	if (flags & FAULT_FLAG_VMA_LOCK) {
60984ec31152SMatthew Wilcox (Oracle) 		vma_end_read(vma);
60994ec31152SMatthew Wilcox (Oracle) 		return VM_FAULT_RETRY;
61004ec31152SMatthew Wilcox (Oracle) 	}
61014ec31152SMatthew Wilcox (Oracle) 
61023935baa9SDavid Gibson 	/*
61033935baa9SDavid Gibson 	 * Serialize hugepage allocation and instantiation, so that we don't
61043935baa9SDavid Gibson 	 * get spurious allocation failures if two CPUs race to instantiate
61053935baa9SDavid Gibson 	 * the same page in the page cache.
61063935baa9SDavid Gibson 	 */
610740549ba8SMike Kravetz 	mapping = vma->vm_file->f_mapping;
610840549ba8SMike Kravetz 	idx = vma_hugecache_offset(h, vma, haddr);
6109188b04a7SWei Yang 	hash = hugetlb_fault_mutex_hash(mapping, idx);
6110c672c7f2SMike Kravetz 	mutex_lock(&hugetlb_fault_mutex_table[hash]);
61118382d914SDavidlohr Bueso 
611240549ba8SMike Kravetz 	/*
611340549ba8SMike Kravetz 	 * Acquire vma lock before calling huge_pte_alloc and hold
611440549ba8SMike Kravetz 	 * until finished with ptep.  This prevents huge_pmd_unshare from
611540549ba8SMike Kravetz 	 * being called elsewhere and making the ptep no longer valid.
611640549ba8SMike Kravetz 	 */
611740549ba8SMike Kravetz 	hugetlb_vma_lock_read(vma);
611840549ba8SMike Kravetz 	ptep = huge_pte_alloc(mm, vma, haddr, huge_page_size(h));
611940549ba8SMike Kravetz 	if (!ptep) {
612040549ba8SMike Kravetz 		hugetlb_vma_unlock_read(vma);
612140549ba8SMike Kravetz 		mutex_unlock(&hugetlb_fault_mutex_table[hash]);
612240549ba8SMike Kravetz 		return VM_FAULT_OOM;
612340549ba8SMike Kravetz 	}
612440549ba8SMike Kravetz 
61257f2e9525SGerald Schaefer 	entry = huge_ptep_get(ptep);
6126af19487fSAxel Rasmussen 	if (huge_pte_none_mostly(entry)) {
6127af19487fSAxel Rasmussen 		if (is_pte_marker(entry)) {
6128af19487fSAxel Rasmussen 			pte_marker marker =
6129af19487fSAxel Rasmussen 				pte_marker_get(pte_to_swp_entry(entry));
6130af19487fSAxel Rasmussen 
6131af19487fSAxel Rasmussen 			if (marker & PTE_MARKER_POISONED) {
6132af19487fSAxel Rasmussen 				ret = VM_FAULT_HWPOISON_LARGE;
6133af19487fSAxel Rasmussen 				goto out_mutex;
6134af19487fSAxel Rasmussen 			}
6135af19487fSAxel Rasmussen 		}
6136af19487fSAxel Rasmussen 
6137958f32ceSLiu Shixin 		/*
6138af19487fSAxel Rasmussen 		 * Other PTE markers should be handled the same way as none PTE.
6139af19487fSAxel Rasmussen 		 *
6140958f32ceSLiu Shixin 		 * hugetlb_no_page will drop vma lock and hugetlb fault
6141958f32ceSLiu Shixin 		 * mutex internally, which make us return immediately.
6142958f32ceSLiu Shixin 		 */
6143958f32ceSLiu Shixin 		return hugetlb_no_page(mm, vma, mapping, idx, address, ptep,
6144c64e912cSPeter Xu 				      entry, flags);
6145af19487fSAxel Rasmussen 	}
614686e5216fSAdam Litke 
614783c54070SNick Piggin 	ret = 0;
61481e8f889bSDavid Gibson 
614957303d80SAndy Whitcroft 	/*
61500f792cf9SNaoya Horiguchi 	 * entry could be a migration/hwpoison entry at this point, so this
61510f792cf9SNaoya Horiguchi 	 * check prevents the kernel from going below assuming that we have
61527c8de358SEthon Paul 	 * an active hugepage in pagecache. This goto expects the 2nd page
61537c8de358SEthon Paul 	 * fault, and is_hugetlb_entry_(migration|hwpoisoned) check will
61547c8de358SEthon Paul 	 * properly handle it.
61550f792cf9SNaoya Horiguchi 	 */
6156fcd48540SPeter Xu 	if (!pte_present(entry)) {
6157fcd48540SPeter Xu 		if (unlikely(is_hugetlb_entry_migration(entry))) {
6158fcd48540SPeter Xu 			/*
6159fcd48540SPeter Xu 			 * Release the hugetlb fault lock now, but retain
6160fcd48540SPeter Xu 			 * the vma lock, because it is needed to guard the
6161fcd48540SPeter Xu 			 * huge_pte_lockptr() later in
6162fcd48540SPeter Xu 			 * migration_entry_wait_huge(). The vma lock will
6163fcd48540SPeter Xu 			 * be released there.
6164fcd48540SPeter Xu 			 */
6165fcd48540SPeter Xu 			mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6166fcd48540SPeter Xu 			migration_entry_wait_huge(vma, ptep);
6167fcd48540SPeter Xu 			return 0;
6168fcd48540SPeter Xu 		} else if (unlikely(is_hugetlb_entry_hwpoisoned(entry)))
6169fcd48540SPeter Xu 			ret = VM_FAULT_HWPOISON_LARGE |
6170fcd48540SPeter Xu 			    VM_FAULT_SET_HINDEX(hstate_index(h));
61710f792cf9SNaoya Horiguchi 		goto out_mutex;
6172fcd48540SPeter Xu 	}
61730f792cf9SNaoya Horiguchi 
61740f792cf9SNaoya Horiguchi 	/*
6175c89357e2SDavid Hildenbrand 	 * If we are going to COW/unshare the mapping later, we examine the
6176c89357e2SDavid Hildenbrand 	 * pending reservations for this page now. This will ensure that any
617757303d80SAndy Whitcroft 	 * allocations necessary to record that reservation occur outside the
61781d8d1464SDavid Hildenbrand 	 * spinlock. Also lookup the pagecache page now as it is used to
61791d8d1464SDavid Hildenbrand 	 * determine if a reservation has been consumed.
618057303d80SAndy Whitcroft 	 */
6181c89357e2SDavid Hildenbrand 	if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) &&
61821d8d1464SDavid Hildenbrand 	    !(vma->vm_flags & VM_MAYSHARE) && !huge_pte_write(entry)) {
6183285b8dcaSHuang Ying 		if (vma_needs_reservation(h, vma, haddr) < 0) {
61842b26736cSAndy Whitcroft 			ret = VM_FAULT_OOM;
6185b4d1d99fSDavid Gibson 			goto out_mutex;
61862b26736cSAndy Whitcroft 		}
61875e911373SMike Kravetz 		/* Just decrements count, does not deallocate */
6188285b8dcaSHuang Ying 		vma_end_reservation(h, vma, haddr);
618957303d80SAndy Whitcroft 
6190371607a3SSidhartha Kumar 		pagecache_folio = filemap_lock_folio(mapping, idx);
619166dabbb6SChristoph Hellwig 		if (IS_ERR(pagecache_folio))
619266dabbb6SChristoph Hellwig 			pagecache_folio = NULL;
619357303d80SAndy Whitcroft 	}
619457303d80SAndy Whitcroft 
61950f792cf9SNaoya Horiguchi 	ptl = huge_pte_lock(h, mm, ptep);
61960fe6e20bSNaoya Horiguchi 
6197c89357e2SDavid Hildenbrand 	/* Check for a racing update before calling hugetlb_wp() */
6198b4d1d99fSDavid Gibson 	if (unlikely(!pte_same(entry, huge_ptep_get(ptep))))
6199cb900f41SKirill A. Shutemov 		goto out_ptl;
6200b4d1d99fSDavid Gibson 
6201166f3eccSPeter Xu 	/* Handle userfault-wp first, before trying to lock more pages */
6202166f3eccSPeter Xu 	if (userfaultfd_wp(vma) && huge_pte_uffd_wp(huge_ptep_get(ptep)) &&
6203166f3eccSPeter Xu 	    (flags & FAULT_FLAG_WRITE) && !huge_pte_write(entry)) {
6204166f3eccSPeter Xu 		struct vm_fault vmf = {
6205166f3eccSPeter Xu 			.vma = vma,
6206166f3eccSPeter Xu 			.address = haddr,
6207166f3eccSPeter Xu 			.real_address = address,
6208166f3eccSPeter Xu 			.flags = flags,
6209166f3eccSPeter Xu 		};
6210166f3eccSPeter Xu 
6211166f3eccSPeter Xu 		spin_unlock(ptl);
6212371607a3SSidhartha Kumar 		if (pagecache_folio) {
6213371607a3SSidhartha Kumar 			folio_unlock(pagecache_folio);
6214371607a3SSidhartha Kumar 			folio_put(pagecache_folio);
6215166f3eccSPeter Xu 		}
621640549ba8SMike Kravetz 		hugetlb_vma_unlock_read(vma);
6217166f3eccSPeter Xu 		mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6218166f3eccSPeter Xu 		return handle_userfault(&vmf, VM_UFFD_WP);
6219166f3eccSPeter Xu 	}
6220166f3eccSPeter Xu 
62210f792cf9SNaoya Horiguchi 	/*
6222c89357e2SDavid Hildenbrand 	 * hugetlb_wp() requires page locks of pte_page(entry) and
6223371607a3SSidhartha Kumar 	 * pagecache_folio, so here we need take the former one
6224061e62e8SZhangPeng 	 * when folio != pagecache_folio or !pagecache_folio.
62250f792cf9SNaoya Horiguchi 	 */
6226061e62e8SZhangPeng 	folio = page_folio(pte_page(entry));
6227061e62e8SZhangPeng 	if (folio != pagecache_folio)
6228061e62e8SZhangPeng 		if (!folio_trylock(folio)) {
62290f792cf9SNaoya Horiguchi 			need_wait_lock = 1;
62300f792cf9SNaoya Horiguchi 			goto out_ptl;
62310f792cf9SNaoya Horiguchi 		}
62320f792cf9SNaoya Horiguchi 
6233061e62e8SZhangPeng 	folio_get(folio);
6234b4d1d99fSDavid Gibson 
6235c89357e2SDavid Hildenbrand 	if (flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) {
6236106c992aSGerald Schaefer 		if (!huge_pte_write(entry)) {
6237c89357e2SDavid Hildenbrand 			ret = hugetlb_wp(mm, vma, address, ptep, flags,
6238371607a3SSidhartha Kumar 					 pagecache_folio, ptl);
62390f792cf9SNaoya Horiguchi 			goto out_put_page;
6240c89357e2SDavid Hildenbrand 		} else if (likely(flags & FAULT_FLAG_WRITE)) {
6241106c992aSGerald Schaefer 			entry = huge_pte_mkdirty(entry);
6242b4d1d99fSDavid Gibson 		}
6243c89357e2SDavid Hildenbrand 	}
6244b4d1d99fSDavid Gibson 	entry = pte_mkyoung(entry);
6245285b8dcaSHuang Ying 	if (huge_ptep_set_access_flags(vma, haddr, ptep, entry,
6246788c7df4SHugh Dickins 						flags & FAULT_FLAG_WRITE))
6247285b8dcaSHuang Ying 		update_mmu_cache(vma, haddr, ptep);
62480f792cf9SNaoya Horiguchi out_put_page:
6249061e62e8SZhangPeng 	if (folio != pagecache_folio)
6250061e62e8SZhangPeng 		folio_unlock(folio);
6251061e62e8SZhangPeng 	folio_put(folio);
6252cb900f41SKirill A. Shutemov out_ptl:
6253cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
625457303d80SAndy Whitcroft 
6255371607a3SSidhartha Kumar 	if (pagecache_folio) {
6256371607a3SSidhartha Kumar 		folio_unlock(pagecache_folio);
6257371607a3SSidhartha Kumar 		folio_put(pagecache_folio);
625857303d80SAndy Whitcroft 	}
6259b4d1d99fSDavid Gibson out_mutex:
626040549ba8SMike Kravetz 	hugetlb_vma_unlock_read(vma);
6261c672c7f2SMike Kravetz 	mutex_unlock(&hugetlb_fault_mutex_table[hash]);
62620f792cf9SNaoya Horiguchi 	/*
62630f792cf9SNaoya Horiguchi 	 * Generally it's safe to hold refcount during waiting page lock. But
62640f792cf9SNaoya Horiguchi 	 * here we just wait to defer the next page fault to avoid busy loop and
62650f792cf9SNaoya Horiguchi 	 * the page is not used after unlocked before returning from the current
62660f792cf9SNaoya Horiguchi 	 * page fault. So we are safe from accessing freed page, even if we wait
62670f792cf9SNaoya Horiguchi 	 * here without taking refcount.
62680f792cf9SNaoya Horiguchi 	 */
62690f792cf9SNaoya Horiguchi 	if (need_wait_lock)
6270061e62e8SZhangPeng 		folio_wait_locked(folio);
62711e8f889bSDavid Gibson 	return ret;
627286e5216fSAdam Litke }
627386e5216fSAdam Litke 
6274714c1891SAxel Rasmussen #ifdef CONFIG_USERFAULTFD
62758fb5debcSMike Kravetz /*
6276a734991cSAxel Rasmussen  * Used by userfaultfd UFFDIO_* ioctls. Based on userfaultfd's mfill_atomic_pte
6277a734991cSAxel Rasmussen  * with modifications for hugetlb pages.
62788fb5debcSMike Kravetz  */
hugetlb_mfill_atomic_pte(pte_t * dst_pte,struct vm_area_struct * dst_vma,unsigned long dst_addr,unsigned long src_addr,uffd_flags_t flags,struct folio ** foliop)627961c50040SAxel Rasmussen int hugetlb_mfill_atomic_pte(pte_t *dst_pte,
62808fb5debcSMike Kravetz 			     struct vm_area_struct *dst_vma,
62818fb5debcSMike Kravetz 			     unsigned long dst_addr,
62828fb5debcSMike Kravetz 			     unsigned long src_addr,
6283d9712937SAxel Rasmussen 			     uffd_flags_t flags,
62840169fd51SZhangPeng 			     struct folio **foliop)
62858fb5debcSMike Kravetz {
628661c50040SAxel Rasmussen 	struct mm_struct *dst_mm = dst_vma->vm_mm;
6287d9712937SAxel Rasmussen 	bool is_continue = uffd_flags_mode_is(flags, MFILL_ATOMIC_CONTINUE);
6288d9712937SAxel Rasmussen 	bool wp_enabled = (flags & MFILL_ATOMIC_WP);
62898cc5fcbbSMina Almasry 	struct hstate *h = hstate_vma(dst_vma);
62908cc5fcbbSMina Almasry 	struct address_space *mapping = dst_vma->vm_file->f_mapping;
62918cc5fcbbSMina Almasry 	pgoff_t idx = vma_hugecache_offset(h, dst_vma, dst_addr);
62921e392147SAndrea Arcangeli 	unsigned long size;
62931c9e8defSMike Kravetz 	int vm_shared = dst_vma->vm_flags & VM_SHARED;
62948fb5debcSMike Kravetz 	pte_t _dst_pte;
62958fb5debcSMike Kravetz 	spinlock_t *ptl;
62968cc5fcbbSMina Almasry 	int ret = -ENOMEM;
6297d0ce0e47SSidhartha Kumar 	struct folio *folio;
6298f6191471SAxel Rasmussen 	int writable;
6299d0ce0e47SSidhartha Kumar 	bool folio_in_pagecache = false;
63008fb5debcSMike Kravetz 
63018a13897fSAxel Rasmussen 	if (uffd_flags_mode_is(flags, MFILL_ATOMIC_POISON)) {
63028a13897fSAxel Rasmussen 		ptl = huge_pte_lock(h, dst_mm, dst_pte);
63038a13897fSAxel Rasmussen 
63048a13897fSAxel Rasmussen 		/* Don't overwrite any existing PTEs (even markers) */
63058a13897fSAxel Rasmussen 		if (!huge_pte_none(huge_ptep_get(dst_pte))) {
63068a13897fSAxel Rasmussen 			spin_unlock(ptl);
63078a13897fSAxel Rasmussen 			return -EEXIST;
63088a13897fSAxel Rasmussen 		}
63098a13897fSAxel Rasmussen 
63108a13897fSAxel Rasmussen 		_dst_pte = make_pte_marker(PTE_MARKER_POISONED);
6311935d4f0cSRyan Roberts 		set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte,
6312935d4f0cSRyan Roberts 				huge_page_size(h));
63138a13897fSAxel Rasmussen 
63148a13897fSAxel Rasmussen 		/* No need to invalidate - it was non-present before */
63158a13897fSAxel Rasmussen 		update_mmu_cache(dst_vma, dst_addr, dst_pte);
63168a13897fSAxel Rasmussen 
63178a13897fSAxel Rasmussen 		spin_unlock(ptl);
63188a13897fSAxel Rasmussen 		return 0;
63198a13897fSAxel Rasmussen 	}
63208a13897fSAxel Rasmussen 
6321f6191471SAxel Rasmussen 	if (is_continue) {
6322f6191471SAxel Rasmussen 		ret = -EFAULT;
6323d0ce0e47SSidhartha Kumar 		folio = filemap_lock_folio(mapping, idx);
632466dabbb6SChristoph Hellwig 		if (IS_ERR(folio))
6325f6191471SAxel Rasmussen 			goto out;
6326d0ce0e47SSidhartha Kumar 		folio_in_pagecache = true;
63270169fd51SZhangPeng 	} else if (!*foliop) {
63280169fd51SZhangPeng 		/* If a folio already exists, then it's UFFDIO_COPY for
6329d84cf06eSMina Almasry 		 * a non-missing case. Return -EEXIST.
6330d84cf06eSMina Almasry 		 */
6331d84cf06eSMina Almasry 		if (vm_shared &&
6332d84cf06eSMina Almasry 		    hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
6333d84cf06eSMina Almasry 			ret = -EEXIST;
63348fb5debcSMike Kravetz 			goto out;
6335d84cf06eSMina Almasry 		}
6336d84cf06eSMina Almasry 
6337d0ce0e47SSidhartha Kumar 		folio = alloc_hugetlb_folio(dst_vma, dst_addr, 0);
6338d0ce0e47SSidhartha Kumar 		if (IS_ERR(folio)) {
6339d84cf06eSMina Almasry 			ret = -ENOMEM;
6340d84cf06eSMina Almasry 			goto out;
6341d84cf06eSMina Almasry 		}
63428fb5debcSMike Kravetz 
6343e87340caSZhangPeng 		ret = copy_folio_from_user(folio, (const void __user *) src_addr,
6344e87340caSZhangPeng 					   false);
63458fb5debcSMike Kravetz 
6346c1e8d7c6SMichel Lespinasse 		/* fallback to copy_from_user outside mmap_lock */
63478fb5debcSMike Kravetz 		if (unlikely(ret)) {
63489e368259SAndrea Arcangeli 			ret = -ENOENT;
6349d0ce0e47SSidhartha Kumar 			/* Free the allocated folio which may have
63508cc5fcbbSMina Almasry 			 * consumed a reservation.
63518cc5fcbbSMina Almasry 			 */
6352d2d7bb44SSidhartha Kumar 			restore_reserve_on_error(h, dst_vma, dst_addr, folio);
6353d0ce0e47SSidhartha Kumar 			folio_put(folio);
63548cc5fcbbSMina Almasry 
6355d0ce0e47SSidhartha Kumar 			/* Allocate a temporary folio to hold the copied
63568cc5fcbbSMina Almasry 			 * contents.
63578cc5fcbbSMina Almasry 			 */
6358d0ce0e47SSidhartha Kumar 			folio = alloc_hugetlb_folio_vma(h, dst_vma, dst_addr);
6359d0ce0e47SSidhartha Kumar 			if (!folio) {
63608cc5fcbbSMina Almasry 				ret = -ENOMEM;
63618cc5fcbbSMina Almasry 				goto out;
63628cc5fcbbSMina Almasry 			}
63630169fd51SZhangPeng 			*foliop = folio;
63640169fd51SZhangPeng 			/* Set the outparam foliop and return to the caller to
63658cc5fcbbSMina Almasry 			 * copy the contents outside the lock. Don't free the
63660169fd51SZhangPeng 			 * folio.
63678cc5fcbbSMina Almasry 			 */
63688fb5debcSMike Kravetz 			goto out;
63698fb5debcSMike Kravetz 		}
63708fb5debcSMike Kravetz 	} else {
63718cc5fcbbSMina Almasry 		if (vm_shared &&
63728cc5fcbbSMina Almasry 		    hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
63730169fd51SZhangPeng 			folio_put(*foliop);
63748cc5fcbbSMina Almasry 			ret = -EEXIST;
63750169fd51SZhangPeng 			*foliop = NULL;
63768cc5fcbbSMina Almasry 			goto out;
63778cc5fcbbSMina Almasry 		}
63788cc5fcbbSMina Almasry 
6379d0ce0e47SSidhartha Kumar 		folio = alloc_hugetlb_folio(dst_vma, dst_addr, 0);
6380d0ce0e47SSidhartha Kumar 		if (IS_ERR(folio)) {
63810169fd51SZhangPeng 			folio_put(*foliop);
63828cc5fcbbSMina Almasry 			ret = -ENOMEM;
63830169fd51SZhangPeng 			*foliop = NULL;
63848cc5fcbbSMina Almasry 			goto out;
63858cc5fcbbSMina Almasry 		}
63861cb9dc4bSLiu Shixin 		ret = copy_user_large_folio(folio, *foliop, dst_addr, dst_vma);
63870169fd51SZhangPeng 		folio_put(*foliop);
63880169fd51SZhangPeng 		*foliop = NULL;
63891cb9dc4bSLiu Shixin 		if (ret) {
63901cb9dc4bSLiu Shixin 			folio_put(folio);
63911cb9dc4bSLiu Shixin 			goto out;
63921cb9dc4bSLiu Shixin 		}
63938fb5debcSMike Kravetz 	}
63948fb5debcSMike Kravetz 
63958fb5debcSMike Kravetz 	/*
6396d0ce0e47SSidhartha Kumar 	 * The memory barrier inside __folio_mark_uptodate makes sure that
63978fb5debcSMike Kravetz 	 * preceding stores to the page contents become visible before
63988fb5debcSMike Kravetz 	 * the set_pte_at() write.
63998fb5debcSMike Kravetz 	 */
6400d0ce0e47SSidhartha Kumar 	__folio_mark_uptodate(folio);
64018fb5debcSMike Kravetz 
6402f6191471SAxel Rasmussen 	/* Add shared, newly allocated pages to the page cache. */
6403f6191471SAxel Rasmussen 	if (vm_shared && !is_continue) {
64041e392147SAndrea Arcangeli 		size = i_size_read(mapping->host) >> huge_page_shift(h);
64051e392147SAndrea Arcangeli 		ret = -EFAULT;
64061e392147SAndrea Arcangeli 		if (idx >= size)
64071e392147SAndrea Arcangeli 			goto out_release_nounlock;
64081c9e8defSMike Kravetz 
64091e392147SAndrea Arcangeli 		/*
64101e392147SAndrea Arcangeli 		 * Serialization between remove_inode_hugepages() and
64117e1813d4SMike Kravetz 		 * hugetlb_add_to_page_cache() below happens through the
64121e392147SAndrea Arcangeli 		 * hugetlb_fault_mutex_table that here must be hold by
64131e392147SAndrea Arcangeli 		 * the caller.
64141e392147SAndrea Arcangeli 		 */
64159b91c0e2SSidhartha Kumar 		ret = hugetlb_add_to_page_cache(folio, mapping, idx);
64161c9e8defSMike Kravetz 		if (ret)
64171c9e8defSMike Kravetz 			goto out_release_nounlock;
6418d0ce0e47SSidhartha Kumar 		folio_in_pagecache = true;
64191c9e8defSMike Kravetz 	}
64201c9e8defSMike Kravetz 
6421bcc66543SMiaohe Lin 	ptl = huge_pte_lock(h, dst_mm, dst_pte);
64228fb5debcSMike Kravetz 
64238625147cSJames Houghton 	ret = -EIO;
6424d0ce0e47SSidhartha Kumar 	if (folio_test_hwpoison(folio))
64258625147cSJames Houghton 		goto out_release_unlock;
64268625147cSJames Houghton 
64271e392147SAndrea Arcangeli 	/*
64286041c691SPeter Xu 	 * We allow to overwrite a pte marker: consider when both MISSING|WP
64296041c691SPeter Xu 	 * registered, we firstly wr-protect a none pte which has no page cache
64306041c691SPeter Xu 	 * page backing it, then access the page.
64316041c691SPeter Xu 	 */
6432fa27759aSMike Kravetz 	ret = -EEXIST;
64336041c691SPeter Xu 	if (!huge_pte_none_mostly(huge_ptep_get(dst_pte)))
64348fb5debcSMike Kravetz 		goto out_release_unlock;
64358fb5debcSMike Kravetz 
6436d0ce0e47SSidhartha Kumar 	if (folio_in_pagecache)
6437d0ce0e47SSidhartha Kumar 		page_dup_file_rmap(&folio->page, true);
64384781593dSPeter Xu 	else
6439d0ce0e47SSidhartha Kumar 		hugepage_add_new_anon_rmap(folio, dst_vma, dst_addr);
64408fb5debcSMike Kravetz 
64416041c691SPeter Xu 	/*
64426041c691SPeter Xu 	 * For either: (1) CONTINUE on a non-shared VMA, or (2) UFFDIO_COPY
64436041c691SPeter Xu 	 * with wp flag set, don't set pte write bit.
64446041c691SPeter Xu 	 */
6445d9712937SAxel Rasmussen 	if (wp_enabled || (is_continue && !vm_shared))
6446f6191471SAxel Rasmussen 		writable = 0;
6447f6191471SAxel Rasmussen 	else
6448f6191471SAxel Rasmussen 		writable = dst_vma->vm_flags & VM_WRITE;
6449f6191471SAxel Rasmussen 
6450d0ce0e47SSidhartha Kumar 	_dst_pte = make_huge_pte(dst_vma, &folio->page, writable);
64516041c691SPeter Xu 	/*
64526041c691SPeter Xu 	 * Always mark UFFDIO_COPY page dirty; note that this may not be
64536041c691SPeter Xu 	 * extremely important for hugetlbfs for now since swapping is not
64546041c691SPeter Xu 	 * supported, but we should still be clear in that this page cannot be
64556041c691SPeter Xu 	 * thrown away at will, even if write bit not set.
64566041c691SPeter Xu 	 */
64578fb5debcSMike Kravetz 	_dst_pte = huge_pte_mkdirty(_dst_pte);
64588fb5debcSMike Kravetz 	_dst_pte = pte_mkyoung(_dst_pte);
64598fb5debcSMike Kravetz 
6460d9712937SAxel Rasmussen 	if (wp_enabled)
64616041c691SPeter Xu 		_dst_pte = huge_pte_mkuffd_wp(_dst_pte);
64626041c691SPeter Xu 
6463935d4f0cSRyan Roberts 	set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte, huge_page_size(h));
64648fb5debcSMike Kravetz 
64658fb5debcSMike Kravetz 	hugetlb_count_add(pages_per_huge_page(h), dst_mm);
64668fb5debcSMike Kravetz 
64678fb5debcSMike Kravetz 	/* No need to invalidate - it was non-present before */
64688fb5debcSMike Kravetz 	update_mmu_cache(dst_vma, dst_addr, dst_pte);
64698fb5debcSMike Kravetz 
64708fb5debcSMike Kravetz 	spin_unlock(ptl);
6471f6191471SAxel Rasmussen 	if (!is_continue)
6472d0ce0e47SSidhartha Kumar 		folio_set_hugetlb_migratable(folio);
6473f6191471SAxel Rasmussen 	if (vm_shared || is_continue)
6474d0ce0e47SSidhartha Kumar 		folio_unlock(folio);
64758fb5debcSMike Kravetz 	ret = 0;
64768fb5debcSMike Kravetz out:
64778fb5debcSMike Kravetz 	return ret;
64788fb5debcSMike Kravetz out_release_unlock:
64798fb5debcSMike Kravetz 	spin_unlock(ptl);
6480f6191471SAxel Rasmussen 	if (vm_shared || is_continue)
6481d0ce0e47SSidhartha Kumar 		folio_unlock(folio);
64825af10dfdSAndrea Arcangeli out_release_nounlock:
6483d0ce0e47SSidhartha Kumar 	if (!folio_in_pagecache)
6484d2d7bb44SSidhartha Kumar 		restore_reserve_on_error(h, dst_vma, dst_addr, folio);
6485d0ce0e47SSidhartha Kumar 	folio_put(folio);
64868fb5debcSMike Kravetz 	goto out;
64878fb5debcSMike Kravetz }
6488714c1891SAxel Rasmussen #endif /* CONFIG_USERFAULTFD */
64898fb5debcSMike Kravetz 
hugetlb_follow_page_mask(struct vm_area_struct * vma,unsigned long address,unsigned int flags,unsigned int * page_mask)649057a196a5SMike Kravetz struct page *hugetlb_follow_page_mask(struct vm_area_struct *vma,
64915502ea44SPeter Xu 				      unsigned long address, unsigned int flags,
64925502ea44SPeter Xu 				      unsigned int *page_mask)
649357a196a5SMike Kravetz {
649457a196a5SMike Kravetz 	struct hstate *h = hstate_vma(vma);
649557a196a5SMike Kravetz 	struct mm_struct *mm = vma->vm_mm;
649657a196a5SMike Kravetz 	unsigned long haddr = address & huge_page_mask(h);
649757a196a5SMike Kravetz 	struct page *page = NULL;
649857a196a5SMike Kravetz 	spinlock_t *ptl;
649957a196a5SMike Kravetz 	pte_t *pte, entry;
6500458568c9SPeter Xu 	int ret;
650157a196a5SMike Kravetz 
65027d049f3aSPeter Xu 	hugetlb_vma_lock_read(vma);
65039c67a207SPeter Xu 	pte = hugetlb_walk(vma, haddr, huge_page_size(h));
650457a196a5SMike Kravetz 	if (!pte)
65057d049f3aSPeter Xu 		goto out_unlock;
650657a196a5SMike Kravetz 
650757a196a5SMike Kravetz 	ptl = huge_pte_lock(h, mm, pte);
650857a196a5SMike Kravetz 	entry = huge_ptep_get(pte);
650957a196a5SMike Kravetz 	if (pte_present(entry)) {
6510458568c9SPeter Xu 		page = pte_page(entry);
6511458568c9SPeter Xu 
6512458568c9SPeter Xu 		if (!huge_pte_write(entry)) {
6513458568c9SPeter Xu 			if (flags & FOLL_WRITE) {
6514458568c9SPeter Xu 				page = NULL;
6515458568c9SPeter Xu 				goto out;
6516458568c9SPeter Xu 			}
6517458568c9SPeter Xu 
6518458568c9SPeter Xu 			if (gup_must_unshare(vma, flags, page)) {
6519458568c9SPeter Xu 				/* Tell the caller to do unsharing */
6520458568c9SPeter Xu 				page = ERR_PTR(-EMLINK);
6521458568c9SPeter Xu 				goto out;
6522458568c9SPeter Xu 			}
6523458568c9SPeter Xu 		}
6524458568c9SPeter Xu 
652518576d12SZi Yan 		page = nth_page(page, ((address & ~huge_page_mask(h)) >> PAGE_SHIFT));
6526458568c9SPeter Xu 
652757a196a5SMike Kravetz 		/*
652857a196a5SMike Kravetz 		 * Note that page may be a sub-page, and with vmemmap
652957a196a5SMike Kravetz 		 * optimizations the page struct may be read only.
653057a196a5SMike Kravetz 		 * try_grab_page() will increase the ref count on the
653157a196a5SMike Kravetz 		 * head page, so this will be OK.
653257a196a5SMike Kravetz 		 *
6533e2ca6ba6SLinus Torvalds 		 * try_grab_page() should always be able to get the page here,
6534e2ca6ba6SLinus Torvalds 		 * because we hold the ptl lock and have verified pte_present().
653557a196a5SMike Kravetz 		 */
653626273f5fSYang Shi 		ret = try_grab_folio(page_folio(page), 1, flags);
6537458568c9SPeter Xu 
6538458568c9SPeter Xu 		if (WARN_ON_ONCE(ret)) {
6539458568c9SPeter Xu 			page = ERR_PTR(ret);
654057a196a5SMike Kravetz 			goto out;
654157a196a5SMike Kravetz 		}
65425502ea44SPeter Xu 
65435502ea44SPeter Xu 		*page_mask = (1U << huge_page_order(h)) - 1;
654457a196a5SMike Kravetz 	}
654557a196a5SMike Kravetz out:
654657a196a5SMike Kravetz 	spin_unlock(ptl);
65477d049f3aSPeter Xu out_unlock:
65487d049f3aSPeter Xu 	hugetlb_vma_unlock_read(vma);
6549dd767aaaSPeter Xu 
6550dd767aaaSPeter Xu 	/*
6551dd767aaaSPeter Xu 	 * Fixup retval for dump requests: if pagecache doesn't exist,
6552dd767aaaSPeter Xu 	 * don't try to allocate a new page but just skip it.
6553dd767aaaSPeter Xu 	 */
6554dd767aaaSPeter Xu 	if (!page && (flags & FOLL_DUMP) &&
6555dd767aaaSPeter Xu 	    !hugetlbfs_pagecache_present(h, vma, address))
6556dd767aaaSPeter Xu 		page = ERR_PTR(-EFAULT);
6557dd767aaaSPeter Xu 
655857a196a5SMike Kravetz 	return page;
655957a196a5SMike Kravetz }
656057a196a5SMike Kravetz 
hugetlb_change_protection(struct vm_area_struct * vma,unsigned long address,unsigned long end,pgprot_t newprot,unsigned long cp_flags)6561a79390f5SPeter Xu long hugetlb_change_protection(struct vm_area_struct *vma,
65625a90d5a1SPeter Xu 		unsigned long address, unsigned long end,
65635a90d5a1SPeter Xu 		pgprot_t newprot, unsigned long cp_flags)
65648f860591SZhang, Yanmin {
65658f860591SZhang, Yanmin 	struct mm_struct *mm = vma->vm_mm;
65668f860591SZhang, Yanmin 	unsigned long start = address;
65678f860591SZhang, Yanmin 	pte_t *ptep;
65688f860591SZhang, Yanmin 	pte_t pte;
6569a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
6570a79390f5SPeter Xu 	long pages = 0, psize = huge_page_size(h);
6571dff11abeSMike Kravetz 	bool shared_pmd = false;
6572ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
6573e95a9851SMike Kravetz 	unsigned long last_addr_mask;
65745a90d5a1SPeter Xu 	bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
65755a90d5a1SPeter Xu 	bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
6576dff11abeSMike Kravetz 
6577dff11abeSMike Kravetz 	/*
6578dff11abeSMike Kravetz 	 * In the case of shared PMDs, the area to flush could be beyond
6579ac46d4f3SJérôme Glisse 	 * start/end.  Set range.start/range.end to cover the maximum possible
6580dff11abeSMike Kravetz 	 * range if PMD sharing is possible.
6581dff11abeSMike Kravetz 	 */
65827269f999SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_VMA,
65837d4a8be0SAlistair Popple 				0, mm, start, end);
6584ac46d4f3SJérôme Glisse 	adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
65858f860591SZhang, Yanmin 
65868f860591SZhang, Yanmin 	BUG_ON(address >= end);
6587ac46d4f3SJérôme Glisse 	flush_cache_range(vma, range.start, range.end);
65888f860591SZhang, Yanmin 
6589ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
659040549ba8SMike Kravetz 	hugetlb_vma_lock_write(vma);
659183cde9e8SDavidlohr Bueso 	i_mmap_lock_write(vma->vm_file->f_mapping);
659240549ba8SMike Kravetz 	last_addr_mask = hugetlb_mask_last_page(h);
659360dfaad6SPeter Xu 	for (; address < end; address += psize) {
6594cb900f41SKirill A. Shutemov 		spinlock_t *ptl;
65959c67a207SPeter Xu 		ptep = hugetlb_walk(vma, address, psize);
6596e95a9851SMike Kravetz 		if (!ptep) {
6597fed15f13SPeter Xu 			if (!uffd_wp) {
6598e95a9851SMike Kravetz 				address |= last_addr_mask;
65998f860591SZhang, Yanmin 				continue;
6600e95a9851SMike Kravetz 			}
6601fed15f13SPeter Xu 			/*
6602fed15f13SPeter Xu 			 * Userfaultfd wr-protect requires pgtable
6603fed15f13SPeter Xu 			 * pre-allocations to install pte markers.
6604fed15f13SPeter Xu 			 */
6605fed15f13SPeter Xu 			ptep = huge_pte_alloc(mm, vma, address, psize);
6606d1751118SPeter Xu 			if (!ptep) {
6607d1751118SPeter Xu 				pages = -ENOMEM;
6608fed15f13SPeter Xu 				break;
6609fed15f13SPeter Xu 			}
6610d1751118SPeter Xu 		}
6611cb900f41SKirill A. Shutemov 		ptl = huge_pte_lock(h, mm, ptep);
66124ddb4d91SMike Kravetz 		if (huge_pmd_unshare(mm, vma, address, ptep)) {
661360dfaad6SPeter Xu 			/*
661460dfaad6SPeter Xu 			 * When uffd-wp is enabled on the vma, unshare
661560dfaad6SPeter Xu 			 * shouldn't happen at all.  Warn about it if it
661660dfaad6SPeter Xu 			 * happened due to some reason.
661760dfaad6SPeter Xu 			 */
661860dfaad6SPeter Xu 			WARN_ON_ONCE(uffd_wp || uffd_wp_resolve);
66197da4d641SPeter Zijlstra 			pages++;
6620cb900f41SKirill A. Shutemov 			spin_unlock(ptl);
6621dff11abeSMike Kravetz 			shared_pmd = true;
66224ddb4d91SMike Kravetz 			address |= last_addr_mask;
662339dde65cSChen, Kenneth W 			continue;
66247da4d641SPeter Zijlstra 		}
6625a8bda28dSNaoya Horiguchi 		pte = huge_ptep_get(ptep);
6626a8bda28dSNaoya Horiguchi 		if (unlikely(is_hugetlb_entry_hwpoisoned(pte))) {
66270e678153SDavid Hildenbrand 			/* Nothing to do. */
66280e678153SDavid Hildenbrand 		} else if (unlikely(is_hugetlb_entry_migration(pte))) {
6629a8bda28dSNaoya Horiguchi 			swp_entry_t entry = pte_to_swp_entry(pte);
66306c287605SDavid Hildenbrand 			struct page *page = pfn_swap_entry_to_page(entry);
663144f86392SDavid Hildenbrand 			pte_t newpte = pte;
6632a8bda28dSNaoya Horiguchi 
663344f86392SDavid Hildenbrand 			if (is_writable_migration_entry(entry)) {
66346c287605SDavid Hildenbrand 				if (PageAnon(page))
66356c287605SDavid Hildenbrand 					entry = make_readable_exclusive_migration_entry(
66366c287605SDavid Hildenbrand 								swp_offset(entry));
66376c287605SDavid Hildenbrand 				else
66384dd845b5SAlistair Popple 					entry = make_readable_migration_entry(
66394dd845b5SAlistair Popple 								swp_offset(entry));
6640a8bda28dSNaoya Horiguchi 				newpte = swp_entry_to_pte(entry);
664144f86392SDavid Hildenbrand 				pages++;
664244f86392SDavid Hildenbrand 			}
664344f86392SDavid Hildenbrand 
66445a90d5a1SPeter Xu 			if (uffd_wp)
66455a90d5a1SPeter Xu 				newpte = pte_swp_mkuffd_wp(newpte);
66465a90d5a1SPeter Xu 			else if (uffd_wp_resolve)
66475a90d5a1SPeter Xu 				newpte = pte_swp_clear_uffd_wp(newpte);
664844f86392SDavid Hildenbrand 			if (!pte_same(pte, newpte))
6649935d4f0cSRyan Roberts 				set_huge_pte_at(mm, address, ptep, newpte, psize);
66500e678153SDavid Hildenbrand 		} else if (unlikely(is_pte_marker(pte))) {
6651db01bfbdSPeter Xu 			/*
6652db01bfbdSPeter Xu 			 * Do nothing on a poison marker; page is
6653db01bfbdSPeter Xu 			 * corrupted, permissons do not apply.  Here
6654db01bfbdSPeter Xu 			 * pte_marker_uffd_wp()==true implies !poison
6655db01bfbdSPeter Xu 			 * because they're mutual exclusive.
6656db01bfbdSPeter Xu 			 */
6657db01bfbdSPeter Xu 			if (pte_marker_uffd_wp(pte) && uffd_wp_resolve)
66580e678153SDavid Hildenbrand 				/* Safe to modify directly (non-present->none). */
665960dfaad6SPeter Xu 				huge_pte_clear(mm, address, ptep, psize);
66600e678153SDavid Hildenbrand 		} else if (!huge_pte_none(pte)) {
6661023bdd00SAneesh Kumar K.V 			pte_t old_pte;
666279c1c594SChristophe Leroy 			unsigned int shift = huge_page_shift(hstate_vma(vma));
6663023bdd00SAneesh Kumar K.V 
6664023bdd00SAneesh Kumar K.V 			old_pte = huge_ptep_modify_prot_start(vma, address, ptep);
666516785bd7SAnshuman Khandual 			pte = huge_pte_modify(old_pte, newprot);
666679c1c594SChristophe Leroy 			pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
66675a90d5a1SPeter Xu 			if (uffd_wp)
6668f1eb1bacSPeter Xu 				pte = huge_pte_mkuffd_wp(pte);
66695a90d5a1SPeter Xu 			else if (uffd_wp_resolve)
66705a90d5a1SPeter Xu 				pte = huge_pte_clear_uffd_wp(pte);
6671023bdd00SAneesh Kumar K.V 			huge_ptep_modify_prot_commit(vma, address, ptep, old_pte, pte);
66727da4d641SPeter Zijlstra 			pages++;
667360dfaad6SPeter Xu 		} else {
667460dfaad6SPeter Xu 			/* None pte */
667560dfaad6SPeter Xu 			if (unlikely(uffd_wp))
667660dfaad6SPeter Xu 				/* Safe to modify directly (none->non-present). */
667760dfaad6SPeter Xu 				set_huge_pte_at(mm, address, ptep,
6678935d4f0cSRyan Roberts 						make_pte_marker(PTE_MARKER_UFFD_WP),
6679935d4f0cSRyan Roberts 						psize);
66808f860591SZhang, Yanmin 		}
6681cb900f41SKirill A. Shutemov 		spin_unlock(ptl);
66828f860591SZhang, Yanmin 	}
6683d833352aSMel Gorman 	/*
6684c8c06efaSDavidlohr Bueso 	 * Must flush TLB before releasing i_mmap_rwsem: x86's huge_pmd_unshare
6685d833352aSMel Gorman 	 * may have cleared our pud entry and done put_page on the page table:
6686c8c06efaSDavidlohr Bueso 	 * once we release i_mmap_rwsem, another task can do the final put_page
6687dff11abeSMike Kravetz 	 * and that page table be reused and filled with junk.  If we actually
6688dff11abeSMike Kravetz 	 * did unshare a page of pmds, flush the range corresponding to the pud.
6689d833352aSMel Gorman 	 */
6690dff11abeSMike Kravetz 	if (shared_pmd)
6691ac46d4f3SJérôme Glisse 		flush_hugetlb_tlb_range(vma, range.start, range.end);
6692dff11abeSMike Kravetz 	else
66935491ae7bSAneesh Kumar K.V 		flush_hugetlb_tlb_range(vma, start, end);
66940f10851eSJérôme Glisse 	/*
66951af5a810SAlistair Popple 	 * No need to call mmu_notifier_arch_invalidate_secondary_tlbs() we are
66961af5a810SAlistair Popple 	 * downgrading page table protection not changing it to point to a new
66971af5a810SAlistair Popple 	 * page.
66980f10851eSJérôme Glisse 	 *
6699ee65728eSMike Rapoport 	 * See Documentation/mm/mmu_notifier.rst
67000f10851eSJérôme Glisse 	 */
670183cde9e8SDavidlohr Bueso 	i_mmap_unlock_write(vma->vm_file->f_mapping);
670240549ba8SMike Kravetz 	hugetlb_vma_unlock_write(vma);
6703ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
67047da4d641SPeter Zijlstra 
6705d1751118SPeter Xu 	return pages > 0 ? (pages << h->order) : pages;
67068f860591SZhang, Yanmin }
67078f860591SZhang, Yanmin 
670833b8f84aSMike Kravetz /* Return true if reservation was successful, false otherwise.  */
hugetlb_reserve_pages(struct inode * inode,long from,long to,struct vm_area_struct * vma,vm_flags_t vm_flags)670933b8f84aSMike Kravetz bool hugetlb_reserve_pages(struct inode *inode,
6710a1e78772SMel Gorman 					long from, long to,
67115a6fe125SMel Gorman 					struct vm_area_struct *vma,
6712ca16d140SKOSAKI Motohiro 					vm_flags_t vm_flags)
6713e4e574b7SAdam Litke {
6714c5094ec7SMike Kravetz 	long chg = -1, add = -1;
6715a5516438SAndi Kleen 	struct hstate *h = hstate_inode(inode);
671690481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_inode(inode);
67179119a41eSJoonsoo Kim 	struct resv_map *resv_map;
6718075a61d0SMina Almasry 	struct hugetlb_cgroup *h_cg = NULL;
67190db9d74eSMina Almasry 	long gbl_reserve, regions_needed = 0;
6720e4e574b7SAdam Litke 
672163489f8eSMike Kravetz 	/* This should never happen */
672263489f8eSMike Kravetz 	if (from > to) {
672363489f8eSMike Kravetz 		VM_WARN(1, "%s called with a negative range\n", __func__);
672433b8f84aSMike Kravetz 		return false;
672563489f8eSMike Kravetz 	}
672663489f8eSMike Kravetz 
6727a1e78772SMel Gorman 	/*
6728e700898fSMike Kravetz 	 * vma specific semaphore used for pmd sharing and fault/truncation
6729e700898fSMike Kravetz 	 * synchronization
67308d9bfb26SMike Kravetz 	 */
67318d9bfb26SMike Kravetz 	hugetlb_vma_lock_alloc(vma);
67328d9bfb26SMike Kravetz 
67338d9bfb26SMike Kravetz 	/*
673417c9d12eSMel Gorman 	 * Only apply hugepage reservation if asked. At fault time, an
673517c9d12eSMel Gorman 	 * attempt will be made for VM_NORESERVE to allocate a page
673690481622SDavid Gibson 	 * without using reserves
673717c9d12eSMel Gorman 	 */
6738ca16d140SKOSAKI Motohiro 	if (vm_flags & VM_NORESERVE)
673933b8f84aSMike Kravetz 		return true;
674017c9d12eSMel Gorman 
674117c9d12eSMel Gorman 	/*
6742a1e78772SMel Gorman 	 * Shared mappings base their reservation on the number of pages that
6743a1e78772SMel Gorman 	 * are already allocated on behalf of the file. Private mappings need
6744a1e78772SMel Gorman 	 * to reserve the full area even if read-only as mprotect() may be
6745a1e78772SMel Gorman 	 * called to make the mapping read-write. Assume !vma is a shm mapping
6746a1e78772SMel Gorman 	 */
67479119a41eSJoonsoo Kim 	if (!vma || vma->vm_flags & VM_MAYSHARE) {
6748f27a5136SMike Kravetz 		/*
6749f27a5136SMike Kravetz 		 * resv_map can not be NULL as hugetlb_reserve_pages is only
6750f27a5136SMike Kravetz 		 * called for inodes for which resv_maps were created (see
6751f27a5136SMike Kravetz 		 * hugetlbfs_get_inode).
6752f27a5136SMike Kravetz 		 */
67534e35f483SJoonsoo Kim 		resv_map = inode_resv_map(inode);
67549119a41eSJoonsoo Kim 
67550db9d74eSMina Almasry 		chg = region_chg(resv_map, from, to, &regions_needed);
67569119a41eSJoonsoo Kim 	} else {
6757e9fe92aeSMina Almasry 		/* Private mapping. */
67589119a41eSJoonsoo Kim 		resv_map = resv_map_alloc();
67595a6fe125SMel Gorman 		if (!resv_map)
67608d9bfb26SMike Kravetz 			goto out_err;
67615a6fe125SMel Gorman 
676217c9d12eSMel Gorman 		chg = to - from;
676317c9d12eSMel Gorman 
67645a6fe125SMel Gorman 		set_vma_resv_map(vma, resv_map);
67655a6fe125SMel Gorman 		set_vma_resv_flags(vma, HPAGE_RESV_OWNER);
67665a6fe125SMel Gorman 	}
67675a6fe125SMel Gorman 
676833b8f84aSMike Kravetz 	if (chg < 0)
6769c50ac050SDave Hansen 		goto out_err;
677017c9d12eSMel Gorman 
677133b8f84aSMike Kravetz 	if (hugetlb_cgroup_charge_cgroup_rsvd(hstate_index(h),
677233b8f84aSMike Kravetz 				chg * pages_per_huge_page(h), &h_cg) < 0)
6773075a61d0SMina Almasry 		goto out_err;
6774075a61d0SMina Almasry 
6775075a61d0SMina Almasry 	if (vma && !(vma->vm_flags & VM_MAYSHARE) && h_cg) {
6776075a61d0SMina Almasry 		/* For private mappings, the hugetlb_cgroup uncharge info hangs
6777075a61d0SMina Almasry 		 * of the resv_map.
6778075a61d0SMina Almasry 		 */
6779075a61d0SMina Almasry 		resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, h_cg, h);
6780075a61d0SMina Almasry 	}
6781075a61d0SMina Almasry 
67821c5ecae3SMike Kravetz 	/*
67831c5ecae3SMike Kravetz 	 * There must be enough pages in the subpool for the mapping. If
67841c5ecae3SMike Kravetz 	 * the subpool has a minimum size, there may be some global
67851c5ecae3SMike Kravetz 	 * reservations already in place (gbl_reserve).
67861c5ecae3SMike Kravetz 	 */
67871c5ecae3SMike Kravetz 	gbl_reserve = hugepage_subpool_get_pages(spool, chg);
678833b8f84aSMike Kravetz 	if (gbl_reserve < 0)
6789075a61d0SMina Almasry 		goto out_uncharge_cgroup;
679017c9d12eSMel Gorman 
679117c9d12eSMel Gorman 	/*
679217c9d12eSMel Gorman 	 * Check enough hugepages are available for the reservation.
679390481622SDavid Gibson 	 * Hand the pages back to the subpool if there are not
679417c9d12eSMel Gorman 	 */
679533b8f84aSMike Kravetz 	if (hugetlb_acct_memory(h, gbl_reserve) < 0)
6796075a61d0SMina Almasry 		goto out_put_pages;
679717c9d12eSMel Gorman 
679817c9d12eSMel Gorman 	/*
679917c9d12eSMel Gorman 	 * Account for the reservations made. Shared mappings record regions
680017c9d12eSMel Gorman 	 * that have reservations as they are shared by multiple VMAs.
680117c9d12eSMel Gorman 	 * When the last VMA disappears, the region map says how much
680217c9d12eSMel Gorman 	 * the reservation was and the page cache tells how much of
680317c9d12eSMel Gorman 	 * the reservation was consumed. Private mappings are per-VMA and
680417c9d12eSMel Gorman 	 * only the consumed reservations are tracked. When the VMA
680517c9d12eSMel Gorman 	 * disappears, the original reservation is the VMA size and the
680617c9d12eSMel Gorman 	 * consumed reservations are stored in the map. Hence, nothing
680717c9d12eSMel Gorman 	 * else has to be done for private mappings here
680817c9d12eSMel Gorman 	 */
680933039678SMike Kravetz 	if (!vma || vma->vm_flags & VM_MAYSHARE) {
6810075a61d0SMina Almasry 		add = region_add(resv_map, from, to, regions_needed, h, h_cg);
681133039678SMike Kravetz 
68120db9d74eSMina Almasry 		if (unlikely(add < 0)) {
68130db9d74eSMina Almasry 			hugetlb_acct_memory(h, -gbl_reserve);
6814075a61d0SMina Almasry 			goto out_put_pages;
68150db9d74eSMina Almasry 		} else if (unlikely(chg > add)) {
681633039678SMike Kravetz 			/*
681733039678SMike Kravetz 			 * pages in this range were added to the reserve
681833039678SMike Kravetz 			 * map between region_chg and region_add.  This
6819d0ce0e47SSidhartha Kumar 			 * indicates a race with alloc_hugetlb_folio.  Adjust
682033039678SMike Kravetz 			 * the subpool and reserve counts modified above
682133039678SMike Kravetz 			 * based on the difference.
682233039678SMike Kravetz 			 */
682333039678SMike Kravetz 			long rsv_adjust;
682433039678SMike Kravetz 
6825d85aecf2SMiaohe Lin 			/*
6826d85aecf2SMiaohe Lin 			 * hugetlb_cgroup_uncharge_cgroup_rsvd() will put the
6827d85aecf2SMiaohe Lin 			 * reference to h_cg->css. See comment below for detail.
6828d85aecf2SMiaohe Lin 			 */
6829075a61d0SMina Almasry 			hugetlb_cgroup_uncharge_cgroup_rsvd(
6830075a61d0SMina Almasry 				hstate_index(h),
6831075a61d0SMina Almasry 				(chg - add) * pages_per_huge_page(h), h_cg);
6832075a61d0SMina Almasry 
683333039678SMike Kravetz 			rsv_adjust = hugepage_subpool_put_pages(spool,
683433039678SMike Kravetz 								chg - add);
683533039678SMike Kravetz 			hugetlb_acct_memory(h, -rsv_adjust);
6836d85aecf2SMiaohe Lin 		} else if (h_cg) {
6837d85aecf2SMiaohe Lin 			/*
6838d85aecf2SMiaohe Lin 			 * The file_regions will hold their own reference to
6839d85aecf2SMiaohe Lin 			 * h_cg->css. So we should release the reference held
6840d85aecf2SMiaohe Lin 			 * via hugetlb_cgroup_charge_cgroup_rsvd() when we are
6841d85aecf2SMiaohe Lin 			 * done.
6842d85aecf2SMiaohe Lin 			 */
6843d85aecf2SMiaohe Lin 			hugetlb_cgroup_put_rsvd_cgroup(h_cg);
684433039678SMike Kravetz 		}
684533039678SMike Kravetz 	}
684633b8f84aSMike Kravetz 	return true;
684733b8f84aSMike Kravetz 
6848075a61d0SMina Almasry out_put_pages:
6849075a61d0SMina Almasry 	/* put back original number of pages, chg */
6850075a61d0SMina Almasry 	(void)hugepage_subpool_put_pages(spool, chg);
6851075a61d0SMina Almasry out_uncharge_cgroup:
6852075a61d0SMina Almasry 	hugetlb_cgroup_uncharge_cgroup_rsvd(hstate_index(h),
6853075a61d0SMina Almasry 					    chg * pages_per_huge_page(h), h_cg);
6854c50ac050SDave Hansen out_err:
68558d9bfb26SMike Kravetz 	hugetlb_vma_lock_free(vma);
68565e911373SMike Kravetz 	if (!vma || vma->vm_flags & VM_MAYSHARE)
68570db9d74eSMina Almasry 		/* Only call region_abort if the region_chg succeeded but the
68580db9d74eSMina Almasry 		 * region_add failed or didn't run.
68590db9d74eSMina Almasry 		 */
68600db9d74eSMina Almasry 		if (chg >= 0 && add < 0)
68610db9d74eSMina Almasry 			region_abort(resv_map, from, to, regions_needed);
686292fe9dcbSRik van Riel 	if (vma && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
6863f031dd27SJoonsoo Kim 		kref_put(&resv_map->refs, resv_map_release);
686492fe9dcbSRik van Riel 		set_vma_resv_map(vma, NULL);
686592fe9dcbSRik van Riel 	}
686633b8f84aSMike Kravetz 	return false;
6867a43a8c39SChen, Kenneth W }
6868a43a8c39SChen, Kenneth W 
hugetlb_unreserve_pages(struct inode * inode,long start,long end,long freed)6869b5cec28dSMike Kravetz long hugetlb_unreserve_pages(struct inode *inode, long start, long end,
6870b5cec28dSMike Kravetz 								long freed)
6871a43a8c39SChen, Kenneth W {
6872a5516438SAndi Kleen 	struct hstate *h = hstate_inode(inode);
68734e35f483SJoonsoo Kim 	struct resv_map *resv_map = inode_resv_map(inode);
68749119a41eSJoonsoo Kim 	long chg = 0;
687590481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_inode(inode);
68761c5ecae3SMike Kravetz 	long gbl_reserve;
687745c682a6SKen Chen 
6878f27a5136SMike Kravetz 	/*
6879f27a5136SMike Kravetz 	 * Since this routine can be called in the evict inode path for all
6880f27a5136SMike Kravetz 	 * hugetlbfs inodes, resv_map could be NULL.
6881f27a5136SMike Kravetz 	 */
6882b5cec28dSMike Kravetz 	if (resv_map) {
6883b5cec28dSMike Kravetz 		chg = region_del(resv_map, start, end);
6884b5cec28dSMike Kravetz 		/*
6885b5cec28dSMike Kravetz 		 * region_del() can fail in the rare case where a region
6886b5cec28dSMike Kravetz 		 * must be split and another region descriptor can not be
6887b5cec28dSMike Kravetz 		 * allocated.  If end == LONG_MAX, it will not fail.
6888b5cec28dSMike Kravetz 		 */
6889b5cec28dSMike Kravetz 		if (chg < 0)
6890b5cec28dSMike Kravetz 			return chg;
6891b5cec28dSMike Kravetz 	}
6892b5cec28dSMike Kravetz 
689345c682a6SKen Chen 	spin_lock(&inode->i_lock);
6894e4c6f8beSEric Sandeen 	inode->i_blocks -= (blocks_per_huge_page(h) * freed);
689545c682a6SKen Chen 	spin_unlock(&inode->i_lock);
689645c682a6SKen Chen 
68971c5ecae3SMike Kravetz 	/*
68981c5ecae3SMike Kravetz 	 * If the subpool has a minimum size, the number of global
68991c5ecae3SMike Kravetz 	 * reservations to be released may be adjusted.
6900dddf31a4SMiaohe Lin 	 *
6901dddf31a4SMiaohe Lin 	 * Note that !resv_map implies freed == 0. So (chg - freed)
6902dddf31a4SMiaohe Lin 	 * won't go negative.
69031c5ecae3SMike Kravetz 	 */
69041c5ecae3SMike Kravetz 	gbl_reserve = hugepage_subpool_put_pages(spool, (chg - freed));
69051c5ecae3SMike Kravetz 	hugetlb_acct_memory(h, -gbl_reserve);
6906b5cec28dSMike Kravetz 
6907b5cec28dSMike Kravetz 	return 0;
6908a43a8c39SChen, Kenneth W }
690993f70f90SNaoya Horiguchi 
6910ec500230SDavid Hildenbrand #ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING
page_table_shareable(struct vm_area_struct * svma,struct vm_area_struct * vma,unsigned long addr,pgoff_t idx)69113212b535SSteve Capper static unsigned long page_table_shareable(struct vm_area_struct *svma,
69123212b535SSteve Capper 				struct vm_area_struct *vma,
69133212b535SSteve Capper 				unsigned long addr, pgoff_t idx)
69143212b535SSteve Capper {
69153212b535SSteve Capper 	unsigned long saddr = ((idx - svma->vm_pgoff) << PAGE_SHIFT) +
69163212b535SSteve Capper 				svma->vm_start;
69173212b535SSteve Capper 	unsigned long sbase = saddr & PUD_MASK;
69183212b535SSteve Capper 	unsigned long s_end = sbase + PUD_SIZE;
69193212b535SSteve Capper 
69203212b535SSteve Capper 	/* Allow segments to share if only one is marked locked */
6921e430a95aSSuren Baghdasaryan 	unsigned long vm_flags = vma->vm_flags & ~VM_LOCKED_MASK;
6922e430a95aSSuren Baghdasaryan 	unsigned long svm_flags = svma->vm_flags & ~VM_LOCKED_MASK;
69233212b535SSteve Capper 
69243212b535SSteve Capper 	/*
69253212b535SSteve Capper 	 * match the virtual addresses, permission and the alignment of the
69263212b535SSteve Capper 	 * page table page.
6927131a79b4SMike Kravetz 	 *
6928131a79b4SMike Kravetz 	 * Also, vma_lock (vm_private_data) is required for sharing.
69293212b535SSteve Capper 	 */
69303212b535SSteve Capper 	if (pmd_index(addr) != pmd_index(saddr) ||
69313212b535SSteve Capper 	    vm_flags != svm_flags ||
6932131a79b4SMike Kravetz 	    !range_in_vma(svma, sbase, s_end) ||
6933131a79b4SMike Kravetz 	    !svma->vm_private_data)
69343212b535SSteve Capper 		return 0;
69353212b535SSteve Capper 
69363212b535SSteve Capper 	return saddr;
69373212b535SSteve Capper }
69383212b535SSteve Capper 
want_pmd_share(struct vm_area_struct * vma,unsigned long addr)6939bbff39ccSMike Kravetz bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
69403212b535SSteve Capper {
6941bbff39ccSMike Kravetz 	unsigned long start = addr & PUD_MASK;
6942bbff39ccSMike Kravetz 	unsigned long end = start + PUD_SIZE;
6943bbff39ccSMike Kravetz 
69448d9bfb26SMike Kravetz #ifdef CONFIG_USERFAULTFD
69458d9bfb26SMike Kravetz 	if (uffd_disable_huge_pmd_share(vma))
69468d9bfb26SMike Kravetz 		return false;
69478d9bfb26SMike Kravetz #endif
69483212b535SSteve Capper 	/*
69493212b535SSteve Capper 	 * check on proper vm_flags and page table alignment
69503212b535SSteve Capper 	 */
69518d9bfb26SMike Kravetz 	if (!(vma->vm_flags & VM_MAYSHARE))
695231aafb45SNicholas Krause 		return false;
6953bbff39ccSMike Kravetz 	if (!vma->vm_private_data)	/* vma lock required for sharing */
69548d9bfb26SMike Kravetz 		return false;
69558d9bfb26SMike Kravetz 	if (!range_in_vma(vma, start, end))
69568d9bfb26SMike Kravetz 		return false;
69578d9bfb26SMike Kravetz 	return true;
69588d9bfb26SMike Kravetz }
69598d9bfb26SMike Kravetz 
69603212b535SSteve Capper /*
6961017b1660SMike Kravetz  * Determine if start,end range within vma could be mapped by shared pmd.
6962017b1660SMike Kravetz  * If yes, adjust start and end to cover range associated with possible
6963017b1660SMike Kravetz  * shared pmd mappings.
6964017b1660SMike Kravetz  */
adjust_range_if_pmd_sharing_possible(struct vm_area_struct * vma,unsigned long * start,unsigned long * end)6965017b1660SMike Kravetz void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
6966017b1660SMike Kravetz 				unsigned long *start, unsigned long *end)
6967017b1660SMike Kravetz {
6968a1ba9da8SLi Xinhai 	unsigned long v_start = ALIGN(vma->vm_start, PUD_SIZE),
6969a1ba9da8SLi Xinhai 		v_end = ALIGN_DOWN(vma->vm_end, PUD_SIZE);
6970017b1660SMike Kravetz 
6971a1ba9da8SLi Xinhai 	/*
6972f0953a1bSIngo Molnar 	 * vma needs to span at least one aligned PUD size, and the range
6973f0953a1bSIngo Molnar 	 * must be at least partially within in.
6974a1ba9da8SLi Xinhai 	 */
6975a1ba9da8SLi Xinhai 	if (!(vma->vm_flags & VM_MAYSHARE) || !(v_end > v_start) ||
6976a1ba9da8SLi Xinhai 		(*end <= v_start) || (*start >= v_end))
6977017b1660SMike Kravetz 		return;
6978017b1660SMike Kravetz 
697975802ca6SPeter Xu 	/* Extend the range to be PUD aligned for a worst case scenario */
6980a1ba9da8SLi Xinhai 	if (*start > v_start)
6981a1ba9da8SLi Xinhai 		*start = ALIGN_DOWN(*start, PUD_SIZE);
6982017b1660SMike Kravetz 
6983a1ba9da8SLi Xinhai 	if (*end < v_end)
6984a1ba9da8SLi Xinhai 		*end = ALIGN(*end, PUD_SIZE);
6985017b1660SMike Kravetz }
6986017b1660SMike Kravetz 
6987017b1660SMike Kravetz /*
69883212b535SSteve Capper  * Search for a shareable pmd page for hugetlb. In any case calls pmd_alloc()
69893212b535SSteve Capper  * and returns the corresponding pte. While this is not necessary for the
69903212b535SSteve Capper  * !shared pmd case because we can allocate the pmd later as well, it makes the
69913a47c54fSMike Kravetz  * code much cleaner. pmd allocation is essential for the shared case because
69923a47c54fSMike Kravetz  * pud has to be populated inside the same i_mmap_rwsem section - otherwise
69933a47c54fSMike Kravetz  * racing tasks could either miss the sharing (see huge_pte_offset) or select a
69943a47c54fSMike Kravetz  * bad pmd for sharing.
69953212b535SSteve Capper  */
huge_pmd_share(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long addr,pud_t * pud)6996aec44e0fSPeter Xu pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
6997aec44e0fSPeter Xu 		      unsigned long addr, pud_t *pud)
69983212b535SSteve Capper {
69993212b535SSteve Capper 	struct address_space *mapping = vma->vm_file->f_mapping;
70003212b535SSteve Capper 	pgoff_t idx = ((addr - vma->vm_start) >> PAGE_SHIFT) +
70013212b535SSteve Capper 			vma->vm_pgoff;
70023212b535SSteve Capper 	struct vm_area_struct *svma;
70033212b535SSteve Capper 	unsigned long saddr;
70043212b535SSteve Capper 	pte_t *spte = NULL;
70053212b535SSteve Capper 	pte_t *pte;
70063212b535SSteve Capper 
70073a47c54fSMike Kravetz 	i_mmap_lock_read(mapping);
70083212b535SSteve Capper 	vma_interval_tree_foreach(svma, &mapping->i_mmap, idx, idx) {
70093212b535SSteve Capper 		if (svma == vma)
70103212b535SSteve Capper 			continue;
70113212b535SSteve Capper 
70123212b535SSteve Capper 		saddr = page_table_shareable(svma, vma, addr, idx);
70133212b535SSteve Capper 		if (saddr) {
70149c67a207SPeter Xu 			spte = hugetlb_walk(svma, saddr,
70157868a208SPunit Agrawal 					    vma_mmu_pagesize(svma));
70163212b535SSteve Capper 			if (spte) {
701756b27447SLiu Shixin 				ptdesc_pmd_pts_inc(virt_to_ptdesc(spte));
70183212b535SSteve Capper 				break;
70193212b535SSteve Capper 			}
70203212b535SSteve Capper 		}
70213212b535SSteve Capper 	}
70223212b535SSteve Capper 
70233212b535SSteve Capper 	if (!spte)
70243212b535SSteve Capper 		goto out;
70253212b535SSteve Capper 
7026349d1670SPeter Xu 	spin_lock(&mm->page_table_lock);
7027dc6c9a35SKirill A. Shutemov 	if (pud_none(*pud)) {
70283212b535SSteve Capper 		pud_populate(mm, pud,
70293212b535SSteve Capper 				(pmd_t *)((unsigned long)spte & PAGE_MASK));
7030c17b1f42SKirill A. Shutemov 		mm_inc_nr_pmds(mm);
7031dc6c9a35SKirill A. Shutemov 	} else {
703256b27447SLiu Shixin 		ptdesc_pmd_pts_dec(virt_to_ptdesc(spte));
7033dc6c9a35SKirill A. Shutemov 	}
7034349d1670SPeter Xu 	spin_unlock(&mm->page_table_lock);
70353212b535SSteve Capper out:
70363212b535SSteve Capper 	pte = (pte_t *)pmd_alloc(mm, pud, addr);
70373a47c54fSMike Kravetz 	i_mmap_unlock_read(mapping);
70383212b535SSteve Capper 	return pte;
70393212b535SSteve Capper }
70403212b535SSteve Capper 
70413212b535SSteve Capper /*
70423212b535SSteve Capper  * unmap huge page backed by shared pte.
70433212b535SSteve Capper  *
70443a47c54fSMike Kravetz  * Called with page table lock held.
70453212b535SSteve Capper  *
70463212b535SSteve Capper  * returns: 1 successfully unmapped a shared pte page
70473212b535SSteve Capper  *	    0 the underlying pte page is not shared, or it is the last user
70483212b535SSteve Capper  */
huge_pmd_unshare(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long addr,pte_t * ptep)704934ae204fSMike Kravetz int huge_pmd_unshare(struct mm_struct *mm, struct vm_area_struct *vma,
70504ddb4d91SMike Kravetz 					unsigned long addr, pte_t *ptep)
70513212b535SSteve Capper {
705256b27447SLiu Shixin 	unsigned long sz = huge_page_size(hstate_vma(vma));
70534ddb4d91SMike Kravetz 	pgd_t *pgd = pgd_offset(mm, addr);
70544ddb4d91SMike Kravetz 	p4d_t *p4d = p4d_offset(pgd, addr);
70554ddb4d91SMike Kravetz 	pud_t *pud = pud_offset(p4d, addr);
70563212b535SSteve Capper 
705734ae204fSMike Kravetz 	i_mmap_assert_write_locked(vma->vm_file->f_mapping);
705840549ba8SMike Kravetz 	hugetlb_vma_assert_locked(vma);
705956b27447SLiu Shixin 	if (sz != PMD_SIZE)
706056b27447SLiu Shixin 		return 0;
706156b27447SLiu Shixin 	if (!ptdesc_pmd_pts_count(virt_to_ptdesc(ptep)))
70623212b535SSteve Capper 		return 0;
70633212b535SSteve Capper 
70643212b535SSteve Capper 	pud_clear(pud);
706556b27447SLiu Shixin 	ptdesc_pmd_pts_dec(virt_to_ptdesc(ptep));
7066dc6c9a35SKirill A. Shutemov 	mm_dec_nr_pmds(mm);
70673212b535SSteve Capper 	return 1;
70683212b535SSteve Capper }
7069c1991e07SPeter Xu 
7070ec500230SDavid Hildenbrand #else /* !CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING */
70718d9bfb26SMike Kravetz 
huge_pmd_share(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long addr,pud_t * pud)7072aec44e0fSPeter Xu pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
7073aec44e0fSPeter Xu 		      unsigned long addr, pud_t *pud)
70749e5fc74cSSteve Capper {
70759e5fc74cSSteve Capper 	return NULL;
70769e5fc74cSSteve Capper }
7077e81f2d22SZhang Zhen 
huge_pmd_unshare(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long addr,pte_t * ptep)707834ae204fSMike Kravetz int huge_pmd_unshare(struct mm_struct *mm, struct vm_area_struct *vma,
70794ddb4d91SMike Kravetz 				unsigned long addr, pte_t *ptep)
7080e81f2d22SZhang Zhen {
7081e81f2d22SZhang Zhen 	return 0;
7082e81f2d22SZhang Zhen }
7083017b1660SMike Kravetz 
adjust_range_if_pmd_sharing_possible(struct vm_area_struct * vma,unsigned long * start,unsigned long * end)7084017b1660SMike Kravetz void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
7085017b1660SMike Kravetz 				unsigned long *start, unsigned long *end)
7086017b1660SMike Kravetz {
7087017b1660SMike Kravetz }
7088c1991e07SPeter Xu 
want_pmd_share(struct vm_area_struct * vma,unsigned long addr)7089c1991e07SPeter Xu bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
7090c1991e07SPeter Xu {
7091c1991e07SPeter Xu 	return false;
7092c1991e07SPeter Xu }
7093ec500230SDavid Hildenbrand #endif /* CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING */
70943212b535SSteve Capper 
70959e5fc74cSSteve Capper #ifdef CONFIG_ARCH_WANT_GENERAL_HUGETLB
huge_pte_alloc(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long addr,unsigned long sz)7096aec44e0fSPeter Xu pte_t *huge_pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma,
70979e5fc74cSSteve Capper 			unsigned long addr, unsigned long sz)
70989e5fc74cSSteve Capper {
70999e5fc74cSSteve Capper 	pgd_t *pgd;
7100c2febafcSKirill A. Shutemov 	p4d_t *p4d;
71019e5fc74cSSteve Capper 	pud_t *pud;
71029e5fc74cSSteve Capper 	pte_t *pte = NULL;
71039e5fc74cSSteve Capper 
71049e5fc74cSSteve Capper 	pgd = pgd_offset(mm, addr);
7105f4f0a3d8SKirill A. Shutemov 	p4d = p4d_alloc(mm, pgd, addr);
7106f4f0a3d8SKirill A. Shutemov 	if (!p4d)
7107f4f0a3d8SKirill A. Shutemov 		return NULL;
7108c2febafcSKirill A. Shutemov 	pud = pud_alloc(mm, p4d, addr);
71099e5fc74cSSteve Capper 	if (pud) {
71109e5fc74cSSteve Capper 		if (sz == PUD_SIZE) {
71119e5fc74cSSteve Capper 			pte = (pte_t *)pud;
71129e5fc74cSSteve Capper 		} else {
71139e5fc74cSSteve Capper 			BUG_ON(sz != PMD_SIZE);
7114c1991e07SPeter Xu 			if (want_pmd_share(vma, addr) && pud_none(*pud))
7115aec44e0fSPeter Xu 				pte = huge_pmd_share(mm, vma, addr, pud);
71169e5fc74cSSteve Capper 			else
71179e5fc74cSSteve Capper 				pte = (pte_t *)pmd_alloc(mm, pud, addr);
71189e5fc74cSSteve Capper 		}
71199e5fc74cSSteve Capper 	}
7120191fcdb6SJohn Hubbard 
7121191fcdb6SJohn Hubbard 	if (pte) {
7122191fcdb6SJohn Hubbard 		pte_t pteval = ptep_get_lockless(pte);
7123191fcdb6SJohn Hubbard 
7124191fcdb6SJohn Hubbard 		BUG_ON(pte_present(pteval) && !pte_huge(pteval));
7125191fcdb6SJohn Hubbard 	}
71269e5fc74cSSteve Capper 
71279e5fc74cSSteve Capper 	return pte;
71289e5fc74cSSteve Capper }
71299e5fc74cSSteve Capper 
71309b19df29SPunit Agrawal /*
71319b19df29SPunit Agrawal  * huge_pte_offset() - Walk the page table to resolve the hugepage
71329b19df29SPunit Agrawal  * entry at address @addr
71339b19df29SPunit Agrawal  *
71348ac0b81aSLi Xinhai  * Return: Pointer to page table entry (PUD or PMD) for
71358ac0b81aSLi Xinhai  * address @addr, or NULL if a !p*d_present() entry is encountered and the
71369b19df29SPunit Agrawal  * size @sz doesn't match the hugepage size at this level of the page
71379b19df29SPunit Agrawal  * table.
71389b19df29SPunit Agrawal  */
huge_pte_offset(struct mm_struct * mm,unsigned long addr,unsigned long sz)71397868a208SPunit Agrawal pte_t *huge_pte_offset(struct mm_struct *mm,
71407868a208SPunit Agrawal 		       unsigned long addr, unsigned long sz)
71419e5fc74cSSteve Capper {
71429e5fc74cSSteve Capper 	pgd_t *pgd;
7143c2febafcSKirill A. Shutemov 	p4d_t *p4d;
71448ac0b81aSLi Xinhai 	pud_t *pud;
71458ac0b81aSLi Xinhai 	pmd_t *pmd;
71469e5fc74cSSteve Capper 
71479e5fc74cSSteve Capper 	pgd = pgd_offset(mm, addr);
7148c2febafcSKirill A. Shutemov 	if (!pgd_present(*pgd))
7149c2febafcSKirill A. Shutemov 		return NULL;
7150c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, addr);
7151c2febafcSKirill A. Shutemov 	if (!p4d_present(*p4d))
7152c2febafcSKirill A. Shutemov 		return NULL;
71539b19df29SPunit Agrawal 
7154c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, addr);
71558ac0b81aSLi Xinhai 	if (sz == PUD_SIZE)
71568ac0b81aSLi Xinhai 		/* must be pud huge, non-present or none */
71579e5fc74cSSteve Capper 		return (pte_t *)pud;
71588ac0b81aSLi Xinhai 	if (!pud_present(*pud))
71598ac0b81aSLi Xinhai 		return NULL;
71608ac0b81aSLi Xinhai 	/* must have a valid entry and size to go further */
71619b19df29SPunit Agrawal 
71629e5fc74cSSteve Capper 	pmd = pmd_offset(pud, addr);
71638ac0b81aSLi Xinhai 	/* must be pmd huge, non-present or none */
71649e5fc74cSSteve Capper 	return (pte_t *)pmd;
71659e5fc74cSSteve Capper }
71669e5fc74cSSteve Capper 
7167e95a9851SMike Kravetz /*
7168e95a9851SMike Kravetz  * Return a mask that can be used to update an address to the last huge
7169e95a9851SMike Kravetz  * page in a page table page mapping size.  Used to skip non-present
7170e95a9851SMike Kravetz  * page table entries when linearly scanning address ranges.  Architectures
7171e95a9851SMike Kravetz  * with unique huge page to page table relationships can define their own
7172e95a9851SMike Kravetz  * version of this routine.
7173e95a9851SMike Kravetz  */
hugetlb_mask_last_page(struct hstate * h)7174e95a9851SMike Kravetz unsigned long hugetlb_mask_last_page(struct hstate *h)
7175e95a9851SMike Kravetz {
7176e95a9851SMike Kravetz 	unsigned long hp_size = huge_page_size(h);
7177e95a9851SMike Kravetz 
7178e95a9851SMike Kravetz 	if (hp_size == PUD_SIZE)
7179e95a9851SMike Kravetz 		return P4D_SIZE - PUD_SIZE;
7180e95a9851SMike Kravetz 	else if (hp_size == PMD_SIZE)
7181e95a9851SMike Kravetz 		return PUD_SIZE - PMD_SIZE;
7182e95a9851SMike Kravetz 	else
7183e95a9851SMike Kravetz 		return 0UL;
7184e95a9851SMike Kravetz }
7185e95a9851SMike Kravetz 
7186e95a9851SMike Kravetz #else
7187e95a9851SMike Kravetz 
7188e95a9851SMike Kravetz /* See description above.  Architectures can provide their own version. */
hugetlb_mask_last_page(struct hstate * h)7189e95a9851SMike Kravetz __weak unsigned long hugetlb_mask_last_page(struct hstate *h)
7190e95a9851SMike Kravetz {
7191ec500230SDavid Hildenbrand #ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING
71924ddb4d91SMike Kravetz 	if (huge_page_size(h) == PMD_SIZE)
71934ddb4d91SMike Kravetz 		return PUD_SIZE - PMD_SIZE;
71944ddb4d91SMike Kravetz #endif
7195e95a9851SMike Kravetz 	return 0UL;
7196e95a9851SMike Kravetz }
7197e95a9851SMike Kravetz 
719861f77edaSNaoya Horiguchi #endif /* CONFIG_ARCH_WANT_GENERAL_HUGETLB */
719961f77edaSNaoya Horiguchi 
720061f77edaSNaoya Horiguchi /*
720161f77edaSNaoya Horiguchi  * These functions are overwritable if your architecture needs its own
720261f77edaSNaoya Horiguchi  * behavior.
720361f77edaSNaoya Horiguchi  */
isolate_hugetlb(struct folio * folio,struct list_head * list)72049747b9e9SBaolin Wang bool isolate_hugetlb(struct folio *folio, struct list_head *list)
720531caf665SNaoya Horiguchi {
72069747b9e9SBaolin Wang 	bool ret = true;
7207bcc54222SNaoya Horiguchi 
7208db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
72096aa3a920SSidhartha Kumar 	if (!folio_test_hugetlb(folio) ||
72106aa3a920SSidhartha Kumar 	    !folio_test_hugetlb_migratable(folio) ||
72116aa3a920SSidhartha Kumar 	    !folio_try_get(folio)) {
72129747b9e9SBaolin Wang 		ret = false;
7213bcc54222SNaoya Horiguchi 		goto unlock;
7214bcc54222SNaoya Horiguchi 	}
72156aa3a920SSidhartha Kumar 	folio_clear_hugetlb_migratable(folio);
72166aa3a920SSidhartha Kumar 	list_move_tail(&folio->lru, list);
7217bcc54222SNaoya Horiguchi unlock:
7218db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
7219bcc54222SNaoya Horiguchi 	return ret;
722031caf665SNaoya Horiguchi }
722131caf665SNaoya Horiguchi 
get_hwpoison_hugetlb_folio(struct folio * folio,bool * hugetlb,bool unpoison)722204bac040SSidhartha Kumar int get_hwpoison_hugetlb_folio(struct folio *folio, bool *hugetlb, bool unpoison)
722325182f05SNaoya Horiguchi {
722425182f05SNaoya Horiguchi 	int ret = 0;
722525182f05SNaoya Horiguchi 
722625182f05SNaoya Horiguchi 	*hugetlb = false;
722725182f05SNaoya Horiguchi 	spin_lock_irq(&hugetlb_lock);
722804bac040SSidhartha Kumar 	if (folio_test_hugetlb(folio)) {
722925182f05SNaoya Horiguchi 		*hugetlb = true;
723004bac040SSidhartha Kumar 		if (folio_test_hugetlb_freed(folio))
7231b283d983SNaoya Horiguchi 			ret = 0;
723204bac040SSidhartha Kumar 		else if (folio_test_hugetlb_migratable(folio) || unpoison)
723304bac040SSidhartha Kumar 			ret = folio_try_get(folio);
72340ed950d1SNaoya Horiguchi 		else
72350ed950d1SNaoya Horiguchi 			ret = -EBUSY;
723625182f05SNaoya Horiguchi 	}
723725182f05SNaoya Horiguchi 	spin_unlock_irq(&hugetlb_lock);
723825182f05SNaoya Horiguchi 	return ret;
723925182f05SNaoya Horiguchi }
724025182f05SNaoya Horiguchi 
get_huge_page_for_hwpoison(unsigned long pfn,int flags,bool * migratable_cleared)7241e591ef7dSNaoya Horiguchi int get_huge_page_for_hwpoison(unsigned long pfn, int flags,
7242e591ef7dSNaoya Horiguchi 				bool *migratable_cleared)
7243405ce051SNaoya Horiguchi {
7244405ce051SNaoya Horiguchi 	int ret;
7245405ce051SNaoya Horiguchi 
7246405ce051SNaoya Horiguchi 	spin_lock_irq(&hugetlb_lock);
7247e591ef7dSNaoya Horiguchi 	ret = __get_huge_page_for_hwpoison(pfn, flags, migratable_cleared);
7248405ce051SNaoya Horiguchi 	spin_unlock_irq(&hugetlb_lock);
7249405ce051SNaoya Horiguchi 	return ret;
7250405ce051SNaoya Horiguchi }
7251405ce051SNaoya Horiguchi 
folio_putback_active_hugetlb(struct folio * folio)7252ea8e72f4SSidhartha Kumar void folio_putback_active_hugetlb(struct folio *folio)
725331caf665SNaoya Horiguchi {
7254db71ef79SMike Kravetz 	spin_lock_irq(&hugetlb_lock);
7255ea8e72f4SSidhartha Kumar 	folio_set_hugetlb_migratable(folio);
7256ea8e72f4SSidhartha Kumar 	list_move_tail(&folio->lru, &(folio_hstate(folio))->hugepage_activelist);
7257db71ef79SMike Kravetz 	spin_unlock_irq(&hugetlb_lock);
7258ea8e72f4SSidhartha Kumar 	folio_put(folio);
725931caf665SNaoya Horiguchi }
7260ab5ac90aSMichal Hocko 
move_hugetlb_state(struct folio * old_folio,struct folio * new_folio,int reason)7261345c62d1SSidhartha Kumar void move_hugetlb_state(struct folio *old_folio, struct folio *new_folio, int reason)
7262ab5ac90aSMichal Hocko {
7263345c62d1SSidhartha Kumar 	struct hstate *h = folio_hstate(old_folio);
7264ab5ac90aSMichal Hocko 
7265345c62d1SSidhartha Kumar 	hugetlb_cgroup_migrate(old_folio, new_folio);
7266345c62d1SSidhartha Kumar 	set_page_owner_migrate_reason(&new_folio->page, reason);
7267ab5ac90aSMichal Hocko 
7268ab5ac90aSMichal Hocko 	/*
7269345c62d1SSidhartha Kumar 	 * transfer temporary state of the new hugetlb folio. This is
7270ab5ac90aSMichal Hocko 	 * reverse to other transitions because the newpage is going to
7271ab5ac90aSMichal Hocko 	 * be final while the old one will be freed so it takes over
7272ab5ac90aSMichal Hocko 	 * the temporary status.
7273ab5ac90aSMichal Hocko 	 *
7274ab5ac90aSMichal Hocko 	 * Also note that we have to transfer the per-node surplus state
7275ab5ac90aSMichal Hocko 	 * here as well otherwise the global surplus count will not match
7276ab5ac90aSMichal Hocko 	 * the per-node's.
7277ab5ac90aSMichal Hocko 	 */
7278345c62d1SSidhartha Kumar 	if (folio_test_hugetlb_temporary(new_folio)) {
7279345c62d1SSidhartha Kumar 		int old_nid = folio_nid(old_folio);
7280345c62d1SSidhartha Kumar 		int new_nid = folio_nid(new_folio);
7281ab5ac90aSMichal Hocko 
7282345c62d1SSidhartha Kumar 		folio_set_hugetlb_temporary(old_folio);
7283345c62d1SSidhartha Kumar 		folio_clear_hugetlb_temporary(new_folio);
7284345c62d1SSidhartha Kumar 
7285ab5ac90aSMichal Hocko 
72865af1ab1dSMiaohe Lin 		/*
72875af1ab1dSMiaohe Lin 		 * There is no need to transfer the per-node surplus state
72885af1ab1dSMiaohe Lin 		 * when we do not cross the node.
72895af1ab1dSMiaohe Lin 		 */
72905af1ab1dSMiaohe Lin 		if (new_nid == old_nid)
72915af1ab1dSMiaohe Lin 			return;
7292db71ef79SMike Kravetz 		spin_lock_irq(&hugetlb_lock);
7293ab5ac90aSMichal Hocko 		if (h->surplus_huge_pages_node[old_nid]) {
7294ab5ac90aSMichal Hocko 			h->surplus_huge_pages_node[old_nid]--;
7295ab5ac90aSMichal Hocko 			h->surplus_huge_pages_node[new_nid]++;
7296ab5ac90aSMichal Hocko 		}
7297db71ef79SMike Kravetz 		spin_unlock_irq(&hugetlb_lock);
7298ab5ac90aSMichal Hocko 	}
7299ab5ac90aSMichal Hocko }
7300cf11e85fSRoman Gushchin 
hugetlb_unshare_pmds(struct vm_area_struct * vma,unsigned long start,unsigned long end)7301b30c14cdSJames Houghton static void hugetlb_unshare_pmds(struct vm_area_struct *vma,
7302b30c14cdSJames Houghton 				   unsigned long start,
7303b30c14cdSJames Houghton 				   unsigned long end)
73046dfeaff9SPeter Xu {
73056dfeaff9SPeter Xu 	struct hstate *h = hstate_vma(vma);
73066dfeaff9SPeter Xu 	unsigned long sz = huge_page_size(h);
73076dfeaff9SPeter Xu 	struct mm_struct *mm = vma->vm_mm;
73086dfeaff9SPeter Xu 	struct mmu_notifier_range range;
7309b30c14cdSJames Houghton 	unsigned long address;
73106dfeaff9SPeter Xu 	spinlock_t *ptl;
73116dfeaff9SPeter Xu 	pte_t *ptep;
73126dfeaff9SPeter Xu 
73136dfeaff9SPeter Xu 	if (!(vma->vm_flags & VM_MAYSHARE))
73146dfeaff9SPeter Xu 		return;
73156dfeaff9SPeter Xu 
73166dfeaff9SPeter Xu 	if (start >= end)
73176dfeaff9SPeter Xu 		return;
73186dfeaff9SPeter Xu 
73199c8bbfacSBaolin Wang 	flush_cache_range(vma, start, end);
73206dfeaff9SPeter Xu 	/*
73216dfeaff9SPeter Xu 	 * No need to call adjust_range_if_pmd_sharing_possible(), because
73226dfeaff9SPeter Xu 	 * we have already done the PUD_SIZE alignment.
73236dfeaff9SPeter Xu 	 */
73247d4a8be0SAlistair Popple 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
73256dfeaff9SPeter Xu 				start, end);
73266dfeaff9SPeter Xu 	mmu_notifier_invalidate_range_start(&range);
732740549ba8SMike Kravetz 	hugetlb_vma_lock_write(vma);
73286dfeaff9SPeter Xu 	i_mmap_lock_write(vma->vm_file->f_mapping);
73296dfeaff9SPeter Xu 	for (address = start; address < end; address += PUD_SIZE) {
73309c67a207SPeter Xu 		ptep = hugetlb_walk(vma, address, sz);
73316dfeaff9SPeter Xu 		if (!ptep)
73326dfeaff9SPeter Xu 			continue;
73336dfeaff9SPeter Xu 		ptl = huge_pte_lock(h, mm, ptep);
73344ddb4d91SMike Kravetz 		huge_pmd_unshare(mm, vma, address, ptep);
73356dfeaff9SPeter Xu 		spin_unlock(ptl);
73366dfeaff9SPeter Xu 	}
73376dfeaff9SPeter Xu 	flush_hugetlb_tlb_range(vma, start, end);
73386dfeaff9SPeter Xu 	i_mmap_unlock_write(vma->vm_file->f_mapping);
733940549ba8SMike Kravetz 	hugetlb_vma_unlock_write(vma);
73406dfeaff9SPeter Xu 	/*
73411af5a810SAlistair Popple 	 * No need to call mmu_notifier_arch_invalidate_secondary_tlbs(), see
7342ee65728eSMike Rapoport 	 * Documentation/mm/mmu_notifier.rst.
73436dfeaff9SPeter Xu 	 */
73446dfeaff9SPeter Xu 	mmu_notifier_invalidate_range_end(&range);
73456dfeaff9SPeter Xu }
73466dfeaff9SPeter Xu 
7347b30c14cdSJames Houghton /*
7348b30c14cdSJames Houghton  * This function will unconditionally remove all the shared pmd pgtable entries
7349b30c14cdSJames Houghton  * within the specific vma for a hugetlbfs memory range.
7350b30c14cdSJames Houghton  */
hugetlb_unshare_all_pmds(struct vm_area_struct * vma)7351b30c14cdSJames Houghton void hugetlb_unshare_all_pmds(struct vm_area_struct *vma)
7352b30c14cdSJames Houghton {
7353b30c14cdSJames Houghton 	hugetlb_unshare_pmds(vma, ALIGN(vma->vm_start, PUD_SIZE),
7354b30c14cdSJames Houghton 			ALIGN_DOWN(vma->vm_end, PUD_SIZE));
7355b30c14cdSJames Houghton }
7356b30c14cdSJames Houghton 
7357cf11e85fSRoman Gushchin #ifdef CONFIG_CMA
7358cf11e85fSRoman Gushchin static bool cma_reserve_called __initdata;
7359cf11e85fSRoman Gushchin 
cmdline_parse_hugetlb_cma(char * p)7360cf11e85fSRoman Gushchin static int __init cmdline_parse_hugetlb_cma(char *p)
7361cf11e85fSRoman Gushchin {
736238e719abSBaolin Wang 	int nid, count = 0;
736338e719abSBaolin Wang 	unsigned long tmp;
736438e719abSBaolin Wang 	char *s = p;
736538e719abSBaolin Wang 
736638e719abSBaolin Wang 	while (*s) {
736738e719abSBaolin Wang 		if (sscanf(s, "%lu%n", &tmp, &count) != 1)
736838e719abSBaolin Wang 			break;
736938e719abSBaolin Wang 
737038e719abSBaolin Wang 		if (s[count] == ':') {
7371f9317f77SMike Kravetz 			if (tmp >= MAX_NUMNODES)
737238e719abSBaolin Wang 				break;
7373f9317f77SMike Kravetz 			nid = array_index_nospec(tmp, MAX_NUMNODES);
737438e719abSBaolin Wang 
737538e719abSBaolin Wang 			s += count + 1;
737638e719abSBaolin Wang 			tmp = memparse(s, &s);
737738e719abSBaolin Wang 			hugetlb_cma_size_in_node[nid] = tmp;
737838e719abSBaolin Wang 			hugetlb_cma_size += tmp;
737938e719abSBaolin Wang 
738038e719abSBaolin Wang 			/*
738138e719abSBaolin Wang 			 * Skip the separator if have one, otherwise
738238e719abSBaolin Wang 			 * break the parsing.
738338e719abSBaolin Wang 			 */
738438e719abSBaolin Wang 			if (*s == ',')
738538e719abSBaolin Wang 				s++;
738638e719abSBaolin Wang 			else
738738e719abSBaolin Wang 				break;
738838e719abSBaolin Wang 		} else {
7389cf11e85fSRoman Gushchin 			hugetlb_cma_size = memparse(p, &p);
739038e719abSBaolin Wang 			break;
739138e719abSBaolin Wang 		}
739238e719abSBaolin Wang 	}
739338e719abSBaolin Wang 
7394cf11e85fSRoman Gushchin 	return 0;
7395cf11e85fSRoman Gushchin }
7396cf11e85fSRoman Gushchin 
7397cf11e85fSRoman Gushchin early_param("hugetlb_cma", cmdline_parse_hugetlb_cma);
7398cf11e85fSRoman Gushchin 
hugetlb_cma_reserve(int order)7399cf11e85fSRoman Gushchin void __init hugetlb_cma_reserve(int order)
7400cf11e85fSRoman Gushchin {
7401cf11e85fSRoman Gushchin 	unsigned long size, reserved, per_node;
740238e719abSBaolin Wang 	bool node_specific_cma_alloc = false;
7403cf11e85fSRoman Gushchin 	int nid;
7404cf11e85fSRoman Gushchin 
7405cf11e85fSRoman Gushchin 	cma_reserve_called = true;
7406cf11e85fSRoman Gushchin 
7407cf11e85fSRoman Gushchin 	if (!hugetlb_cma_size)
7408cf11e85fSRoman Gushchin 		return;
7409cf11e85fSRoman Gushchin 
741038e719abSBaolin Wang 	for (nid = 0; nid < MAX_NUMNODES; nid++) {
741138e719abSBaolin Wang 		if (hugetlb_cma_size_in_node[nid] == 0)
741238e719abSBaolin Wang 			continue;
741338e719abSBaolin Wang 
741430a51400SPeng Liu 		if (!node_online(nid)) {
741538e719abSBaolin Wang 			pr_warn("hugetlb_cma: invalid node %d specified\n", nid);
741638e719abSBaolin Wang 			hugetlb_cma_size -= hugetlb_cma_size_in_node[nid];
741738e719abSBaolin Wang 			hugetlb_cma_size_in_node[nid] = 0;
741838e719abSBaolin Wang 			continue;
741938e719abSBaolin Wang 		}
742038e719abSBaolin Wang 
742138e719abSBaolin Wang 		if (hugetlb_cma_size_in_node[nid] < (PAGE_SIZE << order)) {
742238e719abSBaolin Wang 			pr_warn("hugetlb_cma: cma area of node %d should be at least %lu MiB\n",
742338e719abSBaolin Wang 				nid, (PAGE_SIZE << order) / SZ_1M);
742438e719abSBaolin Wang 			hugetlb_cma_size -= hugetlb_cma_size_in_node[nid];
742538e719abSBaolin Wang 			hugetlb_cma_size_in_node[nid] = 0;
742638e719abSBaolin Wang 		} else {
742738e719abSBaolin Wang 			node_specific_cma_alloc = true;
742838e719abSBaolin Wang 		}
742938e719abSBaolin Wang 	}
743038e719abSBaolin Wang 
743138e719abSBaolin Wang 	/* Validate the CMA size again in case some invalid nodes specified. */
743238e719abSBaolin Wang 	if (!hugetlb_cma_size)
743338e719abSBaolin Wang 		return;
743438e719abSBaolin Wang 
7435cf11e85fSRoman Gushchin 	if (hugetlb_cma_size < (PAGE_SIZE << order)) {
7436cf11e85fSRoman Gushchin 		pr_warn("hugetlb_cma: cma area should be at least %lu MiB\n",
7437cf11e85fSRoman Gushchin 			(PAGE_SIZE << order) / SZ_1M);
7438a01f4390SMike Kravetz 		hugetlb_cma_size = 0;
7439cf11e85fSRoman Gushchin 		return;
7440cf11e85fSRoman Gushchin 	}
7441cf11e85fSRoman Gushchin 
744238e719abSBaolin Wang 	if (!node_specific_cma_alloc) {
7443cf11e85fSRoman Gushchin 		/*
7444cf11e85fSRoman Gushchin 		 * If 3 GB area is requested on a machine with 4 numa nodes,
7445cf11e85fSRoman Gushchin 		 * let's allocate 1 GB on first three nodes and ignore the last one.
7446cf11e85fSRoman Gushchin 		 */
7447cf11e85fSRoman Gushchin 		per_node = DIV_ROUND_UP(hugetlb_cma_size, nr_online_nodes);
7448cf11e85fSRoman Gushchin 		pr_info("hugetlb_cma: reserve %lu MiB, up to %lu MiB per node\n",
7449cf11e85fSRoman Gushchin 			hugetlb_cma_size / SZ_1M, per_node / SZ_1M);
745038e719abSBaolin Wang 	}
7451cf11e85fSRoman Gushchin 
7452cf11e85fSRoman Gushchin 	reserved = 0;
745330a51400SPeng Liu 	for_each_online_node(nid) {
7454cf11e85fSRoman Gushchin 		int res;
74552281f797SBarry Song 		char name[CMA_MAX_NAME];
7456cf11e85fSRoman Gushchin 
745738e719abSBaolin Wang 		if (node_specific_cma_alloc) {
745838e719abSBaolin Wang 			if (hugetlb_cma_size_in_node[nid] == 0)
745938e719abSBaolin Wang 				continue;
746038e719abSBaolin Wang 
746138e719abSBaolin Wang 			size = hugetlb_cma_size_in_node[nid];
746238e719abSBaolin Wang 		} else {
7463cf11e85fSRoman Gushchin 			size = min(per_node, hugetlb_cma_size - reserved);
746438e719abSBaolin Wang 		}
746538e719abSBaolin Wang 
7466cf11e85fSRoman Gushchin 		size = round_up(size, PAGE_SIZE << order);
7467cf11e85fSRoman Gushchin 
74682281f797SBarry Song 		snprintf(name, sizeof(name), "hugetlb%d", nid);
7469a01f4390SMike Kravetz 		/*
7470a01f4390SMike Kravetz 		 * Note that 'order per bit' is based on smallest size that
7471a01f4390SMike Kravetz 		 * may be returned to CMA allocator in the case of
7472a01f4390SMike Kravetz 		 * huge page demotion.
7473a01f4390SMike Kravetz 		 */
7474a01f4390SMike Kravetz 		res = cma_declare_contiguous_nid(0, size, 0,
7475a01f4390SMike Kravetz 					PAGE_SIZE << HUGETLB_PAGE_ORDER,
7476cb3ea768SFrank van der Linden 					HUGETLB_PAGE_ORDER, false, name,
7477cf11e85fSRoman Gushchin 					&hugetlb_cma[nid], nid);
7478cf11e85fSRoman Gushchin 		if (res) {
7479cf11e85fSRoman Gushchin 			pr_warn("hugetlb_cma: reservation failed: err %d, node %d",
7480cf11e85fSRoman Gushchin 				res, nid);
7481cf11e85fSRoman Gushchin 			continue;
7482cf11e85fSRoman Gushchin 		}
7483cf11e85fSRoman Gushchin 
7484cf11e85fSRoman Gushchin 		reserved += size;
7485cf11e85fSRoman Gushchin 		pr_info("hugetlb_cma: reserved %lu MiB on node %d\n",
7486cf11e85fSRoman Gushchin 			size / SZ_1M, nid);
7487cf11e85fSRoman Gushchin 
7488cf11e85fSRoman Gushchin 		if (reserved >= hugetlb_cma_size)
7489cf11e85fSRoman Gushchin 			break;
7490cf11e85fSRoman Gushchin 	}
7491a01f4390SMike Kravetz 
7492a01f4390SMike Kravetz 	if (!reserved)
7493a01f4390SMike Kravetz 		/*
7494a01f4390SMike Kravetz 		 * hugetlb_cma_size is used to determine if allocations from
7495a01f4390SMike Kravetz 		 * cma are possible.  Set to zero if no cma regions are set up.
7496a01f4390SMike Kravetz 		 */
7497a01f4390SMike Kravetz 		hugetlb_cma_size = 0;
7498cf11e85fSRoman Gushchin }
7499cf11e85fSRoman Gushchin 
hugetlb_cma_check(void)7500263b8998SMiaohe Lin static void __init hugetlb_cma_check(void)
7501cf11e85fSRoman Gushchin {
7502cf11e85fSRoman Gushchin 	if (!hugetlb_cma_size || cma_reserve_called)
7503cf11e85fSRoman Gushchin 		return;
7504cf11e85fSRoman Gushchin 
7505cf11e85fSRoman Gushchin 	pr_warn("hugetlb_cma: the option isn't supported by current arch\n");
7506cf11e85fSRoman Gushchin }
7507cf11e85fSRoman Gushchin 
7508cf11e85fSRoman Gushchin #endif /* CONFIG_CMA */
7509