xref: /openbmc/linux/mm/hugetlb.c (revision faf53def)
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>
2263489f8eSMike Kravetz #include <linux/mmdebug.h>
23174cd4b1SIngo Molnar #include <linux/sched/signal.h>
240fe6e20bSNaoya Horiguchi #include <linux/rmap.h>
25c6247f72SMatthew Wilcox #include <linux/string_helpers.h>
26fd6a03edSNaoya Horiguchi #include <linux/swap.h>
27fd6a03edSNaoya Horiguchi #include <linux/swapops.h>
288382d914SDavidlohr Bueso #include <linux/jhash.h>
2998fa15f3SAnshuman Khandual #include <linux/numa.h>
30d6606683SLinus Torvalds 
3163551ae0SDavid Gibson #include <asm/page.h>
3263551ae0SDavid Gibson #include <asm/pgtable.h>
3324669e58SAneesh Kumar K.V #include <asm/tlb.h>
3463551ae0SDavid Gibson 
3524669e58SAneesh Kumar K.V #include <linux/io.h>
3663551ae0SDavid Gibson #include <linux/hugetlb.h>
379dd540e2SAneesh Kumar K.V #include <linux/hugetlb_cgroup.h>
389a305230SLee Schermerhorn #include <linux/node.h>
391a1aad8aSMike Kravetz #include <linux/userfaultfd_k.h>
40ab5ac90aSMichal Hocko #include <linux/page_owner.h>
417835e98bSNick Piggin #include "internal.h"
421da177e4SLinus Torvalds 
43c3f38a38SAneesh Kumar K.V int hugetlb_max_hstate __read_mostly;
44e5ff2159SAndi Kleen unsigned int default_hstate_idx;
45e5ff2159SAndi Kleen struct hstate hstates[HUGE_MAX_HSTATE];
46641844f5SNaoya Horiguchi /*
47641844f5SNaoya Horiguchi  * Minimum page order among possible hugepage sizes, set to a proper value
48641844f5SNaoya Horiguchi  * at boot time.
49641844f5SNaoya Horiguchi  */
50641844f5SNaoya Horiguchi static unsigned int minimum_order __read_mostly = UINT_MAX;
51e5ff2159SAndi Kleen 
5253ba51d2SJon Tollefson __initdata LIST_HEAD(huge_boot_pages);
5353ba51d2SJon Tollefson 
54e5ff2159SAndi Kleen /* for command line parsing */
55e5ff2159SAndi Kleen static struct hstate * __initdata parsed_hstate;
56e5ff2159SAndi Kleen static unsigned long __initdata default_hstate_max_huge_pages;
57e11bfbfcSNick Piggin static unsigned long __initdata default_hstate_size;
589fee021dSVaishali Thakkar static bool __initdata parsed_valid_hugepagesz = true;
59e5ff2159SAndi Kleen 
603935baa9SDavid Gibson /*
6131caf665SNaoya Horiguchi  * Protects updates to hugepage_freelists, hugepage_activelist, nr_huge_pages,
6231caf665SNaoya Horiguchi  * free_huge_pages, and surplus_huge_pages.
633935baa9SDavid Gibson  */
64c3f38a38SAneesh Kumar K.V DEFINE_SPINLOCK(hugetlb_lock);
650bd0f9fbSEric Paris 
668382d914SDavidlohr Bueso /*
678382d914SDavidlohr Bueso  * Serializes faults on the same logical page.  This is used to
688382d914SDavidlohr Bueso  * prevent spurious OOMs when the hugepage pool is fully utilized.
698382d914SDavidlohr Bueso  */
708382d914SDavidlohr Bueso static int num_fault_mutexes;
71c672c7f2SMike Kravetz struct mutex *hugetlb_fault_mutex_table ____cacheline_aligned_in_smp;
728382d914SDavidlohr Bueso 
737ca02d0aSMike Kravetz /* Forward declaration */
747ca02d0aSMike Kravetz static int hugetlb_acct_memory(struct hstate *h, long delta);
757ca02d0aSMike Kravetz 
7690481622SDavid Gibson static inline void unlock_or_release_subpool(struct hugepage_subpool *spool)
7790481622SDavid Gibson {
7890481622SDavid Gibson 	bool free = (spool->count == 0) && (spool->used_hpages == 0);
7990481622SDavid Gibson 
8090481622SDavid Gibson 	spin_unlock(&spool->lock);
8190481622SDavid Gibson 
8290481622SDavid Gibson 	/* If no pages are used, and no other handles to the subpool
837ca02d0aSMike Kravetz 	 * remain, give up any reservations mased on minimum size and
847ca02d0aSMike Kravetz 	 * free the subpool */
857ca02d0aSMike Kravetz 	if (free) {
867ca02d0aSMike Kravetz 		if (spool->min_hpages != -1)
877ca02d0aSMike Kravetz 			hugetlb_acct_memory(spool->hstate,
887ca02d0aSMike Kravetz 						-spool->min_hpages);
8990481622SDavid Gibson 		kfree(spool);
9090481622SDavid Gibson 	}
917ca02d0aSMike Kravetz }
9290481622SDavid Gibson 
937ca02d0aSMike Kravetz struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages,
947ca02d0aSMike Kravetz 						long min_hpages)
9590481622SDavid Gibson {
9690481622SDavid Gibson 	struct hugepage_subpool *spool;
9790481622SDavid Gibson 
98c6a91820SMike Kravetz 	spool = kzalloc(sizeof(*spool), GFP_KERNEL);
9990481622SDavid Gibson 	if (!spool)
10090481622SDavid Gibson 		return NULL;
10190481622SDavid Gibson 
10290481622SDavid Gibson 	spin_lock_init(&spool->lock);
10390481622SDavid Gibson 	spool->count = 1;
1047ca02d0aSMike Kravetz 	spool->max_hpages = max_hpages;
1057ca02d0aSMike Kravetz 	spool->hstate = h;
1067ca02d0aSMike Kravetz 	spool->min_hpages = min_hpages;
1077ca02d0aSMike Kravetz 
1087ca02d0aSMike Kravetz 	if (min_hpages != -1 && hugetlb_acct_memory(h, min_hpages)) {
1097ca02d0aSMike Kravetz 		kfree(spool);
1107ca02d0aSMike Kravetz 		return NULL;
1117ca02d0aSMike Kravetz 	}
1127ca02d0aSMike Kravetz 	spool->rsv_hpages = min_hpages;
11390481622SDavid Gibson 
11490481622SDavid Gibson 	return spool;
11590481622SDavid Gibson }
11690481622SDavid Gibson 
11790481622SDavid Gibson void hugepage_put_subpool(struct hugepage_subpool *spool)
11890481622SDavid Gibson {
11990481622SDavid Gibson 	spin_lock(&spool->lock);
12090481622SDavid Gibson 	BUG_ON(!spool->count);
12190481622SDavid Gibson 	spool->count--;
12290481622SDavid Gibson 	unlock_or_release_subpool(spool);
12390481622SDavid Gibson }
12490481622SDavid Gibson 
1251c5ecae3SMike Kravetz /*
1261c5ecae3SMike Kravetz  * Subpool accounting for allocating and reserving pages.
1271c5ecae3SMike Kravetz  * Return -ENOMEM if there are not enough resources to satisfy the
1281c5ecae3SMike Kravetz  * the request.  Otherwise, return the number of pages by which the
1291c5ecae3SMike Kravetz  * global pools must be adjusted (upward).  The returned value may
1301c5ecae3SMike Kravetz  * only be different than the passed value (delta) in the case where
1311c5ecae3SMike Kravetz  * a subpool minimum size must be manitained.
1321c5ecae3SMike Kravetz  */
1331c5ecae3SMike Kravetz static long hugepage_subpool_get_pages(struct hugepage_subpool *spool,
13490481622SDavid Gibson 				      long delta)
13590481622SDavid Gibson {
1361c5ecae3SMike Kravetz 	long ret = delta;
13790481622SDavid Gibson 
13890481622SDavid Gibson 	if (!spool)
1391c5ecae3SMike Kravetz 		return ret;
14090481622SDavid Gibson 
14190481622SDavid Gibson 	spin_lock(&spool->lock);
14290481622SDavid Gibson 
1431c5ecae3SMike Kravetz 	if (spool->max_hpages != -1) {		/* maximum size accounting */
1441c5ecae3SMike Kravetz 		if ((spool->used_hpages + delta) <= spool->max_hpages)
1451c5ecae3SMike Kravetz 			spool->used_hpages += delta;
1461c5ecae3SMike Kravetz 		else {
1471c5ecae3SMike Kravetz 			ret = -ENOMEM;
1481c5ecae3SMike Kravetz 			goto unlock_ret;
1491c5ecae3SMike Kravetz 		}
1501c5ecae3SMike Kravetz 	}
1511c5ecae3SMike Kravetz 
15209a95e29SMike Kravetz 	/* minimum size accounting */
15309a95e29SMike Kravetz 	if (spool->min_hpages != -1 && spool->rsv_hpages) {
1541c5ecae3SMike Kravetz 		if (delta > spool->rsv_hpages) {
1551c5ecae3SMike Kravetz 			/*
1561c5ecae3SMike Kravetz 			 * Asking for more reserves than those already taken on
1571c5ecae3SMike Kravetz 			 * behalf of subpool.  Return difference.
1581c5ecae3SMike Kravetz 			 */
1591c5ecae3SMike Kravetz 			ret = delta - spool->rsv_hpages;
1601c5ecae3SMike Kravetz 			spool->rsv_hpages = 0;
1611c5ecae3SMike Kravetz 		} else {
1621c5ecae3SMike Kravetz 			ret = 0;	/* reserves already accounted for */
1631c5ecae3SMike Kravetz 			spool->rsv_hpages -= delta;
1641c5ecae3SMike Kravetz 		}
1651c5ecae3SMike Kravetz 	}
1661c5ecae3SMike Kravetz 
1671c5ecae3SMike Kravetz unlock_ret:
1681c5ecae3SMike Kravetz 	spin_unlock(&spool->lock);
16990481622SDavid Gibson 	return ret;
17090481622SDavid Gibson }
17190481622SDavid Gibson 
1721c5ecae3SMike Kravetz /*
1731c5ecae3SMike Kravetz  * Subpool accounting for freeing and unreserving pages.
1741c5ecae3SMike Kravetz  * Return the number of global page reservations that must be dropped.
1751c5ecae3SMike Kravetz  * The return value may only be different than the passed value (delta)
1761c5ecae3SMike Kravetz  * in the case where a subpool minimum size must be maintained.
1771c5ecae3SMike Kravetz  */
1781c5ecae3SMike Kravetz static long hugepage_subpool_put_pages(struct hugepage_subpool *spool,
17990481622SDavid Gibson 				       long delta)
18090481622SDavid Gibson {
1811c5ecae3SMike Kravetz 	long ret = delta;
1821c5ecae3SMike Kravetz 
18390481622SDavid Gibson 	if (!spool)
1841c5ecae3SMike Kravetz 		return delta;
18590481622SDavid Gibson 
18690481622SDavid Gibson 	spin_lock(&spool->lock);
1871c5ecae3SMike Kravetz 
1881c5ecae3SMike Kravetz 	if (spool->max_hpages != -1)		/* maximum size accounting */
18990481622SDavid Gibson 		spool->used_hpages -= delta;
1901c5ecae3SMike Kravetz 
19109a95e29SMike Kravetz 	 /* minimum size accounting */
19209a95e29SMike Kravetz 	if (spool->min_hpages != -1 && spool->used_hpages < spool->min_hpages) {
1931c5ecae3SMike Kravetz 		if (spool->rsv_hpages + delta <= spool->min_hpages)
1941c5ecae3SMike Kravetz 			ret = 0;
1951c5ecae3SMike Kravetz 		else
1961c5ecae3SMike Kravetz 			ret = spool->rsv_hpages + delta - spool->min_hpages;
1971c5ecae3SMike Kravetz 
1981c5ecae3SMike Kravetz 		spool->rsv_hpages += delta;
1991c5ecae3SMike Kravetz 		if (spool->rsv_hpages > spool->min_hpages)
2001c5ecae3SMike Kravetz 			spool->rsv_hpages = spool->min_hpages;
2011c5ecae3SMike Kravetz 	}
2021c5ecae3SMike Kravetz 
2031c5ecae3SMike Kravetz 	/*
2041c5ecae3SMike Kravetz 	 * If hugetlbfs_put_super couldn't free spool due to an outstanding
2051c5ecae3SMike Kravetz 	 * quota reference, free it now.
2061c5ecae3SMike Kravetz 	 */
20790481622SDavid Gibson 	unlock_or_release_subpool(spool);
2081c5ecae3SMike Kravetz 
2091c5ecae3SMike Kravetz 	return ret;
21090481622SDavid Gibson }
21190481622SDavid Gibson 
21290481622SDavid Gibson static inline struct hugepage_subpool *subpool_inode(struct inode *inode)
21390481622SDavid Gibson {
21490481622SDavid Gibson 	return HUGETLBFS_SB(inode->i_sb)->spool;
21590481622SDavid Gibson }
21690481622SDavid Gibson 
21790481622SDavid Gibson static inline struct hugepage_subpool *subpool_vma(struct vm_area_struct *vma)
21890481622SDavid Gibson {
219496ad9aaSAl Viro 	return subpool_inode(file_inode(vma->vm_file));
22090481622SDavid Gibson }
22190481622SDavid Gibson 
222e7c4b0bfSAndy Whitcroft /*
22396822904SAndy Whitcroft  * Region tracking -- allows tracking of reservations and instantiated pages
22496822904SAndy Whitcroft  *                    across the pages in a mapping.
22584afd99bSAndy Whitcroft  *
2261dd308a7SMike Kravetz  * The region data structures are embedded into a resv_map and protected
2271dd308a7SMike Kravetz  * by a resv_map's lock.  The set of regions within the resv_map represent
2281dd308a7SMike Kravetz  * reservations for huge pages, or huge pages that have already been
2291dd308a7SMike Kravetz  * instantiated within the map.  The from and to elements are huge page
2301dd308a7SMike Kravetz  * indicies into the associated mapping.  from indicates the starting index
2311dd308a7SMike Kravetz  * of the region.  to represents the first index past the end of  the region.
2321dd308a7SMike Kravetz  *
2331dd308a7SMike Kravetz  * For example, a file region structure with from == 0 and to == 4 represents
2341dd308a7SMike Kravetz  * four huge pages in a mapping.  It is important to note that the to element
2351dd308a7SMike Kravetz  * represents the first element past the end of the region. This is used in
2361dd308a7SMike Kravetz  * arithmetic as 4(to) - 0(from) = 4 huge pages in the region.
2371dd308a7SMike Kravetz  *
2381dd308a7SMike Kravetz  * Interval notation of the form [from, to) will be used to indicate that
2391dd308a7SMike Kravetz  * the endpoint from is inclusive and to is exclusive.
24096822904SAndy Whitcroft  */
24196822904SAndy Whitcroft struct file_region {
24296822904SAndy Whitcroft 	struct list_head link;
24396822904SAndy Whitcroft 	long from;
24496822904SAndy Whitcroft 	long to;
24596822904SAndy Whitcroft };
24696822904SAndy Whitcroft 
2471dd308a7SMike Kravetz /*
2481dd308a7SMike Kravetz  * Add the huge page range represented by [f, t) to the reserve
2495e911373SMike Kravetz  * map.  In the normal case, existing regions will be expanded
2505e911373SMike Kravetz  * to accommodate the specified range.  Sufficient regions should
2515e911373SMike Kravetz  * exist for expansion due to the previous call to region_chg
2525e911373SMike Kravetz  * with the same range.  However, it is possible that region_del
2535e911373SMike Kravetz  * could have been called after region_chg and modifed the map
2545e911373SMike Kravetz  * in such a way that no region exists to be expanded.  In this
2555e911373SMike Kravetz  * case, pull a region descriptor from the cache associated with
2565e911373SMike Kravetz  * the map and use that for the new range.
257cf3ad20bSMike Kravetz  *
258cf3ad20bSMike Kravetz  * Return the number of new huge pages added to the map.  This
259cf3ad20bSMike Kravetz  * number is greater than or equal to zero.
2601dd308a7SMike Kravetz  */
2611406ec9bSJoonsoo Kim static long region_add(struct resv_map *resv, long f, long t)
26296822904SAndy Whitcroft {
2631406ec9bSJoonsoo Kim 	struct list_head *head = &resv->regions;
26496822904SAndy Whitcroft 	struct file_region *rg, *nrg, *trg;
265cf3ad20bSMike Kravetz 	long add = 0;
26696822904SAndy Whitcroft 
2677b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
26896822904SAndy Whitcroft 	/* Locate the region we are either in or before. */
26996822904SAndy Whitcroft 	list_for_each_entry(rg, head, link)
27096822904SAndy Whitcroft 		if (f <= rg->to)
27196822904SAndy Whitcroft 			break;
27296822904SAndy Whitcroft 
2735e911373SMike Kravetz 	/*
2745e911373SMike Kravetz 	 * If no region exists which can be expanded to include the
2755e911373SMike Kravetz 	 * specified range, the list must have been modified by an
2765e911373SMike Kravetz 	 * interleving call to region_del().  Pull a region descriptor
2775e911373SMike Kravetz 	 * from the cache and use it for this range.
2785e911373SMike Kravetz 	 */
2795e911373SMike Kravetz 	if (&rg->link == head || t < rg->from) {
2805e911373SMike Kravetz 		VM_BUG_ON(resv->region_cache_count <= 0);
2815e911373SMike Kravetz 
2825e911373SMike Kravetz 		resv->region_cache_count--;
2835e911373SMike Kravetz 		nrg = list_first_entry(&resv->region_cache, struct file_region,
2845e911373SMike Kravetz 					link);
2855e911373SMike Kravetz 		list_del(&nrg->link);
2865e911373SMike Kravetz 
2875e911373SMike Kravetz 		nrg->from = f;
2885e911373SMike Kravetz 		nrg->to = t;
2895e911373SMike Kravetz 		list_add(&nrg->link, rg->link.prev);
2905e911373SMike Kravetz 
2915e911373SMike Kravetz 		add += t - f;
2925e911373SMike Kravetz 		goto out_locked;
2935e911373SMike Kravetz 	}
2945e911373SMike Kravetz 
29596822904SAndy Whitcroft 	/* Round our left edge to the current segment if it encloses us. */
29696822904SAndy Whitcroft 	if (f > rg->from)
29796822904SAndy Whitcroft 		f = rg->from;
29896822904SAndy Whitcroft 
29996822904SAndy Whitcroft 	/* Check for and consume any regions we now overlap with. */
30096822904SAndy Whitcroft 	nrg = rg;
30196822904SAndy Whitcroft 	list_for_each_entry_safe(rg, trg, rg->link.prev, link) {
30296822904SAndy Whitcroft 		if (&rg->link == head)
30396822904SAndy Whitcroft 			break;
30496822904SAndy Whitcroft 		if (rg->from > t)
30596822904SAndy Whitcroft 			break;
30696822904SAndy Whitcroft 
30796822904SAndy Whitcroft 		/* If this area reaches higher then extend our area to
30896822904SAndy Whitcroft 		 * include it completely.  If this is not the first area
30996822904SAndy Whitcroft 		 * which we intend to reuse, free it. */
31096822904SAndy Whitcroft 		if (rg->to > t)
31196822904SAndy Whitcroft 			t = rg->to;
31296822904SAndy Whitcroft 		if (rg != nrg) {
313cf3ad20bSMike Kravetz 			/* Decrement return value by the deleted range.
314cf3ad20bSMike Kravetz 			 * Another range will span this area so that by
315cf3ad20bSMike Kravetz 			 * end of routine add will be >= zero
316cf3ad20bSMike Kravetz 			 */
317cf3ad20bSMike Kravetz 			add -= (rg->to - rg->from);
31896822904SAndy Whitcroft 			list_del(&rg->link);
31996822904SAndy Whitcroft 			kfree(rg);
32096822904SAndy Whitcroft 		}
32196822904SAndy Whitcroft 	}
322cf3ad20bSMike Kravetz 
323cf3ad20bSMike Kravetz 	add += (nrg->from - f);		/* Added to beginning of region */
32496822904SAndy Whitcroft 	nrg->from = f;
325cf3ad20bSMike Kravetz 	add += t - nrg->to;		/* Added to end of region */
32696822904SAndy Whitcroft 	nrg->to = t;
327cf3ad20bSMike Kravetz 
3285e911373SMike Kravetz out_locked:
3295e911373SMike Kravetz 	resv->adds_in_progress--;
3307b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
331cf3ad20bSMike Kravetz 	VM_BUG_ON(add < 0);
332cf3ad20bSMike Kravetz 	return add;
33396822904SAndy Whitcroft }
33496822904SAndy Whitcroft 
3351dd308a7SMike Kravetz /*
3361dd308a7SMike Kravetz  * Examine the existing reserve map and determine how many
3371dd308a7SMike Kravetz  * huge pages in the specified range [f, t) are NOT currently
3381dd308a7SMike Kravetz  * represented.  This routine is called before a subsequent
3391dd308a7SMike Kravetz  * call to region_add that will actually modify the reserve
3401dd308a7SMike Kravetz  * map to add the specified range [f, t).  region_chg does
3411dd308a7SMike Kravetz  * not change the number of huge pages represented by the
3421dd308a7SMike Kravetz  * map.  However, if the existing regions in the map can not
3431dd308a7SMike Kravetz  * be expanded to represent the new range, a new file_region
3441dd308a7SMike Kravetz  * structure is added to the map as a placeholder.  This is
3451dd308a7SMike Kravetz  * so that the subsequent region_add call will have all the
3461dd308a7SMike Kravetz  * regions it needs and will not fail.
3471dd308a7SMike Kravetz  *
3485e911373SMike Kravetz  * Upon entry, region_chg will also examine the cache of region descriptors
3495e911373SMike Kravetz  * associated with the map.  If there are not enough descriptors cached, one
3505e911373SMike Kravetz  * will be allocated for the in progress add operation.
3515e911373SMike Kravetz  *
3525e911373SMike Kravetz  * Returns the number of huge pages that need to be added to the existing
3535e911373SMike Kravetz  * reservation map for the range [f, t).  This number is greater or equal to
3545e911373SMike Kravetz  * zero.  -ENOMEM is returned if a new file_region structure or cache entry
3555e911373SMike Kravetz  * is needed and can not be allocated.
3561dd308a7SMike Kravetz  */
3571406ec9bSJoonsoo Kim static long region_chg(struct resv_map *resv, long f, long t)
35896822904SAndy Whitcroft {
3591406ec9bSJoonsoo Kim 	struct list_head *head = &resv->regions;
3607b24d861SDavidlohr Bueso 	struct file_region *rg, *nrg = NULL;
36196822904SAndy Whitcroft 	long chg = 0;
36296822904SAndy Whitcroft 
3637b24d861SDavidlohr Bueso retry:
3647b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
3655e911373SMike Kravetz retry_locked:
3665e911373SMike Kravetz 	resv->adds_in_progress++;
3675e911373SMike Kravetz 
3685e911373SMike Kravetz 	/*
3695e911373SMike Kravetz 	 * Check for sufficient descriptors in the cache to accommodate
3705e911373SMike Kravetz 	 * the number of in progress add operations.
3715e911373SMike Kravetz 	 */
3725e911373SMike Kravetz 	if (resv->adds_in_progress > resv->region_cache_count) {
3735e911373SMike Kravetz 		struct file_region *trg;
3745e911373SMike Kravetz 
3755e911373SMike Kravetz 		VM_BUG_ON(resv->adds_in_progress - resv->region_cache_count > 1);
3765e911373SMike Kravetz 		/* Must drop lock to allocate a new descriptor. */
3775e911373SMike Kravetz 		resv->adds_in_progress--;
3785e911373SMike Kravetz 		spin_unlock(&resv->lock);
3795e911373SMike Kravetz 
3805e911373SMike Kravetz 		trg = kmalloc(sizeof(*trg), GFP_KERNEL);
381dbe409e4SMike Kravetz 		if (!trg) {
382dbe409e4SMike Kravetz 			kfree(nrg);
3835e911373SMike Kravetz 			return -ENOMEM;
384dbe409e4SMike Kravetz 		}
3855e911373SMike Kravetz 
3865e911373SMike Kravetz 		spin_lock(&resv->lock);
3875e911373SMike Kravetz 		list_add(&trg->link, &resv->region_cache);
3885e911373SMike Kravetz 		resv->region_cache_count++;
3895e911373SMike Kravetz 		goto retry_locked;
3905e911373SMike Kravetz 	}
3915e911373SMike Kravetz 
39296822904SAndy Whitcroft 	/* Locate the region we are before or in. */
39396822904SAndy Whitcroft 	list_for_each_entry(rg, head, link)
39496822904SAndy Whitcroft 		if (f <= rg->to)
39596822904SAndy Whitcroft 			break;
39696822904SAndy Whitcroft 
39796822904SAndy Whitcroft 	/* If we are below the current region then a new region is required.
39896822904SAndy Whitcroft 	 * Subtle, allocate a new region at the position but make it zero
39996822904SAndy Whitcroft 	 * size such that we can guarantee to record the reservation. */
40096822904SAndy Whitcroft 	if (&rg->link == head || t < rg->from) {
4017b24d861SDavidlohr Bueso 		if (!nrg) {
4025e911373SMike Kravetz 			resv->adds_in_progress--;
4037b24d861SDavidlohr Bueso 			spin_unlock(&resv->lock);
40496822904SAndy Whitcroft 			nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
40596822904SAndy Whitcroft 			if (!nrg)
40696822904SAndy Whitcroft 				return -ENOMEM;
4077b24d861SDavidlohr Bueso 
40896822904SAndy Whitcroft 			nrg->from = f;
40996822904SAndy Whitcroft 			nrg->to   = f;
41096822904SAndy Whitcroft 			INIT_LIST_HEAD(&nrg->link);
4117b24d861SDavidlohr Bueso 			goto retry;
4127b24d861SDavidlohr Bueso 		}
41396822904SAndy Whitcroft 
4147b24d861SDavidlohr Bueso 		list_add(&nrg->link, rg->link.prev);
4157b24d861SDavidlohr Bueso 		chg = t - f;
4167b24d861SDavidlohr Bueso 		goto out_nrg;
41796822904SAndy Whitcroft 	}
41896822904SAndy Whitcroft 
41996822904SAndy Whitcroft 	/* Round our left edge to the current segment if it encloses us. */
42096822904SAndy Whitcroft 	if (f > rg->from)
42196822904SAndy Whitcroft 		f = rg->from;
42296822904SAndy Whitcroft 	chg = t - f;
42396822904SAndy Whitcroft 
42496822904SAndy Whitcroft 	/* Check for and consume any regions we now overlap with. */
42596822904SAndy Whitcroft 	list_for_each_entry(rg, rg->link.prev, link) {
42696822904SAndy Whitcroft 		if (&rg->link == head)
42796822904SAndy Whitcroft 			break;
42896822904SAndy Whitcroft 		if (rg->from > t)
4297b24d861SDavidlohr Bueso 			goto out;
43096822904SAndy Whitcroft 
43125985edcSLucas De Marchi 		/* We overlap with this area, if it extends further than
43296822904SAndy Whitcroft 		 * us then we must extend ourselves.  Account for its
43396822904SAndy Whitcroft 		 * existing reservation. */
43496822904SAndy Whitcroft 		if (rg->to > t) {
43596822904SAndy Whitcroft 			chg += rg->to - t;
43696822904SAndy Whitcroft 			t = rg->to;
43796822904SAndy Whitcroft 		}
43896822904SAndy Whitcroft 		chg -= rg->to - rg->from;
43996822904SAndy Whitcroft 	}
4407b24d861SDavidlohr Bueso 
4417b24d861SDavidlohr Bueso out:
4427b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
4437b24d861SDavidlohr Bueso 	/*  We already know we raced and no longer need the new region */
4447b24d861SDavidlohr Bueso 	kfree(nrg);
4457b24d861SDavidlohr Bueso 	return chg;
4467b24d861SDavidlohr Bueso out_nrg:
4477b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
44896822904SAndy Whitcroft 	return chg;
44996822904SAndy Whitcroft }
45096822904SAndy Whitcroft 
4511dd308a7SMike Kravetz /*
4525e911373SMike Kravetz  * Abort the in progress add operation.  The adds_in_progress field
4535e911373SMike Kravetz  * of the resv_map keeps track of the operations in progress between
4545e911373SMike Kravetz  * calls to region_chg and region_add.  Operations are sometimes
4555e911373SMike Kravetz  * aborted after the call to region_chg.  In such cases, region_abort
4565e911373SMike Kravetz  * is called to decrement the adds_in_progress counter.
4575e911373SMike Kravetz  *
4585e911373SMike Kravetz  * NOTE: The range arguments [f, t) are not needed or used in this
4595e911373SMike Kravetz  * routine.  They are kept to make reading the calling code easier as
4605e911373SMike Kravetz  * arguments will match the associated region_chg call.
4615e911373SMike Kravetz  */
4625e911373SMike Kravetz static void region_abort(struct resv_map *resv, long f, long t)
4635e911373SMike Kravetz {
4645e911373SMike Kravetz 	spin_lock(&resv->lock);
4655e911373SMike Kravetz 	VM_BUG_ON(!resv->region_cache_count);
4665e911373SMike Kravetz 	resv->adds_in_progress--;
4675e911373SMike Kravetz 	spin_unlock(&resv->lock);
4685e911373SMike Kravetz }
4695e911373SMike Kravetz 
4705e911373SMike Kravetz /*
471feba16e2SMike Kravetz  * Delete the specified range [f, t) from the reserve map.  If the
472feba16e2SMike Kravetz  * t parameter is LONG_MAX, this indicates that ALL regions after f
473feba16e2SMike Kravetz  * should be deleted.  Locate the regions which intersect [f, t)
474feba16e2SMike Kravetz  * and either trim, delete or split the existing regions.
475feba16e2SMike Kravetz  *
476feba16e2SMike Kravetz  * Returns the number of huge pages deleted from the reserve map.
477feba16e2SMike Kravetz  * In the normal case, the return value is zero or more.  In the
478feba16e2SMike Kravetz  * case where a region must be split, a new region descriptor must
479feba16e2SMike Kravetz  * be allocated.  If the allocation fails, -ENOMEM will be returned.
480feba16e2SMike Kravetz  * NOTE: If the parameter t == LONG_MAX, then we will never split
481feba16e2SMike Kravetz  * a region and possibly return -ENOMEM.  Callers specifying
482feba16e2SMike Kravetz  * t == LONG_MAX do not need to check for -ENOMEM error.
4831dd308a7SMike Kravetz  */
484feba16e2SMike Kravetz static long region_del(struct resv_map *resv, long f, long t)
48596822904SAndy Whitcroft {
4861406ec9bSJoonsoo Kim 	struct list_head *head = &resv->regions;
48796822904SAndy Whitcroft 	struct file_region *rg, *trg;
488feba16e2SMike Kravetz 	struct file_region *nrg = NULL;
489feba16e2SMike Kravetz 	long del = 0;
49096822904SAndy Whitcroft 
491feba16e2SMike Kravetz retry:
4927b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
493feba16e2SMike Kravetz 	list_for_each_entry_safe(rg, trg, head, link) {
494dbe409e4SMike Kravetz 		/*
495dbe409e4SMike Kravetz 		 * Skip regions before the range to be deleted.  file_region
496dbe409e4SMike Kravetz 		 * ranges are normally of the form [from, to).  However, there
497dbe409e4SMike Kravetz 		 * may be a "placeholder" entry in the map which is of the form
498dbe409e4SMike Kravetz 		 * (from, to) with from == to.  Check for placeholder entries
499dbe409e4SMike Kravetz 		 * at the beginning of the range to be deleted.
500dbe409e4SMike Kravetz 		 */
501dbe409e4SMike Kravetz 		if (rg->to <= f && (rg->to != rg->from || rg->to != f))
502feba16e2SMike Kravetz 			continue;
503dbe409e4SMike Kravetz 
504feba16e2SMike Kravetz 		if (rg->from >= t)
50596822904SAndy Whitcroft 			break;
50696822904SAndy Whitcroft 
507feba16e2SMike Kravetz 		if (f > rg->from && t < rg->to) { /* Must split region */
508feba16e2SMike Kravetz 			/*
509feba16e2SMike Kravetz 			 * Check for an entry in the cache before dropping
510feba16e2SMike Kravetz 			 * lock and attempting allocation.
511feba16e2SMike Kravetz 			 */
512feba16e2SMike Kravetz 			if (!nrg &&
513feba16e2SMike Kravetz 			    resv->region_cache_count > resv->adds_in_progress) {
514feba16e2SMike Kravetz 				nrg = list_first_entry(&resv->region_cache,
515feba16e2SMike Kravetz 							struct file_region,
516feba16e2SMike Kravetz 							link);
517feba16e2SMike Kravetz 				list_del(&nrg->link);
518feba16e2SMike Kravetz 				resv->region_cache_count--;
51996822904SAndy Whitcroft 			}
52096822904SAndy Whitcroft 
521feba16e2SMike Kravetz 			if (!nrg) {
522feba16e2SMike Kravetz 				spin_unlock(&resv->lock);
523feba16e2SMike Kravetz 				nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
524feba16e2SMike Kravetz 				if (!nrg)
525feba16e2SMike Kravetz 					return -ENOMEM;
526feba16e2SMike Kravetz 				goto retry;
527feba16e2SMike Kravetz 			}
528feba16e2SMike Kravetz 
529feba16e2SMike Kravetz 			del += t - f;
530feba16e2SMike Kravetz 
531feba16e2SMike Kravetz 			/* New entry for end of split region */
532feba16e2SMike Kravetz 			nrg->from = t;
533feba16e2SMike Kravetz 			nrg->to = rg->to;
534feba16e2SMike Kravetz 			INIT_LIST_HEAD(&nrg->link);
535feba16e2SMike Kravetz 
536feba16e2SMike Kravetz 			/* Original entry is trimmed */
537feba16e2SMike Kravetz 			rg->to = f;
538feba16e2SMike Kravetz 
539feba16e2SMike Kravetz 			list_add(&nrg->link, &rg->link);
540feba16e2SMike Kravetz 			nrg = NULL;
54196822904SAndy Whitcroft 			break;
542feba16e2SMike Kravetz 		}
543feba16e2SMike Kravetz 
544feba16e2SMike Kravetz 		if (f <= rg->from && t >= rg->to) { /* Remove entire region */
545feba16e2SMike Kravetz 			del += rg->to - rg->from;
54696822904SAndy Whitcroft 			list_del(&rg->link);
54796822904SAndy Whitcroft 			kfree(rg);
548feba16e2SMike Kravetz 			continue;
54996822904SAndy Whitcroft 		}
5507b24d861SDavidlohr Bueso 
551feba16e2SMike Kravetz 		if (f <= rg->from) {	/* Trim beginning of region */
552feba16e2SMike Kravetz 			del += t - rg->from;
553feba16e2SMike Kravetz 			rg->from = t;
554feba16e2SMike Kravetz 		} else {		/* Trim end of region */
555feba16e2SMike Kravetz 			del += rg->to - f;
556feba16e2SMike Kravetz 			rg->to = f;
557feba16e2SMike Kravetz 		}
558feba16e2SMike Kravetz 	}
559feba16e2SMike Kravetz 
5607b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
561feba16e2SMike Kravetz 	kfree(nrg);
562feba16e2SMike Kravetz 	return del;
56396822904SAndy Whitcroft }
56496822904SAndy Whitcroft 
5651dd308a7SMike Kravetz /*
566b5cec28dSMike Kravetz  * A rare out of memory error was encountered which prevented removal of
567b5cec28dSMike Kravetz  * the reserve map region for a page.  The huge page itself was free'ed
568b5cec28dSMike Kravetz  * and removed from the page cache.  This routine will adjust the subpool
569b5cec28dSMike Kravetz  * usage count, and the global reserve count if needed.  By incrementing
570b5cec28dSMike Kravetz  * these counts, the reserve map entry which could not be deleted will
571b5cec28dSMike Kravetz  * appear as a "reserved" entry instead of simply dangling with incorrect
572b5cec28dSMike Kravetz  * counts.
573b5cec28dSMike Kravetz  */
57472e2936cSzhong jiang void hugetlb_fix_reserve_counts(struct inode *inode)
575b5cec28dSMike Kravetz {
576b5cec28dSMike Kravetz 	struct hugepage_subpool *spool = subpool_inode(inode);
577b5cec28dSMike Kravetz 	long rsv_adjust;
578b5cec28dSMike Kravetz 
579b5cec28dSMike Kravetz 	rsv_adjust = hugepage_subpool_get_pages(spool, 1);
58072e2936cSzhong jiang 	if (rsv_adjust) {
581b5cec28dSMike Kravetz 		struct hstate *h = hstate_inode(inode);
582b5cec28dSMike Kravetz 
583b5cec28dSMike Kravetz 		hugetlb_acct_memory(h, 1);
584b5cec28dSMike Kravetz 	}
585b5cec28dSMike Kravetz }
586b5cec28dSMike Kravetz 
587b5cec28dSMike Kravetz /*
5881dd308a7SMike Kravetz  * Count and return the number of huge pages in the reserve map
5891dd308a7SMike Kravetz  * that intersect with the range [f, t).
5901dd308a7SMike Kravetz  */
5911406ec9bSJoonsoo Kim static long region_count(struct resv_map *resv, long f, long t)
59284afd99bSAndy Whitcroft {
5931406ec9bSJoonsoo Kim 	struct list_head *head = &resv->regions;
59484afd99bSAndy Whitcroft 	struct file_region *rg;
59584afd99bSAndy Whitcroft 	long chg = 0;
59684afd99bSAndy Whitcroft 
5977b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
59884afd99bSAndy Whitcroft 	/* Locate each segment we overlap with, and count that overlap. */
59984afd99bSAndy Whitcroft 	list_for_each_entry(rg, head, link) {
600f2135a4aSWang Sheng-Hui 		long seg_from;
601f2135a4aSWang Sheng-Hui 		long seg_to;
60284afd99bSAndy Whitcroft 
60384afd99bSAndy Whitcroft 		if (rg->to <= f)
60484afd99bSAndy Whitcroft 			continue;
60584afd99bSAndy Whitcroft 		if (rg->from >= t)
60684afd99bSAndy Whitcroft 			break;
60784afd99bSAndy Whitcroft 
60884afd99bSAndy Whitcroft 		seg_from = max(rg->from, f);
60984afd99bSAndy Whitcroft 		seg_to = min(rg->to, t);
61084afd99bSAndy Whitcroft 
61184afd99bSAndy Whitcroft 		chg += seg_to - seg_from;
61284afd99bSAndy Whitcroft 	}
6137b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
61484afd99bSAndy Whitcroft 
61584afd99bSAndy Whitcroft 	return chg;
61684afd99bSAndy Whitcroft }
61784afd99bSAndy Whitcroft 
61896822904SAndy Whitcroft /*
619e7c4b0bfSAndy Whitcroft  * Convert the address within this vma to the page offset within
620e7c4b0bfSAndy Whitcroft  * the mapping, in pagecache page units; huge pages here.
621e7c4b0bfSAndy Whitcroft  */
622a5516438SAndi Kleen static pgoff_t vma_hugecache_offset(struct hstate *h,
623a5516438SAndi Kleen 			struct vm_area_struct *vma, unsigned long address)
624e7c4b0bfSAndy Whitcroft {
625a5516438SAndi Kleen 	return ((address - vma->vm_start) >> huge_page_shift(h)) +
626a5516438SAndi Kleen 			(vma->vm_pgoff >> huge_page_order(h));
627e7c4b0bfSAndy Whitcroft }
628e7c4b0bfSAndy Whitcroft 
6290fe6e20bSNaoya Horiguchi pgoff_t linear_hugepage_index(struct vm_area_struct *vma,
6300fe6e20bSNaoya Horiguchi 				     unsigned long address)
6310fe6e20bSNaoya Horiguchi {
6320fe6e20bSNaoya Horiguchi 	return vma_hugecache_offset(hstate_vma(vma), vma, address);
6330fe6e20bSNaoya Horiguchi }
634dee41079SDan Williams EXPORT_SYMBOL_GPL(linear_hugepage_index);
6350fe6e20bSNaoya Horiguchi 
63684afd99bSAndy Whitcroft /*
63708fba699SMel Gorman  * Return the size of the pages allocated when backing a VMA. In the majority
63808fba699SMel Gorman  * cases this will be same size as used by the page table entries.
63908fba699SMel Gorman  */
64008fba699SMel Gorman unsigned long vma_kernel_pagesize(struct vm_area_struct *vma)
64108fba699SMel Gorman {
64205ea8860SDan Williams 	if (vma->vm_ops && vma->vm_ops->pagesize)
64305ea8860SDan Williams 		return vma->vm_ops->pagesize(vma);
64408fba699SMel Gorman 	return PAGE_SIZE;
64508fba699SMel Gorman }
646f340ca0fSJoerg Roedel EXPORT_SYMBOL_GPL(vma_kernel_pagesize);
64708fba699SMel Gorman 
64808fba699SMel Gorman /*
6493340289dSMel Gorman  * Return the page size being used by the MMU to back a VMA. In the majority
6503340289dSMel Gorman  * of cases, the page size used by the kernel matches the MMU size. On
65109135cc5SDan Williams  * architectures where it differs, an architecture-specific 'strong'
65209135cc5SDan Williams  * version of this symbol is required.
6533340289dSMel Gorman  */
65409135cc5SDan Williams __weak unsigned long vma_mmu_pagesize(struct vm_area_struct *vma)
6553340289dSMel Gorman {
6563340289dSMel Gorman 	return vma_kernel_pagesize(vma);
6573340289dSMel Gorman }
6583340289dSMel Gorman 
6593340289dSMel Gorman /*
66084afd99bSAndy Whitcroft  * Flags for MAP_PRIVATE reservations.  These are stored in the bottom
66184afd99bSAndy Whitcroft  * bits of the reservation map pointer, which are always clear due to
66284afd99bSAndy Whitcroft  * alignment.
66384afd99bSAndy Whitcroft  */
66484afd99bSAndy Whitcroft #define HPAGE_RESV_OWNER    (1UL << 0)
66584afd99bSAndy Whitcroft #define HPAGE_RESV_UNMAPPED (1UL << 1)
66604f2cbe3SMel Gorman #define HPAGE_RESV_MASK (HPAGE_RESV_OWNER | HPAGE_RESV_UNMAPPED)
66784afd99bSAndy Whitcroft 
668a1e78772SMel Gorman /*
669a1e78772SMel Gorman  * These helpers are used to track how many pages are reserved for
670a1e78772SMel Gorman  * faults in a MAP_PRIVATE mapping. Only the process that called mmap()
671a1e78772SMel Gorman  * is guaranteed to have their future faults succeed.
672a1e78772SMel Gorman  *
673a1e78772SMel Gorman  * With the exception of reset_vma_resv_huge_pages() which is called at fork(),
674a1e78772SMel Gorman  * the reserve counters are updated with the hugetlb_lock held. It is safe
675a1e78772SMel Gorman  * to reset the VMA at fork() time as it is not in use yet and there is no
676a1e78772SMel Gorman  * chance of the global counters getting corrupted as a result of the values.
67784afd99bSAndy Whitcroft  *
67884afd99bSAndy Whitcroft  * The private mapping reservation is represented in a subtly different
67984afd99bSAndy Whitcroft  * manner to a shared mapping.  A shared mapping has a region map associated
68084afd99bSAndy Whitcroft  * with the underlying file, this region map represents the backing file
68184afd99bSAndy Whitcroft  * pages which have ever had a reservation assigned which this persists even
68284afd99bSAndy Whitcroft  * after the page is instantiated.  A private mapping has a region map
68384afd99bSAndy Whitcroft  * associated with the original mmap which is attached to all VMAs which
68484afd99bSAndy Whitcroft  * reference it, this region map represents those offsets which have consumed
68584afd99bSAndy Whitcroft  * reservation ie. where pages have been instantiated.
686a1e78772SMel Gorman  */
687e7c4b0bfSAndy Whitcroft static unsigned long get_vma_private_data(struct vm_area_struct *vma)
688e7c4b0bfSAndy Whitcroft {
689e7c4b0bfSAndy Whitcroft 	return (unsigned long)vma->vm_private_data;
690e7c4b0bfSAndy Whitcroft }
691e7c4b0bfSAndy Whitcroft 
692e7c4b0bfSAndy Whitcroft static void set_vma_private_data(struct vm_area_struct *vma,
693e7c4b0bfSAndy Whitcroft 							unsigned long value)
694e7c4b0bfSAndy Whitcroft {
695e7c4b0bfSAndy Whitcroft 	vma->vm_private_data = (void *)value;
696e7c4b0bfSAndy Whitcroft }
697e7c4b0bfSAndy Whitcroft 
6989119a41eSJoonsoo Kim struct resv_map *resv_map_alloc(void)
69984afd99bSAndy Whitcroft {
70084afd99bSAndy Whitcroft 	struct resv_map *resv_map = kmalloc(sizeof(*resv_map), GFP_KERNEL);
7015e911373SMike Kravetz 	struct file_region *rg = kmalloc(sizeof(*rg), GFP_KERNEL);
7025e911373SMike Kravetz 
7035e911373SMike Kravetz 	if (!resv_map || !rg) {
7045e911373SMike Kravetz 		kfree(resv_map);
7055e911373SMike Kravetz 		kfree(rg);
70684afd99bSAndy Whitcroft 		return NULL;
7075e911373SMike Kravetz 	}
70884afd99bSAndy Whitcroft 
70984afd99bSAndy Whitcroft 	kref_init(&resv_map->refs);
7107b24d861SDavidlohr Bueso 	spin_lock_init(&resv_map->lock);
71184afd99bSAndy Whitcroft 	INIT_LIST_HEAD(&resv_map->regions);
71284afd99bSAndy Whitcroft 
7135e911373SMike Kravetz 	resv_map->adds_in_progress = 0;
7145e911373SMike Kravetz 
7155e911373SMike Kravetz 	INIT_LIST_HEAD(&resv_map->region_cache);
7165e911373SMike Kravetz 	list_add(&rg->link, &resv_map->region_cache);
7175e911373SMike Kravetz 	resv_map->region_cache_count = 1;
7185e911373SMike Kravetz 
71984afd99bSAndy Whitcroft 	return resv_map;
72084afd99bSAndy Whitcroft }
72184afd99bSAndy Whitcroft 
7229119a41eSJoonsoo Kim void resv_map_release(struct kref *ref)
72384afd99bSAndy Whitcroft {
72484afd99bSAndy Whitcroft 	struct resv_map *resv_map = container_of(ref, struct resv_map, refs);
7255e911373SMike Kravetz 	struct list_head *head = &resv_map->region_cache;
7265e911373SMike Kravetz 	struct file_region *rg, *trg;
72784afd99bSAndy Whitcroft 
72884afd99bSAndy Whitcroft 	/* Clear out any active regions before we release the map. */
729feba16e2SMike Kravetz 	region_del(resv_map, 0, LONG_MAX);
7305e911373SMike Kravetz 
7315e911373SMike Kravetz 	/* ... and any entries left in the cache */
7325e911373SMike Kravetz 	list_for_each_entry_safe(rg, trg, head, link) {
7335e911373SMike Kravetz 		list_del(&rg->link);
7345e911373SMike Kravetz 		kfree(rg);
7355e911373SMike Kravetz 	}
7365e911373SMike Kravetz 
7375e911373SMike Kravetz 	VM_BUG_ON(resv_map->adds_in_progress);
7385e911373SMike Kravetz 
73984afd99bSAndy Whitcroft 	kfree(resv_map);
74084afd99bSAndy Whitcroft }
74184afd99bSAndy Whitcroft 
7424e35f483SJoonsoo Kim static inline struct resv_map *inode_resv_map(struct inode *inode)
7434e35f483SJoonsoo Kim {
744f27a5136SMike Kravetz 	/*
745f27a5136SMike Kravetz 	 * At inode evict time, i_mapping may not point to the original
746f27a5136SMike Kravetz 	 * address space within the inode.  This original address space
747f27a5136SMike Kravetz 	 * contains the pointer to the resv_map.  So, always use the
748f27a5136SMike Kravetz 	 * address space embedded within the inode.
749f27a5136SMike Kravetz 	 * The VERY common case is inode->mapping == &inode->i_data but,
750f27a5136SMike Kravetz 	 * this may not be true for device special inodes.
751f27a5136SMike Kravetz 	 */
752f27a5136SMike Kravetz 	return (struct resv_map *)(&inode->i_data)->private_data;
7534e35f483SJoonsoo Kim }
7544e35f483SJoonsoo Kim 
75584afd99bSAndy Whitcroft static struct resv_map *vma_resv_map(struct vm_area_struct *vma)
756a1e78772SMel Gorman {
75781d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
7584e35f483SJoonsoo Kim 	if (vma->vm_flags & VM_MAYSHARE) {
7594e35f483SJoonsoo Kim 		struct address_space *mapping = vma->vm_file->f_mapping;
7604e35f483SJoonsoo Kim 		struct inode *inode = mapping->host;
7614e35f483SJoonsoo Kim 
7624e35f483SJoonsoo Kim 		return inode_resv_map(inode);
7634e35f483SJoonsoo Kim 
7644e35f483SJoonsoo Kim 	} else {
76584afd99bSAndy Whitcroft 		return (struct resv_map *)(get_vma_private_data(vma) &
76684afd99bSAndy Whitcroft 							~HPAGE_RESV_MASK);
7674e35f483SJoonsoo Kim 	}
768a1e78772SMel Gorman }
769a1e78772SMel Gorman 
77084afd99bSAndy Whitcroft static void set_vma_resv_map(struct vm_area_struct *vma, struct resv_map *map)
771a1e78772SMel Gorman {
77281d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
77381d1b09cSSasha Levin 	VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
774a1e78772SMel Gorman 
77584afd99bSAndy Whitcroft 	set_vma_private_data(vma, (get_vma_private_data(vma) &
77684afd99bSAndy Whitcroft 				HPAGE_RESV_MASK) | (unsigned long)map);
77704f2cbe3SMel Gorman }
77804f2cbe3SMel Gorman 
77904f2cbe3SMel Gorman static void set_vma_resv_flags(struct vm_area_struct *vma, unsigned long flags)
78004f2cbe3SMel Gorman {
78181d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
78281d1b09cSSasha Levin 	VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
783e7c4b0bfSAndy Whitcroft 
784e7c4b0bfSAndy Whitcroft 	set_vma_private_data(vma, get_vma_private_data(vma) | flags);
78504f2cbe3SMel Gorman }
78604f2cbe3SMel Gorman 
78704f2cbe3SMel Gorman static int is_vma_resv_set(struct vm_area_struct *vma, unsigned long flag)
78804f2cbe3SMel Gorman {
78981d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
790e7c4b0bfSAndy Whitcroft 
791e7c4b0bfSAndy Whitcroft 	return (get_vma_private_data(vma) & flag) != 0;
792a1e78772SMel Gorman }
793a1e78772SMel Gorman 
79404f2cbe3SMel Gorman /* Reset counters to 0 and clear all HPAGE_RESV_* flags */
795a1e78772SMel Gorman void reset_vma_resv_huge_pages(struct vm_area_struct *vma)
796a1e78772SMel Gorman {
79781d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
798f83a275dSMel Gorman 	if (!(vma->vm_flags & VM_MAYSHARE))
799a1e78772SMel Gorman 		vma->vm_private_data = (void *)0;
800a1e78772SMel Gorman }
801a1e78772SMel Gorman 
802a1e78772SMel Gorman /* Returns true if the VMA has associated reserve pages */
803559ec2f8SNicholas Krause static bool vma_has_reserves(struct vm_area_struct *vma, long chg)
804a1e78772SMel Gorman {
805af0ed73eSJoonsoo Kim 	if (vma->vm_flags & VM_NORESERVE) {
806af0ed73eSJoonsoo Kim 		/*
807af0ed73eSJoonsoo Kim 		 * This address is already reserved by other process(chg == 0),
808af0ed73eSJoonsoo Kim 		 * so, we should decrement reserved count. Without decrementing,
809af0ed73eSJoonsoo Kim 		 * reserve count remains after releasing inode, because this
810af0ed73eSJoonsoo Kim 		 * allocated page will go into page cache and is regarded as
811af0ed73eSJoonsoo Kim 		 * coming from reserved pool in releasing step.  Currently, we
812af0ed73eSJoonsoo Kim 		 * don't have any other solution to deal with this situation
813af0ed73eSJoonsoo Kim 		 * properly, so add work-around here.
814af0ed73eSJoonsoo Kim 		 */
815af0ed73eSJoonsoo Kim 		if (vma->vm_flags & VM_MAYSHARE && chg == 0)
816559ec2f8SNicholas Krause 			return true;
817af0ed73eSJoonsoo Kim 		else
818559ec2f8SNicholas Krause 			return false;
819af0ed73eSJoonsoo Kim 	}
820a63884e9SJoonsoo Kim 
821a63884e9SJoonsoo Kim 	/* Shared mappings always use reserves */
8221fb1b0e9SMike Kravetz 	if (vma->vm_flags & VM_MAYSHARE) {
8231fb1b0e9SMike Kravetz 		/*
8241fb1b0e9SMike Kravetz 		 * We know VM_NORESERVE is not set.  Therefore, there SHOULD
8251fb1b0e9SMike Kravetz 		 * be a region map for all pages.  The only situation where
8261fb1b0e9SMike Kravetz 		 * there is no region map is if a hole was punched via
8271fb1b0e9SMike Kravetz 		 * fallocate.  In this case, there really are no reverves to
8281fb1b0e9SMike Kravetz 		 * use.  This situation is indicated if chg != 0.
8291fb1b0e9SMike Kravetz 		 */
8301fb1b0e9SMike Kravetz 		if (chg)
8311fb1b0e9SMike Kravetz 			return false;
8321fb1b0e9SMike Kravetz 		else
833559ec2f8SNicholas Krause 			return true;
8341fb1b0e9SMike Kravetz 	}
835a63884e9SJoonsoo Kim 
836a63884e9SJoonsoo Kim 	/*
837a63884e9SJoonsoo Kim 	 * Only the process that called mmap() has reserves for
838a63884e9SJoonsoo Kim 	 * private mappings.
839a63884e9SJoonsoo Kim 	 */
84067961f9dSMike Kravetz 	if (is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
84167961f9dSMike Kravetz 		/*
84267961f9dSMike Kravetz 		 * Like the shared case above, a hole punch or truncate
84367961f9dSMike Kravetz 		 * could have been performed on the private mapping.
84467961f9dSMike Kravetz 		 * Examine the value of chg to determine if reserves
84567961f9dSMike Kravetz 		 * actually exist or were previously consumed.
84667961f9dSMike Kravetz 		 * Very Subtle - The value of chg comes from a previous
84767961f9dSMike Kravetz 		 * call to vma_needs_reserves().  The reserve map for
84867961f9dSMike Kravetz 		 * private mappings has different (opposite) semantics
84967961f9dSMike Kravetz 		 * than that of shared mappings.  vma_needs_reserves()
85067961f9dSMike Kravetz 		 * has already taken this difference in semantics into
85167961f9dSMike Kravetz 		 * account.  Therefore, the meaning of chg is the same
85267961f9dSMike Kravetz 		 * as in the shared case above.  Code could easily be
85367961f9dSMike Kravetz 		 * combined, but keeping it separate draws attention to
85467961f9dSMike Kravetz 		 * subtle differences.
85567961f9dSMike Kravetz 		 */
85667961f9dSMike Kravetz 		if (chg)
85767961f9dSMike Kravetz 			return false;
85867961f9dSMike Kravetz 		else
859559ec2f8SNicholas Krause 			return true;
86067961f9dSMike Kravetz 	}
861a63884e9SJoonsoo Kim 
862559ec2f8SNicholas Krause 	return false;
863a1e78772SMel Gorman }
864a1e78772SMel Gorman 
865a5516438SAndi Kleen static void enqueue_huge_page(struct hstate *h, struct page *page)
8661da177e4SLinus Torvalds {
8671da177e4SLinus Torvalds 	int nid = page_to_nid(page);
8680edaecfaSAneesh Kumar K.V 	list_move(&page->lru, &h->hugepage_freelists[nid]);
869a5516438SAndi Kleen 	h->free_huge_pages++;
870a5516438SAndi Kleen 	h->free_huge_pages_node[nid]++;
8711da177e4SLinus Torvalds }
8721da177e4SLinus Torvalds 
87394310cbcSAnshuman Khandual static struct page *dequeue_huge_page_node_exact(struct hstate *h, int nid)
874bf50bab2SNaoya Horiguchi {
875bf50bab2SNaoya Horiguchi 	struct page *page;
876bf50bab2SNaoya Horiguchi 
877c8721bbbSNaoya Horiguchi 	list_for_each_entry(page, &h->hugepage_freelists[nid], lru)
878243abd5bSNaoya Horiguchi 		if (!PageHWPoison(page))
879c8721bbbSNaoya Horiguchi 			break;
880c8721bbbSNaoya Horiguchi 	/*
881c8721bbbSNaoya Horiguchi 	 * if 'non-isolated free hugepage' not found on the list,
882c8721bbbSNaoya Horiguchi 	 * the allocation fails.
883c8721bbbSNaoya Horiguchi 	 */
884c8721bbbSNaoya Horiguchi 	if (&h->hugepage_freelists[nid] == &page->lru)
885bf50bab2SNaoya Horiguchi 		return NULL;
8860edaecfaSAneesh Kumar K.V 	list_move(&page->lru, &h->hugepage_activelist);
887a9869b83SNaoya Horiguchi 	set_page_refcounted(page);
888bf50bab2SNaoya Horiguchi 	h->free_huge_pages--;
889bf50bab2SNaoya Horiguchi 	h->free_huge_pages_node[nid]--;
890bf50bab2SNaoya Horiguchi 	return page;
891bf50bab2SNaoya Horiguchi }
892bf50bab2SNaoya Horiguchi 
8933e59fcb0SMichal Hocko static struct page *dequeue_huge_page_nodemask(struct hstate *h, gfp_t gfp_mask, int nid,
8943e59fcb0SMichal Hocko 		nodemask_t *nmask)
89594310cbcSAnshuman Khandual {
8963e59fcb0SMichal Hocko 	unsigned int cpuset_mems_cookie;
8973e59fcb0SMichal Hocko 	struct zonelist *zonelist;
8983e59fcb0SMichal Hocko 	struct zone *zone;
8993e59fcb0SMichal Hocko 	struct zoneref *z;
90098fa15f3SAnshuman Khandual 	int node = NUMA_NO_NODE;
9013e59fcb0SMichal Hocko 
9023e59fcb0SMichal Hocko 	zonelist = node_zonelist(nid, gfp_mask);
9033e59fcb0SMichal Hocko 
9043e59fcb0SMichal Hocko retry_cpuset:
9053e59fcb0SMichal Hocko 	cpuset_mems_cookie = read_mems_allowed_begin();
9063e59fcb0SMichal Hocko 	for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nmask) {
90794310cbcSAnshuman Khandual 		struct page *page;
90894310cbcSAnshuman Khandual 
9093e59fcb0SMichal Hocko 		if (!cpuset_zone_allowed(zone, gfp_mask))
9103e59fcb0SMichal Hocko 			continue;
9113e59fcb0SMichal Hocko 		/*
9123e59fcb0SMichal Hocko 		 * no need to ask again on the same node. Pool is node rather than
9133e59fcb0SMichal Hocko 		 * zone aware
9143e59fcb0SMichal Hocko 		 */
9153e59fcb0SMichal Hocko 		if (zone_to_nid(zone) == node)
9163e59fcb0SMichal Hocko 			continue;
9173e59fcb0SMichal Hocko 		node = zone_to_nid(zone);
91894310cbcSAnshuman Khandual 
91994310cbcSAnshuman Khandual 		page = dequeue_huge_page_node_exact(h, node);
92094310cbcSAnshuman Khandual 		if (page)
92194310cbcSAnshuman Khandual 			return page;
92294310cbcSAnshuman Khandual 	}
9233e59fcb0SMichal Hocko 	if (unlikely(read_mems_allowed_retry(cpuset_mems_cookie)))
9243e59fcb0SMichal Hocko 		goto retry_cpuset;
9253e59fcb0SMichal Hocko 
92694310cbcSAnshuman Khandual 	return NULL;
92794310cbcSAnshuman Khandual }
92894310cbcSAnshuman Khandual 
92986cdb465SNaoya Horiguchi /* Movability of hugepages depends on migration support. */
93086cdb465SNaoya Horiguchi static inline gfp_t htlb_alloc_mask(struct hstate *h)
93186cdb465SNaoya Horiguchi {
9327ed2c31dSAnshuman Khandual 	if (hugepage_movable_supported(h))
93386cdb465SNaoya Horiguchi 		return GFP_HIGHUSER_MOVABLE;
93486cdb465SNaoya Horiguchi 	else
93586cdb465SNaoya Horiguchi 		return GFP_HIGHUSER;
93686cdb465SNaoya Horiguchi }
93786cdb465SNaoya Horiguchi 
938a5516438SAndi Kleen static struct page *dequeue_huge_page_vma(struct hstate *h,
939a5516438SAndi Kleen 				struct vm_area_struct *vma,
940af0ed73eSJoonsoo Kim 				unsigned long address, int avoid_reserve,
941af0ed73eSJoonsoo Kim 				long chg)
9421da177e4SLinus Torvalds {
9433e59fcb0SMichal Hocko 	struct page *page;
944480eccf9SLee Schermerhorn 	struct mempolicy *mpol;
94504ec6264SVlastimil Babka 	gfp_t gfp_mask;
9463e59fcb0SMichal Hocko 	nodemask_t *nodemask;
94704ec6264SVlastimil Babka 	int nid;
9481da177e4SLinus Torvalds 
949a1e78772SMel Gorman 	/*
950a1e78772SMel Gorman 	 * A child process with MAP_PRIVATE mappings created by their parent
951a1e78772SMel Gorman 	 * have no page reserves. This check ensures that reservations are
952a1e78772SMel Gorman 	 * not "stolen". The child may still get SIGKILLed
953a1e78772SMel Gorman 	 */
954af0ed73eSJoonsoo Kim 	if (!vma_has_reserves(vma, chg) &&
955a5516438SAndi Kleen 			h->free_huge_pages - h->resv_huge_pages == 0)
956c0ff7453SMiao Xie 		goto err;
957a1e78772SMel Gorman 
95804f2cbe3SMel Gorman 	/* If reserves cannot be used, ensure enough pages are in the pool */
959a5516438SAndi Kleen 	if (avoid_reserve && h->free_huge_pages - h->resv_huge_pages == 0)
9606eab04a8SJustin P. Mattock 		goto err;
96104f2cbe3SMel Gorman 
96204ec6264SVlastimil Babka 	gfp_mask = htlb_alloc_mask(h);
96304ec6264SVlastimil Babka 	nid = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
9643e59fcb0SMichal Hocko 	page = dequeue_huge_page_nodemask(h, gfp_mask, nid, nodemask);
9653e59fcb0SMichal Hocko 	if (page && !avoid_reserve && vma_has_reserves(vma, chg)) {
96607443a85SJoonsoo Kim 		SetPagePrivate(page);
967a63884e9SJoonsoo Kim 		h->resv_huge_pages--;
968bf50bab2SNaoya Horiguchi 	}
969cc9a6c87SMel Gorman 
970cc9a6c87SMel Gorman 	mpol_cond_put(mpol);
971cc9a6c87SMel Gorman 	return page;
972cc9a6c87SMel Gorman 
973c0ff7453SMiao Xie err:
974cc9a6c87SMel Gorman 	return NULL;
9751da177e4SLinus Torvalds }
9761da177e4SLinus Torvalds 
9771cac6f2cSLuiz Capitulino /*
9781cac6f2cSLuiz Capitulino  * common helper functions for hstate_next_node_to_{alloc|free}.
9791cac6f2cSLuiz Capitulino  * We may have allocated or freed a huge page based on a different
9801cac6f2cSLuiz Capitulino  * nodes_allowed previously, so h->next_node_to_{alloc|free} might
9811cac6f2cSLuiz Capitulino  * be outside of *nodes_allowed.  Ensure that we use an allowed
9821cac6f2cSLuiz Capitulino  * node for alloc or free.
9831cac6f2cSLuiz Capitulino  */
9841cac6f2cSLuiz Capitulino static int next_node_allowed(int nid, nodemask_t *nodes_allowed)
9851cac6f2cSLuiz Capitulino {
9860edaf86cSAndrew Morton 	nid = next_node_in(nid, *nodes_allowed);
9871cac6f2cSLuiz Capitulino 	VM_BUG_ON(nid >= MAX_NUMNODES);
9881cac6f2cSLuiz Capitulino 
9891cac6f2cSLuiz Capitulino 	return nid;
9901cac6f2cSLuiz Capitulino }
9911cac6f2cSLuiz Capitulino 
9921cac6f2cSLuiz Capitulino static int get_valid_node_allowed(int nid, nodemask_t *nodes_allowed)
9931cac6f2cSLuiz Capitulino {
9941cac6f2cSLuiz Capitulino 	if (!node_isset(nid, *nodes_allowed))
9951cac6f2cSLuiz Capitulino 		nid = next_node_allowed(nid, nodes_allowed);
9961cac6f2cSLuiz Capitulino 	return nid;
9971cac6f2cSLuiz Capitulino }
9981cac6f2cSLuiz Capitulino 
9991cac6f2cSLuiz Capitulino /*
10001cac6f2cSLuiz Capitulino  * returns the previously saved node ["this node"] from which to
10011cac6f2cSLuiz Capitulino  * allocate a persistent huge page for the pool and advance the
10021cac6f2cSLuiz Capitulino  * next node from which to allocate, handling wrap at end of node
10031cac6f2cSLuiz Capitulino  * mask.
10041cac6f2cSLuiz Capitulino  */
10051cac6f2cSLuiz Capitulino static int hstate_next_node_to_alloc(struct hstate *h,
10061cac6f2cSLuiz Capitulino 					nodemask_t *nodes_allowed)
10071cac6f2cSLuiz Capitulino {
10081cac6f2cSLuiz Capitulino 	int nid;
10091cac6f2cSLuiz Capitulino 
10101cac6f2cSLuiz Capitulino 	VM_BUG_ON(!nodes_allowed);
10111cac6f2cSLuiz Capitulino 
10121cac6f2cSLuiz Capitulino 	nid = get_valid_node_allowed(h->next_nid_to_alloc, nodes_allowed);
10131cac6f2cSLuiz Capitulino 	h->next_nid_to_alloc = next_node_allowed(nid, nodes_allowed);
10141cac6f2cSLuiz Capitulino 
10151cac6f2cSLuiz Capitulino 	return nid;
10161cac6f2cSLuiz Capitulino }
10171cac6f2cSLuiz Capitulino 
10181cac6f2cSLuiz Capitulino /*
10191cac6f2cSLuiz Capitulino  * helper for free_pool_huge_page() - return the previously saved
10201cac6f2cSLuiz Capitulino  * node ["this node"] from which to free a huge page.  Advance the
10211cac6f2cSLuiz Capitulino  * next node id whether or not we find a free huge page to free so
10221cac6f2cSLuiz Capitulino  * that the next attempt to free addresses the next node.
10231cac6f2cSLuiz Capitulino  */
10241cac6f2cSLuiz Capitulino static int hstate_next_node_to_free(struct hstate *h, nodemask_t *nodes_allowed)
10251cac6f2cSLuiz Capitulino {
10261cac6f2cSLuiz Capitulino 	int nid;
10271cac6f2cSLuiz Capitulino 
10281cac6f2cSLuiz Capitulino 	VM_BUG_ON(!nodes_allowed);
10291cac6f2cSLuiz Capitulino 
10301cac6f2cSLuiz Capitulino 	nid = get_valid_node_allowed(h->next_nid_to_free, nodes_allowed);
10311cac6f2cSLuiz Capitulino 	h->next_nid_to_free = next_node_allowed(nid, nodes_allowed);
10321cac6f2cSLuiz Capitulino 
10331cac6f2cSLuiz Capitulino 	return nid;
10341cac6f2cSLuiz Capitulino }
10351cac6f2cSLuiz Capitulino 
10361cac6f2cSLuiz Capitulino #define for_each_node_mask_to_alloc(hs, nr_nodes, node, mask)		\
10371cac6f2cSLuiz Capitulino 	for (nr_nodes = nodes_weight(*mask);				\
10381cac6f2cSLuiz Capitulino 		nr_nodes > 0 &&						\
10391cac6f2cSLuiz Capitulino 		((node = hstate_next_node_to_alloc(hs, mask)) || 1);	\
10401cac6f2cSLuiz Capitulino 		nr_nodes--)
10411cac6f2cSLuiz Capitulino 
10421cac6f2cSLuiz Capitulino #define for_each_node_mask_to_free(hs, nr_nodes, node, mask)		\
10431cac6f2cSLuiz Capitulino 	for (nr_nodes = nodes_weight(*mask);				\
10441cac6f2cSLuiz Capitulino 		nr_nodes > 0 &&						\
10451cac6f2cSLuiz Capitulino 		((node = hstate_next_node_to_free(hs, mask)) || 1);	\
10461cac6f2cSLuiz Capitulino 		nr_nodes--)
10471cac6f2cSLuiz Capitulino 
1048e1073d1eSAneesh Kumar K.V #ifdef CONFIG_ARCH_HAS_GIGANTIC_PAGE
1049944d9fecSLuiz Capitulino static void destroy_compound_gigantic_page(struct page *page,
1050d00181b9SKirill A. Shutemov 					unsigned int order)
1051944d9fecSLuiz Capitulino {
1052944d9fecSLuiz Capitulino 	int i;
1053944d9fecSLuiz Capitulino 	int nr_pages = 1 << order;
1054944d9fecSLuiz Capitulino 	struct page *p = page + 1;
1055944d9fecSLuiz Capitulino 
1056c8cc708aSGerald Schaefer 	atomic_set(compound_mapcount_ptr(page), 0);
1057944d9fecSLuiz Capitulino 	for (i = 1; i < nr_pages; i++, p = mem_map_next(p, page, i)) {
10581d798ca3SKirill A. Shutemov 		clear_compound_head(p);
1059944d9fecSLuiz Capitulino 		set_page_refcounted(p);
1060944d9fecSLuiz Capitulino 	}
1061944d9fecSLuiz Capitulino 
1062944d9fecSLuiz Capitulino 	set_compound_order(page, 0);
1063944d9fecSLuiz Capitulino 	__ClearPageHead(page);
1064944d9fecSLuiz Capitulino }
1065944d9fecSLuiz Capitulino 
1066d00181b9SKirill A. Shutemov static void free_gigantic_page(struct page *page, unsigned int order)
1067944d9fecSLuiz Capitulino {
1068944d9fecSLuiz Capitulino 	free_contig_range(page_to_pfn(page), 1 << order);
1069944d9fecSLuiz Capitulino }
1070944d9fecSLuiz Capitulino 
10714eb0716eSAlexandre Ghiti #ifdef CONFIG_CONTIG_ALLOC
1072944d9fecSLuiz Capitulino static int __alloc_gigantic_page(unsigned long start_pfn,
107379b63f12SMichal Hocko 				unsigned long nr_pages, gfp_t gfp_mask)
1074944d9fecSLuiz Capitulino {
1075944d9fecSLuiz Capitulino 	unsigned long end_pfn = start_pfn + nr_pages;
1076ca96b625SLucas Stach 	return alloc_contig_range(start_pfn, end_pfn, MIGRATE_MOVABLE,
107779b63f12SMichal Hocko 				  gfp_mask);
1078944d9fecSLuiz Capitulino }
1079944d9fecSLuiz Capitulino 
1080f44b2ddaSJoonsoo Kim static bool pfn_range_valid_gigantic(struct zone *z,
1081f44b2ddaSJoonsoo Kim 			unsigned long start_pfn, unsigned long nr_pages)
1082944d9fecSLuiz Capitulino {
1083944d9fecSLuiz Capitulino 	unsigned long i, end_pfn = start_pfn + nr_pages;
1084944d9fecSLuiz Capitulino 	struct page *page;
1085944d9fecSLuiz Capitulino 
1086944d9fecSLuiz Capitulino 	for (i = start_pfn; i < end_pfn; i++) {
1087944d9fecSLuiz Capitulino 		if (!pfn_valid(i))
1088944d9fecSLuiz Capitulino 			return false;
1089944d9fecSLuiz Capitulino 
1090944d9fecSLuiz Capitulino 		page = pfn_to_page(i);
1091944d9fecSLuiz Capitulino 
1092f44b2ddaSJoonsoo Kim 		if (page_zone(page) != z)
1093f44b2ddaSJoonsoo Kim 			return false;
1094f44b2ddaSJoonsoo Kim 
1095944d9fecSLuiz Capitulino 		if (PageReserved(page))
1096944d9fecSLuiz Capitulino 			return false;
1097944d9fecSLuiz Capitulino 
1098944d9fecSLuiz Capitulino 		if (page_count(page) > 0)
1099944d9fecSLuiz Capitulino 			return false;
1100944d9fecSLuiz Capitulino 
1101944d9fecSLuiz Capitulino 		if (PageHuge(page))
1102944d9fecSLuiz Capitulino 			return false;
1103944d9fecSLuiz Capitulino 	}
1104944d9fecSLuiz Capitulino 
1105944d9fecSLuiz Capitulino 	return true;
1106944d9fecSLuiz Capitulino }
1107944d9fecSLuiz Capitulino 
1108944d9fecSLuiz Capitulino static bool zone_spans_last_pfn(const struct zone *zone,
1109944d9fecSLuiz Capitulino 			unsigned long start_pfn, unsigned long nr_pages)
1110944d9fecSLuiz Capitulino {
1111944d9fecSLuiz Capitulino 	unsigned long last_pfn = start_pfn + nr_pages - 1;
1112944d9fecSLuiz Capitulino 	return zone_spans_pfn(zone, last_pfn);
1113944d9fecSLuiz Capitulino }
1114944d9fecSLuiz Capitulino 
1115d9cc948fSMichal Hocko static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
1116d9cc948fSMichal Hocko 		int nid, nodemask_t *nodemask)
1117944d9fecSLuiz Capitulino {
111879b63f12SMichal Hocko 	unsigned int order = huge_page_order(h);
1119944d9fecSLuiz Capitulino 	unsigned long nr_pages = 1 << order;
1120944d9fecSLuiz Capitulino 	unsigned long ret, pfn, flags;
112179b63f12SMichal Hocko 	struct zonelist *zonelist;
112279b63f12SMichal Hocko 	struct zone *zone;
112379b63f12SMichal Hocko 	struct zoneref *z;
1124944d9fecSLuiz Capitulino 
112579b63f12SMichal Hocko 	zonelist = node_zonelist(nid, gfp_mask);
1126d9cc948fSMichal Hocko 	for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nodemask) {
112779b63f12SMichal Hocko 		spin_lock_irqsave(&zone->lock, flags);
1128944d9fecSLuiz Capitulino 
112979b63f12SMichal Hocko 		pfn = ALIGN(zone->zone_start_pfn, nr_pages);
113079b63f12SMichal Hocko 		while (zone_spans_last_pfn(zone, pfn, nr_pages)) {
113179b63f12SMichal Hocko 			if (pfn_range_valid_gigantic(zone, pfn, nr_pages)) {
1132944d9fecSLuiz Capitulino 				/*
1133944d9fecSLuiz Capitulino 				 * We release the zone lock here because
1134944d9fecSLuiz Capitulino 				 * alloc_contig_range() will also lock the zone
1135944d9fecSLuiz Capitulino 				 * at some point. If there's an allocation
1136944d9fecSLuiz Capitulino 				 * spinning on this lock, it may win the race
1137944d9fecSLuiz Capitulino 				 * and cause alloc_contig_range() to fail...
1138944d9fecSLuiz Capitulino 				 */
113979b63f12SMichal Hocko 				spin_unlock_irqrestore(&zone->lock, flags);
114079b63f12SMichal Hocko 				ret = __alloc_gigantic_page(pfn, nr_pages, gfp_mask);
1141944d9fecSLuiz Capitulino 				if (!ret)
1142944d9fecSLuiz Capitulino 					return pfn_to_page(pfn);
114379b63f12SMichal Hocko 				spin_lock_irqsave(&zone->lock, flags);
1144944d9fecSLuiz Capitulino 			}
1145944d9fecSLuiz Capitulino 			pfn += nr_pages;
1146944d9fecSLuiz Capitulino 		}
1147944d9fecSLuiz Capitulino 
114879b63f12SMichal Hocko 		spin_unlock_irqrestore(&zone->lock, flags);
1149944d9fecSLuiz Capitulino 	}
1150944d9fecSLuiz Capitulino 
1151944d9fecSLuiz Capitulino 	return NULL;
1152944d9fecSLuiz Capitulino }
1153944d9fecSLuiz Capitulino 
1154944d9fecSLuiz Capitulino static void prep_new_huge_page(struct hstate *h, struct page *page, int nid);
1155d00181b9SKirill A. Shutemov static void prep_compound_gigantic_page(struct page *page, unsigned int order);
11564eb0716eSAlexandre Ghiti #else /* !CONFIG_CONTIG_ALLOC */
11574eb0716eSAlexandre Ghiti static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
11584eb0716eSAlexandre Ghiti 					int nid, nodemask_t *nodemask)
11594eb0716eSAlexandre Ghiti {
11604eb0716eSAlexandre Ghiti 	return NULL;
11614eb0716eSAlexandre Ghiti }
11624eb0716eSAlexandre Ghiti #endif /* CONFIG_CONTIG_ALLOC */
1163944d9fecSLuiz Capitulino 
1164e1073d1eSAneesh Kumar K.V #else /* !CONFIG_ARCH_HAS_GIGANTIC_PAGE */
1165d9cc948fSMichal Hocko static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
11664eb0716eSAlexandre Ghiti 					int nid, nodemask_t *nodemask)
11674eb0716eSAlexandre Ghiti {
11684eb0716eSAlexandre Ghiti 	return NULL;
11694eb0716eSAlexandre Ghiti }
1170d00181b9SKirill A. Shutemov static inline void free_gigantic_page(struct page *page, unsigned int order) { }
1171944d9fecSLuiz Capitulino static inline void destroy_compound_gigantic_page(struct page *page,
1172d00181b9SKirill A. Shutemov 						unsigned int order) { }
1173944d9fecSLuiz Capitulino #endif
1174944d9fecSLuiz Capitulino 
1175a5516438SAndi Kleen static void update_and_free_page(struct hstate *h, struct page *page)
11766af2acb6SAdam Litke {
11776af2acb6SAdam Litke 	int i;
1178a5516438SAndi Kleen 
11794eb0716eSAlexandre Ghiti 	if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
1180944d9fecSLuiz Capitulino 		return;
118118229df5SAndy Whitcroft 
1182a5516438SAndi Kleen 	h->nr_huge_pages--;
1183a5516438SAndi Kleen 	h->nr_huge_pages_node[page_to_nid(page)]--;
1184a5516438SAndi Kleen 	for (i = 0; i < pages_per_huge_page(h); i++) {
118532f84528SChris Forbes 		page[i].flags &= ~(1 << PG_locked | 1 << PG_error |
118632f84528SChris Forbes 				1 << PG_referenced | 1 << PG_dirty |
1187a7407a27SLuiz Capitulino 				1 << PG_active | 1 << PG_private |
1188a7407a27SLuiz Capitulino 				1 << PG_writeback);
11896af2acb6SAdam Litke 	}
1190309381feSSasha Levin 	VM_BUG_ON_PAGE(hugetlb_cgroup_from_page(page), page);
1191f1e61557SKirill A. Shutemov 	set_compound_page_dtor(page, NULL_COMPOUND_DTOR);
11926af2acb6SAdam Litke 	set_page_refcounted(page);
1193944d9fecSLuiz Capitulino 	if (hstate_is_gigantic(h)) {
1194944d9fecSLuiz Capitulino 		destroy_compound_gigantic_page(page, huge_page_order(h));
1195944d9fecSLuiz Capitulino 		free_gigantic_page(page, huge_page_order(h));
1196944d9fecSLuiz Capitulino 	} else {
1197a5516438SAndi Kleen 		__free_pages(page, huge_page_order(h));
11986af2acb6SAdam Litke 	}
1199944d9fecSLuiz Capitulino }
12006af2acb6SAdam Litke 
1201e5ff2159SAndi Kleen struct hstate *size_to_hstate(unsigned long size)
1202e5ff2159SAndi Kleen {
1203e5ff2159SAndi Kleen 	struct hstate *h;
1204e5ff2159SAndi Kleen 
1205e5ff2159SAndi Kleen 	for_each_hstate(h) {
1206e5ff2159SAndi Kleen 		if (huge_page_size(h) == size)
1207e5ff2159SAndi Kleen 			return h;
1208e5ff2159SAndi Kleen 	}
1209e5ff2159SAndi Kleen 	return NULL;
1210e5ff2159SAndi Kleen }
1211e5ff2159SAndi Kleen 
1212bcc54222SNaoya Horiguchi /*
1213bcc54222SNaoya Horiguchi  * Test to determine whether the hugepage is "active/in-use" (i.e. being linked
1214bcc54222SNaoya Horiguchi  * to hstate->hugepage_activelist.)
1215bcc54222SNaoya Horiguchi  *
1216bcc54222SNaoya Horiguchi  * This function can be called for tail pages, but never returns true for them.
1217bcc54222SNaoya Horiguchi  */
1218bcc54222SNaoya Horiguchi bool page_huge_active(struct page *page)
1219bcc54222SNaoya Horiguchi {
1220bcc54222SNaoya Horiguchi 	VM_BUG_ON_PAGE(!PageHuge(page), page);
1221bcc54222SNaoya Horiguchi 	return PageHead(page) && PagePrivate(&page[1]);
1222bcc54222SNaoya Horiguchi }
1223bcc54222SNaoya Horiguchi 
1224bcc54222SNaoya Horiguchi /* never called for tail page */
1225bcc54222SNaoya Horiguchi static void set_page_huge_active(struct page *page)
1226bcc54222SNaoya Horiguchi {
1227bcc54222SNaoya Horiguchi 	VM_BUG_ON_PAGE(!PageHeadHuge(page), page);
1228bcc54222SNaoya Horiguchi 	SetPagePrivate(&page[1]);
1229bcc54222SNaoya Horiguchi }
1230bcc54222SNaoya Horiguchi 
1231bcc54222SNaoya Horiguchi static void clear_page_huge_active(struct page *page)
1232bcc54222SNaoya Horiguchi {
1233bcc54222SNaoya Horiguchi 	VM_BUG_ON_PAGE(!PageHeadHuge(page), page);
1234bcc54222SNaoya Horiguchi 	ClearPagePrivate(&page[1]);
1235bcc54222SNaoya Horiguchi }
1236bcc54222SNaoya Horiguchi 
1237ab5ac90aSMichal Hocko /*
1238ab5ac90aSMichal Hocko  * Internal hugetlb specific page flag. Do not use outside of the hugetlb
1239ab5ac90aSMichal Hocko  * code
1240ab5ac90aSMichal Hocko  */
1241ab5ac90aSMichal Hocko static inline bool PageHugeTemporary(struct page *page)
1242ab5ac90aSMichal Hocko {
1243ab5ac90aSMichal Hocko 	if (!PageHuge(page))
1244ab5ac90aSMichal Hocko 		return false;
1245ab5ac90aSMichal Hocko 
1246ab5ac90aSMichal Hocko 	return (unsigned long)page[2].mapping == -1U;
1247ab5ac90aSMichal Hocko }
1248ab5ac90aSMichal Hocko 
1249ab5ac90aSMichal Hocko static inline void SetPageHugeTemporary(struct page *page)
1250ab5ac90aSMichal Hocko {
1251ab5ac90aSMichal Hocko 	page[2].mapping = (void *)-1U;
1252ab5ac90aSMichal Hocko }
1253ab5ac90aSMichal Hocko 
1254ab5ac90aSMichal Hocko static inline void ClearPageHugeTemporary(struct page *page)
1255ab5ac90aSMichal Hocko {
1256ab5ac90aSMichal Hocko 	page[2].mapping = NULL;
1257ab5ac90aSMichal Hocko }
1258ab5ac90aSMichal Hocko 
12598f1d26d0SAtsushi Kumagai void free_huge_page(struct page *page)
126027a85ef1SDavid Gibson {
1261a5516438SAndi Kleen 	/*
1262a5516438SAndi Kleen 	 * Can't pass hstate in here because it is called from the
1263a5516438SAndi Kleen 	 * compound page destructor.
1264a5516438SAndi Kleen 	 */
1265e5ff2159SAndi Kleen 	struct hstate *h = page_hstate(page);
12667893d1d5SAdam Litke 	int nid = page_to_nid(page);
126790481622SDavid Gibson 	struct hugepage_subpool *spool =
126890481622SDavid Gibson 		(struct hugepage_subpool *)page_private(page);
126907443a85SJoonsoo Kim 	bool restore_reserve;
127027a85ef1SDavid Gibson 
1271b4330afbSMike Kravetz 	VM_BUG_ON_PAGE(page_count(page), page);
1272b4330afbSMike Kravetz 	VM_BUG_ON_PAGE(page_mapcount(page), page);
12738ace22bcSYongkai Wu 
12748ace22bcSYongkai Wu 	set_page_private(page, 0);
12758ace22bcSYongkai Wu 	page->mapping = NULL;
127607443a85SJoonsoo Kim 	restore_reserve = PagePrivate(page);
127716c794b4SJoonsoo Kim 	ClearPagePrivate(page);
127827a85ef1SDavid Gibson 
12791c5ecae3SMike Kravetz 	/*
12800919e1b6SMike Kravetz 	 * If PagePrivate() was set on page, page allocation consumed a
12810919e1b6SMike Kravetz 	 * reservation.  If the page was associated with a subpool, there
12820919e1b6SMike Kravetz 	 * would have been a page reserved in the subpool before allocation
12830919e1b6SMike Kravetz 	 * via hugepage_subpool_get_pages().  Since we are 'restoring' the
12840919e1b6SMike Kravetz 	 * reservtion, do not call hugepage_subpool_put_pages() as this will
12850919e1b6SMike Kravetz 	 * remove the reserved page from the subpool.
12860919e1b6SMike Kravetz 	 */
12870919e1b6SMike Kravetz 	if (!restore_reserve) {
12880919e1b6SMike Kravetz 		/*
12890919e1b6SMike Kravetz 		 * A return code of zero implies that the subpool will be
12900919e1b6SMike Kravetz 		 * under its minimum size if the reservation is not restored
12910919e1b6SMike Kravetz 		 * after page is free.  Therefore, force restore_reserve
12920919e1b6SMike Kravetz 		 * operation.
12931c5ecae3SMike Kravetz 		 */
12941c5ecae3SMike Kravetz 		if (hugepage_subpool_put_pages(spool, 1) == 0)
12951c5ecae3SMike Kravetz 			restore_reserve = true;
12960919e1b6SMike Kravetz 	}
12971c5ecae3SMike Kravetz 
129827a85ef1SDavid Gibson 	spin_lock(&hugetlb_lock);
1299bcc54222SNaoya Horiguchi 	clear_page_huge_active(page);
13006d76dcf4SAneesh Kumar K.V 	hugetlb_cgroup_uncharge_page(hstate_index(h),
13016d76dcf4SAneesh Kumar K.V 				     pages_per_huge_page(h), page);
130207443a85SJoonsoo Kim 	if (restore_reserve)
130307443a85SJoonsoo Kim 		h->resv_huge_pages++;
130407443a85SJoonsoo Kim 
1305ab5ac90aSMichal Hocko 	if (PageHugeTemporary(page)) {
1306ab5ac90aSMichal Hocko 		list_del(&page->lru);
1307ab5ac90aSMichal Hocko 		ClearPageHugeTemporary(page);
1308ab5ac90aSMichal Hocko 		update_and_free_page(h, page);
1309ab5ac90aSMichal Hocko 	} else if (h->surplus_huge_pages_node[nid]) {
13100edaecfaSAneesh Kumar K.V 		/* remove the page from active list */
13110edaecfaSAneesh Kumar K.V 		list_del(&page->lru);
1312a5516438SAndi Kleen 		update_and_free_page(h, page);
1313a5516438SAndi Kleen 		h->surplus_huge_pages--;
1314a5516438SAndi Kleen 		h->surplus_huge_pages_node[nid]--;
13157893d1d5SAdam Litke 	} else {
13165d3a551cSWill Deacon 		arch_clear_hugepage_flags(page);
1317a5516438SAndi Kleen 		enqueue_huge_page(h, page);
13187893d1d5SAdam Litke 	}
131927a85ef1SDavid Gibson 	spin_unlock(&hugetlb_lock);
132027a85ef1SDavid Gibson }
132127a85ef1SDavid Gibson 
1322a5516438SAndi Kleen static void prep_new_huge_page(struct hstate *h, struct page *page, int nid)
1323b7ba30c6SAndi Kleen {
13240edaecfaSAneesh Kumar K.V 	INIT_LIST_HEAD(&page->lru);
1325f1e61557SKirill A. Shutemov 	set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
1326b7ba30c6SAndi Kleen 	spin_lock(&hugetlb_lock);
13279dd540e2SAneesh Kumar K.V 	set_hugetlb_cgroup(page, NULL);
1328a5516438SAndi Kleen 	h->nr_huge_pages++;
1329a5516438SAndi Kleen 	h->nr_huge_pages_node[nid]++;
1330b7ba30c6SAndi Kleen 	spin_unlock(&hugetlb_lock);
1331b7ba30c6SAndi Kleen }
1332b7ba30c6SAndi Kleen 
1333d00181b9SKirill A. Shutemov static void prep_compound_gigantic_page(struct page *page, unsigned int order)
133420a0307cSWu Fengguang {
133520a0307cSWu Fengguang 	int i;
133620a0307cSWu Fengguang 	int nr_pages = 1 << order;
133720a0307cSWu Fengguang 	struct page *p = page + 1;
133820a0307cSWu Fengguang 
133920a0307cSWu Fengguang 	/* we rely on prep_new_huge_page to set the destructor */
134020a0307cSWu Fengguang 	set_compound_order(page, order);
1341ef5a22beSAndrea Arcangeli 	__ClearPageReserved(page);
1342de09d31dSKirill A. Shutemov 	__SetPageHead(page);
134320a0307cSWu Fengguang 	for (i = 1; i < nr_pages; i++, p = mem_map_next(p, page, i)) {
1344ef5a22beSAndrea Arcangeli 		/*
1345ef5a22beSAndrea Arcangeli 		 * For gigantic hugepages allocated through bootmem at
1346ef5a22beSAndrea Arcangeli 		 * boot, it's safer to be consistent with the not-gigantic
1347ef5a22beSAndrea Arcangeli 		 * hugepages and clear the PG_reserved bit from all tail pages
1348ef5a22beSAndrea Arcangeli 		 * too.  Otherwse drivers using get_user_pages() to access tail
1349ef5a22beSAndrea Arcangeli 		 * pages may get the reference counting wrong if they see
1350ef5a22beSAndrea Arcangeli 		 * PG_reserved set on a tail page (despite the head page not
1351ef5a22beSAndrea Arcangeli 		 * having PG_reserved set).  Enforcing this consistency between
1352ef5a22beSAndrea Arcangeli 		 * head and tail pages allows drivers to optimize away a check
1353ef5a22beSAndrea Arcangeli 		 * on the head page when they need know if put_page() is needed
1354ef5a22beSAndrea Arcangeli 		 * after get_user_pages().
1355ef5a22beSAndrea Arcangeli 		 */
1356ef5a22beSAndrea Arcangeli 		__ClearPageReserved(p);
135758a84aa9SYouquan Song 		set_page_count(p, 0);
13581d798ca3SKirill A. Shutemov 		set_compound_head(p, page);
135920a0307cSWu Fengguang 	}
1360b4330afbSMike Kravetz 	atomic_set(compound_mapcount_ptr(page), -1);
136120a0307cSWu Fengguang }
136220a0307cSWu Fengguang 
13637795912cSAndrew Morton /*
13647795912cSAndrew Morton  * PageHuge() only returns true for hugetlbfs pages, but not for normal or
13657795912cSAndrew Morton  * transparent huge pages.  See the PageTransHuge() documentation for more
13667795912cSAndrew Morton  * details.
13677795912cSAndrew Morton  */
136820a0307cSWu Fengguang int PageHuge(struct page *page)
136920a0307cSWu Fengguang {
137020a0307cSWu Fengguang 	if (!PageCompound(page))
137120a0307cSWu Fengguang 		return 0;
137220a0307cSWu Fengguang 
137320a0307cSWu Fengguang 	page = compound_head(page);
1374f1e61557SKirill A. Shutemov 	return page[1].compound_dtor == HUGETLB_PAGE_DTOR;
137520a0307cSWu Fengguang }
137643131e14SNaoya Horiguchi EXPORT_SYMBOL_GPL(PageHuge);
137743131e14SNaoya Horiguchi 
137827c73ae7SAndrea Arcangeli /*
137927c73ae7SAndrea Arcangeli  * PageHeadHuge() only returns true for hugetlbfs head page, but not for
138027c73ae7SAndrea Arcangeli  * normal or transparent huge pages.
138127c73ae7SAndrea Arcangeli  */
138227c73ae7SAndrea Arcangeli int PageHeadHuge(struct page *page_head)
138327c73ae7SAndrea Arcangeli {
138427c73ae7SAndrea Arcangeli 	if (!PageHead(page_head))
138527c73ae7SAndrea Arcangeli 		return 0;
138627c73ae7SAndrea Arcangeli 
1387758f66a2SAndrew Morton 	return get_compound_page_dtor(page_head) == free_huge_page;
138827c73ae7SAndrea Arcangeli }
138927c73ae7SAndrea Arcangeli 
139013d60f4bSZhang Yi pgoff_t __basepage_index(struct page *page)
139113d60f4bSZhang Yi {
139213d60f4bSZhang Yi 	struct page *page_head = compound_head(page);
139313d60f4bSZhang Yi 	pgoff_t index = page_index(page_head);
139413d60f4bSZhang Yi 	unsigned long compound_idx;
139513d60f4bSZhang Yi 
139613d60f4bSZhang Yi 	if (!PageHuge(page_head))
139713d60f4bSZhang Yi 		return page_index(page);
139813d60f4bSZhang Yi 
139913d60f4bSZhang Yi 	if (compound_order(page_head) >= MAX_ORDER)
140013d60f4bSZhang Yi 		compound_idx = page_to_pfn(page) - page_to_pfn(page_head);
140113d60f4bSZhang Yi 	else
140213d60f4bSZhang Yi 		compound_idx = page - page_head;
140313d60f4bSZhang Yi 
140413d60f4bSZhang Yi 	return (index << compound_order(page_head)) + compound_idx;
140513d60f4bSZhang Yi }
140613d60f4bSZhang Yi 
14070c397daeSMichal Hocko static struct page *alloc_buddy_huge_page(struct hstate *h,
1408af0fb9dfSMichal Hocko 		gfp_t gfp_mask, int nid, nodemask_t *nmask)
14091da177e4SLinus Torvalds {
1410af0fb9dfSMichal Hocko 	int order = huge_page_order(h);
14111da177e4SLinus Torvalds 	struct page *page;
1412f96efd58SJoe Jin 
1413af0fb9dfSMichal Hocko 	gfp_mask |= __GFP_COMP|__GFP_RETRY_MAYFAIL|__GFP_NOWARN;
1414af0fb9dfSMichal Hocko 	if (nid == NUMA_NO_NODE)
1415af0fb9dfSMichal Hocko 		nid = numa_mem_id();
1416af0fb9dfSMichal Hocko 	page = __alloc_pages_nodemask(gfp_mask, order, nid, nmask);
1417af0fb9dfSMichal Hocko 	if (page)
1418af0fb9dfSMichal Hocko 		__count_vm_event(HTLB_BUDDY_PGALLOC);
1419af0fb9dfSMichal Hocko 	else
1420af0fb9dfSMichal Hocko 		__count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
142163b4613cSNishanth Aravamudan 
142263b4613cSNishanth Aravamudan 	return page;
142363b4613cSNishanth Aravamudan }
142463b4613cSNishanth Aravamudan 
1425af0fb9dfSMichal Hocko /*
14260c397daeSMichal Hocko  * Common helper to allocate a fresh hugetlb page. All specific allocators
14270c397daeSMichal Hocko  * should use this function to get new hugetlb pages
14280c397daeSMichal Hocko  */
14290c397daeSMichal Hocko static struct page *alloc_fresh_huge_page(struct hstate *h,
14300c397daeSMichal Hocko 		gfp_t gfp_mask, int nid, nodemask_t *nmask)
14310c397daeSMichal Hocko {
14320c397daeSMichal Hocko 	struct page *page;
14330c397daeSMichal Hocko 
14340c397daeSMichal Hocko 	if (hstate_is_gigantic(h))
14350c397daeSMichal Hocko 		page = alloc_gigantic_page(h, gfp_mask, nid, nmask);
14360c397daeSMichal Hocko 	else
14370c397daeSMichal Hocko 		page = alloc_buddy_huge_page(h, gfp_mask,
14380c397daeSMichal Hocko 				nid, nmask);
14390c397daeSMichal Hocko 	if (!page)
14400c397daeSMichal Hocko 		return NULL;
14410c397daeSMichal Hocko 
14420c397daeSMichal Hocko 	if (hstate_is_gigantic(h))
14430c397daeSMichal Hocko 		prep_compound_gigantic_page(page, huge_page_order(h));
14440c397daeSMichal Hocko 	prep_new_huge_page(h, page, page_to_nid(page));
14450c397daeSMichal Hocko 
14460c397daeSMichal Hocko 	return page;
14470c397daeSMichal Hocko }
14480c397daeSMichal Hocko 
14490c397daeSMichal Hocko /*
1450af0fb9dfSMichal Hocko  * Allocates a fresh page to the hugetlb allocator pool in the node interleaved
1451af0fb9dfSMichal Hocko  * manner.
1452af0fb9dfSMichal Hocko  */
14530c397daeSMichal Hocko static int alloc_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed)
1454b2261026SJoonsoo Kim {
1455b2261026SJoonsoo Kim 	struct page *page;
1456b2261026SJoonsoo Kim 	int nr_nodes, node;
1457af0fb9dfSMichal Hocko 	gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
1458b2261026SJoonsoo Kim 
1459b2261026SJoonsoo Kim 	for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
14600c397daeSMichal Hocko 		page = alloc_fresh_huge_page(h, gfp_mask, node, nodes_allowed);
1461af0fb9dfSMichal Hocko 		if (page)
1462b2261026SJoonsoo Kim 			break;
1463b2261026SJoonsoo Kim 	}
1464b2261026SJoonsoo Kim 
1465af0fb9dfSMichal Hocko 	if (!page)
1466af0fb9dfSMichal Hocko 		return 0;
1467b2261026SJoonsoo Kim 
1468af0fb9dfSMichal Hocko 	put_page(page); /* free it into the hugepage allocator */
1469af0fb9dfSMichal Hocko 
1470af0fb9dfSMichal Hocko 	return 1;
1471b2261026SJoonsoo Kim }
1472b2261026SJoonsoo Kim 
1473e8c5c824SLee Schermerhorn /*
1474e8c5c824SLee Schermerhorn  * Free huge page from pool from next node to free.
1475e8c5c824SLee Schermerhorn  * Attempt to keep persistent huge pages more or less
1476e8c5c824SLee Schermerhorn  * balanced over allowed nodes.
1477e8c5c824SLee Schermerhorn  * Called with hugetlb_lock locked.
1478e8c5c824SLee Schermerhorn  */
14796ae11b27SLee Schermerhorn static int free_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed,
14806ae11b27SLee Schermerhorn 							 bool acct_surplus)
1481e8c5c824SLee Schermerhorn {
1482b2261026SJoonsoo Kim 	int nr_nodes, node;
1483e8c5c824SLee Schermerhorn 	int ret = 0;
1484e8c5c824SLee Schermerhorn 
1485b2261026SJoonsoo Kim 	for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
1486685f3457SLee Schermerhorn 		/*
1487685f3457SLee Schermerhorn 		 * If we're returning unused surplus pages, only examine
1488685f3457SLee Schermerhorn 		 * nodes with surplus pages.
1489685f3457SLee Schermerhorn 		 */
1490b2261026SJoonsoo Kim 		if ((!acct_surplus || h->surplus_huge_pages_node[node]) &&
1491b2261026SJoonsoo Kim 		    !list_empty(&h->hugepage_freelists[node])) {
1492e8c5c824SLee Schermerhorn 			struct page *page =
1493b2261026SJoonsoo Kim 				list_entry(h->hugepage_freelists[node].next,
1494e8c5c824SLee Schermerhorn 					  struct page, lru);
1495e8c5c824SLee Schermerhorn 			list_del(&page->lru);
1496e8c5c824SLee Schermerhorn 			h->free_huge_pages--;
1497b2261026SJoonsoo Kim 			h->free_huge_pages_node[node]--;
1498685f3457SLee Schermerhorn 			if (acct_surplus) {
1499685f3457SLee Schermerhorn 				h->surplus_huge_pages--;
1500b2261026SJoonsoo Kim 				h->surplus_huge_pages_node[node]--;
1501685f3457SLee Schermerhorn 			}
1502e8c5c824SLee Schermerhorn 			update_and_free_page(h, page);
1503e8c5c824SLee Schermerhorn 			ret = 1;
15049a76db09SLee Schermerhorn 			break;
1505e8c5c824SLee Schermerhorn 		}
1506b2261026SJoonsoo Kim 	}
1507e8c5c824SLee Schermerhorn 
1508e8c5c824SLee Schermerhorn 	return ret;
1509e8c5c824SLee Schermerhorn }
1510e8c5c824SLee Schermerhorn 
1511c8721bbbSNaoya Horiguchi /*
1512c8721bbbSNaoya Horiguchi  * Dissolve a given free hugepage into free buddy pages. This function does
1513faf53defSNaoya Horiguchi  * nothing for in-use hugepages and non-hugepages.
1514faf53defSNaoya Horiguchi  * This function returns values like below:
1515faf53defSNaoya Horiguchi  *
1516faf53defSNaoya Horiguchi  *  -EBUSY: failed to dissolved free hugepages or the hugepage is in-use
1517faf53defSNaoya Horiguchi  *          (allocated or reserved.)
1518faf53defSNaoya Horiguchi  *       0: successfully dissolved free hugepages or the page is not a
1519faf53defSNaoya Horiguchi  *          hugepage (considered as already dissolved)
1520c8721bbbSNaoya Horiguchi  */
1521c3114a84SAnshuman Khandual int dissolve_free_huge_page(struct page *page)
1522c8721bbbSNaoya Horiguchi {
15236bc9b564SNaoya Horiguchi 	int rc = -EBUSY;
1524082d5b6bSGerald Schaefer 
1525faf53defSNaoya Horiguchi 	/* Not to disrupt normal path by vainly holding hugetlb_lock */
1526faf53defSNaoya Horiguchi 	if (!PageHuge(page))
1527faf53defSNaoya Horiguchi 		return 0;
1528faf53defSNaoya Horiguchi 
1529c8721bbbSNaoya Horiguchi 	spin_lock(&hugetlb_lock);
1530faf53defSNaoya Horiguchi 	if (!PageHuge(page)) {
1531faf53defSNaoya Horiguchi 		rc = 0;
1532faf53defSNaoya Horiguchi 		goto out;
1533faf53defSNaoya Horiguchi 	}
1534faf53defSNaoya Horiguchi 
1535faf53defSNaoya Horiguchi 	if (!page_count(page)) {
15362247bb33SGerald Schaefer 		struct page *head = compound_head(page);
15372247bb33SGerald Schaefer 		struct hstate *h = page_hstate(head);
15382247bb33SGerald Schaefer 		int nid = page_to_nid(head);
15396bc9b564SNaoya Horiguchi 		if (h->free_huge_pages - h->resv_huge_pages == 0)
1540082d5b6bSGerald Schaefer 			goto out;
1541c3114a84SAnshuman Khandual 		/*
1542c3114a84SAnshuman Khandual 		 * Move PageHWPoison flag from head page to the raw error page,
1543c3114a84SAnshuman Khandual 		 * which makes any subpages rather than the error page reusable.
1544c3114a84SAnshuman Khandual 		 */
1545c3114a84SAnshuman Khandual 		if (PageHWPoison(head) && page != head) {
1546c3114a84SAnshuman Khandual 			SetPageHWPoison(page);
1547c3114a84SAnshuman Khandual 			ClearPageHWPoison(head);
1548c3114a84SAnshuman Khandual 		}
15492247bb33SGerald Schaefer 		list_del(&head->lru);
1550c8721bbbSNaoya Horiguchi 		h->free_huge_pages--;
1551c8721bbbSNaoya Horiguchi 		h->free_huge_pages_node[nid]--;
1552c1470b33Szhong jiang 		h->max_huge_pages--;
15532247bb33SGerald Schaefer 		update_and_free_page(h, head);
15546bc9b564SNaoya Horiguchi 		rc = 0;
1555c8721bbbSNaoya Horiguchi 	}
1556082d5b6bSGerald Schaefer out:
1557c8721bbbSNaoya Horiguchi 	spin_unlock(&hugetlb_lock);
1558082d5b6bSGerald Schaefer 	return rc;
1559c8721bbbSNaoya Horiguchi }
1560c8721bbbSNaoya Horiguchi 
1561c8721bbbSNaoya Horiguchi /*
1562c8721bbbSNaoya Horiguchi  * Dissolve free hugepages in a given pfn range. Used by memory hotplug to
1563c8721bbbSNaoya Horiguchi  * make specified memory blocks removable from the system.
15642247bb33SGerald Schaefer  * Note that this will dissolve a free gigantic hugepage completely, if any
15652247bb33SGerald Schaefer  * part of it lies within the given range.
1566082d5b6bSGerald Schaefer  * Also note that if dissolve_free_huge_page() returns with an error, all
1567082d5b6bSGerald Schaefer  * free hugepages that were dissolved before that error are lost.
1568c8721bbbSNaoya Horiguchi  */
1569082d5b6bSGerald Schaefer int dissolve_free_huge_pages(unsigned long start_pfn, unsigned long end_pfn)
1570c8721bbbSNaoya Horiguchi {
1571c8721bbbSNaoya Horiguchi 	unsigned long pfn;
1572eb03aa00SGerald Schaefer 	struct page *page;
1573082d5b6bSGerald Schaefer 	int rc = 0;
1574c8721bbbSNaoya Horiguchi 
1575d0177639SLi Zhong 	if (!hugepages_supported())
1576082d5b6bSGerald Schaefer 		return rc;
1577d0177639SLi Zhong 
1578eb03aa00SGerald Schaefer 	for (pfn = start_pfn; pfn < end_pfn; pfn += 1 << minimum_order) {
1579eb03aa00SGerald Schaefer 		page = pfn_to_page(pfn);
1580eb03aa00SGerald Schaefer 		rc = dissolve_free_huge_page(page);
1581eb03aa00SGerald Schaefer 		if (rc)
1582082d5b6bSGerald Schaefer 			break;
1583eb03aa00SGerald Schaefer 	}
1584082d5b6bSGerald Schaefer 
1585082d5b6bSGerald Schaefer 	return rc;
1586c8721bbbSNaoya Horiguchi }
1587c8721bbbSNaoya Horiguchi 
1588ab5ac90aSMichal Hocko /*
1589ab5ac90aSMichal Hocko  * Allocates a fresh surplus page from the page allocator.
1590ab5ac90aSMichal Hocko  */
15910c397daeSMichal Hocko static struct page *alloc_surplus_huge_page(struct hstate *h, gfp_t gfp_mask,
1592aaf14e40SMichal Hocko 		int nid, nodemask_t *nmask)
15937893d1d5SAdam Litke {
15949980d744SMichal Hocko 	struct page *page = NULL;
15957893d1d5SAdam Litke 
1596bae7f4aeSLuiz Capitulino 	if (hstate_is_gigantic(h))
1597aa888a74SAndi Kleen 		return NULL;
1598aa888a74SAndi Kleen 
1599d1c3fb1fSNishanth Aravamudan 	spin_lock(&hugetlb_lock);
16009980d744SMichal Hocko 	if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages)
16019980d744SMichal Hocko 		goto out_unlock;
1602d1c3fb1fSNishanth Aravamudan 	spin_unlock(&hugetlb_lock);
1603d1c3fb1fSNishanth Aravamudan 
16040c397daeSMichal Hocko 	page = alloc_fresh_huge_page(h, gfp_mask, nid, nmask);
16059980d744SMichal Hocko 	if (!page)
16060c397daeSMichal Hocko 		return NULL;
1607d1c3fb1fSNishanth Aravamudan 
16087893d1d5SAdam Litke 	spin_lock(&hugetlb_lock);
16099980d744SMichal Hocko 	/*
16109980d744SMichal Hocko 	 * We could have raced with the pool size change.
16119980d744SMichal Hocko 	 * Double check that and simply deallocate the new page
16129980d744SMichal Hocko 	 * if we would end up overcommiting the surpluses. Abuse
16139980d744SMichal Hocko 	 * temporary page to workaround the nasty free_huge_page
16149980d744SMichal Hocko 	 * codeflow
16159980d744SMichal Hocko 	 */
16169980d744SMichal Hocko 	if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) {
16179980d744SMichal Hocko 		SetPageHugeTemporary(page);
16182bf753e6SKai Shen 		spin_unlock(&hugetlb_lock);
16199980d744SMichal Hocko 		put_page(page);
16202bf753e6SKai Shen 		return NULL;
16219980d744SMichal Hocko 	} else {
16229980d744SMichal Hocko 		h->surplus_huge_pages++;
16234704dea3SMichal Hocko 		h->surplus_huge_pages_node[page_to_nid(page)]++;
16247893d1d5SAdam Litke 	}
16259980d744SMichal Hocko 
16269980d744SMichal Hocko out_unlock:
1627d1c3fb1fSNishanth Aravamudan 	spin_unlock(&hugetlb_lock);
16287893d1d5SAdam Litke 
16297893d1d5SAdam Litke 	return page;
16307893d1d5SAdam Litke }
16317893d1d5SAdam Litke 
16329a4e9f3bSAneesh Kumar K.V struct page *alloc_migrate_huge_page(struct hstate *h, gfp_t gfp_mask,
1633ab5ac90aSMichal Hocko 				     int nid, nodemask_t *nmask)
1634ab5ac90aSMichal Hocko {
1635ab5ac90aSMichal Hocko 	struct page *page;
1636ab5ac90aSMichal Hocko 
1637ab5ac90aSMichal Hocko 	if (hstate_is_gigantic(h))
1638ab5ac90aSMichal Hocko 		return NULL;
1639ab5ac90aSMichal Hocko 
16400c397daeSMichal Hocko 	page = alloc_fresh_huge_page(h, gfp_mask, nid, nmask);
1641ab5ac90aSMichal Hocko 	if (!page)
1642ab5ac90aSMichal Hocko 		return NULL;
1643ab5ac90aSMichal Hocko 
1644ab5ac90aSMichal Hocko 	/*
1645ab5ac90aSMichal Hocko 	 * We do not account these pages as surplus because they are only
1646ab5ac90aSMichal Hocko 	 * temporary and will be released properly on the last reference
1647ab5ac90aSMichal Hocko 	 */
1648ab5ac90aSMichal Hocko 	SetPageHugeTemporary(page);
1649ab5ac90aSMichal Hocko 
1650ab5ac90aSMichal Hocko 	return page;
1651ab5ac90aSMichal Hocko }
1652ab5ac90aSMichal Hocko 
1653e4e574b7SAdam Litke /*
1654099730d6SDave Hansen  * Use the VMA's mpolicy to allocate a huge page from the buddy.
1655099730d6SDave Hansen  */
1656e0ec90eeSDave Hansen static
16570c397daeSMichal Hocko struct page *alloc_buddy_huge_page_with_mpol(struct hstate *h,
1658099730d6SDave Hansen 		struct vm_area_struct *vma, unsigned long addr)
1659099730d6SDave Hansen {
1660aaf14e40SMichal Hocko 	struct page *page;
1661aaf14e40SMichal Hocko 	struct mempolicy *mpol;
1662aaf14e40SMichal Hocko 	gfp_t gfp_mask = htlb_alloc_mask(h);
1663aaf14e40SMichal Hocko 	int nid;
1664aaf14e40SMichal Hocko 	nodemask_t *nodemask;
1665aaf14e40SMichal Hocko 
1666aaf14e40SMichal Hocko 	nid = huge_node(vma, addr, gfp_mask, &mpol, &nodemask);
16670c397daeSMichal Hocko 	page = alloc_surplus_huge_page(h, gfp_mask, nid, nodemask);
1668aaf14e40SMichal Hocko 	mpol_cond_put(mpol);
1669aaf14e40SMichal Hocko 
1670aaf14e40SMichal Hocko 	return page;
1671099730d6SDave Hansen }
1672099730d6SDave Hansen 
1673ab5ac90aSMichal Hocko /* page migration callback function */
1674bf50bab2SNaoya Horiguchi struct page *alloc_huge_page_node(struct hstate *h, int nid)
1675bf50bab2SNaoya Horiguchi {
1676aaf14e40SMichal Hocko 	gfp_t gfp_mask = htlb_alloc_mask(h);
16774ef91848SJoonsoo Kim 	struct page *page = NULL;
1678bf50bab2SNaoya Horiguchi 
1679aaf14e40SMichal Hocko 	if (nid != NUMA_NO_NODE)
1680aaf14e40SMichal Hocko 		gfp_mask |= __GFP_THISNODE;
1681aaf14e40SMichal Hocko 
1682bf50bab2SNaoya Horiguchi 	spin_lock(&hugetlb_lock);
16834ef91848SJoonsoo Kim 	if (h->free_huge_pages - h->resv_huge_pages > 0)
16843e59fcb0SMichal Hocko 		page = dequeue_huge_page_nodemask(h, gfp_mask, nid, NULL);
1685bf50bab2SNaoya Horiguchi 	spin_unlock(&hugetlb_lock);
1686bf50bab2SNaoya Horiguchi 
168794ae8ba7SAneesh Kumar K.V 	if (!page)
16880c397daeSMichal Hocko 		page = alloc_migrate_huge_page(h, gfp_mask, nid, NULL);
1689bf50bab2SNaoya Horiguchi 
1690bf50bab2SNaoya Horiguchi 	return page;
1691bf50bab2SNaoya Horiguchi }
1692bf50bab2SNaoya Horiguchi 
1693ab5ac90aSMichal Hocko /* page migration callback function */
16943e59fcb0SMichal Hocko struct page *alloc_huge_page_nodemask(struct hstate *h, int preferred_nid,
16953e59fcb0SMichal Hocko 		nodemask_t *nmask)
16964db9b2efSMichal Hocko {
1697aaf14e40SMichal Hocko 	gfp_t gfp_mask = htlb_alloc_mask(h);
16984db9b2efSMichal Hocko 
16994db9b2efSMichal Hocko 	spin_lock(&hugetlb_lock);
17004db9b2efSMichal Hocko 	if (h->free_huge_pages - h->resv_huge_pages > 0) {
17013e59fcb0SMichal Hocko 		struct page *page;
17023e59fcb0SMichal Hocko 
17033e59fcb0SMichal Hocko 		page = dequeue_huge_page_nodemask(h, gfp_mask, preferred_nid, nmask);
17043e59fcb0SMichal Hocko 		if (page) {
17053e59fcb0SMichal Hocko 			spin_unlock(&hugetlb_lock);
17063e59fcb0SMichal Hocko 			return page;
17074db9b2efSMichal Hocko 		}
17084db9b2efSMichal Hocko 	}
17094db9b2efSMichal Hocko 	spin_unlock(&hugetlb_lock);
17104db9b2efSMichal Hocko 
17110c397daeSMichal Hocko 	return alloc_migrate_huge_page(h, gfp_mask, preferred_nid, nmask);
17124db9b2efSMichal Hocko }
17134db9b2efSMichal Hocko 
1714ebd63723SMichal Hocko /* mempolicy aware migration callback */
1715389c8178SMichal Hocko struct page *alloc_huge_page_vma(struct hstate *h, struct vm_area_struct *vma,
1716389c8178SMichal Hocko 		unsigned long address)
1717ebd63723SMichal Hocko {
1718ebd63723SMichal Hocko 	struct mempolicy *mpol;
1719ebd63723SMichal Hocko 	nodemask_t *nodemask;
1720ebd63723SMichal Hocko 	struct page *page;
1721ebd63723SMichal Hocko 	gfp_t gfp_mask;
1722ebd63723SMichal Hocko 	int node;
1723ebd63723SMichal Hocko 
1724ebd63723SMichal Hocko 	gfp_mask = htlb_alloc_mask(h);
1725ebd63723SMichal Hocko 	node = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
1726ebd63723SMichal Hocko 	page = alloc_huge_page_nodemask(h, node, nodemask);
1727ebd63723SMichal Hocko 	mpol_cond_put(mpol);
1728ebd63723SMichal Hocko 
1729ebd63723SMichal Hocko 	return page;
1730ebd63723SMichal Hocko }
1731ebd63723SMichal Hocko 
1732bf50bab2SNaoya Horiguchi /*
173325985edcSLucas De Marchi  * Increase the hugetlb pool such that it can accommodate a reservation
1734e4e574b7SAdam Litke  * of size 'delta'.
1735e4e574b7SAdam Litke  */
1736a5516438SAndi Kleen static int gather_surplus_pages(struct hstate *h, int delta)
1737e4e574b7SAdam Litke {
1738e4e574b7SAdam Litke 	struct list_head surplus_list;
1739e4e574b7SAdam Litke 	struct page *page, *tmp;
1740e4e574b7SAdam Litke 	int ret, i;
1741e4e574b7SAdam Litke 	int needed, allocated;
174228073b02SHillf Danton 	bool alloc_ok = true;
1743e4e574b7SAdam Litke 
1744a5516438SAndi Kleen 	needed = (h->resv_huge_pages + delta) - h->free_huge_pages;
1745ac09b3a1SAdam Litke 	if (needed <= 0) {
1746a5516438SAndi Kleen 		h->resv_huge_pages += delta;
1747e4e574b7SAdam Litke 		return 0;
1748ac09b3a1SAdam Litke 	}
1749e4e574b7SAdam Litke 
1750e4e574b7SAdam Litke 	allocated = 0;
1751e4e574b7SAdam Litke 	INIT_LIST_HEAD(&surplus_list);
1752e4e574b7SAdam Litke 
1753e4e574b7SAdam Litke 	ret = -ENOMEM;
1754e4e574b7SAdam Litke retry:
1755e4e574b7SAdam Litke 	spin_unlock(&hugetlb_lock);
1756e4e574b7SAdam Litke 	for (i = 0; i < needed; i++) {
17570c397daeSMichal Hocko 		page = alloc_surplus_huge_page(h, htlb_alloc_mask(h),
1758aaf14e40SMichal Hocko 				NUMA_NO_NODE, NULL);
175928073b02SHillf Danton 		if (!page) {
176028073b02SHillf Danton 			alloc_ok = false;
176128073b02SHillf Danton 			break;
176228073b02SHillf Danton 		}
1763e4e574b7SAdam Litke 		list_add(&page->lru, &surplus_list);
176469ed779aSDavid Rientjes 		cond_resched();
1765e4e574b7SAdam Litke 	}
176628073b02SHillf Danton 	allocated += i;
1767e4e574b7SAdam Litke 
1768e4e574b7SAdam Litke 	/*
1769e4e574b7SAdam Litke 	 * After retaking hugetlb_lock, we need to recalculate 'needed'
1770e4e574b7SAdam Litke 	 * because either resv_huge_pages or free_huge_pages may have changed.
1771e4e574b7SAdam Litke 	 */
1772e4e574b7SAdam Litke 	spin_lock(&hugetlb_lock);
1773a5516438SAndi Kleen 	needed = (h->resv_huge_pages + delta) -
1774a5516438SAndi Kleen 			(h->free_huge_pages + allocated);
177528073b02SHillf Danton 	if (needed > 0) {
177628073b02SHillf Danton 		if (alloc_ok)
1777e4e574b7SAdam Litke 			goto retry;
177828073b02SHillf Danton 		/*
177928073b02SHillf Danton 		 * We were not able to allocate enough pages to
178028073b02SHillf Danton 		 * satisfy the entire reservation so we free what
178128073b02SHillf Danton 		 * we've allocated so far.
178228073b02SHillf Danton 		 */
178328073b02SHillf Danton 		goto free;
178428073b02SHillf Danton 	}
1785e4e574b7SAdam Litke 	/*
1786e4e574b7SAdam Litke 	 * The surplus_list now contains _at_least_ the number of extra pages
178725985edcSLucas De Marchi 	 * needed to accommodate the reservation.  Add the appropriate number
1788e4e574b7SAdam Litke 	 * of pages to the hugetlb pool and free the extras back to the buddy
1789ac09b3a1SAdam Litke 	 * allocator.  Commit the entire reservation here to prevent another
1790ac09b3a1SAdam Litke 	 * process from stealing the pages as they are added to the pool but
1791ac09b3a1SAdam Litke 	 * before they are reserved.
1792e4e574b7SAdam Litke 	 */
1793e4e574b7SAdam Litke 	needed += allocated;
1794a5516438SAndi Kleen 	h->resv_huge_pages += delta;
1795e4e574b7SAdam Litke 	ret = 0;
1796a9869b83SNaoya Horiguchi 
179719fc3f0aSAdam Litke 	/* Free the needed pages to the hugetlb pool */
179819fc3f0aSAdam Litke 	list_for_each_entry_safe(page, tmp, &surplus_list, lru) {
179919fc3f0aSAdam Litke 		if ((--needed) < 0)
180019fc3f0aSAdam Litke 			break;
1801a9869b83SNaoya Horiguchi 		/*
1802a9869b83SNaoya Horiguchi 		 * This page is now managed by the hugetlb allocator and has
1803a9869b83SNaoya Horiguchi 		 * no users -- drop the buddy allocator's reference.
1804a9869b83SNaoya Horiguchi 		 */
1805a9869b83SNaoya Horiguchi 		put_page_testzero(page);
1806309381feSSasha Levin 		VM_BUG_ON_PAGE(page_count(page), page);
1807a5516438SAndi Kleen 		enqueue_huge_page(h, page);
180819fc3f0aSAdam Litke 	}
180928073b02SHillf Danton free:
1810b0365c8dSHillf Danton 	spin_unlock(&hugetlb_lock);
181119fc3f0aSAdam Litke 
181219fc3f0aSAdam Litke 	/* Free unnecessary surplus pages to the buddy allocator */
1813c0d934baSJoonsoo Kim 	list_for_each_entry_safe(page, tmp, &surplus_list, lru)
1814a9869b83SNaoya Horiguchi 		put_page(page);
181519fc3f0aSAdam Litke 	spin_lock(&hugetlb_lock);
1816e4e574b7SAdam Litke 
1817e4e574b7SAdam Litke 	return ret;
1818e4e574b7SAdam Litke }
1819e4e574b7SAdam Litke 
1820e4e574b7SAdam Litke /*
1821e5bbc8a6SMike Kravetz  * This routine has two main purposes:
1822e5bbc8a6SMike Kravetz  * 1) Decrement the reservation count (resv_huge_pages) by the value passed
1823e5bbc8a6SMike Kravetz  *    in unused_resv_pages.  This corresponds to the prior adjustments made
1824e5bbc8a6SMike Kravetz  *    to the associated reservation map.
1825e5bbc8a6SMike Kravetz  * 2) Free any unused surplus pages that may have been allocated to satisfy
1826e5bbc8a6SMike Kravetz  *    the reservation.  As many as unused_resv_pages may be freed.
1827e5bbc8a6SMike Kravetz  *
1828e5bbc8a6SMike Kravetz  * Called with hugetlb_lock held.  However, the lock could be dropped (and
1829e5bbc8a6SMike Kravetz  * reacquired) during calls to cond_resched_lock.  Whenever dropping the lock,
1830e5bbc8a6SMike Kravetz  * we must make sure nobody else can claim pages we are in the process of
1831e5bbc8a6SMike Kravetz  * freeing.  Do this by ensuring resv_huge_page always is greater than the
1832e5bbc8a6SMike Kravetz  * number of huge pages we plan to free when dropping the lock.
1833e4e574b7SAdam Litke  */
1834a5516438SAndi Kleen static void return_unused_surplus_pages(struct hstate *h,
1835a5516438SAndi Kleen 					unsigned long unused_resv_pages)
1836e4e574b7SAdam Litke {
1837e4e574b7SAdam Litke 	unsigned long nr_pages;
1838e4e574b7SAdam Litke 
1839aa888a74SAndi Kleen 	/* Cannot return gigantic pages currently */
1840bae7f4aeSLuiz Capitulino 	if (hstate_is_gigantic(h))
1841e5bbc8a6SMike Kravetz 		goto out;
1842aa888a74SAndi Kleen 
1843e5bbc8a6SMike Kravetz 	/*
1844e5bbc8a6SMike Kravetz 	 * Part (or even all) of the reservation could have been backed
1845e5bbc8a6SMike Kravetz 	 * by pre-allocated pages. Only free surplus pages.
1846e5bbc8a6SMike Kravetz 	 */
1847a5516438SAndi Kleen 	nr_pages = min(unused_resv_pages, h->surplus_huge_pages);
1848e4e574b7SAdam Litke 
1849685f3457SLee Schermerhorn 	/*
1850685f3457SLee Schermerhorn 	 * We want to release as many surplus pages as possible, spread
18519b5e5d0fSLee Schermerhorn 	 * evenly across all nodes with memory. Iterate across these nodes
18529b5e5d0fSLee Schermerhorn 	 * until we can no longer free unreserved surplus pages. This occurs
18539b5e5d0fSLee Schermerhorn 	 * when the nodes with surplus pages have no free pages.
18549b5e5d0fSLee Schermerhorn 	 * free_pool_huge_page() will balance the the freed pages across the
18559b5e5d0fSLee Schermerhorn 	 * on-line nodes with memory and will handle the hstate accounting.
1856e5bbc8a6SMike Kravetz 	 *
1857e5bbc8a6SMike Kravetz 	 * Note that we decrement resv_huge_pages as we free the pages.  If
1858e5bbc8a6SMike Kravetz 	 * we drop the lock, resv_huge_pages will still be sufficiently large
1859e5bbc8a6SMike Kravetz 	 * to cover subsequent pages we may free.
1860685f3457SLee Schermerhorn 	 */
1861685f3457SLee Schermerhorn 	while (nr_pages--) {
1862e5bbc8a6SMike Kravetz 		h->resv_huge_pages--;
1863e5bbc8a6SMike Kravetz 		unused_resv_pages--;
18648cebfcd0SLai Jiangshan 		if (!free_pool_huge_page(h, &node_states[N_MEMORY], 1))
1865e5bbc8a6SMike Kravetz 			goto out;
18667848a4bfSMizuma, Masayoshi 		cond_resched_lock(&hugetlb_lock);
1867e4e574b7SAdam Litke 	}
1868e5bbc8a6SMike Kravetz 
1869e5bbc8a6SMike Kravetz out:
1870e5bbc8a6SMike Kravetz 	/* Fully uncommit the reservation */
1871e5bbc8a6SMike Kravetz 	h->resv_huge_pages -= unused_resv_pages;
1872e4e574b7SAdam Litke }
1873e4e574b7SAdam Litke 
18745e911373SMike Kravetz 
1875c37f9fb1SAndy Whitcroft /*
1876feba16e2SMike Kravetz  * vma_needs_reservation, vma_commit_reservation and vma_end_reservation
18775e911373SMike Kravetz  * are used by the huge page allocation routines to manage reservations.
1878cf3ad20bSMike Kravetz  *
1879cf3ad20bSMike Kravetz  * vma_needs_reservation is called to determine if the huge page at addr
1880cf3ad20bSMike Kravetz  * within the vma has an associated reservation.  If a reservation is
1881cf3ad20bSMike Kravetz  * needed, the value 1 is returned.  The caller is then responsible for
1882cf3ad20bSMike Kravetz  * managing the global reservation and subpool usage counts.  After
1883cf3ad20bSMike Kravetz  * the huge page has been allocated, vma_commit_reservation is called
1884feba16e2SMike Kravetz  * to add the page to the reservation map.  If the page allocation fails,
1885feba16e2SMike Kravetz  * the reservation must be ended instead of committed.  vma_end_reservation
1886feba16e2SMike Kravetz  * is called in such cases.
1887cf3ad20bSMike Kravetz  *
1888cf3ad20bSMike Kravetz  * In the normal case, vma_commit_reservation returns the same value
1889cf3ad20bSMike Kravetz  * as the preceding vma_needs_reservation call.  The only time this
1890cf3ad20bSMike Kravetz  * is not the case is if a reserve map was changed between calls.  It
1891cf3ad20bSMike Kravetz  * is the responsibility of the caller to notice the difference and
1892cf3ad20bSMike Kravetz  * take appropriate action.
189396b96a96SMike Kravetz  *
189496b96a96SMike Kravetz  * vma_add_reservation is used in error paths where a reservation must
189596b96a96SMike Kravetz  * be restored when a newly allocated huge page must be freed.  It is
189696b96a96SMike Kravetz  * to be called after calling vma_needs_reservation to determine if a
189796b96a96SMike Kravetz  * reservation exists.
1898c37f9fb1SAndy Whitcroft  */
18995e911373SMike Kravetz enum vma_resv_mode {
19005e911373SMike Kravetz 	VMA_NEEDS_RESV,
19015e911373SMike Kravetz 	VMA_COMMIT_RESV,
1902feba16e2SMike Kravetz 	VMA_END_RESV,
190396b96a96SMike Kravetz 	VMA_ADD_RESV,
19045e911373SMike Kravetz };
1905cf3ad20bSMike Kravetz static long __vma_reservation_common(struct hstate *h,
1906cf3ad20bSMike Kravetz 				struct vm_area_struct *vma, unsigned long addr,
19075e911373SMike Kravetz 				enum vma_resv_mode mode)
1908c37f9fb1SAndy Whitcroft {
19094e35f483SJoonsoo Kim 	struct resv_map *resv;
19104e35f483SJoonsoo Kim 	pgoff_t idx;
1911cf3ad20bSMike Kravetz 	long ret;
1912c37f9fb1SAndy Whitcroft 
19134e35f483SJoonsoo Kim 	resv = vma_resv_map(vma);
19144e35f483SJoonsoo Kim 	if (!resv)
1915c37f9fb1SAndy Whitcroft 		return 1;
1916c37f9fb1SAndy Whitcroft 
19174e35f483SJoonsoo Kim 	idx = vma_hugecache_offset(h, vma, addr);
19185e911373SMike Kravetz 	switch (mode) {
19195e911373SMike Kravetz 	case VMA_NEEDS_RESV:
1920cf3ad20bSMike Kravetz 		ret = region_chg(resv, idx, idx + 1);
19215e911373SMike Kravetz 		break;
19225e911373SMike Kravetz 	case VMA_COMMIT_RESV:
19235e911373SMike Kravetz 		ret = region_add(resv, idx, idx + 1);
19245e911373SMike Kravetz 		break;
1925feba16e2SMike Kravetz 	case VMA_END_RESV:
19265e911373SMike Kravetz 		region_abort(resv, idx, idx + 1);
19275e911373SMike Kravetz 		ret = 0;
19285e911373SMike Kravetz 		break;
192996b96a96SMike Kravetz 	case VMA_ADD_RESV:
193096b96a96SMike Kravetz 		if (vma->vm_flags & VM_MAYSHARE)
193196b96a96SMike Kravetz 			ret = region_add(resv, idx, idx + 1);
193296b96a96SMike Kravetz 		else {
193396b96a96SMike Kravetz 			region_abort(resv, idx, idx + 1);
193496b96a96SMike Kravetz 			ret = region_del(resv, idx, idx + 1);
193596b96a96SMike Kravetz 		}
193696b96a96SMike Kravetz 		break;
19375e911373SMike Kravetz 	default:
19385e911373SMike Kravetz 		BUG();
19395e911373SMike Kravetz 	}
194084afd99bSAndy Whitcroft 
19414e35f483SJoonsoo Kim 	if (vma->vm_flags & VM_MAYSHARE)
1942cf3ad20bSMike Kravetz 		return ret;
194367961f9dSMike Kravetz 	else if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) && ret >= 0) {
194467961f9dSMike Kravetz 		/*
194567961f9dSMike Kravetz 		 * In most cases, reserves always exist for private mappings.
194667961f9dSMike Kravetz 		 * However, a file associated with mapping could have been
194767961f9dSMike Kravetz 		 * hole punched or truncated after reserves were consumed.
194867961f9dSMike Kravetz 		 * As subsequent fault on such a range will not use reserves.
194967961f9dSMike Kravetz 		 * Subtle - The reserve map for private mappings has the
195067961f9dSMike Kravetz 		 * opposite meaning than that of shared mappings.  If NO
195167961f9dSMike Kravetz 		 * entry is in the reserve map, it means a reservation exists.
195267961f9dSMike Kravetz 		 * If an entry exists in the reserve map, it means the
195367961f9dSMike Kravetz 		 * reservation has already been consumed.  As a result, the
195467961f9dSMike Kravetz 		 * return value of this routine is the opposite of the
195567961f9dSMike Kravetz 		 * value returned from reserve map manipulation routines above.
195667961f9dSMike Kravetz 		 */
195767961f9dSMike Kravetz 		if (ret)
195867961f9dSMike Kravetz 			return 0;
195967961f9dSMike Kravetz 		else
196067961f9dSMike Kravetz 			return 1;
196167961f9dSMike Kravetz 	}
19624e35f483SJoonsoo Kim 	else
1963cf3ad20bSMike Kravetz 		return ret < 0 ? ret : 0;
196484afd99bSAndy Whitcroft }
1965cf3ad20bSMike Kravetz 
1966cf3ad20bSMike Kravetz static long vma_needs_reservation(struct hstate *h,
1967a5516438SAndi Kleen 			struct vm_area_struct *vma, unsigned long addr)
1968c37f9fb1SAndy Whitcroft {
19695e911373SMike Kravetz 	return __vma_reservation_common(h, vma, addr, VMA_NEEDS_RESV);
1970cf3ad20bSMike Kravetz }
1971c37f9fb1SAndy Whitcroft 
1972cf3ad20bSMike Kravetz static long vma_commit_reservation(struct hstate *h,
1973cf3ad20bSMike Kravetz 			struct vm_area_struct *vma, unsigned long addr)
1974cf3ad20bSMike Kravetz {
19755e911373SMike Kravetz 	return __vma_reservation_common(h, vma, addr, VMA_COMMIT_RESV);
19765e911373SMike Kravetz }
19775e911373SMike Kravetz 
1978feba16e2SMike Kravetz static void vma_end_reservation(struct hstate *h,
19795e911373SMike Kravetz 			struct vm_area_struct *vma, unsigned long addr)
19805e911373SMike Kravetz {
1981feba16e2SMike Kravetz 	(void)__vma_reservation_common(h, vma, addr, VMA_END_RESV);
1982c37f9fb1SAndy Whitcroft }
1983c37f9fb1SAndy Whitcroft 
198496b96a96SMike Kravetz static long vma_add_reservation(struct hstate *h,
198596b96a96SMike Kravetz 			struct vm_area_struct *vma, unsigned long addr)
198696b96a96SMike Kravetz {
198796b96a96SMike Kravetz 	return __vma_reservation_common(h, vma, addr, VMA_ADD_RESV);
198896b96a96SMike Kravetz }
198996b96a96SMike Kravetz 
199096b96a96SMike Kravetz /*
199196b96a96SMike Kravetz  * This routine is called to restore a reservation on error paths.  In the
199296b96a96SMike Kravetz  * specific error paths, a huge page was allocated (via alloc_huge_page)
199396b96a96SMike Kravetz  * and is about to be freed.  If a reservation for the page existed,
199496b96a96SMike Kravetz  * alloc_huge_page would have consumed the reservation and set PagePrivate
199596b96a96SMike Kravetz  * in the newly allocated page.  When the page is freed via free_huge_page,
199696b96a96SMike Kravetz  * the global reservation count will be incremented if PagePrivate is set.
199796b96a96SMike Kravetz  * However, free_huge_page can not adjust the reserve map.  Adjust the
199896b96a96SMike Kravetz  * reserve map here to be consistent with global reserve count adjustments
199996b96a96SMike Kravetz  * to be made by free_huge_page.
200096b96a96SMike Kravetz  */
200196b96a96SMike Kravetz static void restore_reserve_on_error(struct hstate *h,
200296b96a96SMike Kravetz 			struct vm_area_struct *vma, unsigned long address,
200396b96a96SMike Kravetz 			struct page *page)
200496b96a96SMike Kravetz {
200596b96a96SMike Kravetz 	if (unlikely(PagePrivate(page))) {
200696b96a96SMike Kravetz 		long rc = vma_needs_reservation(h, vma, address);
200796b96a96SMike Kravetz 
200896b96a96SMike Kravetz 		if (unlikely(rc < 0)) {
200996b96a96SMike Kravetz 			/*
201096b96a96SMike Kravetz 			 * Rare out of memory condition in reserve map
201196b96a96SMike Kravetz 			 * manipulation.  Clear PagePrivate so that
201296b96a96SMike Kravetz 			 * global reserve count will not be incremented
201396b96a96SMike Kravetz 			 * by free_huge_page.  This will make it appear
201496b96a96SMike Kravetz 			 * as though the reservation for this page was
201596b96a96SMike Kravetz 			 * consumed.  This may prevent the task from
201696b96a96SMike Kravetz 			 * faulting in the page at a later time.  This
201796b96a96SMike Kravetz 			 * is better than inconsistent global huge page
201896b96a96SMike Kravetz 			 * accounting of reserve counts.
201996b96a96SMike Kravetz 			 */
202096b96a96SMike Kravetz 			ClearPagePrivate(page);
202196b96a96SMike Kravetz 		} else if (rc) {
202296b96a96SMike Kravetz 			rc = vma_add_reservation(h, vma, address);
202396b96a96SMike Kravetz 			if (unlikely(rc < 0))
202496b96a96SMike Kravetz 				/*
202596b96a96SMike Kravetz 				 * See above comment about rare out of
202696b96a96SMike Kravetz 				 * memory condition.
202796b96a96SMike Kravetz 				 */
202896b96a96SMike Kravetz 				ClearPagePrivate(page);
202996b96a96SMike Kravetz 		} else
203096b96a96SMike Kravetz 			vma_end_reservation(h, vma, address);
203196b96a96SMike Kravetz 	}
203296b96a96SMike Kravetz }
203396b96a96SMike Kravetz 
203470c3547eSMike Kravetz struct page *alloc_huge_page(struct vm_area_struct *vma,
203504f2cbe3SMel Gorman 				    unsigned long addr, int avoid_reserve)
2036348ea204SAdam Litke {
203790481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_vma(vma);
2038a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
2039348ea204SAdam Litke 	struct page *page;
2040d85f69b0SMike Kravetz 	long map_chg, map_commit;
2041d85f69b0SMike Kravetz 	long gbl_chg;
20426d76dcf4SAneesh Kumar K.V 	int ret, idx;
20436d76dcf4SAneesh Kumar K.V 	struct hugetlb_cgroup *h_cg;
20442fc39cecSAdam Litke 
20456d76dcf4SAneesh Kumar K.V 	idx = hstate_index(h);
2046a1e78772SMel Gorman 	/*
2047d85f69b0SMike Kravetz 	 * Examine the region/reserve map to determine if the process
2048d85f69b0SMike Kravetz 	 * has a reservation for the page to be allocated.  A return
2049d85f69b0SMike Kravetz 	 * code of zero indicates a reservation exists (no change).
2050a1e78772SMel Gorman 	 */
2051d85f69b0SMike Kravetz 	map_chg = gbl_chg = vma_needs_reservation(h, vma, addr);
2052d85f69b0SMike Kravetz 	if (map_chg < 0)
205376dcee75SAneesh Kumar K.V 		return ERR_PTR(-ENOMEM);
2054d85f69b0SMike Kravetz 
2055d85f69b0SMike Kravetz 	/*
2056d85f69b0SMike Kravetz 	 * Processes that did not create the mapping will have no
2057d85f69b0SMike Kravetz 	 * reserves as indicated by the region/reserve map. Check
2058d85f69b0SMike Kravetz 	 * that the allocation will not exceed the subpool limit.
2059d85f69b0SMike Kravetz 	 * Allocations for MAP_NORESERVE mappings also need to be
2060d85f69b0SMike Kravetz 	 * checked against any subpool limit.
2061d85f69b0SMike Kravetz 	 */
2062d85f69b0SMike Kravetz 	if (map_chg || avoid_reserve) {
2063d85f69b0SMike Kravetz 		gbl_chg = hugepage_subpool_get_pages(spool, 1);
2064d85f69b0SMike Kravetz 		if (gbl_chg < 0) {
2065feba16e2SMike Kravetz 			vma_end_reservation(h, vma, addr);
206676dcee75SAneesh Kumar K.V 			return ERR_PTR(-ENOSPC);
20675e911373SMike Kravetz 		}
206890d8b7e6SAdam Litke 
2069d85f69b0SMike Kravetz 		/*
2070d85f69b0SMike Kravetz 		 * Even though there was no reservation in the region/reserve
2071d85f69b0SMike Kravetz 		 * map, there could be reservations associated with the
2072d85f69b0SMike Kravetz 		 * subpool that can be used.  This would be indicated if the
2073d85f69b0SMike Kravetz 		 * return value of hugepage_subpool_get_pages() is zero.
2074d85f69b0SMike Kravetz 		 * However, if avoid_reserve is specified we still avoid even
2075d85f69b0SMike Kravetz 		 * the subpool reservations.
2076d85f69b0SMike Kravetz 		 */
2077d85f69b0SMike Kravetz 		if (avoid_reserve)
2078d85f69b0SMike Kravetz 			gbl_chg = 1;
2079d85f69b0SMike Kravetz 	}
2080d85f69b0SMike Kravetz 
20816d76dcf4SAneesh Kumar K.V 	ret = hugetlb_cgroup_charge_cgroup(idx, pages_per_huge_page(h), &h_cg);
20828f34af6fSJianyu Zhan 	if (ret)
20838f34af6fSJianyu Zhan 		goto out_subpool_put;
20848f34af6fSJianyu Zhan 
2085a1e78772SMel Gorman 	spin_lock(&hugetlb_lock);
2086d85f69b0SMike Kravetz 	/*
2087d85f69b0SMike Kravetz 	 * glb_chg is passed to indicate whether or not a page must be taken
2088d85f69b0SMike Kravetz 	 * from the global free pool (global change).  gbl_chg == 0 indicates
2089d85f69b0SMike Kravetz 	 * a reservation exists for the allocation.
2090d85f69b0SMike Kravetz 	 */
2091d85f69b0SMike Kravetz 	page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve, gbl_chg);
209281a6fcaeSJoonsoo Kim 	if (!page) {
209394ae8ba7SAneesh Kumar K.V 		spin_unlock(&hugetlb_lock);
20940c397daeSMichal Hocko 		page = alloc_buddy_huge_page_with_mpol(h, vma, addr);
20958f34af6fSJianyu Zhan 		if (!page)
20968f34af6fSJianyu Zhan 			goto out_uncharge_cgroup;
2097a88c7695SNaoya Horiguchi 		if (!avoid_reserve && vma_has_reserves(vma, gbl_chg)) {
2098a88c7695SNaoya Horiguchi 			SetPagePrivate(page);
2099a88c7695SNaoya Horiguchi 			h->resv_huge_pages--;
2100a88c7695SNaoya Horiguchi 		}
210179dbb236SAneesh Kumar K.V 		spin_lock(&hugetlb_lock);
210279dbb236SAneesh Kumar K.V 		list_move(&page->lru, &h->hugepage_activelist);
210381a6fcaeSJoonsoo Kim 		/* Fall through */
2104a1e78772SMel Gorman 	}
210581a6fcaeSJoonsoo Kim 	hugetlb_cgroup_commit_charge(idx, pages_per_huge_page(h), h_cg, page);
210681a6fcaeSJoonsoo Kim 	spin_unlock(&hugetlb_lock);
2107a1e78772SMel Gorman 
210890481622SDavid Gibson 	set_page_private(page, (unsigned long)spool);
2109a1e78772SMel Gorman 
2110d85f69b0SMike Kravetz 	map_commit = vma_commit_reservation(h, vma, addr);
2111d85f69b0SMike Kravetz 	if (unlikely(map_chg > map_commit)) {
211233039678SMike Kravetz 		/*
211333039678SMike Kravetz 		 * The page was added to the reservation map between
211433039678SMike Kravetz 		 * vma_needs_reservation and vma_commit_reservation.
211533039678SMike Kravetz 		 * This indicates a race with hugetlb_reserve_pages.
211633039678SMike Kravetz 		 * Adjust for the subpool count incremented above AND
211733039678SMike Kravetz 		 * in hugetlb_reserve_pages for the same page.  Also,
211833039678SMike Kravetz 		 * the reservation count added in hugetlb_reserve_pages
211933039678SMike Kravetz 		 * no longer applies.
212033039678SMike Kravetz 		 */
212133039678SMike Kravetz 		long rsv_adjust;
212233039678SMike Kravetz 
212333039678SMike Kravetz 		rsv_adjust = hugepage_subpool_put_pages(spool, 1);
212433039678SMike Kravetz 		hugetlb_acct_memory(h, -rsv_adjust);
212533039678SMike Kravetz 	}
21267893d1d5SAdam Litke 	return page;
21278f34af6fSJianyu Zhan 
21288f34af6fSJianyu Zhan out_uncharge_cgroup:
21298f34af6fSJianyu Zhan 	hugetlb_cgroup_uncharge_cgroup(idx, pages_per_huge_page(h), h_cg);
21308f34af6fSJianyu Zhan out_subpool_put:
2131d85f69b0SMike Kravetz 	if (map_chg || avoid_reserve)
21328f34af6fSJianyu Zhan 		hugepage_subpool_put_pages(spool, 1);
2133feba16e2SMike Kravetz 	vma_end_reservation(h, vma, addr);
21348f34af6fSJianyu Zhan 	return ERR_PTR(-ENOSPC);
2135b45b5bd6SDavid Gibson }
2136b45b5bd6SDavid Gibson 
2137e24a1307SAneesh Kumar K.V int alloc_bootmem_huge_page(struct hstate *h)
2138e24a1307SAneesh Kumar K.V 	__attribute__ ((weak, alias("__alloc_bootmem_huge_page")));
2139e24a1307SAneesh Kumar K.V int __alloc_bootmem_huge_page(struct hstate *h)
2140aa888a74SAndi Kleen {
2141aa888a74SAndi Kleen 	struct huge_bootmem_page *m;
2142b2261026SJoonsoo Kim 	int nr_nodes, node;
2143aa888a74SAndi Kleen 
2144b2261026SJoonsoo Kim 	for_each_node_mask_to_alloc(h, nr_nodes, node, &node_states[N_MEMORY]) {
2145aa888a74SAndi Kleen 		void *addr;
2146aa888a74SAndi Kleen 
2147eb31d559SMike Rapoport 		addr = memblock_alloc_try_nid_raw(
21488b89a116SGrygorii Strashko 				huge_page_size(h), huge_page_size(h),
214997ad1087SMike Rapoport 				0, MEMBLOCK_ALLOC_ACCESSIBLE, node);
2150aa888a74SAndi Kleen 		if (addr) {
2151aa888a74SAndi Kleen 			/*
2152aa888a74SAndi Kleen 			 * Use the beginning of the huge page to store the
2153aa888a74SAndi Kleen 			 * huge_bootmem_page struct (until gather_bootmem
2154aa888a74SAndi Kleen 			 * puts them into the mem_map).
2155aa888a74SAndi Kleen 			 */
2156aa888a74SAndi Kleen 			m = addr;
2157aa888a74SAndi Kleen 			goto found;
2158aa888a74SAndi Kleen 		}
2159aa888a74SAndi Kleen 	}
2160aa888a74SAndi Kleen 	return 0;
2161aa888a74SAndi Kleen 
2162aa888a74SAndi Kleen found:
2163df994eadSLuiz Capitulino 	BUG_ON(!IS_ALIGNED(virt_to_phys(m), huge_page_size(h)));
2164aa888a74SAndi Kleen 	/* Put them into a private list first because mem_map is not up yet */
2165330d6e48SCannon Matthews 	INIT_LIST_HEAD(&m->list);
2166aa888a74SAndi Kleen 	list_add(&m->list, &huge_boot_pages);
2167aa888a74SAndi Kleen 	m->hstate = h;
2168aa888a74SAndi Kleen 	return 1;
2169aa888a74SAndi Kleen }
2170aa888a74SAndi Kleen 
2171d00181b9SKirill A. Shutemov static void __init prep_compound_huge_page(struct page *page,
2172d00181b9SKirill A. Shutemov 		unsigned int order)
217318229df5SAndy Whitcroft {
217418229df5SAndy Whitcroft 	if (unlikely(order > (MAX_ORDER - 1)))
217518229df5SAndy Whitcroft 		prep_compound_gigantic_page(page, order);
217618229df5SAndy Whitcroft 	else
217718229df5SAndy Whitcroft 		prep_compound_page(page, order);
217818229df5SAndy Whitcroft }
217918229df5SAndy Whitcroft 
2180aa888a74SAndi Kleen /* Put bootmem huge pages into the standard lists after mem_map is up */
2181aa888a74SAndi Kleen static void __init gather_bootmem_prealloc(void)
2182aa888a74SAndi Kleen {
2183aa888a74SAndi Kleen 	struct huge_bootmem_page *m;
2184aa888a74SAndi Kleen 
2185aa888a74SAndi Kleen 	list_for_each_entry(m, &huge_boot_pages, list) {
218640d18ebfSMike Kravetz 		struct page *page = virt_to_page(m);
2187aa888a74SAndi Kleen 		struct hstate *h = m->hstate;
2188ee8f248dSBecky Bruce 
2189aa888a74SAndi Kleen 		WARN_ON(page_count(page) != 1);
219018229df5SAndy Whitcroft 		prep_compound_huge_page(page, h->order);
2191ef5a22beSAndrea Arcangeli 		WARN_ON(PageReserved(page));
2192aa888a74SAndi Kleen 		prep_new_huge_page(h, page, page_to_nid(page));
2193af0fb9dfSMichal Hocko 		put_page(page); /* free it into the hugepage allocator */
2194af0fb9dfSMichal Hocko 
2195b0320c7bSRafael Aquini 		/*
2196b0320c7bSRafael Aquini 		 * If we had gigantic hugepages allocated at boot time, we need
2197b0320c7bSRafael Aquini 		 * to restore the 'stolen' pages to totalram_pages in order to
2198b0320c7bSRafael Aquini 		 * fix confusing memory reports from free(1) and another
2199b0320c7bSRafael Aquini 		 * side-effects, like CommitLimit going negative.
2200b0320c7bSRafael Aquini 		 */
2201bae7f4aeSLuiz Capitulino 		if (hstate_is_gigantic(h))
22023dcc0571SJiang Liu 			adjust_managed_page_count(page, 1 << h->order);
2203520495feSCannon Matthews 		cond_resched();
2204aa888a74SAndi Kleen 	}
2205aa888a74SAndi Kleen }
2206aa888a74SAndi Kleen 
22078faa8b07SAndi Kleen static void __init hugetlb_hstate_alloc_pages(struct hstate *h)
22081da177e4SLinus Torvalds {
22091da177e4SLinus Torvalds 	unsigned long i;
22101da177e4SLinus Torvalds 
2211e5ff2159SAndi Kleen 	for (i = 0; i < h->max_huge_pages; ++i) {
2212bae7f4aeSLuiz Capitulino 		if (hstate_is_gigantic(h)) {
2213aa888a74SAndi Kleen 			if (!alloc_bootmem_huge_page(h))
2214aa888a74SAndi Kleen 				break;
22150c397daeSMichal Hocko 		} else if (!alloc_pool_huge_page(h,
22168cebfcd0SLai Jiangshan 					 &node_states[N_MEMORY]))
22171da177e4SLinus Torvalds 			break;
221869ed779aSDavid Rientjes 		cond_resched();
22191da177e4SLinus Torvalds 	}
2220d715cf80SLiam R. Howlett 	if (i < h->max_huge_pages) {
2221d715cf80SLiam R. Howlett 		char buf[32];
2222d715cf80SLiam R. Howlett 
2223c6247f72SMatthew Wilcox 		string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
2224d715cf80SLiam R. Howlett 		pr_warn("HugeTLB: allocating %lu of page size %s failed.  Only allocated %lu hugepages.\n",
2225d715cf80SLiam R. Howlett 			h->max_huge_pages, buf, i);
22268faa8b07SAndi Kleen 		h->max_huge_pages = i;
2227e5ff2159SAndi Kleen 	}
2228d715cf80SLiam R. Howlett }
2229e5ff2159SAndi Kleen 
2230e5ff2159SAndi Kleen static void __init hugetlb_init_hstates(void)
2231e5ff2159SAndi Kleen {
2232e5ff2159SAndi Kleen 	struct hstate *h;
2233e5ff2159SAndi Kleen 
2234e5ff2159SAndi Kleen 	for_each_hstate(h) {
2235641844f5SNaoya Horiguchi 		if (minimum_order > huge_page_order(h))
2236641844f5SNaoya Horiguchi 			minimum_order = huge_page_order(h);
2237641844f5SNaoya Horiguchi 
22388faa8b07SAndi Kleen 		/* oversize hugepages were init'ed in early boot */
2239bae7f4aeSLuiz Capitulino 		if (!hstate_is_gigantic(h))
22408faa8b07SAndi Kleen 			hugetlb_hstate_alloc_pages(h);
2241e5ff2159SAndi Kleen 	}
2242641844f5SNaoya Horiguchi 	VM_BUG_ON(minimum_order == UINT_MAX);
2243e5ff2159SAndi Kleen }
2244e5ff2159SAndi Kleen 
2245e5ff2159SAndi Kleen static void __init report_hugepages(void)
2246e5ff2159SAndi Kleen {
2247e5ff2159SAndi Kleen 	struct hstate *h;
2248e5ff2159SAndi Kleen 
2249e5ff2159SAndi Kleen 	for_each_hstate(h) {
22504abd32dbSAndi Kleen 		char buf[32];
2251c6247f72SMatthew Wilcox 
2252c6247f72SMatthew Wilcox 		string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
2253ffb22af5SAndrew Morton 		pr_info("HugeTLB registered %s page size, pre-allocated %ld pages\n",
2254c6247f72SMatthew Wilcox 			buf, h->free_huge_pages);
2255e5ff2159SAndi Kleen 	}
2256e5ff2159SAndi Kleen }
2257e5ff2159SAndi Kleen 
22581da177e4SLinus Torvalds #ifdef CONFIG_HIGHMEM
22596ae11b27SLee Schermerhorn static void try_to_free_low(struct hstate *h, unsigned long count,
22606ae11b27SLee Schermerhorn 						nodemask_t *nodes_allowed)
22611da177e4SLinus Torvalds {
22624415cc8dSChristoph Lameter 	int i;
22634415cc8dSChristoph Lameter 
2264bae7f4aeSLuiz Capitulino 	if (hstate_is_gigantic(h))
2265aa888a74SAndi Kleen 		return;
2266aa888a74SAndi Kleen 
22676ae11b27SLee Schermerhorn 	for_each_node_mask(i, *nodes_allowed) {
22681da177e4SLinus Torvalds 		struct page *page, *next;
2269a5516438SAndi Kleen 		struct list_head *freel = &h->hugepage_freelists[i];
2270a5516438SAndi Kleen 		list_for_each_entry_safe(page, next, freel, lru) {
2271a5516438SAndi Kleen 			if (count >= h->nr_huge_pages)
22726b0c880dSAdam Litke 				return;
22731da177e4SLinus Torvalds 			if (PageHighMem(page))
22741da177e4SLinus Torvalds 				continue;
22751da177e4SLinus Torvalds 			list_del(&page->lru);
2276e5ff2159SAndi Kleen 			update_and_free_page(h, page);
2277a5516438SAndi Kleen 			h->free_huge_pages--;
2278a5516438SAndi Kleen 			h->free_huge_pages_node[page_to_nid(page)]--;
22791da177e4SLinus Torvalds 		}
22801da177e4SLinus Torvalds 	}
22811da177e4SLinus Torvalds }
22821da177e4SLinus Torvalds #else
22836ae11b27SLee Schermerhorn static inline void try_to_free_low(struct hstate *h, unsigned long count,
22846ae11b27SLee Schermerhorn 						nodemask_t *nodes_allowed)
22851da177e4SLinus Torvalds {
22861da177e4SLinus Torvalds }
22871da177e4SLinus Torvalds #endif
22881da177e4SLinus Torvalds 
228920a0307cSWu Fengguang /*
229020a0307cSWu Fengguang  * Increment or decrement surplus_huge_pages.  Keep node-specific counters
229120a0307cSWu Fengguang  * balanced by operating on them in a round-robin fashion.
229220a0307cSWu Fengguang  * Returns 1 if an adjustment was made.
229320a0307cSWu Fengguang  */
22946ae11b27SLee Schermerhorn static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed,
22956ae11b27SLee Schermerhorn 				int delta)
229620a0307cSWu Fengguang {
2297b2261026SJoonsoo Kim 	int nr_nodes, node;
229820a0307cSWu Fengguang 
229920a0307cSWu Fengguang 	VM_BUG_ON(delta != -1 && delta != 1);
230020a0307cSWu Fengguang 
2301e8c5c824SLee Schermerhorn 	if (delta < 0) {
2302b2261026SJoonsoo Kim 		for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
2303b2261026SJoonsoo Kim 			if (h->surplus_huge_pages_node[node])
2304b2261026SJoonsoo Kim 				goto found;
2305b2261026SJoonsoo Kim 		}
2306b2261026SJoonsoo Kim 	} else {
2307b2261026SJoonsoo Kim 		for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
2308b2261026SJoonsoo Kim 			if (h->surplus_huge_pages_node[node] <
2309b2261026SJoonsoo Kim 					h->nr_huge_pages_node[node])
2310b2261026SJoonsoo Kim 				goto found;
2311e8c5c824SLee Schermerhorn 		}
23129a76db09SLee Schermerhorn 	}
2313b2261026SJoonsoo Kim 	return 0;
231420a0307cSWu Fengguang 
2315b2261026SJoonsoo Kim found:
231620a0307cSWu Fengguang 	h->surplus_huge_pages += delta;
2317b2261026SJoonsoo Kim 	h->surplus_huge_pages_node[node] += delta;
2318b2261026SJoonsoo Kim 	return 1;
231920a0307cSWu Fengguang }
232020a0307cSWu Fengguang 
2321a5516438SAndi Kleen #define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages)
2322fd875dcaSMike Kravetz static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,
23236ae11b27SLee Schermerhorn 			      nodemask_t *nodes_allowed)
23241da177e4SLinus Torvalds {
23257893d1d5SAdam Litke 	unsigned long min_count, ret;
23261da177e4SLinus Torvalds 
23274eb0716eSAlexandre Ghiti 	spin_lock(&hugetlb_lock);
23284eb0716eSAlexandre Ghiti 
23294eb0716eSAlexandre Ghiti 	/*
2330fd875dcaSMike Kravetz 	 * Check for a node specific request.
2331fd875dcaSMike Kravetz 	 * Changing node specific huge page count may require a corresponding
2332fd875dcaSMike Kravetz 	 * change to the global count.  In any case, the passed node mask
2333fd875dcaSMike Kravetz 	 * (nodes_allowed) will restrict alloc/free to the specified node.
2334fd875dcaSMike Kravetz 	 */
2335fd875dcaSMike Kravetz 	if (nid != NUMA_NO_NODE) {
2336fd875dcaSMike Kravetz 		unsigned long old_count = count;
2337fd875dcaSMike Kravetz 
2338fd875dcaSMike Kravetz 		count += h->nr_huge_pages - h->nr_huge_pages_node[nid];
2339fd875dcaSMike Kravetz 		/*
2340fd875dcaSMike Kravetz 		 * User may have specified a large count value which caused the
2341fd875dcaSMike Kravetz 		 * above calculation to overflow.  In this case, they wanted
2342fd875dcaSMike Kravetz 		 * to allocate as many huge pages as possible.  Set count to
2343fd875dcaSMike Kravetz 		 * largest possible value to align with their intention.
2344fd875dcaSMike Kravetz 		 */
2345fd875dcaSMike Kravetz 		if (count < old_count)
2346fd875dcaSMike Kravetz 			count = ULONG_MAX;
2347fd875dcaSMike Kravetz 	}
2348fd875dcaSMike Kravetz 
2349fd875dcaSMike Kravetz 	/*
23504eb0716eSAlexandre Ghiti 	 * Gigantic pages runtime allocation depend on the capability for large
23514eb0716eSAlexandre Ghiti 	 * page range allocation.
23524eb0716eSAlexandre Ghiti 	 * If the system does not provide this feature, return an error when
23534eb0716eSAlexandre Ghiti 	 * the user tries to allocate gigantic pages but let the user free the
23544eb0716eSAlexandre Ghiti 	 * boottime allocated gigantic pages.
23554eb0716eSAlexandre Ghiti 	 */
23564eb0716eSAlexandre Ghiti 	if (hstate_is_gigantic(h) && !IS_ENABLED(CONFIG_CONTIG_ALLOC)) {
23574eb0716eSAlexandre Ghiti 		if (count > persistent_huge_pages(h)) {
23584eb0716eSAlexandre Ghiti 			spin_unlock(&hugetlb_lock);
23594eb0716eSAlexandre Ghiti 			return -EINVAL;
23604eb0716eSAlexandre Ghiti 		}
23614eb0716eSAlexandre Ghiti 		/* Fall through to decrease pool */
23624eb0716eSAlexandre Ghiti 	}
2363aa888a74SAndi Kleen 
23647893d1d5SAdam Litke 	/*
23657893d1d5SAdam Litke 	 * Increase the pool size
23667893d1d5SAdam Litke 	 * First take pages out of surplus state.  Then make up the
23677893d1d5SAdam Litke 	 * remaining difference by allocating fresh huge pages.
2368d1c3fb1fSNishanth Aravamudan 	 *
23690c397daeSMichal Hocko 	 * We might race with alloc_surplus_huge_page() here and be unable
2370d1c3fb1fSNishanth Aravamudan 	 * to convert a surplus huge page to a normal huge page. That is
2371d1c3fb1fSNishanth Aravamudan 	 * not critical, though, it just means the overall size of the
2372d1c3fb1fSNishanth Aravamudan 	 * pool might be one hugepage larger than it needs to be, but
2373d1c3fb1fSNishanth Aravamudan 	 * within all the constraints specified by the sysctls.
23747893d1d5SAdam Litke 	 */
2375a5516438SAndi Kleen 	while (h->surplus_huge_pages && count > persistent_huge_pages(h)) {
23766ae11b27SLee Schermerhorn 		if (!adjust_pool_surplus(h, nodes_allowed, -1))
23777893d1d5SAdam Litke 			break;
23787893d1d5SAdam Litke 	}
23797893d1d5SAdam Litke 
2380a5516438SAndi Kleen 	while (count > persistent_huge_pages(h)) {
23817893d1d5SAdam Litke 		/*
23827893d1d5SAdam Litke 		 * If this allocation races such that we no longer need the
23837893d1d5SAdam Litke 		 * page, free_huge_page will handle it by freeing the page
23847893d1d5SAdam Litke 		 * and reducing the surplus.
23857893d1d5SAdam Litke 		 */
23867893d1d5SAdam Litke 		spin_unlock(&hugetlb_lock);
2387649920c6SJia He 
2388649920c6SJia He 		/* yield cpu to avoid soft lockup */
2389649920c6SJia He 		cond_resched();
2390649920c6SJia He 
23910c397daeSMichal Hocko 		ret = alloc_pool_huge_page(h, nodes_allowed);
23927893d1d5SAdam Litke 		spin_lock(&hugetlb_lock);
23937893d1d5SAdam Litke 		if (!ret)
23947893d1d5SAdam Litke 			goto out;
23957893d1d5SAdam Litke 
2396536240f2SMel Gorman 		/* Bail for signals. Probably ctrl-c from user */
2397536240f2SMel Gorman 		if (signal_pending(current))
2398536240f2SMel Gorman 			goto out;
23997893d1d5SAdam Litke 	}
24007893d1d5SAdam Litke 
24017893d1d5SAdam Litke 	/*
24027893d1d5SAdam Litke 	 * Decrease the pool size
24037893d1d5SAdam Litke 	 * First return free pages to the buddy allocator (being careful
24047893d1d5SAdam Litke 	 * to keep enough around to satisfy reservations).  Then place
24057893d1d5SAdam Litke 	 * pages into surplus state as needed so the pool will shrink
24067893d1d5SAdam Litke 	 * to the desired size as pages become free.
2407d1c3fb1fSNishanth Aravamudan 	 *
2408d1c3fb1fSNishanth Aravamudan 	 * By placing pages into the surplus state independent of the
2409d1c3fb1fSNishanth Aravamudan 	 * overcommit value, we are allowing the surplus pool size to
2410d1c3fb1fSNishanth Aravamudan 	 * exceed overcommit. There are few sane options here. Since
24110c397daeSMichal Hocko 	 * alloc_surplus_huge_page() is checking the global counter,
2412d1c3fb1fSNishanth Aravamudan 	 * though, we'll note that we're not allowed to exceed surplus
2413d1c3fb1fSNishanth Aravamudan 	 * and won't grow the pool anywhere else. Not until one of the
2414d1c3fb1fSNishanth Aravamudan 	 * sysctls are changed, or the surplus pages go out of use.
24157893d1d5SAdam Litke 	 */
2416a5516438SAndi Kleen 	min_count = h->resv_huge_pages + h->nr_huge_pages - h->free_huge_pages;
24176b0c880dSAdam Litke 	min_count = max(count, min_count);
24186ae11b27SLee Schermerhorn 	try_to_free_low(h, min_count, nodes_allowed);
2419a5516438SAndi Kleen 	while (min_count < persistent_huge_pages(h)) {
24206ae11b27SLee Schermerhorn 		if (!free_pool_huge_page(h, nodes_allowed, 0))
24211da177e4SLinus Torvalds 			break;
242255f67141SMizuma, Masayoshi 		cond_resched_lock(&hugetlb_lock);
24231da177e4SLinus Torvalds 	}
2424a5516438SAndi Kleen 	while (count < persistent_huge_pages(h)) {
24256ae11b27SLee Schermerhorn 		if (!adjust_pool_surplus(h, nodes_allowed, 1))
24267893d1d5SAdam Litke 			break;
24277893d1d5SAdam Litke 	}
24287893d1d5SAdam Litke out:
24294eb0716eSAlexandre Ghiti 	h->max_huge_pages = persistent_huge_pages(h);
24301da177e4SLinus Torvalds 	spin_unlock(&hugetlb_lock);
24314eb0716eSAlexandre Ghiti 
24324eb0716eSAlexandre Ghiti 	return 0;
24331da177e4SLinus Torvalds }
24341da177e4SLinus Torvalds 
2435a3437870SNishanth Aravamudan #define HSTATE_ATTR_RO(_name) \
2436a3437870SNishanth Aravamudan 	static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
2437a3437870SNishanth Aravamudan 
2438a3437870SNishanth Aravamudan #define HSTATE_ATTR(_name) \
2439a3437870SNishanth Aravamudan 	static struct kobj_attribute _name##_attr = \
2440a3437870SNishanth Aravamudan 		__ATTR(_name, 0644, _name##_show, _name##_store)
2441a3437870SNishanth Aravamudan 
2442a3437870SNishanth Aravamudan static struct kobject *hugepages_kobj;
2443a3437870SNishanth Aravamudan static struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
2444a3437870SNishanth Aravamudan 
24459a305230SLee Schermerhorn static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp);
24469a305230SLee Schermerhorn 
24479a305230SLee Schermerhorn static struct hstate *kobj_to_hstate(struct kobject *kobj, int *nidp)
2448a3437870SNishanth Aravamudan {
2449a3437870SNishanth Aravamudan 	int i;
24509a305230SLee Schermerhorn 
2451a3437870SNishanth Aravamudan 	for (i = 0; i < HUGE_MAX_HSTATE; i++)
24529a305230SLee Schermerhorn 		if (hstate_kobjs[i] == kobj) {
24539a305230SLee Schermerhorn 			if (nidp)
24549a305230SLee Schermerhorn 				*nidp = NUMA_NO_NODE;
2455a3437870SNishanth Aravamudan 			return &hstates[i];
24569a305230SLee Schermerhorn 		}
24579a305230SLee Schermerhorn 
24589a305230SLee Schermerhorn 	return kobj_to_node_hstate(kobj, nidp);
2459a3437870SNishanth Aravamudan }
2460a3437870SNishanth Aravamudan 
246106808b08SLee Schermerhorn static ssize_t nr_hugepages_show_common(struct kobject *kobj,
2462a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
2463a3437870SNishanth Aravamudan {
24649a305230SLee Schermerhorn 	struct hstate *h;
24659a305230SLee Schermerhorn 	unsigned long nr_huge_pages;
24669a305230SLee Schermerhorn 	int nid;
24679a305230SLee Schermerhorn 
24689a305230SLee Schermerhorn 	h = kobj_to_hstate(kobj, &nid);
24699a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE)
24709a305230SLee Schermerhorn 		nr_huge_pages = h->nr_huge_pages;
24719a305230SLee Schermerhorn 	else
24729a305230SLee Schermerhorn 		nr_huge_pages = h->nr_huge_pages_node[nid];
24739a305230SLee Schermerhorn 
24749a305230SLee Schermerhorn 	return sprintf(buf, "%lu\n", nr_huge_pages);
2475a3437870SNishanth Aravamudan }
2476adbe8726SEric B Munson 
2477238d3c13SDavid Rientjes static ssize_t __nr_hugepages_store_common(bool obey_mempolicy,
2478238d3c13SDavid Rientjes 					   struct hstate *h, int nid,
2479238d3c13SDavid Rientjes 					   unsigned long count, size_t len)
2480a3437870SNishanth Aravamudan {
2481a3437870SNishanth Aravamudan 	int err;
24822d0adf7eSOscar Salvador 	nodemask_t nodes_allowed, *n_mask;
2483a3437870SNishanth Aravamudan 
24842d0adf7eSOscar Salvador 	if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
24852d0adf7eSOscar Salvador 		return -EINVAL;
2486adbe8726SEric B Munson 
24879a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE) {
24889a305230SLee Schermerhorn 		/*
24899a305230SLee Schermerhorn 		 * global hstate attribute
24909a305230SLee Schermerhorn 		 */
24919a305230SLee Schermerhorn 		if (!(obey_mempolicy &&
24922d0adf7eSOscar Salvador 				init_nodemask_of_mempolicy(&nodes_allowed)))
24932d0adf7eSOscar Salvador 			n_mask = &node_states[N_MEMORY];
24942d0adf7eSOscar Salvador 		else
24952d0adf7eSOscar Salvador 			n_mask = &nodes_allowed;
24962d0adf7eSOscar Salvador 	} else {
24979a305230SLee Schermerhorn 		/*
2498fd875dcaSMike Kravetz 		 * Node specific request.  count adjustment happens in
2499fd875dcaSMike Kravetz 		 * set_max_huge_pages() after acquiring hugetlb_lock.
25009a305230SLee Schermerhorn 		 */
25012d0adf7eSOscar Salvador 		init_nodemask_of_node(&nodes_allowed, nid);
25022d0adf7eSOscar Salvador 		n_mask = &nodes_allowed;
2503fd875dcaSMike Kravetz 	}
25049a305230SLee Schermerhorn 
25052d0adf7eSOscar Salvador 	err = set_max_huge_pages(h, count, nid, n_mask);
250606808b08SLee Schermerhorn 
25074eb0716eSAlexandre Ghiti 	return err ? err : len;
250806808b08SLee Schermerhorn }
250906808b08SLee Schermerhorn 
2510238d3c13SDavid Rientjes static ssize_t nr_hugepages_store_common(bool obey_mempolicy,
2511238d3c13SDavid Rientjes 					 struct kobject *kobj, const char *buf,
2512238d3c13SDavid Rientjes 					 size_t len)
2513238d3c13SDavid Rientjes {
2514238d3c13SDavid Rientjes 	struct hstate *h;
2515238d3c13SDavid Rientjes 	unsigned long count;
2516238d3c13SDavid Rientjes 	int nid;
2517238d3c13SDavid Rientjes 	int err;
2518238d3c13SDavid Rientjes 
2519238d3c13SDavid Rientjes 	err = kstrtoul(buf, 10, &count);
2520238d3c13SDavid Rientjes 	if (err)
2521238d3c13SDavid Rientjes 		return err;
2522238d3c13SDavid Rientjes 
2523238d3c13SDavid Rientjes 	h = kobj_to_hstate(kobj, &nid);
2524238d3c13SDavid Rientjes 	return __nr_hugepages_store_common(obey_mempolicy, h, nid, count, len);
2525238d3c13SDavid Rientjes }
2526238d3c13SDavid Rientjes 
252706808b08SLee Schermerhorn static ssize_t nr_hugepages_show(struct kobject *kobj,
252806808b08SLee Schermerhorn 				       struct kobj_attribute *attr, char *buf)
252906808b08SLee Schermerhorn {
253006808b08SLee Schermerhorn 	return nr_hugepages_show_common(kobj, attr, buf);
253106808b08SLee Schermerhorn }
253206808b08SLee Schermerhorn 
253306808b08SLee Schermerhorn static ssize_t nr_hugepages_store(struct kobject *kobj,
253406808b08SLee Schermerhorn 	       struct kobj_attribute *attr, const char *buf, size_t len)
253506808b08SLee Schermerhorn {
2536238d3c13SDavid Rientjes 	return nr_hugepages_store_common(false, kobj, buf, len);
2537a3437870SNishanth Aravamudan }
2538a3437870SNishanth Aravamudan HSTATE_ATTR(nr_hugepages);
2539a3437870SNishanth Aravamudan 
254006808b08SLee Schermerhorn #ifdef CONFIG_NUMA
254106808b08SLee Schermerhorn 
254206808b08SLee Schermerhorn /*
254306808b08SLee Schermerhorn  * hstate attribute for optionally mempolicy-based constraint on persistent
254406808b08SLee Schermerhorn  * huge page alloc/free.
254506808b08SLee Schermerhorn  */
254606808b08SLee Schermerhorn static ssize_t nr_hugepages_mempolicy_show(struct kobject *kobj,
254706808b08SLee Schermerhorn 				       struct kobj_attribute *attr, char *buf)
254806808b08SLee Schermerhorn {
254906808b08SLee Schermerhorn 	return nr_hugepages_show_common(kobj, attr, buf);
255006808b08SLee Schermerhorn }
255106808b08SLee Schermerhorn 
255206808b08SLee Schermerhorn static ssize_t nr_hugepages_mempolicy_store(struct kobject *kobj,
255306808b08SLee Schermerhorn 	       struct kobj_attribute *attr, const char *buf, size_t len)
255406808b08SLee Schermerhorn {
2555238d3c13SDavid Rientjes 	return nr_hugepages_store_common(true, kobj, buf, len);
255606808b08SLee Schermerhorn }
255706808b08SLee Schermerhorn HSTATE_ATTR(nr_hugepages_mempolicy);
255806808b08SLee Schermerhorn #endif
255906808b08SLee Schermerhorn 
256006808b08SLee Schermerhorn 
2561a3437870SNishanth Aravamudan static ssize_t nr_overcommit_hugepages_show(struct kobject *kobj,
2562a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
2563a3437870SNishanth Aravamudan {
25649a305230SLee Schermerhorn 	struct hstate *h = kobj_to_hstate(kobj, NULL);
2565a3437870SNishanth Aravamudan 	return sprintf(buf, "%lu\n", h->nr_overcommit_huge_pages);
2566a3437870SNishanth Aravamudan }
2567adbe8726SEric B Munson 
2568a3437870SNishanth Aravamudan static ssize_t nr_overcommit_hugepages_store(struct kobject *kobj,
2569a3437870SNishanth Aravamudan 		struct kobj_attribute *attr, const char *buf, size_t count)
2570a3437870SNishanth Aravamudan {
2571a3437870SNishanth Aravamudan 	int err;
2572a3437870SNishanth Aravamudan 	unsigned long input;
25739a305230SLee Schermerhorn 	struct hstate *h = kobj_to_hstate(kobj, NULL);
2574a3437870SNishanth Aravamudan 
2575bae7f4aeSLuiz Capitulino 	if (hstate_is_gigantic(h))
2576adbe8726SEric B Munson 		return -EINVAL;
2577adbe8726SEric B Munson 
25783dbb95f7SJingoo Han 	err = kstrtoul(buf, 10, &input);
2579a3437870SNishanth Aravamudan 	if (err)
258073ae31e5SEric B Munson 		return err;
2581a3437870SNishanth Aravamudan 
2582a3437870SNishanth Aravamudan 	spin_lock(&hugetlb_lock);
2583a3437870SNishanth Aravamudan 	h->nr_overcommit_huge_pages = input;
2584a3437870SNishanth Aravamudan 	spin_unlock(&hugetlb_lock);
2585a3437870SNishanth Aravamudan 
2586a3437870SNishanth Aravamudan 	return count;
2587a3437870SNishanth Aravamudan }
2588a3437870SNishanth Aravamudan HSTATE_ATTR(nr_overcommit_hugepages);
2589a3437870SNishanth Aravamudan 
2590a3437870SNishanth Aravamudan static ssize_t free_hugepages_show(struct kobject *kobj,
2591a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
2592a3437870SNishanth Aravamudan {
25939a305230SLee Schermerhorn 	struct hstate *h;
25949a305230SLee Schermerhorn 	unsigned long free_huge_pages;
25959a305230SLee Schermerhorn 	int nid;
25969a305230SLee Schermerhorn 
25979a305230SLee Schermerhorn 	h = kobj_to_hstate(kobj, &nid);
25989a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE)
25999a305230SLee Schermerhorn 		free_huge_pages = h->free_huge_pages;
26009a305230SLee Schermerhorn 	else
26019a305230SLee Schermerhorn 		free_huge_pages = h->free_huge_pages_node[nid];
26029a305230SLee Schermerhorn 
26039a305230SLee Schermerhorn 	return sprintf(buf, "%lu\n", free_huge_pages);
2604a3437870SNishanth Aravamudan }
2605a3437870SNishanth Aravamudan HSTATE_ATTR_RO(free_hugepages);
2606a3437870SNishanth Aravamudan 
2607a3437870SNishanth Aravamudan static ssize_t resv_hugepages_show(struct kobject *kobj,
2608a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
2609a3437870SNishanth Aravamudan {
26109a305230SLee Schermerhorn 	struct hstate *h = kobj_to_hstate(kobj, NULL);
2611a3437870SNishanth Aravamudan 	return sprintf(buf, "%lu\n", h->resv_huge_pages);
2612a3437870SNishanth Aravamudan }
2613a3437870SNishanth Aravamudan HSTATE_ATTR_RO(resv_hugepages);
2614a3437870SNishanth Aravamudan 
2615a3437870SNishanth Aravamudan static ssize_t surplus_hugepages_show(struct kobject *kobj,
2616a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
2617a3437870SNishanth Aravamudan {
26189a305230SLee Schermerhorn 	struct hstate *h;
26199a305230SLee Schermerhorn 	unsigned long surplus_huge_pages;
26209a305230SLee Schermerhorn 	int nid;
26219a305230SLee Schermerhorn 
26229a305230SLee Schermerhorn 	h = kobj_to_hstate(kobj, &nid);
26239a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE)
26249a305230SLee Schermerhorn 		surplus_huge_pages = h->surplus_huge_pages;
26259a305230SLee Schermerhorn 	else
26269a305230SLee Schermerhorn 		surplus_huge_pages = h->surplus_huge_pages_node[nid];
26279a305230SLee Schermerhorn 
26289a305230SLee Schermerhorn 	return sprintf(buf, "%lu\n", surplus_huge_pages);
2629a3437870SNishanth Aravamudan }
2630a3437870SNishanth Aravamudan HSTATE_ATTR_RO(surplus_hugepages);
2631a3437870SNishanth Aravamudan 
2632a3437870SNishanth Aravamudan static struct attribute *hstate_attrs[] = {
2633a3437870SNishanth Aravamudan 	&nr_hugepages_attr.attr,
2634a3437870SNishanth Aravamudan 	&nr_overcommit_hugepages_attr.attr,
2635a3437870SNishanth Aravamudan 	&free_hugepages_attr.attr,
2636a3437870SNishanth Aravamudan 	&resv_hugepages_attr.attr,
2637a3437870SNishanth Aravamudan 	&surplus_hugepages_attr.attr,
263806808b08SLee Schermerhorn #ifdef CONFIG_NUMA
263906808b08SLee Schermerhorn 	&nr_hugepages_mempolicy_attr.attr,
264006808b08SLee Schermerhorn #endif
2641a3437870SNishanth Aravamudan 	NULL,
2642a3437870SNishanth Aravamudan };
2643a3437870SNishanth Aravamudan 
264467e5ed96SArvind Yadav static const struct attribute_group hstate_attr_group = {
2645a3437870SNishanth Aravamudan 	.attrs = hstate_attrs,
2646a3437870SNishanth Aravamudan };
2647a3437870SNishanth Aravamudan 
2648094e9539SJeff Mahoney static int hugetlb_sysfs_add_hstate(struct hstate *h, struct kobject *parent,
26499a305230SLee Schermerhorn 				    struct kobject **hstate_kobjs,
265067e5ed96SArvind Yadav 				    const struct attribute_group *hstate_attr_group)
2651a3437870SNishanth Aravamudan {
2652a3437870SNishanth Aravamudan 	int retval;
2653972dc4deSAneesh Kumar K.V 	int hi = hstate_index(h);
2654a3437870SNishanth Aravamudan 
26559a305230SLee Schermerhorn 	hstate_kobjs[hi] = kobject_create_and_add(h->name, parent);
26569a305230SLee Schermerhorn 	if (!hstate_kobjs[hi])
2657a3437870SNishanth Aravamudan 		return -ENOMEM;
2658a3437870SNishanth Aravamudan 
26599a305230SLee Schermerhorn 	retval = sysfs_create_group(hstate_kobjs[hi], hstate_attr_group);
2660a3437870SNishanth Aravamudan 	if (retval)
26619a305230SLee Schermerhorn 		kobject_put(hstate_kobjs[hi]);
2662a3437870SNishanth Aravamudan 
2663a3437870SNishanth Aravamudan 	return retval;
2664a3437870SNishanth Aravamudan }
2665a3437870SNishanth Aravamudan 
2666a3437870SNishanth Aravamudan static void __init hugetlb_sysfs_init(void)
2667a3437870SNishanth Aravamudan {
2668a3437870SNishanth Aravamudan 	struct hstate *h;
2669a3437870SNishanth Aravamudan 	int err;
2670a3437870SNishanth Aravamudan 
2671a3437870SNishanth Aravamudan 	hugepages_kobj = kobject_create_and_add("hugepages", mm_kobj);
2672a3437870SNishanth Aravamudan 	if (!hugepages_kobj)
2673a3437870SNishanth Aravamudan 		return;
2674a3437870SNishanth Aravamudan 
2675a3437870SNishanth Aravamudan 	for_each_hstate(h) {
26769a305230SLee Schermerhorn 		err = hugetlb_sysfs_add_hstate(h, hugepages_kobj,
26779a305230SLee Schermerhorn 					 hstate_kobjs, &hstate_attr_group);
2678a3437870SNishanth Aravamudan 		if (err)
2679ffb22af5SAndrew Morton 			pr_err("Hugetlb: Unable to add hstate %s", h->name);
2680a3437870SNishanth Aravamudan 	}
2681a3437870SNishanth Aravamudan }
2682a3437870SNishanth Aravamudan 
26839a305230SLee Schermerhorn #ifdef CONFIG_NUMA
26849a305230SLee Schermerhorn 
26859a305230SLee Schermerhorn /*
26869a305230SLee Schermerhorn  * node_hstate/s - associate per node hstate attributes, via their kobjects,
268710fbcf4cSKay Sievers  * with node devices in node_devices[] using a parallel array.  The array
268810fbcf4cSKay Sievers  * index of a node device or _hstate == node id.
268910fbcf4cSKay Sievers  * This is here to avoid any static dependency of the node device driver, in
26909a305230SLee Schermerhorn  * the base kernel, on the hugetlb module.
26919a305230SLee Schermerhorn  */
26929a305230SLee Schermerhorn struct node_hstate {
26939a305230SLee Schermerhorn 	struct kobject		*hugepages_kobj;
26949a305230SLee Schermerhorn 	struct kobject		*hstate_kobjs[HUGE_MAX_HSTATE];
26959a305230SLee Schermerhorn };
2696b4e289a6SAlexander Kuleshov static struct node_hstate node_hstates[MAX_NUMNODES];
26979a305230SLee Schermerhorn 
26989a305230SLee Schermerhorn /*
269910fbcf4cSKay Sievers  * A subset of global hstate attributes for node devices
27009a305230SLee Schermerhorn  */
27019a305230SLee Schermerhorn static struct attribute *per_node_hstate_attrs[] = {
27029a305230SLee Schermerhorn 	&nr_hugepages_attr.attr,
27039a305230SLee Schermerhorn 	&free_hugepages_attr.attr,
27049a305230SLee Schermerhorn 	&surplus_hugepages_attr.attr,
27059a305230SLee Schermerhorn 	NULL,
27069a305230SLee Schermerhorn };
27079a305230SLee Schermerhorn 
270867e5ed96SArvind Yadav static const struct attribute_group per_node_hstate_attr_group = {
27099a305230SLee Schermerhorn 	.attrs = per_node_hstate_attrs,
27109a305230SLee Schermerhorn };
27119a305230SLee Schermerhorn 
27129a305230SLee Schermerhorn /*
271310fbcf4cSKay Sievers  * kobj_to_node_hstate - lookup global hstate for node device hstate attr kobj.
27149a305230SLee Schermerhorn  * Returns node id via non-NULL nidp.
27159a305230SLee Schermerhorn  */
27169a305230SLee Schermerhorn static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
27179a305230SLee Schermerhorn {
27189a305230SLee Schermerhorn 	int nid;
27199a305230SLee Schermerhorn 
27209a305230SLee Schermerhorn 	for (nid = 0; nid < nr_node_ids; nid++) {
27219a305230SLee Schermerhorn 		struct node_hstate *nhs = &node_hstates[nid];
27229a305230SLee Schermerhorn 		int i;
27239a305230SLee Schermerhorn 		for (i = 0; i < HUGE_MAX_HSTATE; i++)
27249a305230SLee Schermerhorn 			if (nhs->hstate_kobjs[i] == kobj) {
27259a305230SLee Schermerhorn 				if (nidp)
27269a305230SLee Schermerhorn 					*nidp = nid;
27279a305230SLee Schermerhorn 				return &hstates[i];
27289a305230SLee Schermerhorn 			}
27299a305230SLee Schermerhorn 	}
27309a305230SLee Schermerhorn 
27319a305230SLee Schermerhorn 	BUG();
27329a305230SLee Schermerhorn 	return NULL;
27339a305230SLee Schermerhorn }
27349a305230SLee Schermerhorn 
27359a305230SLee Schermerhorn /*
273610fbcf4cSKay Sievers  * Unregister hstate attributes from a single node device.
27379a305230SLee Schermerhorn  * No-op if no hstate attributes attached.
27389a305230SLee Schermerhorn  */
27393cd8b44fSClaudiu Ghioc static void hugetlb_unregister_node(struct node *node)
27409a305230SLee Schermerhorn {
27419a305230SLee Schermerhorn 	struct hstate *h;
274210fbcf4cSKay Sievers 	struct node_hstate *nhs = &node_hstates[node->dev.id];
27439a305230SLee Schermerhorn 
27449a305230SLee Schermerhorn 	if (!nhs->hugepages_kobj)
27459b5e5d0fSLee Schermerhorn 		return;		/* no hstate attributes */
27469a305230SLee Schermerhorn 
2747972dc4deSAneesh Kumar K.V 	for_each_hstate(h) {
2748972dc4deSAneesh Kumar K.V 		int idx = hstate_index(h);
2749972dc4deSAneesh Kumar K.V 		if (nhs->hstate_kobjs[idx]) {
2750972dc4deSAneesh Kumar K.V 			kobject_put(nhs->hstate_kobjs[idx]);
2751972dc4deSAneesh Kumar K.V 			nhs->hstate_kobjs[idx] = NULL;
2752972dc4deSAneesh Kumar K.V 		}
27539a305230SLee Schermerhorn 	}
27549a305230SLee Schermerhorn 
27559a305230SLee Schermerhorn 	kobject_put(nhs->hugepages_kobj);
27569a305230SLee Schermerhorn 	nhs->hugepages_kobj = NULL;
27579a305230SLee Schermerhorn }
27589a305230SLee Schermerhorn 
27599a305230SLee Schermerhorn 
27609a305230SLee Schermerhorn /*
276110fbcf4cSKay Sievers  * Register hstate attributes for a single node device.
27629a305230SLee Schermerhorn  * No-op if attributes already registered.
27639a305230SLee Schermerhorn  */
27643cd8b44fSClaudiu Ghioc static void hugetlb_register_node(struct node *node)
27659a305230SLee Schermerhorn {
27669a305230SLee Schermerhorn 	struct hstate *h;
276710fbcf4cSKay Sievers 	struct node_hstate *nhs = &node_hstates[node->dev.id];
27689a305230SLee Schermerhorn 	int err;
27699a305230SLee Schermerhorn 
27709a305230SLee Schermerhorn 	if (nhs->hugepages_kobj)
27719a305230SLee Schermerhorn 		return;		/* already allocated */
27729a305230SLee Schermerhorn 
27739a305230SLee Schermerhorn 	nhs->hugepages_kobj = kobject_create_and_add("hugepages",
277410fbcf4cSKay Sievers 							&node->dev.kobj);
27759a305230SLee Schermerhorn 	if (!nhs->hugepages_kobj)
27769a305230SLee Schermerhorn 		return;
27779a305230SLee Schermerhorn 
27789a305230SLee Schermerhorn 	for_each_hstate(h) {
27799a305230SLee Schermerhorn 		err = hugetlb_sysfs_add_hstate(h, nhs->hugepages_kobj,
27809a305230SLee Schermerhorn 						nhs->hstate_kobjs,
27819a305230SLee Schermerhorn 						&per_node_hstate_attr_group);
27829a305230SLee Schermerhorn 		if (err) {
2783ffb22af5SAndrew Morton 			pr_err("Hugetlb: Unable to add hstate %s for node %d\n",
278410fbcf4cSKay Sievers 				h->name, node->dev.id);
27859a305230SLee Schermerhorn 			hugetlb_unregister_node(node);
27869a305230SLee Schermerhorn 			break;
27879a305230SLee Schermerhorn 		}
27889a305230SLee Schermerhorn 	}
27899a305230SLee Schermerhorn }
27909a305230SLee Schermerhorn 
27919a305230SLee Schermerhorn /*
27929b5e5d0fSLee Schermerhorn  * hugetlb init time:  register hstate attributes for all registered node
279310fbcf4cSKay Sievers  * devices of nodes that have memory.  All on-line nodes should have
279410fbcf4cSKay Sievers  * registered their associated device by this time.
27959a305230SLee Schermerhorn  */
27967d9ca000SLuiz Capitulino static void __init hugetlb_register_all_nodes(void)
27979a305230SLee Schermerhorn {
27989a305230SLee Schermerhorn 	int nid;
27999a305230SLee Schermerhorn 
28008cebfcd0SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
28018732794bSWen Congyang 		struct node *node = node_devices[nid];
280210fbcf4cSKay Sievers 		if (node->dev.id == nid)
28039a305230SLee Schermerhorn 			hugetlb_register_node(node);
28049a305230SLee Schermerhorn 	}
28059a305230SLee Schermerhorn 
28069a305230SLee Schermerhorn 	/*
280710fbcf4cSKay Sievers 	 * Let the node device driver know we're here so it can
28089a305230SLee Schermerhorn 	 * [un]register hstate attributes on node hotplug.
28099a305230SLee Schermerhorn 	 */
28109a305230SLee Schermerhorn 	register_hugetlbfs_with_node(hugetlb_register_node,
28119a305230SLee Schermerhorn 				     hugetlb_unregister_node);
28129a305230SLee Schermerhorn }
28139a305230SLee Schermerhorn #else	/* !CONFIG_NUMA */
28149a305230SLee Schermerhorn 
28159a305230SLee Schermerhorn static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
28169a305230SLee Schermerhorn {
28179a305230SLee Schermerhorn 	BUG();
28189a305230SLee Schermerhorn 	if (nidp)
28199a305230SLee Schermerhorn 		*nidp = -1;
28209a305230SLee Schermerhorn 	return NULL;
28219a305230SLee Schermerhorn }
28229a305230SLee Schermerhorn 
28239a305230SLee Schermerhorn static void hugetlb_register_all_nodes(void) { }
28249a305230SLee Schermerhorn 
28259a305230SLee Schermerhorn #endif
28269a305230SLee Schermerhorn 
2827a3437870SNishanth Aravamudan static int __init hugetlb_init(void)
2828a3437870SNishanth Aravamudan {
28298382d914SDavidlohr Bueso 	int i;
28308382d914SDavidlohr Bueso 
2831457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
28320ef89d25SBenjamin Herrenschmidt 		return 0;
2833a3437870SNishanth Aravamudan 
2834e11bfbfcSNick Piggin 	if (!size_to_hstate(default_hstate_size)) {
2835d715cf80SLiam R. Howlett 		if (default_hstate_size != 0) {
2836d715cf80SLiam R. Howlett 			pr_err("HugeTLB: unsupported default_hugepagesz %lu. Reverting to %lu\n",
2837d715cf80SLiam R. Howlett 			       default_hstate_size, HPAGE_SIZE);
2838d715cf80SLiam R. Howlett 		}
2839d715cf80SLiam R. Howlett 
2840e11bfbfcSNick Piggin 		default_hstate_size = HPAGE_SIZE;
2841e11bfbfcSNick Piggin 		if (!size_to_hstate(default_hstate_size))
2842a3437870SNishanth Aravamudan 			hugetlb_add_hstate(HUGETLB_PAGE_ORDER);
2843a3437870SNishanth Aravamudan 	}
2844972dc4deSAneesh Kumar K.V 	default_hstate_idx = hstate_index(size_to_hstate(default_hstate_size));
2845f8b74815SVaishali Thakkar 	if (default_hstate_max_huge_pages) {
2846f8b74815SVaishali Thakkar 		if (!default_hstate.max_huge_pages)
2847e11bfbfcSNick Piggin 			default_hstate.max_huge_pages = default_hstate_max_huge_pages;
2848f8b74815SVaishali Thakkar 	}
2849a3437870SNishanth Aravamudan 
2850a3437870SNishanth Aravamudan 	hugetlb_init_hstates();
2851aa888a74SAndi Kleen 	gather_bootmem_prealloc();
2852a3437870SNishanth Aravamudan 	report_hugepages();
2853a3437870SNishanth Aravamudan 
2854a3437870SNishanth Aravamudan 	hugetlb_sysfs_init();
28559a305230SLee Schermerhorn 	hugetlb_register_all_nodes();
28567179e7bfSJianguo Wu 	hugetlb_cgroup_file_init();
28579a305230SLee Schermerhorn 
28588382d914SDavidlohr Bueso #ifdef CONFIG_SMP
28598382d914SDavidlohr Bueso 	num_fault_mutexes = roundup_pow_of_two(8 * num_possible_cpus());
28608382d914SDavidlohr Bueso #else
28618382d914SDavidlohr Bueso 	num_fault_mutexes = 1;
28628382d914SDavidlohr Bueso #endif
2863c672c7f2SMike Kravetz 	hugetlb_fault_mutex_table =
28646da2ec56SKees Cook 		kmalloc_array(num_fault_mutexes, sizeof(struct mutex),
28656da2ec56SKees Cook 			      GFP_KERNEL);
2866c672c7f2SMike Kravetz 	BUG_ON(!hugetlb_fault_mutex_table);
28678382d914SDavidlohr Bueso 
28688382d914SDavidlohr Bueso 	for (i = 0; i < num_fault_mutexes; i++)
2869c672c7f2SMike Kravetz 		mutex_init(&hugetlb_fault_mutex_table[i]);
2870a3437870SNishanth Aravamudan 	return 0;
2871a3437870SNishanth Aravamudan }
28723e89e1c5SPaul Gortmaker subsys_initcall(hugetlb_init);
2873a3437870SNishanth Aravamudan 
2874a3437870SNishanth Aravamudan /* Should be called on processing a hugepagesz=... option */
28759fee021dSVaishali Thakkar void __init hugetlb_bad_size(void)
28769fee021dSVaishali Thakkar {
28779fee021dSVaishali Thakkar 	parsed_valid_hugepagesz = false;
28789fee021dSVaishali Thakkar }
28799fee021dSVaishali Thakkar 
2880d00181b9SKirill A. Shutemov void __init hugetlb_add_hstate(unsigned int order)
2881a3437870SNishanth Aravamudan {
2882a3437870SNishanth Aravamudan 	struct hstate *h;
28838faa8b07SAndi Kleen 	unsigned long i;
28848faa8b07SAndi Kleen 
2885a3437870SNishanth Aravamudan 	if (size_to_hstate(PAGE_SIZE << order)) {
2886598d8091SJoe Perches 		pr_warn("hugepagesz= specified twice, ignoring\n");
2887a3437870SNishanth Aravamudan 		return;
2888a3437870SNishanth Aravamudan 	}
288947d38344SAneesh Kumar K.V 	BUG_ON(hugetlb_max_hstate >= HUGE_MAX_HSTATE);
2890a3437870SNishanth Aravamudan 	BUG_ON(order == 0);
289147d38344SAneesh Kumar K.V 	h = &hstates[hugetlb_max_hstate++];
2892a3437870SNishanth Aravamudan 	h->order = order;
2893a3437870SNishanth Aravamudan 	h->mask = ~((1ULL << (order + PAGE_SHIFT)) - 1);
28948faa8b07SAndi Kleen 	h->nr_huge_pages = 0;
28958faa8b07SAndi Kleen 	h->free_huge_pages = 0;
28968faa8b07SAndi Kleen 	for (i = 0; i < MAX_NUMNODES; ++i)
28978faa8b07SAndi Kleen 		INIT_LIST_HEAD(&h->hugepage_freelists[i]);
28980edaecfaSAneesh Kumar K.V 	INIT_LIST_HEAD(&h->hugepage_activelist);
289954f18d35SAndrew Morton 	h->next_nid_to_alloc = first_memory_node;
290054f18d35SAndrew Morton 	h->next_nid_to_free = first_memory_node;
2901a3437870SNishanth Aravamudan 	snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB",
2902a3437870SNishanth Aravamudan 					huge_page_size(h)/1024);
29038faa8b07SAndi Kleen 
2904a3437870SNishanth Aravamudan 	parsed_hstate = h;
2905a3437870SNishanth Aravamudan }
2906a3437870SNishanth Aravamudan 
2907e11bfbfcSNick Piggin static int __init hugetlb_nrpages_setup(char *s)
2908a3437870SNishanth Aravamudan {
2909a3437870SNishanth Aravamudan 	unsigned long *mhp;
29108faa8b07SAndi Kleen 	static unsigned long *last_mhp;
2911a3437870SNishanth Aravamudan 
29129fee021dSVaishali Thakkar 	if (!parsed_valid_hugepagesz) {
29139fee021dSVaishali Thakkar 		pr_warn("hugepages = %s preceded by "
29149fee021dSVaishali Thakkar 			"an unsupported hugepagesz, ignoring\n", s);
29159fee021dSVaishali Thakkar 		parsed_valid_hugepagesz = true;
29169fee021dSVaishali Thakkar 		return 1;
29179fee021dSVaishali Thakkar 	}
2918a3437870SNishanth Aravamudan 	/*
291947d38344SAneesh Kumar K.V 	 * !hugetlb_max_hstate means we haven't parsed a hugepagesz= parameter yet,
2920a3437870SNishanth Aravamudan 	 * so this hugepages= parameter goes to the "default hstate".
2921a3437870SNishanth Aravamudan 	 */
29229fee021dSVaishali Thakkar 	else if (!hugetlb_max_hstate)
2923a3437870SNishanth Aravamudan 		mhp = &default_hstate_max_huge_pages;
2924a3437870SNishanth Aravamudan 	else
2925a3437870SNishanth Aravamudan 		mhp = &parsed_hstate->max_huge_pages;
2926a3437870SNishanth Aravamudan 
29278faa8b07SAndi Kleen 	if (mhp == last_mhp) {
2928598d8091SJoe Perches 		pr_warn("hugepages= specified twice without interleaving hugepagesz=, ignoring\n");
29298faa8b07SAndi Kleen 		return 1;
29308faa8b07SAndi Kleen 	}
29318faa8b07SAndi Kleen 
2932a3437870SNishanth Aravamudan 	if (sscanf(s, "%lu", mhp) <= 0)
2933a3437870SNishanth Aravamudan 		*mhp = 0;
2934a3437870SNishanth Aravamudan 
29358faa8b07SAndi Kleen 	/*
29368faa8b07SAndi Kleen 	 * Global state is always initialized later in hugetlb_init.
29378faa8b07SAndi Kleen 	 * But we need to allocate >= MAX_ORDER hstates here early to still
29388faa8b07SAndi Kleen 	 * use the bootmem allocator.
29398faa8b07SAndi Kleen 	 */
294047d38344SAneesh Kumar K.V 	if (hugetlb_max_hstate && parsed_hstate->order >= MAX_ORDER)
29418faa8b07SAndi Kleen 		hugetlb_hstate_alloc_pages(parsed_hstate);
29428faa8b07SAndi Kleen 
29438faa8b07SAndi Kleen 	last_mhp = mhp;
29448faa8b07SAndi Kleen 
2945a3437870SNishanth Aravamudan 	return 1;
2946a3437870SNishanth Aravamudan }
2947e11bfbfcSNick Piggin __setup("hugepages=", hugetlb_nrpages_setup);
2948e11bfbfcSNick Piggin 
2949e11bfbfcSNick Piggin static int __init hugetlb_default_setup(char *s)
2950e11bfbfcSNick Piggin {
2951e11bfbfcSNick Piggin 	default_hstate_size = memparse(s, &s);
2952e11bfbfcSNick Piggin 	return 1;
2953e11bfbfcSNick Piggin }
2954e11bfbfcSNick Piggin __setup("default_hugepagesz=", hugetlb_default_setup);
2955a3437870SNishanth Aravamudan 
29568a213460SNishanth Aravamudan static unsigned int cpuset_mems_nr(unsigned int *array)
29578a213460SNishanth Aravamudan {
29588a213460SNishanth Aravamudan 	int node;
29598a213460SNishanth Aravamudan 	unsigned int nr = 0;
29608a213460SNishanth Aravamudan 
29618a213460SNishanth Aravamudan 	for_each_node_mask(node, cpuset_current_mems_allowed)
29628a213460SNishanth Aravamudan 		nr += array[node];
29638a213460SNishanth Aravamudan 
29648a213460SNishanth Aravamudan 	return nr;
29658a213460SNishanth Aravamudan }
29668a213460SNishanth Aravamudan 
29678a213460SNishanth Aravamudan #ifdef CONFIG_SYSCTL
296806808b08SLee Schermerhorn static int hugetlb_sysctl_handler_common(bool obey_mempolicy,
296906808b08SLee Schermerhorn 			 struct ctl_table *table, int write,
297006808b08SLee Schermerhorn 			 void __user *buffer, size_t *length, loff_t *ppos)
29711da177e4SLinus Torvalds {
2972e5ff2159SAndi Kleen 	struct hstate *h = &default_hstate;
2973238d3c13SDavid Rientjes 	unsigned long tmp = h->max_huge_pages;
297408d4a246SMichal Hocko 	int ret;
2975e5ff2159SAndi Kleen 
2976457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
297786613628SJan Stancek 		return -EOPNOTSUPP;
2978457c1b27SNishanth Aravamudan 
2979e5ff2159SAndi Kleen 	table->data = &tmp;
2980e5ff2159SAndi Kleen 	table->maxlen = sizeof(unsigned long);
298108d4a246SMichal Hocko 	ret = proc_doulongvec_minmax(table, write, buffer, length, ppos);
298208d4a246SMichal Hocko 	if (ret)
298308d4a246SMichal Hocko 		goto out;
2984e5ff2159SAndi Kleen 
2985238d3c13SDavid Rientjes 	if (write)
2986238d3c13SDavid Rientjes 		ret = __nr_hugepages_store_common(obey_mempolicy, h,
2987238d3c13SDavid Rientjes 						  NUMA_NO_NODE, tmp, *length);
298808d4a246SMichal Hocko out:
298908d4a246SMichal Hocko 	return ret;
29901da177e4SLinus Torvalds }
2991396faf03SMel Gorman 
299206808b08SLee Schermerhorn int hugetlb_sysctl_handler(struct ctl_table *table, int write,
299306808b08SLee Schermerhorn 			  void __user *buffer, size_t *length, loff_t *ppos)
299406808b08SLee Schermerhorn {
299506808b08SLee Schermerhorn 
299606808b08SLee Schermerhorn 	return hugetlb_sysctl_handler_common(false, table, write,
299706808b08SLee Schermerhorn 							buffer, length, ppos);
299806808b08SLee Schermerhorn }
299906808b08SLee Schermerhorn 
300006808b08SLee Schermerhorn #ifdef CONFIG_NUMA
300106808b08SLee Schermerhorn int hugetlb_mempolicy_sysctl_handler(struct ctl_table *table, int write,
300206808b08SLee Schermerhorn 			  void __user *buffer, size_t *length, loff_t *ppos)
300306808b08SLee Schermerhorn {
300406808b08SLee Schermerhorn 	return hugetlb_sysctl_handler_common(true, table, write,
300506808b08SLee Schermerhorn 							buffer, length, ppos);
300606808b08SLee Schermerhorn }
300706808b08SLee Schermerhorn #endif /* CONFIG_NUMA */
300806808b08SLee Schermerhorn 
3009a3d0c6aaSNishanth Aravamudan int hugetlb_overcommit_handler(struct ctl_table *table, int write,
30108d65af78SAlexey Dobriyan 			void __user *buffer,
3011a3d0c6aaSNishanth Aravamudan 			size_t *length, loff_t *ppos)
3012a3d0c6aaSNishanth Aravamudan {
3013a5516438SAndi Kleen 	struct hstate *h = &default_hstate;
3014e5ff2159SAndi Kleen 	unsigned long tmp;
301508d4a246SMichal Hocko 	int ret;
3016e5ff2159SAndi Kleen 
3017457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
301886613628SJan Stancek 		return -EOPNOTSUPP;
3019457c1b27SNishanth Aravamudan 
3020e5ff2159SAndi Kleen 	tmp = h->nr_overcommit_huge_pages;
3021e5ff2159SAndi Kleen 
3022bae7f4aeSLuiz Capitulino 	if (write && hstate_is_gigantic(h))
3023adbe8726SEric B Munson 		return -EINVAL;
3024adbe8726SEric B Munson 
3025e5ff2159SAndi Kleen 	table->data = &tmp;
3026e5ff2159SAndi Kleen 	table->maxlen = sizeof(unsigned long);
302708d4a246SMichal Hocko 	ret = proc_doulongvec_minmax(table, write, buffer, length, ppos);
302808d4a246SMichal Hocko 	if (ret)
302908d4a246SMichal Hocko 		goto out;
3030e5ff2159SAndi Kleen 
3031e5ff2159SAndi Kleen 	if (write) {
3032064d9efeSNishanth Aravamudan 		spin_lock(&hugetlb_lock);
3033e5ff2159SAndi Kleen 		h->nr_overcommit_huge_pages = tmp;
3034a3d0c6aaSNishanth Aravamudan 		spin_unlock(&hugetlb_lock);
3035e5ff2159SAndi Kleen 	}
303608d4a246SMichal Hocko out:
303708d4a246SMichal Hocko 	return ret;
3038a3d0c6aaSNishanth Aravamudan }
3039a3d0c6aaSNishanth Aravamudan 
30401da177e4SLinus Torvalds #endif /* CONFIG_SYSCTL */
30411da177e4SLinus Torvalds 
3042e1759c21SAlexey Dobriyan void hugetlb_report_meminfo(struct seq_file *m)
30431da177e4SLinus Torvalds {
3044fcb2b0c5SRoman Gushchin 	struct hstate *h;
3045fcb2b0c5SRoman Gushchin 	unsigned long total = 0;
3046fcb2b0c5SRoman Gushchin 
3047457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
3048457c1b27SNishanth Aravamudan 		return;
3049fcb2b0c5SRoman Gushchin 
3050fcb2b0c5SRoman Gushchin 	for_each_hstate(h) {
3051fcb2b0c5SRoman Gushchin 		unsigned long count = h->nr_huge_pages;
3052fcb2b0c5SRoman Gushchin 
3053fcb2b0c5SRoman Gushchin 		total += (PAGE_SIZE << huge_page_order(h)) * count;
3054fcb2b0c5SRoman Gushchin 
3055fcb2b0c5SRoman Gushchin 		if (h == &default_hstate)
3056e1759c21SAlexey Dobriyan 			seq_printf(m,
30571da177e4SLinus Torvalds 				   "HugePages_Total:   %5lu\n"
30581da177e4SLinus Torvalds 				   "HugePages_Free:    %5lu\n"
3059b45b5bd6SDavid Gibson 				   "HugePages_Rsvd:    %5lu\n"
30607893d1d5SAdam Litke 				   "HugePages_Surp:    %5lu\n"
30614f98a2feSRik van Riel 				   "Hugepagesize:   %8lu kB\n",
3062fcb2b0c5SRoman Gushchin 				   count,
3063a5516438SAndi Kleen 				   h->free_huge_pages,
3064a5516438SAndi Kleen 				   h->resv_huge_pages,
3065a5516438SAndi Kleen 				   h->surplus_huge_pages,
3066fcb2b0c5SRoman Gushchin 				   (PAGE_SIZE << huge_page_order(h)) / 1024);
3067fcb2b0c5SRoman Gushchin 	}
3068fcb2b0c5SRoman Gushchin 
3069fcb2b0c5SRoman Gushchin 	seq_printf(m, "Hugetlb:        %8lu kB\n", total / 1024);
30701da177e4SLinus Torvalds }
30711da177e4SLinus Torvalds 
30721da177e4SLinus Torvalds int hugetlb_report_node_meminfo(int nid, char *buf)
30731da177e4SLinus Torvalds {
3074a5516438SAndi Kleen 	struct hstate *h = &default_hstate;
3075457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
3076457c1b27SNishanth Aravamudan 		return 0;
30771da177e4SLinus Torvalds 	return sprintf(buf,
30781da177e4SLinus Torvalds 		"Node %d HugePages_Total: %5u\n"
3079a1de0919SNishanth Aravamudan 		"Node %d HugePages_Free:  %5u\n"
3080a1de0919SNishanth Aravamudan 		"Node %d HugePages_Surp:  %5u\n",
3081a5516438SAndi Kleen 		nid, h->nr_huge_pages_node[nid],
3082a5516438SAndi Kleen 		nid, h->free_huge_pages_node[nid],
3083a5516438SAndi Kleen 		nid, h->surplus_huge_pages_node[nid]);
30841da177e4SLinus Torvalds }
30851da177e4SLinus Torvalds 
3086949f7ec5SDavid Rientjes void hugetlb_show_meminfo(void)
3087949f7ec5SDavid Rientjes {
3088949f7ec5SDavid Rientjes 	struct hstate *h;
3089949f7ec5SDavid Rientjes 	int nid;
3090949f7ec5SDavid Rientjes 
3091457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
3092457c1b27SNishanth Aravamudan 		return;
3093457c1b27SNishanth Aravamudan 
3094949f7ec5SDavid Rientjes 	for_each_node_state(nid, N_MEMORY)
3095949f7ec5SDavid Rientjes 		for_each_hstate(h)
3096949f7ec5SDavid Rientjes 			pr_info("Node %d hugepages_total=%u hugepages_free=%u hugepages_surp=%u hugepages_size=%lukB\n",
3097949f7ec5SDavid Rientjes 				nid,
3098949f7ec5SDavid Rientjes 				h->nr_huge_pages_node[nid],
3099949f7ec5SDavid Rientjes 				h->free_huge_pages_node[nid],
3100949f7ec5SDavid Rientjes 				h->surplus_huge_pages_node[nid],
3101949f7ec5SDavid Rientjes 				1UL << (huge_page_order(h) + PAGE_SHIFT - 10));
3102949f7ec5SDavid Rientjes }
3103949f7ec5SDavid Rientjes 
31045d317b2bSNaoya Horiguchi void hugetlb_report_usage(struct seq_file *m, struct mm_struct *mm)
31055d317b2bSNaoya Horiguchi {
31065d317b2bSNaoya Horiguchi 	seq_printf(m, "HugetlbPages:\t%8lu kB\n",
31075d317b2bSNaoya Horiguchi 		   atomic_long_read(&mm->hugetlb_usage) << (PAGE_SHIFT - 10));
31085d317b2bSNaoya Horiguchi }
31095d317b2bSNaoya Horiguchi 
31101da177e4SLinus Torvalds /* Return the number pages of memory we physically have, in PAGE_SIZE units. */
31111da177e4SLinus Torvalds unsigned long hugetlb_total_pages(void)
31121da177e4SLinus Torvalds {
3113d0028588SWanpeng Li 	struct hstate *h;
3114d0028588SWanpeng Li 	unsigned long nr_total_pages = 0;
3115d0028588SWanpeng Li 
3116d0028588SWanpeng Li 	for_each_hstate(h)
3117d0028588SWanpeng Li 		nr_total_pages += h->nr_huge_pages * pages_per_huge_page(h);
3118d0028588SWanpeng Li 	return nr_total_pages;
31191da177e4SLinus Torvalds }
31201da177e4SLinus Torvalds 
3121a5516438SAndi Kleen static int hugetlb_acct_memory(struct hstate *h, long delta)
3122fc1b8a73SMel Gorman {
3123fc1b8a73SMel Gorman 	int ret = -ENOMEM;
3124fc1b8a73SMel Gorman 
3125fc1b8a73SMel Gorman 	spin_lock(&hugetlb_lock);
3126fc1b8a73SMel Gorman 	/*
3127fc1b8a73SMel Gorman 	 * When cpuset is configured, it breaks the strict hugetlb page
3128fc1b8a73SMel Gorman 	 * reservation as the accounting is done on a global variable. Such
3129fc1b8a73SMel Gorman 	 * reservation is completely rubbish in the presence of cpuset because
3130fc1b8a73SMel Gorman 	 * the reservation is not checked against page availability for the
3131fc1b8a73SMel Gorman 	 * current cpuset. Application can still potentially OOM'ed by kernel
3132fc1b8a73SMel Gorman 	 * with lack of free htlb page in cpuset that the task is in.
3133fc1b8a73SMel Gorman 	 * Attempt to enforce strict accounting with cpuset is almost
3134fc1b8a73SMel Gorman 	 * impossible (or too ugly) because cpuset is too fluid that
3135fc1b8a73SMel Gorman 	 * task or memory node can be dynamically moved between cpusets.
3136fc1b8a73SMel Gorman 	 *
3137fc1b8a73SMel Gorman 	 * The change of semantics for shared hugetlb mapping with cpuset is
3138fc1b8a73SMel Gorman 	 * undesirable. However, in order to preserve some of the semantics,
3139fc1b8a73SMel Gorman 	 * we fall back to check against current free page availability as
3140fc1b8a73SMel Gorman 	 * a best attempt and hopefully to minimize the impact of changing
3141fc1b8a73SMel Gorman 	 * semantics that cpuset has.
3142fc1b8a73SMel Gorman 	 */
3143fc1b8a73SMel Gorman 	if (delta > 0) {
3144a5516438SAndi Kleen 		if (gather_surplus_pages(h, delta) < 0)
3145fc1b8a73SMel Gorman 			goto out;
3146fc1b8a73SMel Gorman 
3147a5516438SAndi Kleen 		if (delta > cpuset_mems_nr(h->free_huge_pages_node)) {
3148a5516438SAndi Kleen 			return_unused_surplus_pages(h, delta);
3149fc1b8a73SMel Gorman 			goto out;
3150fc1b8a73SMel Gorman 		}
3151fc1b8a73SMel Gorman 	}
3152fc1b8a73SMel Gorman 
3153fc1b8a73SMel Gorman 	ret = 0;
3154fc1b8a73SMel Gorman 	if (delta < 0)
3155a5516438SAndi Kleen 		return_unused_surplus_pages(h, (unsigned long) -delta);
3156fc1b8a73SMel Gorman 
3157fc1b8a73SMel Gorman out:
3158fc1b8a73SMel Gorman 	spin_unlock(&hugetlb_lock);
3159fc1b8a73SMel Gorman 	return ret;
3160fc1b8a73SMel Gorman }
3161fc1b8a73SMel Gorman 
316284afd99bSAndy Whitcroft static void hugetlb_vm_op_open(struct vm_area_struct *vma)
316384afd99bSAndy Whitcroft {
3164f522c3acSJoonsoo Kim 	struct resv_map *resv = vma_resv_map(vma);
316584afd99bSAndy Whitcroft 
316684afd99bSAndy Whitcroft 	/*
316784afd99bSAndy Whitcroft 	 * This new VMA should share its siblings reservation map if present.
316884afd99bSAndy Whitcroft 	 * The VMA will only ever have a valid reservation map pointer where
316984afd99bSAndy Whitcroft 	 * it is being copied for another still existing VMA.  As that VMA
317025985edcSLucas De Marchi 	 * has a reference to the reservation map it cannot disappear until
317184afd99bSAndy Whitcroft 	 * after this open call completes.  It is therefore safe to take a
317284afd99bSAndy Whitcroft 	 * new reference here without additional locking.
317384afd99bSAndy Whitcroft 	 */
31744e35f483SJoonsoo Kim 	if (resv && is_vma_resv_set(vma, HPAGE_RESV_OWNER))
3175f522c3acSJoonsoo Kim 		kref_get(&resv->refs);
317684afd99bSAndy Whitcroft }
317784afd99bSAndy Whitcroft 
3178a1e78772SMel Gorman static void hugetlb_vm_op_close(struct vm_area_struct *vma)
3179a1e78772SMel Gorman {
3180a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
3181f522c3acSJoonsoo Kim 	struct resv_map *resv = vma_resv_map(vma);
318290481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_vma(vma);
31834e35f483SJoonsoo Kim 	unsigned long reserve, start, end;
31841c5ecae3SMike Kravetz 	long gbl_reserve;
318584afd99bSAndy Whitcroft 
31864e35f483SJoonsoo Kim 	if (!resv || !is_vma_resv_set(vma, HPAGE_RESV_OWNER))
31874e35f483SJoonsoo Kim 		return;
31884e35f483SJoonsoo Kim 
3189a5516438SAndi Kleen 	start = vma_hugecache_offset(h, vma, vma->vm_start);
3190a5516438SAndi Kleen 	end = vma_hugecache_offset(h, vma, vma->vm_end);
319184afd99bSAndy Whitcroft 
31924e35f483SJoonsoo Kim 	reserve = (end - start) - region_count(resv, start, end);
319384afd99bSAndy Whitcroft 
3194f031dd27SJoonsoo Kim 	kref_put(&resv->refs, resv_map_release);
319584afd99bSAndy Whitcroft 
31967251ff78SAdam Litke 	if (reserve) {
31971c5ecae3SMike Kravetz 		/*
31981c5ecae3SMike Kravetz 		 * Decrement reserve counts.  The global reserve count may be
31991c5ecae3SMike Kravetz 		 * adjusted if the subpool has a minimum size.
32001c5ecae3SMike Kravetz 		 */
32011c5ecae3SMike Kravetz 		gbl_reserve = hugepage_subpool_put_pages(spool, reserve);
32021c5ecae3SMike Kravetz 		hugetlb_acct_memory(h, -gbl_reserve);
32037251ff78SAdam Litke 	}
3204a1e78772SMel Gorman }
3205a1e78772SMel Gorman 
320631383c68SDan Williams static int hugetlb_vm_op_split(struct vm_area_struct *vma, unsigned long addr)
320731383c68SDan Williams {
320831383c68SDan Williams 	if (addr & ~(huge_page_mask(hstate_vma(vma))))
320931383c68SDan Williams 		return -EINVAL;
321031383c68SDan Williams 	return 0;
321131383c68SDan Williams }
321231383c68SDan Williams 
321305ea8860SDan Williams static unsigned long hugetlb_vm_op_pagesize(struct vm_area_struct *vma)
321405ea8860SDan Williams {
321505ea8860SDan Williams 	struct hstate *hstate = hstate_vma(vma);
321605ea8860SDan Williams 
321705ea8860SDan Williams 	return 1UL << huge_page_shift(hstate);
321805ea8860SDan Williams }
321905ea8860SDan Williams 
32201da177e4SLinus Torvalds /*
32211da177e4SLinus Torvalds  * We cannot handle pagefaults against hugetlb pages at all.  They cause
32221da177e4SLinus Torvalds  * handle_mm_fault() to try to instantiate regular-sized pages in the
32231da177e4SLinus Torvalds  * hugegpage VMA.  do_page_fault() is supposed to trap this, so BUG is we get
32241da177e4SLinus Torvalds  * this far.
32251da177e4SLinus Torvalds  */
3226b3ec9f33SSouptick Joarder static vm_fault_t hugetlb_vm_op_fault(struct vm_fault *vmf)
32271da177e4SLinus Torvalds {
32281da177e4SLinus Torvalds 	BUG();
3229d0217ac0SNick Piggin 	return 0;
32301da177e4SLinus Torvalds }
32311da177e4SLinus Torvalds 
3232eec3636aSJane Chu /*
3233eec3636aSJane Chu  * When a new function is introduced to vm_operations_struct and added
3234eec3636aSJane Chu  * to hugetlb_vm_ops, please consider adding the function to shm_vm_ops.
3235eec3636aSJane Chu  * This is because under System V memory model, mappings created via
3236eec3636aSJane Chu  * shmget/shmat with "huge page" specified are backed by hugetlbfs files,
3237eec3636aSJane Chu  * their original vm_ops are overwritten with shm_vm_ops.
3238eec3636aSJane Chu  */
3239f0f37e2fSAlexey Dobriyan const struct vm_operations_struct hugetlb_vm_ops = {
3240d0217ac0SNick Piggin 	.fault = hugetlb_vm_op_fault,
324184afd99bSAndy Whitcroft 	.open = hugetlb_vm_op_open,
3242a1e78772SMel Gorman 	.close = hugetlb_vm_op_close,
324331383c68SDan Williams 	.split = hugetlb_vm_op_split,
324405ea8860SDan Williams 	.pagesize = hugetlb_vm_op_pagesize,
32451da177e4SLinus Torvalds };
32461da177e4SLinus Torvalds 
32471e8f889bSDavid Gibson static pte_t make_huge_pte(struct vm_area_struct *vma, struct page *page,
32481e8f889bSDavid Gibson 				int writable)
324963551ae0SDavid Gibson {
325063551ae0SDavid Gibson 	pte_t entry;
325163551ae0SDavid Gibson 
32521e8f889bSDavid Gibson 	if (writable) {
3253106c992aSGerald Schaefer 		entry = huge_pte_mkwrite(huge_pte_mkdirty(mk_huge_pte(page,
3254106c992aSGerald Schaefer 					 vma->vm_page_prot)));
325563551ae0SDavid Gibson 	} else {
3256106c992aSGerald Schaefer 		entry = huge_pte_wrprotect(mk_huge_pte(page,
3257106c992aSGerald Schaefer 					   vma->vm_page_prot));
325863551ae0SDavid Gibson 	}
325963551ae0SDavid Gibson 	entry = pte_mkyoung(entry);
326063551ae0SDavid Gibson 	entry = pte_mkhuge(entry);
3261d9ed9faaSChris Metcalf 	entry = arch_make_huge_pte(entry, vma, page, writable);
326263551ae0SDavid Gibson 
326363551ae0SDavid Gibson 	return entry;
326463551ae0SDavid Gibson }
326563551ae0SDavid Gibson 
32661e8f889bSDavid Gibson static void set_huge_ptep_writable(struct vm_area_struct *vma,
32671e8f889bSDavid Gibson 				   unsigned long address, pte_t *ptep)
32681e8f889bSDavid Gibson {
32691e8f889bSDavid Gibson 	pte_t entry;
32701e8f889bSDavid Gibson 
3271106c992aSGerald Schaefer 	entry = huge_pte_mkwrite(huge_pte_mkdirty(huge_ptep_get(ptep)));
327232f84528SChris Forbes 	if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1))
32734b3073e1SRussell King 		update_mmu_cache(vma, address, ptep);
32741e8f889bSDavid Gibson }
32751e8f889bSDavid Gibson 
3276d5ed7444SAneesh Kumar K.V bool is_hugetlb_entry_migration(pte_t pte)
32774a705fefSNaoya Horiguchi {
32784a705fefSNaoya Horiguchi 	swp_entry_t swp;
32794a705fefSNaoya Horiguchi 
32804a705fefSNaoya Horiguchi 	if (huge_pte_none(pte) || pte_present(pte))
3281d5ed7444SAneesh Kumar K.V 		return false;
32824a705fefSNaoya Horiguchi 	swp = pte_to_swp_entry(pte);
32834a705fefSNaoya Horiguchi 	if (non_swap_entry(swp) && is_migration_entry(swp))
3284d5ed7444SAneesh Kumar K.V 		return true;
32854a705fefSNaoya Horiguchi 	else
3286d5ed7444SAneesh Kumar K.V 		return false;
32874a705fefSNaoya Horiguchi }
32884a705fefSNaoya Horiguchi 
32894a705fefSNaoya Horiguchi static int is_hugetlb_entry_hwpoisoned(pte_t pte)
32904a705fefSNaoya Horiguchi {
32914a705fefSNaoya Horiguchi 	swp_entry_t swp;
32924a705fefSNaoya Horiguchi 
32934a705fefSNaoya Horiguchi 	if (huge_pte_none(pte) || pte_present(pte))
32944a705fefSNaoya Horiguchi 		return 0;
32954a705fefSNaoya Horiguchi 	swp = pte_to_swp_entry(pte);
32964a705fefSNaoya Horiguchi 	if (non_swap_entry(swp) && is_hwpoison_entry(swp))
32974a705fefSNaoya Horiguchi 		return 1;
32984a705fefSNaoya Horiguchi 	else
32994a705fefSNaoya Horiguchi 		return 0;
33004a705fefSNaoya Horiguchi }
33011e8f889bSDavid Gibson 
330263551ae0SDavid Gibson int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src,
330363551ae0SDavid Gibson 			    struct vm_area_struct *vma)
330463551ae0SDavid Gibson {
33055e41540cSMike Kravetz 	pte_t *src_pte, *dst_pte, entry, dst_entry;
330663551ae0SDavid Gibson 	struct page *ptepage;
33071c59827dSHugh Dickins 	unsigned long addr;
33081e8f889bSDavid Gibson 	int cow;
3309a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
3310a5516438SAndi Kleen 	unsigned long sz = huge_page_size(h);
3311ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
3312e8569dd2SAndreas Sandberg 	int ret = 0;
33131e8f889bSDavid Gibson 
33141e8f889bSDavid Gibson 	cow = (vma->vm_flags & (VM_SHARED | VM_MAYWRITE)) == VM_MAYWRITE;
331563551ae0SDavid Gibson 
3316ac46d4f3SJérôme Glisse 	if (cow) {
33177269f999SJérôme Glisse 		mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, src,
33186f4f13e8SJérôme Glisse 					vma->vm_start,
3319ac46d4f3SJérôme Glisse 					vma->vm_end);
3320ac46d4f3SJérôme Glisse 		mmu_notifier_invalidate_range_start(&range);
3321ac46d4f3SJérôme Glisse 	}
3322e8569dd2SAndreas Sandberg 
3323a5516438SAndi Kleen 	for (addr = vma->vm_start; addr < vma->vm_end; addr += sz) {
3324cb900f41SKirill A. Shutemov 		spinlock_t *src_ptl, *dst_ptl;
33257868a208SPunit Agrawal 		src_pte = huge_pte_offset(src, addr, sz);
3326c74df32cSHugh Dickins 		if (!src_pte)
3327c74df32cSHugh Dickins 			continue;
3328a5516438SAndi Kleen 		dst_pte = huge_pte_alloc(dst, addr, sz);
3329e8569dd2SAndreas Sandberg 		if (!dst_pte) {
3330e8569dd2SAndreas Sandberg 			ret = -ENOMEM;
3331e8569dd2SAndreas Sandberg 			break;
3332e8569dd2SAndreas Sandberg 		}
3333c5c99429SLarry Woodman 
33345e41540cSMike Kravetz 		/*
33355e41540cSMike Kravetz 		 * If the pagetables are shared don't copy or take references.
33365e41540cSMike Kravetz 		 * dst_pte == src_pte is the common case of src/dest sharing.
33375e41540cSMike Kravetz 		 *
33385e41540cSMike Kravetz 		 * However, src could have 'unshared' and dst shares with
33395e41540cSMike Kravetz 		 * another vma.  If dst_pte !none, this implies sharing.
33405e41540cSMike Kravetz 		 * Check here before taking page table lock, and once again
33415e41540cSMike Kravetz 		 * after taking the lock below.
33425e41540cSMike Kravetz 		 */
33435e41540cSMike Kravetz 		dst_entry = huge_ptep_get(dst_pte);
33445e41540cSMike Kravetz 		if ((dst_pte == src_pte) || !huge_pte_none(dst_entry))
3345c5c99429SLarry Woodman 			continue;
3346c5c99429SLarry Woodman 
3347cb900f41SKirill A. Shutemov 		dst_ptl = huge_pte_lock(h, dst, dst_pte);
3348cb900f41SKirill A. Shutemov 		src_ptl = huge_pte_lockptr(h, src, src_pte);
3349cb900f41SKirill A. Shutemov 		spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
33504a705fefSNaoya Horiguchi 		entry = huge_ptep_get(src_pte);
33515e41540cSMike Kravetz 		dst_entry = huge_ptep_get(dst_pte);
33525e41540cSMike Kravetz 		if (huge_pte_none(entry) || !huge_pte_none(dst_entry)) {
33535e41540cSMike Kravetz 			/*
33545e41540cSMike Kravetz 			 * Skip if src entry none.  Also, skip in the
33555e41540cSMike Kravetz 			 * unlikely case dst entry !none as this implies
33565e41540cSMike Kravetz 			 * sharing with another vma.
33575e41540cSMike Kravetz 			 */
33584a705fefSNaoya Horiguchi 			;
33594a705fefSNaoya Horiguchi 		} else if (unlikely(is_hugetlb_entry_migration(entry) ||
33604a705fefSNaoya Horiguchi 				    is_hugetlb_entry_hwpoisoned(entry))) {
33614a705fefSNaoya Horiguchi 			swp_entry_t swp_entry = pte_to_swp_entry(entry);
33624a705fefSNaoya Horiguchi 
33634a705fefSNaoya Horiguchi 			if (is_write_migration_entry(swp_entry) && cow) {
33644a705fefSNaoya Horiguchi 				/*
33654a705fefSNaoya Horiguchi 				 * COW mappings require pages in both
33664a705fefSNaoya Horiguchi 				 * parent and child to be set to read.
33674a705fefSNaoya Horiguchi 				 */
33684a705fefSNaoya Horiguchi 				make_migration_entry_read(&swp_entry);
33694a705fefSNaoya Horiguchi 				entry = swp_entry_to_pte(swp_entry);
3370e5251fd4SPunit Agrawal 				set_huge_swap_pte_at(src, addr, src_pte,
3371e5251fd4SPunit Agrawal 						     entry, sz);
33724a705fefSNaoya Horiguchi 			}
3373e5251fd4SPunit Agrawal 			set_huge_swap_pte_at(dst, addr, dst_pte, entry, sz);
33744a705fefSNaoya Horiguchi 		} else {
337534ee645eSJoerg Roedel 			if (cow) {
33760f10851eSJérôme Glisse 				/*
33770f10851eSJérôme Glisse 				 * No need to notify as we are downgrading page
33780f10851eSJérôme Glisse 				 * table protection not changing it to point
33790f10851eSJérôme Glisse 				 * to a new page.
33800f10851eSJérôme Glisse 				 *
3381ad56b738SMike Rapoport 				 * See Documentation/vm/mmu_notifier.rst
33820f10851eSJérôme Glisse 				 */
33837f2e9525SGerald Schaefer 				huge_ptep_set_wrprotect(src, addr, src_pte);
338434ee645eSJoerg Roedel 			}
33850253d634SNaoya Horiguchi 			entry = huge_ptep_get(src_pte);
338663551ae0SDavid Gibson 			ptepage = pte_page(entry);
338763551ae0SDavid Gibson 			get_page(ptepage);
338853f9263bSKirill A. Shutemov 			page_dup_rmap(ptepage, true);
338963551ae0SDavid Gibson 			set_huge_pte_at(dst, addr, dst_pte, entry);
33905d317b2bSNaoya Horiguchi 			hugetlb_count_add(pages_per_huge_page(h), dst);
33911c59827dSHugh Dickins 		}
3392cb900f41SKirill A. Shutemov 		spin_unlock(src_ptl);
3393cb900f41SKirill A. Shutemov 		spin_unlock(dst_ptl);
339463551ae0SDavid Gibson 	}
339563551ae0SDavid Gibson 
3396e8569dd2SAndreas Sandberg 	if (cow)
3397ac46d4f3SJérôme Glisse 		mmu_notifier_invalidate_range_end(&range);
3398e8569dd2SAndreas Sandberg 
3399e8569dd2SAndreas Sandberg 	return ret;
340063551ae0SDavid Gibson }
340163551ae0SDavid Gibson 
340224669e58SAneesh Kumar K.V void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
340324669e58SAneesh Kumar K.V 			    unsigned long start, unsigned long end,
340424669e58SAneesh Kumar K.V 			    struct page *ref_page)
340563551ae0SDavid Gibson {
340663551ae0SDavid Gibson 	struct mm_struct *mm = vma->vm_mm;
340763551ae0SDavid Gibson 	unsigned long address;
3408c7546f8fSDavid Gibson 	pte_t *ptep;
340963551ae0SDavid Gibson 	pte_t pte;
3410cb900f41SKirill A. Shutemov 	spinlock_t *ptl;
341163551ae0SDavid Gibson 	struct page *page;
3412a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
3413a5516438SAndi Kleen 	unsigned long sz = huge_page_size(h);
3414ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
3415a5516438SAndi Kleen 
341663551ae0SDavid Gibson 	WARN_ON(!is_vm_hugetlb_page(vma));
3417a5516438SAndi Kleen 	BUG_ON(start & ~huge_page_mask(h));
3418a5516438SAndi Kleen 	BUG_ON(end & ~huge_page_mask(h));
341963551ae0SDavid Gibson 
342007e32661SAneesh Kumar K.V 	/*
342107e32661SAneesh Kumar K.V 	 * This is a hugetlb vma, all the pte entries should point
342207e32661SAneesh Kumar K.V 	 * to huge page.
342307e32661SAneesh Kumar K.V 	 */
3424ed6a7935SPeter Zijlstra 	tlb_change_page_size(tlb, sz);
342524669e58SAneesh Kumar K.V 	tlb_start_vma(tlb, vma);
3426dff11abeSMike Kravetz 
3427dff11abeSMike Kravetz 	/*
3428dff11abeSMike Kravetz 	 * If sharing possible, alert mmu notifiers of worst case.
3429dff11abeSMike Kravetz 	 */
34306f4f13e8SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, mm, start,
34316f4f13e8SJérôme Glisse 				end);
3432ac46d4f3SJérôme Glisse 	adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
3433ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
3434569f48b8SHillf Danton 	address = start;
3435569f48b8SHillf Danton 	for (; address < end; address += sz) {
34367868a208SPunit Agrawal 		ptep = huge_pte_offset(mm, address, sz);
3437c7546f8fSDavid Gibson 		if (!ptep)
3438c7546f8fSDavid Gibson 			continue;
3439c7546f8fSDavid Gibson 
3440cb900f41SKirill A. Shutemov 		ptl = huge_pte_lock(h, mm, ptep);
344131d49da5SAneesh Kumar K.V 		if (huge_pmd_unshare(mm, &address, ptep)) {
344231d49da5SAneesh Kumar K.V 			spin_unlock(ptl);
3443dff11abeSMike Kravetz 			/*
3444dff11abeSMike Kravetz 			 * We just unmapped a page of PMDs by clearing a PUD.
3445dff11abeSMike Kravetz 			 * The caller's TLB flush range should cover this area.
3446dff11abeSMike Kravetz 			 */
344731d49da5SAneesh Kumar K.V 			continue;
344831d49da5SAneesh Kumar K.V 		}
344939dde65cSChen, Kenneth W 
34506629326bSHillf Danton 		pte = huge_ptep_get(ptep);
345131d49da5SAneesh Kumar K.V 		if (huge_pte_none(pte)) {
345231d49da5SAneesh Kumar K.V 			spin_unlock(ptl);
345331d49da5SAneesh Kumar K.V 			continue;
345431d49da5SAneesh Kumar K.V 		}
34556629326bSHillf Danton 
34566629326bSHillf Danton 		/*
34579fbc1f63SNaoya Horiguchi 		 * Migrating hugepage or HWPoisoned hugepage is already
34589fbc1f63SNaoya Horiguchi 		 * unmapped and its refcount is dropped, so just clear pte here.
34596629326bSHillf Danton 		 */
34609fbc1f63SNaoya Horiguchi 		if (unlikely(!pte_present(pte))) {
34619386fac3SPunit Agrawal 			huge_pte_clear(mm, address, ptep, sz);
346231d49da5SAneesh Kumar K.V 			spin_unlock(ptl);
346331d49da5SAneesh Kumar K.V 			continue;
34648c4894c6SNaoya Horiguchi 		}
34656629326bSHillf Danton 
34666629326bSHillf Danton 		page = pte_page(pte);
346704f2cbe3SMel Gorman 		/*
346804f2cbe3SMel Gorman 		 * If a reference page is supplied, it is because a specific
346904f2cbe3SMel Gorman 		 * page is being unmapped, not a range. Ensure the page we
347004f2cbe3SMel Gorman 		 * are about to unmap is the actual page of interest.
347104f2cbe3SMel Gorman 		 */
347204f2cbe3SMel Gorman 		if (ref_page) {
347331d49da5SAneesh Kumar K.V 			if (page != ref_page) {
347431d49da5SAneesh Kumar K.V 				spin_unlock(ptl);
347531d49da5SAneesh Kumar K.V 				continue;
347631d49da5SAneesh Kumar K.V 			}
347704f2cbe3SMel Gorman 			/*
347804f2cbe3SMel Gorman 			 * Mark the VMA as having unmapped its page so that
347904f2cbe3SMel Gorman 			 * future faults in this VMA will fail rather than
348004f2cbe3SMel Gorman 			 * looking like data was lost
348104f2cbe3SMel Gorman 			 */
348204f2cbe3SMel Gorman 			set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED);
348304f2cbe3SMel Gorman 		}
348404f2cbe3SMel Gorman 
3485c7546f8fSDavid Gibson 		pte = huge_ptep_get_and_clear(mm, address, ptep);
3486b528e4b6SAneesh Kumar K.V 		tlb_remove_huge_tlb_entry(h, tlb, ptep, address);
3487106c992aSGerald Schaefer 		if (huge_pte_dirty(pte))
34886649a386SKen Chen 			set_page_dirty(page);
34899e81130bSHillf Danton 
34905d317b2bSNaoya Horiguchi 		hugetlb_count_sub(pages_per_huge_page(h), mm);
3491d281ee61SKirill A. Shutemov 		page_remove_rmap(page, true);
349231d49da5SAneesh Kumar K.V 
3493cb900f41SKirill A. Shutemov 		spin_unlock(ptl);
3494e77b0852SAneesh Kumar K.V 		tlb_remove_page_size(tlb, page, huge_page_size(h));
349524669e58SAneesh Kumar K.V 		/*
349631d49da5SAneesh Kumar K.V 		 * Bail out after unmapping reference page if supplied
349724669e58SAneesh Kumar K.V 		 */
349831d49da5SAneesh Kumar K.V 		if (ref_page)
349931d49da5SAneesh Kumar K.V 			break;
3500fe1668aeSChen, Kenneth W 	}
3501ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
350224669e58SAneesh Kumar K.V 	tlb_end_vma(tlb, vma);
35031da177e4SLinus Torvalds }
350463551ae0SDavid Gibson 
3505d833352aSMel Gorman void __unmap_hugepage_range_final(struct mmu_gather *tlb,
3506d833352aSMel Gorman 			  struct vm_area_struct *vma, unsigned long start,
3507d833352aSMel Gorman 			  unsigned long end, struct page *ref_page)
3508d833352aSMel Gorman {
3509d833352aSMel Gorman 	__unmap_hugepage_range(tlb, vma, start, end, ref_page);
3510d833352aSMel Gorman 
3511d833352aSMel Gorman 	/*
3512d833352aSMel Gorman 	 * Clear this flag so that x86's huge_pmd_share page_table_shareable
3513d833352aSMel Gorman 	 * test will fail on a vma being torn down, and not grab a page table
3514d833352aSMel Gorman 	 * on its way out.  We're lucky that the flag has such an appropriate
3515d833352aSMel Gorman 	 * name, and can in fact be safely cleared here. We could clear it
3516d833352aSMel Gorman 	 * before the __unmap_hugepage_range above, but all that's necessary
3517c8c06efaSDavidlohr Bueso 	 * is to clear it before releasing the i_mmap_rwsem. This works
3518d833352aSMel Gorman 	 * because in the context this is called, the VMA is about to be
3519c8c06efaSDavidlohr Bueso 	 * destroyed and the i_mmap_rwsem is held.
3520d833352aSMel Gorman 	 */
3521d833352aSMel Gorman 	vma->vm_flags &= ~VM_MAYSHARE;
3522d833352aSMel Gorman }
3523d833352aSMel Gorman 
3524502717f4SChen, Kenneth W void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
352504f2cbe3SMel Gorman 			  unsigned long end, struct page *ref_page)
3526502717f4SChen, Kenneth W {
352724669e58SAneesh Kumar K.V 	struct mm_struct *mm;
352824669e58SAneesh Kumar K.V 	struct mmu_gather tlb;
3529dff11abeSMike Kravetz 	unsigned long tlb_start = start;
3530dff11abeSMike Kravetz 	unsigned long tlb_end = end;
3531dff11abeSMike Kravetz 
3532dff11abeSMike Kravetz 	/*
3533dff11abeSMike Kravetz 	 * If shared PMDs were possibly used within this vma range, adjust
3534dff11abeSMike Kravetz 	 * start/end for worst case tlb flushing.
3535dff11abeSMike Kravetz 	 * Note that we can not be sure if PMDs are shared until we try to
3536dff11abeSMike Kravetz 	 * unmap pages.  However, we want to make sure TLB flushing covers
3537dff11abeSMike Kravetz 	 * the largest possible range.
3538dff11abeSMike Kravetz 	 */
3539dff11abeSMike Kravetz 	adjust_range_if_pmd_sharing_possible(vma, &tlb_start, &tlb_end);
354024669e58SAneesh Kumar K.V 
354124669e58SAneesh Kumar K.V 	mm = vma->vm_mm;
354224669e58SAneesh Kumar K.V 
3543dff11abeSMike Kravetz 	tlb_gather_mmu(&tlb, mm, tlb_start, tlb_end);
354424669e58SAneesh Kumar K.V 	__unmap_hugepage_range(&tlb, vma, start, end, ref_page);
3545dff11abeSMike Kravetz 	tlb_finish_mmu(&tlb, tlb_start, tlb_end);
3546502717f4SChen, Kenneth W }
3547502717f4SChen, Kenneth W 
354804f2cbe3SMel Gorman /*
354904f2cbe3SMel Gorman  * This is called when the original mapper is failing to COW a MAP_PRIVATE
355004f2cbe3SMel Gorman  * mappping it owns the reserve page for. The intention is to unmap the page
355104f2cbe3SMel Gorman  * from other VMAs and let the children be SIGKILLed if they are faulting the
355204f2cbe3SMel Gorman  * same region.
355304f2cbe3SMel Gorman  */
35542f4612afSDavidlohr Bueso static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,
35552a4b3dedSHarvey Harrison 			      struct page *page, unsigned long address)
355604f2cbe3SMel Gorman {
35577526674dSAdam Litke 	struct hstate *h = hstate_vma(vma);
355804f2cbe3SMel Gorman 	struct vm_area_struct *iter_vma;
355904f2cbe3SMel Gorman 	struct address_space *mapping;
356004f2cbe3SMel Gorman 	pgoff_t pgoff;
356104f2cbe3SMel Gorman 
356204f2cbe3SMel Gorman 	/*
356304f2cbe3SMel Gorman 	 * vm_pgoff is in PAGE_SIZE units, hence the different calculation
356404f2cbe3SMel Gorman 	 * from page cache lookup which is in HPAGE_SIZE units.
356504f2cbe3SMel Gorman 	 */
35667526674dSAdam Litke 	address = address & huge_page_mask(h);
356736e4f20aSMichal Hocko 	pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) +
356836e4f20aSMichal Hocko 			vma->vm_pgoff;
356993c76a3dSAl Viro 	mapping = vma->vm_file->f_mapping;
357004f2cbe3SMel Gorman 
35714eb2b1dcSMel Gorman 	/*
35724eb2b1dcSMel Gorman 	 * Take the mapping lock for the duration of the table walk. As
35734eb2b1dcSMel Gorman 	 * this mapping should be shared between all the VMAs,
35744eb2b1dcSMel Gorman 	 * __unmap_hugepage_range() is called as the lock is already held
35754eb2b1dcSMel Gorman 	 */
357683cde9e8SDavidlohr Bueso 	i_mmap_lock_write(mapping);
35776b2dbba8SMichel Lespinasse 	vma_interval_tree_foreach(iter_vma, &mapping->i_mmap, pgoff, pgoff) {
357804f2cbe3SMel Gorman 		/* Do not unmap the current VMA */
357904f2cbe3SMel Gorman 		if (iter_vma == vma)
358004f2cbe3SMel Gorman 			continue;
358104f2cbe3SMel Gorman 
358204f2cbe3SMel Gorman 		/*
35832f84a899SMel Gorman 		 * Shared VMAs have their own reserves and do not affect
35842f84a899SMel Gorman 		 * MAP_PRIVATE accounting but it is possible that a shared
35852f84a899SMel Gorman 		 * VMA is using the same page so check and skip such VMAs.
35862f84a899SMel Gorman 		 */
35872f84a899SMel Gorman 		if (iter_vma->vm_flags & VM_MAYSHARE)
35882f84a899SMel Gorman 			continue;
35892f84a899SMel Gorman 
35902f84a899SMel Gorman 		/*
359104f2cbe3SMel Gorman 		 * Unmap the page from other VMAs without their own reserves.
359204f2cbe3SMel Gorman 		 * They get marked to be SIGKILLed if they fault in these
359304f2cbe3SMel Gorman 		 * areas. This is because a future no-page fault on this VMA
359404f2cbe3SMel Gorman 		 * could insert a zeroed page instead of the data existing
359504f2cbe3SMel Gorman 		 * from the time of fork. This would look like data corruption
359604f2cbe3SMel Gorman 		 */
359704f2cbe3SMel Gorman 		if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER))
359824669e58SAneesh Kumar K.V 			unmap_hugepage_range(iter_vma, address,
359924669e58SAneesh Kumar K.V 					     address + huge_page_size(h), page);
360004f2cbe3SMel Gorman 	}
360183cde9e8SDavidlohr Bueso 	i_mmap_unlock_write(mapping);
360204f2cbe3SMel Gorman }
360304f2cbe3SMel Gorman 
36040fe6e20bSNaoya Horiguchi /*
36050fe6e20bSNaoya Horiguchi  * Hugetlb_cow() should be called with page lock of the original hugepage held.
3606ef009b25SMichal Hocko  * Called with hugetlb_instantiation_mutex held and pte_page locked so we
3607ef009b25SMichal Hocko  * cannot race with other handlers or page migration.
3608ef009b25SMichal Hocko  * Keep the pte_same checks anyway to make transition from the mutex easier.
36090fe6e20bSNaoya Horiguchi  */
36102b740303SSouptick Joarder static vm_fault_t hugetlb_cow(struct mm_struct *mm, struct vm_area_struct *vma,
3611974e6d66SHuang Ying 		       unsigned long address, pte_t *ptep,
3612cb900f41SKirill A. Shutemov 		       struct page *pagecache_page, spinlock_t *ptl)
36131e8f889bSDavid Gibson {
36143999f52eSAneesh Kumar K.V 	pte_t pte;
3615a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
36161e8f889bSDavid Gibson 	struct page *old_page, *new_page;
36172b740303SSouptick Joarder 	int outside_reserve = 0;
36182b740303SSouptick Joarder 	vm_fault_t ret = 0;
3619974e6d66SHuang Ying 	unsigned long haddr = address & huge_page_mask(h);
3620ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
36211e8f889bSDavid Gibson 
36223999f52eSAneesh Kumar K.V 	pte = huge_ptep_get(ptep);
36231e8f889bSDavid Gibson 	old_page = pte_page(pte);
36241e8f889bSDavid Gibson 
362504f2cbe3SMel Gorman retry_avoidcopy:
36261e8f889bSDavid Gibson 	/* If no-one else is actually using this page, avoid the copy
36271e8f889bSDavid Gibson 	 * and just make the page writable */
362837a2140dSJoonsoo Kim 	if (page_mapcount(old_page) == 1 && PageAnon(old_page)) {
36295a49973dSHugh Dickins 		page_move_anon_rmap(old_page, vma);
36305b7a1d40SHuang Ying 		set_huge_ptep_writable(vma, haddr, ptep);
363183c54070SNick Piggin 		return 0;
36321e8f889bSDavid Gibson 	}
36331e8f889bSDavid Gibson 
363404f2cbe3SMel Gorman 	/*
363504f2cbe3SMel Gorman 	 * If the process that created a MAP_PRIVATE mapping is about to
363604f2cbe3SMel Gorman 	 * perform a COW due to a shared page count, attempt to satisfy
363704f2cbe3SMel Gorman 	 * the allocation without using the existing reserves. The pagecache
363804f2cbe3SMel Gorman 	 * page is used to determine if the reserve at this address was
363904f2cbe3SMel Gorman 	 * consumed or not. If reserves were used, a partial faulted mapping
364004f2cbe3SMel Gorman 	 * at the time of fork() could consume its reserves on COW instead
364104f2cbe3SMel Gorman 	 * of the full address range.
364204f2cbe3SMel Gorman 	 */
36435944d011SJoonsoo Kim 	if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) &&
364404f2cbe3SMel Gorman 			old_page != pagecache_page)
364504f2cbe3SMel Gorman 		outside_reserve = 1;
364604f2cbe3SMel Gorman 
364709cbfeafSKirill A. Shutemov 	get_page(old_page);
3648b76c8cfbSLarry Woodman 
3649ad4404a2SDavidlohr Bueso 	/*
3650ad4404a2SDavidlohr Bueso 	 * Drop page table lock as buddy allocator may be called. It will
3651ad4404a2SDavidlohr Bueso 	 * be acquired again before returning to the caller, as expected.
3652ad4404a2SDavidlohr Bueso 	 */
3653cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
36545b7a1d40SHuang Ying 	new_page = alloc_huge_page(vma, haddr, outside_reserve);
36551e8f889bSDavid Gibson 
36562fc39cecSAdam Litke 	if (IS_ERR(new_page)) {
365704f2cbe3SMel Gorman 		/*
365804f2cbe3SMel Gorman 		 * If a process owning a MAP_PRIVATE mapping fails to COW,
365904f2cbe3SMel Gorman 		 * it is due to references held by a child and an insufficient
366004f2cbe3SMel Gorman 		 * huge page pool. To guarantee the original mappers
366104f2cbe3SMel Gorman 		 * reliability, unmap the page from child processes. The child
366204f2cbe3SMel Gorman 		 * may get SIGKILLed if it later faults.
366304f2cbe3SMel Gorman 		 */
366404f2cbe3SMel Gorman 		if (outside_reserve) {
366509cbfeafSKirill A. Shutemov 			put_page(old_page);
366604f2cbe3SMel Gorman 			BUG_ON(huge_pte_none(pte));
36675b7a1d40SHuang Ying 			unmap_ref_private(mm, vma, old_page, haddr);
366804f2cbe3SMel Gorman 			BUG_ON(huge_pte_none(pte));
3669cb900f41SKirill A. Shutemov 			spin_lock(ptl);
36705b7a1d40SHuang Ying 			ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
3671a9af0c5dSNaoya Horiguchi 			if (likely(ptep &&
3672a9af0c5dSNaoya Horiguchi 				   pte_same(huge_ptep_get(ptep), pte)))
367304f2cbe3SMel Gorman 				goto retry_avoidcopy;
3674a734bcc8SHillf Danton 			/*
3675cb900f41SKirill A. Shutemov 			 * race occurs while re-acquiring page table
3676cb900f41SKirill A. Shutemov 			 * lock, and our job is done.
3677a734bcc8SHillf Danton 			 */
3678a734bcc8SHillf Danton 			return 0;
367904f2cbe3SMel Gorman 		}
368004f2cbe3SMel Gorman 
36812b740303SSouptick Joarder 		ret = vmf_error(PTR_ERR(new_page));
3682ad4404a2SDavidlohr Bueso 		goto out_release_old;
36831e8f889bSDavid Gibson 	}
36841e8f889bSDavid Gibson 
36850fe6e20bSNaoya Horiguchi 	/*
36860fe6e20bSNaoya Horiguchi 	 * When the original hugepage is shared one, it does not have
36870fe6e20bSNaoya Horiguchi 	 * anon_vma prepared.
36880fe6e20bSNaoya Horiguchi 	 */
368944e2aa93SDean Nelson 	if (unlikely(anon_vma_prepare(vma))) {
3690ad4404a2SDavidlohr Bueso 		ret = VM_FAULT_OOM;
3691ad4404a2SDavidlohr Bueso 		goto out_release_all;
369244e2aa93SDean Nelson 	}
36930fe6e20bSNaoya Horiguchi 
3694974e6d66SHuang Ying 	copy_user_huge_page(new_page, old_page, address, vma,
369547ad8475SAndrea Arcangeli 			    pages_per_huge_page(h));
36960ed361deSNick Piggin 	__SetPageUptodate(new_page);
36971e8f889bSDavid Gibson 
36987269f999SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm, haddr,
36996f4f13e8SJérôme Glisse 				haddr + huge_page_size(h));
3700ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
3701ad4404a2SDavidlohr Bueso 
3702b76c8cfbSLarry Woodman 	/*
3703cb900f41SKirill A. Shutemov 	 * Retake the page table lock to check for racing updates
3704b76c8cfbSLarry Woodman 	 * before the page tables are altered
3705b76c8cfbSLarry Woodman 	 */
3706cb900f41SKirill A. Shutemov 	spin_lock(ptl);
37075b7a1d40SHuang Ying 	ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
3708a9af0c5dSNaoya Horiguchi 	if (likely(ptep && pte_same(huge_ptep_get(ptep), pte))) {
370907443a85SJoonsoo Kim 		ClearPagePrivate(new_page);
371007443a85SJoonsoo Kim 
37111e8f889bSDavid Gibson 		/* Break COW */
37125b7a1d40SHuang Ying 		huge_ptep_clear_flush(vma, haddr, ptep);
3713ac46d4f3SJérôme Glisse 		mmu_notifier_invalidate_range(mm, range.start, range.end);
37145b7a1d40SHuang Ying 		set_huge_pte_at(mm, haddr, ptep,
37151e8f889bSDavid Gibson 				make_huge_pte(vma, new_page, 1));
3716d281ee61SKirill A. Shutemov 		page_remove_rmap(old_page, true);
37175b7a1d40SHuang Ying 		hugepage_add_new_anon_rmap(new_page, vma, haddr);
3718cb6acd01SMike Kravetz 		set_page_huge_active(new_page);
37191e8f889bSDavid Gibson 		/* Make the old page be freed below */
37201e8f889bSDavid Gibson 		new_page = old_page;
37211e8f889bSDavid Gibson 	}
3722cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
3723ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
3724ad4404a2SDavidlohr Bueso out_release_all:
37255b7a1d40SHuang Ying 	restore_reserve_on_error(h, vma, haddr, new_page);
372609cbfeafSKirill A. Shutemov 	put_page(new_page);
3727ad4404a2SDavidlohr Bueso out_release_old:
372809cbfeafSKirill A. Shutemov 	put_page(old_page);
37298312034fSJoonsoo Kim 
3730ad4404a2SDavidlohr Bueso 	spin_lock(ptl); /* Caller expects lock to be held */
3731ad4404a2SDavidlohr Bueso 	return ret;
37321e8f889bSDavid Gibson }
37331e8f889bSDavid Gibson 
373404f2cbe3SMel Gorman /* Return the pagecache page at a given address within a VMA */
3735a5516438SAndi Kleen static struct page *hugetlbfs_pagecache_page(struct hstate *h,
3736a5516438SAndi Kleen 			struct vm_area_struct *vma, unsigned long address)
373704f2cbe3SMel Gorman {
373804f2cbe3SMel Gorman 	struct address_space *mapping;
3739e7c4b0bfSAndy Whitcroft 	pgoff_t idx;
374004f2cbe3SMel Gorman 
374104f2cbe3SMel Gorman 	mapping = vma->vm_file->f_mapping;
3742a5516438SAndi Kleen 	idx = vma_hugecache_offset(h, vma, address);
374304f2cbe3SMel Gorman 
374404f2cbe3SMel Gorman 	return find_lock_page(mapping, idx);
374504f2cbe3SMel Gorman }
374604f2cbe3SMel Gorman 
37473ae77f43SHugh Dickins /*
37483ae77f43SHugh Dickins  * Return whether there is a pagecache page to back given address within VMA.
37493ae77f43SHugh Dickins  * Caller follow_hugetlb_page() holds page_table_lock so we cannot lock_page.
37503ae77f43SHugh Dickins  */
37513ae77f43SHugh Dickins static bool hugetlbfs_pagecache_present(struct hstate *h,
37522a15efc9SHugh Dickins 			struct vm_area_struct *vma, unsigned long address)
37532a15efc9SHugh Dickins {
37542a15efc9SHugh Dickins 	struct address_space *mapping;
37552a15efc9SHugh Dickins 	pgoff_t idx;
37562a15efc9SHugh Dickins 	struct page *page;
37572a15efc9SHugh Dickins 
37582a15efc9SHugh Dickins 	mapping = vma->vm_file->f_mapping;
37592a15efc9SHugh Dickins 	idx = vma_hugecache_offset(h, vma, address);
37602a15efc9SHugh Dickins 
37612a15efc9SHugh Dickins 	page = find_get_page(mapping, idx);
37622a15efc9SHugh Dickins 	if (page)
37632a15efc9SHugh Dickins 		put_page(page);
37642a15efc9SHugh Dickins 	return page != NULL;
37652a15efc9SHugh Dickins }
37662a15efc9SHugh Dickins 
3767ab76ad54SMike Kravetz int huge_add_to_page_cache(struct page *page, struct address_space *mapping,
3768ab76ad54SMike Kravetz 			   pgoff_t idx)
3769ab76ad54SMike Kravetz {
3770ab76ad54SMike Kravetz 	struct inode *inode = mapping->host;
3771ab76ad54SMike Kravetz 	struct hstate *h = hstate_inode(inode);
3772ab76ad54SMike Kravetz 	int err = add_to_page_cache(page, mapping, idx, GFP_KERNEL);
3773ab76ad54SMike Kravetz 
3774ab76ad54SMike Kravetz 	if (err)
3775ab76ad54SMike Kravetz 		return err;
3776ab76ad54SMike Kravetz 	ClearPagePrivate(page);
3777ab76ad54SMike Kravetz 
377822146c3cSMike Kravetz 	/*
377922146c3cSMike Kravetz 	 * set page dirty so that it will not be removed from cache/file
378022146c3cSMike Kravetz 	 * by non-hugetlbfs specific code paths.
378122146c3cSMike Kravetz 	 */
378222146c3cSMike Kravetz 	set_page_dirty(page);
378322146c3cSMike Kravetz 
3784ab76ad54SMike Kravetz 	spin_lock(&inode->i_lock);
3785ab76ad54SMike Kravetz 	inode->i_blocks += blocks_per_huge_page(h);
3786ab76ad54SMike Kravetz 	spin_unlock(&inode->i_lock);
3787ab76ad54SMike Kravetz 	return 0;
3788ab76ad54SMike Kravetz }
3789ab76ad54SMike Kravetz 
37902b740303SSouptick Joarder static vm_fault_t hugetlb_no_page(struct mm_struct *mm,
37912b740303SSouptick Joarder 			struct vm_area_struct *vma,
37928382d914SDavidlohr Bueso 			struct address_space *mapping, pgoff_t idx,
3793788c7df4SHugh Dickins 			unsigned long address, pte_t *ptep, unsigned int flags)
3794ac9b9c66SHugh Dickins {
3795a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
37962b740303SSouptick Joarder 	vm_fault_t ret = VM_FAULT_SIGBUS;
3797409eb8c2SHillf Danton 	int anon_rmap = 0;
37984c887265SAdam Litke 	unsigned long size;
37994c887265SAdam Litke 	struct page *page;
38001e8f889bSDavid Gibson 	pte_t new_pte;
3801cb900f41SKirill A. Shutemov 	spinlock_t *ptl;
3802285b8dcaSHuang Ying 	unsigned long haddr = address & huge_page_mask(h);
3803cb6acd01SMike Kravetz 	bool new_page = false;
38044c887265SAdam Litke 
380504f2cbe3SMel Gorman 	/*
380604f2cbe3SMel Gorman 	 * Currently, we are forced to kill the process in the event the
380704f2cbe3SMel Gorman 	 * original mapper has unmapped pages from the child due to a failed
380825985edcSLucas De Marchi 	 * COW. Warn that such a situation has occurred as it may not be obvious
380904f2cbe3SMel Gorman 	 */
381004f2cbe3SMel Gorman 	if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) {
3811910154d5SGeoffrey Thomas 		pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n",
381204f2cbe3SMel Gorman 			   current->pid);
381304f2cbe3SMel Gorman 		return ret;
381404f2cbe3SMel Gorman 	}
381504f2cbe3SMel Gorman 
38164c887265SAdam Litke 	/*
3817e7c58097SMike Kravetz 	 * Use page lock to guard against racing truncation
3818e7c58097SMike Kravetz 	 * before we get page_table_lock.
38194c887265SAdam Litke 	 */
3820e7c58097SMike Kravetz retry:
3821e7c58097SMike Kravetz 	page = find_lock_page(mapping, idx);
3822e7c58097SMike Kravetz 	if (!page) {
3823a5516438SAndi Kleen 		size = i_size_read(mapping->host) >> huge_page_shift(h);
3824ebed4bfcSHugh Dickins 		if (idx >= size)
3825ebed4bfcSHugh Dickins 			goto out;
38261a1aad8aSMike Kravetz 
38271a1aad8aSMike Kravetz 		/*
38281a1aad8aSMike Kravetz 		 * Check for page in userfault range
38291a1aad8aSMike Kravetz 		 */
38301a1aad8aSMike Kravetz 		if (userfaultfd_missing(vma)) {
38311a1aad8aSMike Kravetz 			u32 hash;
38321a1aad8aSMike Kravetz 			struct vm_fault vmf = {
38331a1aad8aSMike Kravetz 				.vma = vma,
3834285b8dcaSHuang Ying 				.address = haddr,
38351a1aad8aSMike Kravetz 				.flags = flags,
38361a1aad8aSMike Kravetz 				/*
38371a1aad8aSMike Kravetz 				 * Hard to debug if it ends up being
38381a1aad8aSMike Kravetz 				 * used by a callee that assumes
38391a1aad8aSMike Kravetz 				 * something about the other
38401a1aad8aSMike Kravetz 				 * uninitialized fields... same as in
38411a1aad8aSMike Kravetz 				 * memory.c
38421a1aad8aSMike Kravetz 				 */
38431a1aad8aSMike Kravetz 			};
38441a1aad8aSMike Kravetz 
38451a1aad8aSMike Kravetz 			/*
3846ddeaab32SMike Kravetz 			 * hugetlb_fault_mutex must be dropped before
3847ddeaab32SMike Kravetz 			 * handling userfault.  Reacquire after handling
3848ddeaab32SMike Kravetz 			 * fault to make calling code simpler.
38491a1aad8aSMike Kravetz 			 */
38501b426bacSMike Kravetz 			hash = hugetlb_fault_mutex_hash(h, mapping, idx, haddr);
38511a1aad8aSMike Kravetz 			mutex_unlock(&hugetlb_fault_mutex_table[hash]);
38521a1aad8aSMike Kravetz 			ret = handle_userfault(&vmf, VM_UFFD_MISSING);
38531a1aad8aSMike Kravetz 			mutex_lock(&hugetlb_fault_mutex_table[hash]);
38541a1aad8aSMike Kravetz 			goto out;
38551a1aad8aSMike Kravetz 		}
38561a1aad8aSMike Kravetz 
3857285b8dcaSHuang Ying 		page = alloc_huge_page(vma, haddr, 0);
38582fc39cecSAdam Litke 		if (IS_ERR(page)) {
38592b740303SSouptick Joarder 			ret = vmf_error(PTR_ERR(page));
38606bda666aSChristoph Lameter 			goto out;
38616bda666aSChristoph Lameter 		}
386247ad8475SAndrea Arcangeli 		clear_huge_page(page, address, pages_per_huge_page(h));
38630ed361deSNick Piggin 		__SetPageUptodate(page);
3864cb6acd01SMike Kravetz 		new_page = true;
3865ac9b9c66SHugh Dickins 
3866f83a275dSMel Gorman 		if (vma->vm_flags & VM_MAYSHARE) {
3867ab76ad54SMike Kravetz 			int err = huge_add_to_page_cache(page, mapping, idx);
38686bda666aSChristoph Lameter 			if (err) {
38696bda666aSChristoph Lameter 				put_page(page);
38706bda666aSChristoph Lameter 				if (err == -EEXIST)
38716bda666aSChristoph Lameter 					goto retry;
38726bda666aSChristoph Lameter 				goto out;
38736bda666aSChristoph Lameter 			}
387423be7468SMel Gorman 		} else {
38756bda666aSChristoph Lameter 			lock_page(page);
38760fe6e20bSNaoya Horiguchi 			if (unlikely(anon_vma_prepare(vma))) {
38770fe6e20bSNaoya Horiguchi 				ret = VM_FAULT_OOM;
38780fe6e20bSNaoya Horiguchi 				goto backout_unlocked;
387923be7468SMel Gorman 			}
3880409eb8c2SHillf Danton 			anon_rmap = 1;
38810fe6e20bSNaoya Horiguchi 		}
38820fe6e20bSNaoya Horiguchi 	} else {
388357303d80SAndy Whitcroft 		/*
3884998b4382SNaoya Horiguchi 		 * If memory error occurs between mmap() and fault, some process
3885998b4382SNaoya Horiguchi 		 * don't have hwpoisoned swap entry for errored virtual address.
3886998b4382SNaoya Horiguchi 		 * So we need to block hugepage fault by PG_hwpoison bit check.
3887fd6a03edSNaoya Horiguchi 		 */
3888fd6a03edSNaoya Horiguchi 		if (unlikely(PageHWPoison(page))) {
3889aa50d3a7SAndi Kleen 			ret = VM_FAULT_HWPOISON |
3890972dc4deSAneesh Kumar K.V 				VM_FAULT_SET_HINDEX(hstate_index(h));
3891fd6a03edSNaoya Horiguchi 			goto backout_unlocked;
38926bda666aSChristoph Lameter 		}
3893998b4382SNaoya Horiguchi 	}
38941e8f889bSDavid Gibson 
389557303d80SAndy Whitcroft 	/*
389657303d80SAndy Whitcroft 	 * If we are going to COW a private mapping later, we examine the
389757303d80SAndy Whitcroft 	 * pending reservations for this page now. This will ensure that
389857303d80SAndy Whitcroft 	 * any allocations necessary to record that reservation occur outside
389957303d80SAndy Whitcroft 	 * the spinlock.
390057303d80SAndy Whitcroft 	 */
39015e911373SMike Kravetz 	if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
3902285b8dcaSHuang Ying 		if (vma_needs_reservation(h, vma, haddr) < 0) {
39032b26736cSAndy Whitcroft 			ret = VM_FAULT_OOM;
39042b26736cSAndy Whitcroft 			goto backout_unlocked;
39052b26736cSAndy Whitcroft 		}
39065e911373SMike Kravetz 		/* Just decrements count, does not deallocate */
3907285b8dcaSHuang Ying 		vma_end_reservation(h, vma, haddr);
39085e911373SMike Kravetz 	}
390957303d80SAndy Whitcroft 
39108bea8052SAneesh Kumar K.V 	ptl = huge_pte_lock(h, mm, ptep);
3911e7c58097SMike Kravetz 	size = i_size_read(mapping->host) >> huge_page_shift(h);
3912e7c58097SMike Kravetz 	if (idx >= size)
3913e7c58097SMike Kravetz 		goto backout;
39144c887265SAdam Litke 
391583c54070SNick Piggin 	ret = 0;
39167f2e9525SGerald Schaefer 	if (!huge_pte_none(huge_ptep_get(ptep)))
39174c887265SAdam Litke 		goto backout;
39184c887265SAdam Litke 
391907443a85SJoonsoo Kim 	if (anon_rmap) {
392007443a85SJoonsoo Kim 		ClearPagePrivate(page);
3921285b8dcaSHuang Ying 		hugepage_add_new_anon_rmap(page, vma, haddr);
3922ac714904SChoi Gi-yong 	} else
392353f9263bSKirill A. Shutemov 		page_dup_rmap(page, true);
39241e8f889bSDavid Gibson 	new_pte = make_huge_pte(vma, page, ((vma->vm_flags & VM_WRITE)
39251e8f889bSDavid Gibson 				&& (vma->vm_flags & VM_SHARED)));
3926285b8dcaSHuang Ying 	set_huge_pte_at(mm, haddr, ptep, new_pte);
39271e8f889bSDavid Gibson 
39285d317b2bSNaoya Horiguchi 	hugetlb_count_add(pages_per_huge_page(h), mm);
3929788c7df4SHugh Dickins 	if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
39301e8f889bSDavid Gibson 		/* Optimization, do the COW without a second fault */
3931974e6d66SHuang Ying 		ret = hugetlb_cow(mm, vma, address, ptep, page, ptl);
39321e8f889bSDavid Gibson 	}
39331e8f889bSDavid Gibson 
3934cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
3935cb6acd01SMike Kravetz 
3936cb6acd01SMike Kravetz 	/*
3937cb6acd01SMike Kravetz 	 * Only make newly allocated pages active.  Existing pages found
3938cb6acd01SMike Kravetz 	 * in the pagecache could be !page_huge_active() if they have been
3939cb6acd01SMike Kravetz 	 * isolated for migration.
3940cb6acd01SMike Kravetz 	 */
3941cb6acd01SMike Kravetz 	if (new_page)
3942cb6acd01SMike Kravetz 		set_page_huge_active(page);
3943cb6acd01SMike Kravetz 
39444c887265SAdam Litke 	unlock_page(page);
39454c887265SAdam Litke out:
3946ac9b9c66SHugh Dickins 	return ret;
39474c887265SAdam Litke 
39484c887265SAdam Litke backout:
3949cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
39502b26736cSAndy Whitcroft backout_unlocked:
39514c887265SAdam Litke 	unlock_page(page);
3952285b8dcaSHuang Ying 	restore_reserve_on_error(h, vma, haddr, page);
39534c887265SAdam Litke 	put_page(page);
39544c887265SAdam Litke 	goto out;
3955ac9b9c66SHugh Dickins }
3956ac9b9c66SHugh Dickins 
39578382d914SDavidlohr Bueso #ifdef CONFIG_SMP
39581b426bacSMike Kravetz u32 hugetlb_fault_mutex_hash(struct hstate *h, struct address_space *mapping,
39598382d914SDavidlohr Bueso 			    pgoff_t idx, unsigned long address)
39608382d914SDavidlohr Bueso {
39618382d914SDavidlohr Bueso 	unsigned long key[2];
39628382d914SDavidlohr Bueso 	u32 hash;
39638382d914SDavidlohr Bueso 
39648382d914SDavidlohr Bueso 	key[0] = (unsigned long) mapping;
39658382d914SDavidlohr Bueso 	key[1] = idx;
39668382d914SDavidlohr Bueso 
39678382d914SDavidlohr Bueso 	hash = jhash2((u32 *)&key, sizeof(key)/sizeof(u32), 0);
39688382d914SDavidlohr Bueso 
39698382d914SDavidlohr Bueso 	return hash & (num_fault_mutexes - 1);
39708382d914SDavidlohr Bueso }
39718382d914SDavidlohr Bueso #else
39728382d914SDavidlohr Bueso /*
39738382d914SDavidlohr Bueso  * For uniprocesor systems we always use a single mutex, so just
39748382d914SDavidlohr Bueso  * return 0 and avoid the hashing overhead.
39758382d914SDavidlohr Bueso  */
39761b426bacSMike Kravetz u32 hugetlb_fault_mutex_hash(struct hstate *h, struct address_space *mapping,
39778382d914SDavidlohr Bueso 			    pgoff_t idx, unsigned long address)
39788382d914SDavidlohr Bueso {
39798382d914SDavidlohr Bueso 	return 0;
39808382d914SDavidlohr Bueso }
39818382d914SDavidlohr Bueso #endif
39828382d914SDavidlohr Bueso 
39832b740303SSouptick Joarder vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3984788c7df4SHugh Dickins 			unsigned long address, unsigned int flags)
398586e5216fSAdam Litke {
39868382d914SDavidlohr Bueso 	pte_t *ptep, entry;
3987cb900f41SKirill A. Shutemov 	spinlock_t *ptl;
39882b740303SSouptick Joarder 	vm_fault_t ret;
39898382d914SDavidlohr Bueso 	u32 hash;
39908382d914SDavidlohr Bueso 	pgoff_t idx;
39910fe6e20bSNaoya Horiguchi 	struct page *page = NULL;
399257303d80SAndy Whitcroft 	struct page *pagecache_page = NULL;
3993a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
39948382d914SDavidlohr Bueso 	struct address_space *mapping;
39950f792cf9SNaoya Horiguchi 	int need_wait_lock = 0;
3996285b8dcaSHuang Ying 	unsigned long haddr = address & huge_page_mask(h);
399786e5216fSAdam Litke 
3998285b8dcaSHuang Ying 	ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
3999fd6a03edSNaoya Horiguchi 	if (ptep) {
4000fd6a03edSNaoya Horiguchi 		entry = huge_ptep_get(ptep);
4001290408d4SNaoya Horiguchi 		if (unlikely(is_hugetlb_entry_migration(entry))) {
4002cb900f41SKirill A. Shutemov 			migration_entry_wait_huge(vma, mm, ptep);
4003290408d4SNaoya Horiguchi 			return 0;
4004290408d4SNaoya Horiguchi 		} else if (unlikely(is_hugetlb_entry_hwpoisoned(entry)))
4005aa50d3a7SAndi Kleen 			return VM_FAULT_HWPOISON_LARGE |
4006972dc4deSAneesh Kumar K.V 				VM_FAULT_SET_HINDEX(hstate_index(h));
4007ddeaab32SMike Kravetz 	} else {
4008b43a9990SMike Kravetz 		ptep = huge_pte_alloc(mm, haddr, huge_page_size(h));
4009ddeaab32SMike Kravetz 		if (!ptep)
4010b43a9990SMike Kravetz 			return VM_FAULT_OOM;
4011b43a9990SMike Kravetz 	}
40128382d914SDavidlohr Bueso 
4013ddeaab32SMike Kravetz 	mapping = vma->vm_file->f_mapping;
4014ddeaab32SMike Kravetz 	idx = vma_hugecache_offset(h, vma, haddr);
4015ddeaab32SMike Kravetz 
40163935baa9SDavid Gibson 	/*
40173935baa9SDavid Gibson 	 * Serialize hugepage allocation and instantiation, so that we don't
40183935baa9SDavid Gibson 	 * get spurious allocation failures if two CPUs race to instantiate
40193935baa9SDavid Gibson 	 * the same page in the page cache.
40203935baa9SDavid Gibson 	 */
40211b426bacSMike Kravetz 	hash = hugetlb_fault_mutex_hash(h, mapping, idx, haddr);
4022c672c7f2SMike Kravetz 	mutex_lock(&hugetlb_fault_mutex_table[hash]);
40238382d914SDavidlohr Bueso 
40247f2e9525SGerald Schaefer 	entry = huge_ptep_get(ptep);
40257f2e9525SGerald Schaefer 	if (huge_pte_none(entry)) {
40268382d914SDavidlohr Bueso 		ret = hugetlb_no_page(mm, vma, mapping, idx, address, ptep, flags);
4027b4d1d99fSDavid Gibson 		goto out_mutex;
40283935baa9SDavid Gibson 	}
402986e5216fSAdam Litke 
403083c54070SNick Piggin 	ret = 0;
40311e8f889bSDavid Gibson 
403257303d80SAndy Whitcroft 	/*
40330f792cf9SNaoya Horiguchi 	 * entry could be a migration/hwpoison entry at this point, so this
40340f792cf9SNaoya Horiguchi 	 * check prevents the kernel from going below assuming that we have
40350f792cf9SNaoya Horiguchi 	 * a active hugepage in pagecache. This goto expects the 2nd page fault,
40360f792cf9SNaoya Horiguchi 	 * and is_hugetlb_entry_(migration|hwpoisoned) check will properly
40370f792cf9SNaoya Horiguchi 	 * handle it.
40380f792cf9SNaoya Horiguchi 	 */
40390f792cf9SNaoya Horiguchi 	if (!pte_present(entry))
40400f792cf9SNaoya Horiguchi 		goto out_mutex;
40410f792cf9SNaoya Horiguchi 
40420f792cf9SNaoya Horiguchi 	/*
404357303d80SAndy Whitcroft 	 * If we are going to COW the mapping later, we examine the pending
404457303d80SAndy Whitcroft 	 * reservations for this page now. This will ensure that any
404557303d80SAndy Whitcroft 	 * allocations necessary to record that reservation occur outside the
404657303d80SAndy Whitcroft 	 * spinlock. For private mappings, we also lookup the pagecache
404757303d80SAndy Whitcroft 	 * page now as it is used to determine if a reservation has been
404857303d80SAndy Whitcroft 	 * consumed.
404957303d80SAndy Whitcroft 	 */
4050106c992aSGerald Schaefer 	if ((flags & FAULT_FLAG_WRITE) && !huge_pte_write(entry)) {
4051285b8dcaSHuang Ying 		if (vma_needs_reservation(h, vma, haddr) < 0) {
40522b26736cSAndy Whitcroft 			ret = VM_FAULT_OOM;
4053b4d1d99fSDavid Gibson 			goto out_mutex;
40542b26736cSAndy Whitcroft 		}
40555e911373SMike Kravetz 		/* Just decrements count, does not deallocate */
4056285b8dcaSHuang Ying 		vma_end_reservation(h, vma, haddr);
405757303d80SAndy Whitcroft 
4058f83a275dSMel Gorman 		if (!(vma->vm_flags & VM_MAYSHARE))
405957303d80SAndy Whitcroft 			pagecache_page = hugetlbfs_pagecache_page(h,
4060285b8dcaSHuang Ying 								vma, haddr);
406157303d80SAndy Whitcroft 	}
406257303d80SAndy Whitcroft 
40630f792cf9SNaoya Horiguchi 	ptl = huge_pte_lock(h, mm, ptep);
40640fe6e20bSNaoya Horiguchi 
40651e8f889bSDavid Gibson 	/* Check for a racing update before calling hugetlb_cow */
4066b4d1d99fSDavid Gibson 	if (unlikely(!pte_same(entry, huge_ptep_get(ptep))))
4067cb900f41SKirill A. Shutemov 		goto out_ptl;
4068b4d1d99fSDavid Gibson 
40690f792cf9SNaoya Horiguchi 	/*
40700f792cf9SNaoya Horiguchi 	 * hugetlb_cow() requires page locks of pte_page(entry) and
40710f792cf9SNaoya Horiguchi 	 * pagecache_page, so here we need take the former one
40720f792cf9SNaoya Horiguchi 	 * when page != pagecache_page or !pagecache_page.
40730f792cf9SNaoya Horiguchi 	 */
40740f792cf9SNaoya Horiguchi 	page = pte_page(entry);
40750f792cf9SNaoya Horiguchi 	if (page != pagecache_page)
40760f792cf9SNaoya Horiguchi 		if (!trylock_page(page)) {
40770f792cf9SNaoya Horiguchi 			need_wait_lock = 1;
40780f792cf9SNaoya Horiguchi 			goto out_ptl;
40790f792cf9SNaoya Horiguchi 		}
40800f792cf9SNaoya Horiguchi 
40810f792cf9SNaoya Horiguchi 	get_page(page);
4082b4d1d99fSDavid Gibson 
4083788c7df4SHugh Dickins 	if (flags & FAULT_FLAG_WRITE) {
4084106c992aSGerald Schaefer 		if (!huge_pte_write(entry)) {
4085974e6d66SHuang Ying 			ret = hugetlb_cow(mm, vma, address, ptep,
4086cb900f41SKirill A. Shutemov 					  pagecache_page, ptl);
40870f792cf9SNaoya Horiguchi 			goto out_put_page;
4088b4d1d99fSDavid Gibson 		}
4089106c992aSGerald Schaefer 		entry = huge_pte_mkdirty(entry);
4090b4d1d99fSDavid Gibson 	}
4091b4d1d99fSDavid Gibson 	entry = pte_mkyoung(entry);
4092285b8dcaSHuang Ying 	if (huge_ptep_set_access_flags(vma, haddr, ptep, entry,
4093788c7df4SHugh Dickins 						flags & FAULT_FLAG_WRITE))
4094285b8dcaSHuang Ying 		update_mmu_cache(vma, haddr, ptep);
40950f792cf9SNaoya Horiguchi out_put_page:
40960f792cf9SNaoya Horiguchi 	if (page != pagecache_page)
40970f792cf9SNaoya Horiguchi 		unlock_page(page);
40980f792cf9SNaoya Horiguchi 	put_page(page);
4099cb900f41SKirill A. Shutemov out_ptl:
4100cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
410157303d80SAndy Whitcroft 
410257303d80SAndy Whitcroft 	if (pagecache_page) {
410357303d80SAndy Whitcroft 		unlock_page(pagecache_page);
410457303d80SAndy Whitcroft 		put_page(pagecache_page);
410557303d80SAndy Whitcroft 	}
4106b4d1d99fSDavid Gibson out_mutex:
4107c672c7f2SMike Kravetz 	mutex_unlock(&hugetlb_fault_mutex_table[hash]);
41080f792cf9SNaoya Horiguchi 	/*
41090f792cf9SNaoya Horiguchi 	 * Generally it's safe to hold refcount during waiting page lock. But
41100f792cf9SNaoya Horiguchi 	 * here we just wait to defer the next page fault to avoid busy loop and
41110f792cf9SNaoya Horiguchi 	 * the page is not used after unlocked before returning from the current
41120f792cf9SNaoya Horiguchi 	 * page fault. So we are safe from accessing freed page, even if we wait
41130f792cf9SNaoya Horiguchi 	 * here without taking refcount.
41140f792cf9SNaoya Horiguchi 	 */
41150f792cf9SNaoya Horiguchi 	if (need_wait_lock)
41160f792cf9SNaoya Horiguchi 		wait_on_page_locked(page);
41171e8f889bSDavid Gibson 	return ret;
411886e5216fSAdam Litke }
411986e5216fSAdam Litke 
41208fb5debcSMike Kravetz /*
41218fb5debcSMike Kravetz  * Used by userfaultfd UFFDIO_COPY.  Based on mcopy_atomic_pte with
41228fb5debcSMike Kravetz  * modifications for huge pages.
41238fb5debcSMike Kravetz  */
41248fb5debcSMike Kravetz int hugetlb_mcopy_atomic_pte(struct mm_struct *dst_mm,
41258fb5debcSMike Kravetz 			    pte_t *dst_pte,
41268fb5debcSMike Kravetz 			    struct vm_area_struct *dst_vma,
41278fb5debcSMike Kravetz 			    unsigned long dst_addr,
41288fb5debcSMike Kravetz 			    unsigned long src_addr,
41298fb5debcSMike Kravetz 			    struct page **pagep)
41308fb5debcSMike Kravetz {
41311e392147SAndrea Arcangeli 	struct address_space *mapping;
41321e392147SAndrea Arcangeli 	pgoff_t idx;
41331e392147SAndrea Arcangeli 	unsigned long size;
41341c9e8defSMike Kravetz 	int vm_shared = dst_vma->vm_flags & VM_SHARED;
41358fb5debcSMike Kravetz 	struct hstate *h = hstate_vma(dst_vma);
41368fb5debcSMike Kravetz 	pte_t _dst_pte;
41378fb5debcSMike Kravetz 	spinlock_t *ptl;
41388fb5debcSMike Kravetz 	int ret;
41398fb5debcSMike Kravetz 	struct page *page;
41408fb5debcSMike Kravetz 
41418fb5debcSMike Kravetz 	if (!*pagep) {
41428fb5debcSMike Kravetz 		ret = -ENOMEM;
41438fb5debcSMike Kravetz 		page = alloc_huge_page(dst_vma, dst_addr, 0);
41448fb5debcSMike Kravetz 		if (IS_ERR(page))
41458fb5debcSMike Kravetz 			goto out;
41468fb5debcSMike Kravetz 
41478fb5debcSMike Kravetz 		ret = copy_huge_page_from_user(page,
41488fb5debcSMike Kravetz 						(const void __user *) src_addr,
4149810a56b9SMike Kravetz 						pages_per_huge_page(h), false);
41508fb5debcSMike Kravetz 
41518fb5debcSMike Kravetz 		/* fallback to copy_from_user outside mmap_sem */
41528fb5debcSMike Kravetz 		if (unlikely(ret)) {
41539e368259SAndrea Arcangeli 			ret = -ENOENT;
41548fb5debcSMike Kravetz 			*pagep = page;
41558fb5debcSMike Kravetz 			/* don't free the page */
41568fb5debcSMike Kravetz 			goto out;
41578fb5debcSMike Kravetz 		}
41588fb5debcSMike Kravetz 	} else {
41598fb5debcSMike Kravetz 		page = *pagep;
41608fb5debcSMike Kravetz 		*pagep = NULL;
41618fb5debcSMike Kravetz 	}
41628fb5debcSMike Kravetz 
41638fb5debcSMike Kravetz 	/*
41648fb5debcSMike Kravetz 	 * The memory barrier inside __SetPageUptodate makes sure that
41658fb5debcSMike Kravetz 	 * preceding stores to the page contents become visible before
41668fb5debcSMike Kravetz 	 * the set_pte_at() write.
41678fb5debcSMike Kravetz 	 */
41688fb5debcSMike Kravetz 	__SetPageUptodate(page);
41698fb5debcSMike Kravetz 
41701e392147SAndrea Arcangeli 	mapping = dst_vma->vm_file->f_mapping;
41711e392147SAndrea Arcangeli 	idx = vma_hugecache_offset(h, dst_vma, dst_addr);
41721e392147SAndrea Arcangeli 
41731c9e8defSMike Kravetz 	/*
41741c9e8defSMike Kravetz 	 * If shared, add to page cache
41751c9e8defSMike Kravetz 	 */
41761c9e8defSMike Kravetz 	if (vm_shared) {
41771e392147SAndrea Arcangeli 		size = i_size_read(mapping->host) >> huge_page_shift(h);
41781e392147SAndrea Arcangeli 		ret = -EFAULT;
41791e392147SAndrea Arcangeli 		if (idx >= size)
41801e392147SAndrea Arcangeli 			goto out_release_nounlock;
41811c9e8defSMike Kravetz 
41821e392147SAndrea Arcangeli 		/*
41831e392147SAndrea Arcangeli 		 * Serialization between remove_inode_hugepages() and
41841e392147SAndrea Arcangeli 		 * huge_add_to_page_cache() below happens through the
41851e392147SAndrea Arcangeli 		 * hugetlb_fault_mutex_table that here must be hold by
41861e392147SAndrea Arcangeli 		 * the caller.
41871e392147SAndrea Arcangeli 		 */
41881c9e8defSMike Kravetz 		ret = huge_add_to_page_cache(page, mapping, idx);
41891c9e8defSMike Kravetz 		if (ret)
41901c9e8defSMike Kravetz 			goto out_release_nounlock;
41911c9e8defSMike Kravetz 	}
41921c9e8defSMike Kravetz 
41938fb5debcSMike Kravetz 	ptl = huge_pte_lockptr(h, dst_mm, dst_pte);
41948fb5debcSMike Kravetz 	spin_lock(ptl);
41958fb5debcSMike Kravetz 
41961e392147SAndrea Arcangeli 	/*
41971e392147SAndrea Arcangeli 	 * Recheck the i_size after holding PT lock to make sure not
41981e392147SAndrea Arcangeli 	 * to leave any page mapped (as page_mapped()) beyond the end
41991e392147SAndrea Arcangeli 	 * of the i_size (remove_inode_hugepages() is strict about
42001e392147SAndrea Arcangeli 	 * enforcing that). If we bail out here, we'll also leave a
42011e392147SAndrea Arcangeli 	 * page in the radix tree in the vm_shared case beyond the end
42021e392147SAndrea Arcangeli 	 * of the i_size, but remove_inode_hugepages() will take care
42031e392147SAndrea Arcangeli 	 * of it as soon as we drop the hugetlb_fault_mutex_table.
42041e392147SAndrea Arcangeli 	 */
42051e392147SAndrea Arcangeli 	size = i_size_read(mapping->host) >> huge_page_shift(h);
42061e392147SAndrea Arcangeli 	ret = -EFAULT;
42071e392147SAndrea Arcangeli 	if (idx >= size)
42081e392147SAndrea Arcangeli 		goto out_release_unlock;
42091e392147SAndrea Arcangeli 
42108fb5debcSMike Kravetz 	ret = -EEXIST;
42118fb5debcSMike Kravetz 	if (!huge_pte_none(huge_ptep_get(dst_pte)))
42128fb5debcSMike Kravetz 		goto out_release_unlock;
42138fb5debcSMike Kravetz 
42141c9e8defSMike Kravetz 	if (vm_shared) {
42151c9e8defSMike Kravetz 		page_dup_rmap(page, true);
42161c9e8defSMike Kravetz 	} else {
42178fb5debcSMike Kravetz 		ClearPagePrivate(page);
42188fb5debcSMike Kravetz 		hugepage_add_new_anon_rmap(page, dst_vma, dst_addr);
42191c9e8defSMike Kravetz 	}
42208fb5debcSMike Kravetz 
42218fb5debcSMike Kravetz 	_dst_pte = make_huge_pte(dst_vma, page, dst_vma->vm_flags & VM_WRITE);
42228fb5debcSMike Kravetz 	if (dst_vma->vm_flags & VM_WRITE)
42238fb5debcSMike Kravetz 		_dst_pte = huge_pte_mkdirty(_dst_pte);
42248fb5debcSMike Kravetz 	_dst_pte = pte_mkyoung(_dst_pte);
42258fb5debcSMike Kravetz 
42268fb5debcSMike Kravetz 	set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
42278fb5debcSMike Kravetz 
42288fb5debcSMike Kravetz 	(void)huge_ptep_set_access_flags(dst_vma, dst_addr, dst_pte, _dst_pte,
42298fb5debcSMike Kravetz 					dst_vma->vm_flags & VM_WRITE);
42308fb5debcSMike Kravetz 	hugetlb_count_add(pages_per_huge_page(h), dst_mm);
42318fb5debcSMike Kravetz 
42328fb5debcSMike Kravetz 	/* No need to invalidate - it was non-present before */
42338fb5debcSMike Kravetz 	update_mmu_cache(dst_vma, dst_addr, dst_pte);
42348fb5debcSMike Kravetz 
42358fb5debcSMike Kravetz 	spin_unlock(ptl);
4236cb6acd01SMike Kravetz 	set_page_huge_active(page);
42371c9e8defSMike Kravetz 	if (vm_shared)
42381c9e8defSMike Kravetz 		unlock_page(page);
42398fb5debcSMike Kravetz 	ret = 0;
42408fb5debcSMike Kravetz out:
42418fb5debcSMike Kravetz 	return ret;
42428fb5debcSMike Kravetz out_release_unlock:
42438fb5debcSMike Kravetz 	spin_unlock(ptl);
42441c9e8defSMike Kravetz 	if (vm_shared)
42451c9e8defSMike Kravetz 		unlock_page(page);
42465af10dfdSAndrea Arcangeli out_release_nounlock:
42478fb5debcSMike Kravetz 	put_page(page);
42488fb5debcSMike Kravetz 	goto out;
42498fb5debcSMike Kravetz }
42508fb5debcSMike Kravetz 
425128a35716SMichel Lespinasse long follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma,
425263551ae0SDavid Gibson 			 struct page **pages, struct vm_area_struct **vmas,
425328a35716SMichel Lespinasse 			 unsigned long *position, unsigned long *nr_pages,
425487ffc118SAndrea Arcangeli 			 long i, unsigned int flags, int *nonblocking)
425563551ae0SDavid Gibson {
4256d5d4b0aaSChen, Kenneth W 	unsigned long pfn_offset;
4257d5d4b0aaSChen, Kenneth W 	unsigned long vaddr = *position;
425828a35716SMichel Lespinasse 	unsigned long remainder = *nr_pages;
4259a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
42602be7cfedSDaniel Jordan 	int err = -EFAULT;
426163551ae0SDavid Gibson 
426263551ae0SDavid Gibson 	while (vaddr < vma->vm_end && remainder) {
426363551ae0SDavid Gibson 		pte_t *pte;
4264cb900f41SKirill A. Shutemov 		spinlock_t *ptl = NULL;
42652a15efc9SHugh Dickins 		int absent;
426663551ae0SDavid Gibson 		struct page *page;
426763551ae0SDavid Gibson 
42684c887265SAdam Litke 		/*
426902057967SDavid Rientjes 		 * If we have a pending SIGKILL, don't keep faulting pages and
427002057967SDavid Rientjes 		 * potentially allocating memory.
427102057967SDavid Rientjes 		 */
4272fa45f116SDavidlohr Bueso 		if (fatal_signal_pending(current)) {
427302057967SDavid Rientjes 			remainder = 0;
427402057967SDavid Rientjes 			break;
427502057967SDavid Rientjes 		}
427602057967SDavid Rientjes 
427702057967SDavid Rientjes 		/*
42784c887265SAdam Litke 		 * Some archs (sparc64, sh*) have multiple pte_ts to
42792a15efc9SHugh Dickins 		 * each hugepage.  We have to make sure we get the
42804c887265SAdam Litke 		 * first, for the page indexing below to work.
4281cb900f41SKirill A. Shutemov 		 *
4282cb900f41SKirill A. Shutemov 		 * Note that page table lock is not held when pte is null.
42834c887265SAdam Litke 		 */
42847868a208SPunit Agrawal 		pte = huge_pte_offset(mm, vaddr & huge_page_mask(h),
42857868a208SPunit Agrawal 				      huge_page_size(h));
4286cb900f41SKirill A. Shutemov 		if (pte)
4287cb900f41SKirill A. Shutemov 			ptl = huge_pte_lock(h, mm, pte);
42882a15efc9SHugh Dickins 		absent = !pte || huge_pte_none(huge_ptep_get(pte));
428963551ae0SDavid Gibson 
42902a15efc9SHugh Dickins 		/*
42912a15efc9SHugh Dickins 		 * When coredumping, it suits get_dump_page if we just return
42923ae77f43SHugh Dickins 		 * an error where there's an empty slot with no huge pagecache
42933ae77f43SHugh Dickins 		 * to back it.  This way, we avoid allocating a hugepage, and
42943ae77f43SHugh Dickins 		 * the sparse dumpfile avoids allocating disk blocks, but its
42953ae77f43SHugh Dickins 		 * huge holes still show up with zeroes where they need to be.
42962a15efc9SHugh Dickins 		 */
42973ae77f43SHugh Dickins 		if (absent && (flags & FOLL_DUMP) &&
42983ae77f43SHugh Dickins 		    !hugetlbfs_pagecache_present(h, vma, vaddr)) {
4299cb900f41SKirill A. Shutemov 			if (pte)
4300cb900f41SKirill A. Shutemov 				spin_unlock(ptl);
43012a15efc9SHugh Dickins 			remainder = 0;
43022a15efc9SHugh Dickins 			break;
43032a15efc9SHugh Dickins 		}
43042a15efc9SHugh Dickins 
43059cc3a5bdSNaoya Horiguchi 		/*
43069cc3a5bdSNaoya Horiguchi 		 * We need call hugetlb_fault for both hugepages under migration
43079cc3a5bdSNaoya Horiguchi 		 * (in which case hugetlb_fault waits for the migration,) and
43089cc3a5bdSNaoya Horiguchi 		 * hwpoisoned hugepages (in which case we need to prevent the
43099cc3a5bdSNaoya Horiguchi 		 * caller from accessing to them.) In order to do this, we use
43109cc3a5bdSNaoya Horiguchi 		 * here is_swap_pte instead of is_hugetlb_entry_migration and
43119cc3a5bdSNaoya Horiguchi 		 * is_hugetlb_entry_hwpoisoned. This is because it simply covers
43129cc3a5bdSNaoya Horiguchi 		 * both cases, and because we can't follow correct pages
43139cc3a5bdSNaoya Horiguchi 		 * directly from any kind of swap entries.
43149cc3a5bdSNaoya Horiguchi 		 */
43159cc3a5bdSNaoya Horiguchi 		if (absent || is_swap_pte(huge_ptep_get(pte)) ||
4316106c992aSGerald Schaefer 		    ((flags & FOLL_WRITE) &&
4317106c992aSGerald Schaefer 		      !huge_pte_write(huge_ptep_get(pte)))) {
43182b740303SSouptick Joarder 			vm_fault_t ret;
431987ffc118SAndrea Arcangeli 			unsigned int fault_flags = 0;
43204c887265SAdam Litke 
4321cb900f41SKirill A. Shutemov 			if (pte)
4322cb900f41SKirill A. Shutemov 				spin_unlock(ptl);
432387ffc118SAndrea Arcangeli 			if (flags & FOLL_WRITE)
432487ffc118SAndrea Arcangeli 				fault_flags |= FAULT_FLAG_WRITE;
432587ffc118SAndrea Arcangeli 			if (nonblocking)
432687ffc118SAndrea Arcangeli 				fault_flags |= FAULT_FLAG_ALLOW_RETRY;
432787ffc118SAndrea Arcangeli 			if (flags & FOLL_NOWAIT)
432887ffc118SAndrea Arcangeli 				fault_flags |= FAULT_FLAG_ALLOW_RETRY |
432987ffc118SAndrea Arcangeli 					FAULT_FLAG_RETRY_NOWAIT;
433087ffc118SAndrea Arcangeli 			if (flags & FOLL_TRIED) {
433187ffc118SAndrea Arcangeli 				VM_WARN_ON_ONCE(fault_flags &
433287ffc118SAndrea Arcangeli 						FAULT_FLAG_ALLOW_RETRY);
433387ffc118SAndrea Arcangeli 				fault_flags |= FAULT_FLAG_TRIED;
433487ffc118SAndrea Arcangeli 			}
433587ffc118SAndrea Arcangeli 			ret = hugetlb_fault(mm, vma, vaddr, fault_flags);
433687ffc118SAndrea Arcangeli 			if (ret & VM_FAULT_ERROR) {
43372be7cfedSDaniel Jordan 				err = vm_fault_to_errno(ret, flags);
43381c59827dSHugh Dickins 				remainder = 0;
43391c59827dSHugh Dickins 				break;
43401c59827dSHugh Dickins 			}
434187ffc118SAndrea Arcangeli 			if (ret & VM_FAULT_RETRY) {
43421ac25013SAndrea Arcangeli 				if (nonblocking &&
43431ac25013SAndrea Arcangeli 				    !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
434487ffc118SAndrea Arcangeli 					*nonblocking = 0;
434587ffc118SAndrea Arcangeli 				*nr_pages = 0;
434687ffc118SAndrea Arcangeli 				/*
434787ffc118SAndrea Arcangeli 				 * VM_FAULT_RETRY must not return an
434887ffc118SAndrea Arcangeli 				 * error, it will return zero
434987ffc118SAndrea Arcangeli 				 * instead.
435087ffc118SAndrea Arcangeli 				 *
435187ffc118SAndrea Arcangeli 				 * No need to update "position" as the
435287ffc118SAndrea Arcangeli 				 * caller will not check it after
435387ffc118SAndrea Arcangeli 				 * *nr_pages is set to 0.
435487ffc118SAndrea Arcangeli 				 */
435587ffc118SAndrea Arcangeli 				return i;
435687ffc118SAndrea Arcangeli 			}
435787ffc118SAndrea Arcangeli 			continue;
435887ffc118SAndrea Arcangeli 		}
435963551ae0SDavid Gibson 
4360a5516438SAndi Kleen 		pfn_offset = (vaddr & ~huge_page_mask(h)) >> PAGE_SHIFT;
43617f2e9525SGerald Schaefer 		page = pte_page(huge_ptep_get(pte));
43628fde12caSLinus Torvalds 
43638fde12caSLinus Torvalds 		/*
43648fde12caSLinus Torvalds 		 * Instead of doing 'try_get_page()' below in the same_page
43658fde12caSLinus Torvalds 		 * loop, just check the count once here.
43668fde12caSLinus Torvalds 		 */
43678fde12caSLinus Torvalds 		if (unlikely(page_count(page) <= 0)) {
43688fde12caSLinus Torvalds 			if (pages) {
43698fde12caSLinus Torvalds 				spin_unlock(ptl);
43708fde12caSLinus Torvalds 				remainder = 0;
43718fde12caSLinus Torvalds 				err = -ENOMEM;
43728fde12caSLinus Torvalds 				break;
43738fde12caSLinus Torvalds 			}
43748fde12caSLinus Torvalds 		}
4375d5d4b0aaSChen, Kenneth W same_page:
4376d6692183SChen, Kenneth W 		if (pages) {
437769d177c2SAndy Whitcroft 			pages[i] = mem_map_offset(page, pfn_offset);
4378ddc58f27SKirill A. Shutemov 			get_page(pages[i]);
4379d6692183SChen, Kenneth W 		}
438063551ae0SDavid Gibson 
438163551ae0SDavid Gibson 		if (vmas)
438263551ae0SDavid Gibson 			vmas[i] = vma;
438363551ae0SDavid Gibson 
438463551ae0SDavid Gibson 		vaddr += PAGE_SIZE;
4385d5d4b0aaSChen, Kenneth W 		++pfn_offset;
438663551ae0SDavid Gibson 		--remainder;
438763551ae0SDavid Gibson 		++i;
4388d5d4b0aaSChen, Kenneth W 		if (vaddr < vma->vm_end && remainder &&
4389a5516438SAndi Kleen 				pfn_offset < pages_per_huge_page(h)) {
4390d5d4b0aaSChen, Kenneth W 			/*
4391d5d4b0aaSChen, Kenneth W 			 * We use pfn_offset to avoid touching the pageframes
4392d5d4b0aaSChen, Kenneth W 			 * of this compound page.
4393d5d4b0aaSChen, Kenneth W 			 */
4394d5d4b0aaSChen, Kenneth W 			goto same_page;
4395d5d4b0aaSChen, Kenneth W 		}
4396cb900f41SKirill A. Shutemov 		spin_unlock(ptl);
439763551ae0SDavid Gibson 	}
439828a35716SMichel Lespinasse 	*nr_pages = remainder;
439987ffc118SAndrea Arcangeli 	/*
440087ffc118SAndrea Arcangeli 	 * setting position is actually required only if remainder is
440187ffc118SAndrea Arcangeli 	 * not zero but it's faster not to add a "if (remainder)"
440287ffc118SAndrea Arcangeli 	 * branch.
440387ffc118SAndrea Arcangeli 	 */
440463551ae0SDavid Gibson 	*position = vaddr;
440563551ae0SDavid Gibson 
44062be7cfedSDaniel Jordan 	return i ? i : err;
440763551ae0SDavid Gibson }
44088f860591SZhang, Yanmin 
44095491ae7bSAneesh Kumar K.V #ifndef __HAVE_ARCH_FLUSH_HUGETLB_TLB_RANGE
44105491ae7bSAneesh Kumar K.V /*
44115491ae7bSAneesh Kumar K.V  * ARCHes with special requirements for evicting HUGETLB backing TLB entries can
44125491ae7bSAneesh Kumar K.V  * implement this.
44135491ae7bSAneesh Kumar K.V  */
44145491ae7bSAneesh Kumar K.V #define flush_hugetlb_tlb_range(vma, addr, end)	flush_tlb_range(vma, addr, end)
44155491ae7bSAneesh Kumar K.V #endif
44165491ae7bSAneesh Kumar K.V 
44177da4d641SPeter Zijlstra unsigned long hugetlb_change_protection(struct vm_area_struct *vma,
44188f860591SZhang, Yanmin 		unsigned long address, unsigned long end, pgprot_t newprot)
44198f860591SZhang, Yanmin {
44208f860591SZhang, Yanmin 	struct mm_struct *mm = vma->vm_mm;
44218f860591SZhang, Yanmin 	unsigned long start = address;
44228f860591SZhang, Yanmin 	pte_t *ptep;
44238f860591SZhang, Yanmin 	pte_t pte;
4424a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
44257da4d641SPeter Zijlstra 	unsigned long pages = 0;
4426dff11abeSMike Kravetz 	bool shared_pmd = false;
4427ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
4428dff11abeSMike Kravetz 
4429dff11abeSMike Kravetz 	/*
4430dff11abeSMike Kravetz 	 * In the case of shared PMDs, the area to flush could be beyond
4431ac46d4f3SJérôme Glisse 	 * start/end.  Set range.start/range.end to cover the maximum possible
4432dff11abeSMike Kravetz 	 * range if PMD sharing is possible.
4433dff11abeSMike Kravetz 	 */
44347269f999SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_VMA,
44357269f999SJérôme Glisse 				0, vma, mm, start, end);
4436ac46d4f3SJérôme Glisse 	adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
44378f860591SZhang, Yanmin 
44388f860591SZhang, Yanmin 	BUG_ON(address >= end);
4439ac46d4f3SJérôme Glisse 	flush_cache_range(vma, range.start, range.end);
44408f860591SZhang, Yanmin 
4441ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
444283cde9e8SDavidlohr Bueso 	i_mmap_lock_write(vma->vm_file->f_mapping);
4443a5516438SAndi Kleen 	for (; address < end; address += huge_page_size(h)) {
4444cb900f41SKirill A. Shutemov 		spinlock_t *ptl;
44457868a208SPunit Agrawal 		ptep = huge_pte_offset(mm, address, huge_page_size(h));
44468f860591SZhang, Yanmin 		if (!ptep)
44478f860591SZhang, Yanmin 			continue;
4448cb900f41SKirill A. Shutemov 		ptl = huge_pte_lock(h, mm, ptep);
44497da4d641SPeter Zijlstra 		if (huge_pmd_unshare(mm, &address, ptep)) {
44507da4d641SPeter Zijlstra 			pages++;
4451cb900f41SKirill A. Shutemov 			spin_unlock(ptl);
4452dff11abeSMike Kravetz 			shared_pmd = true;
445339dde65cSChen, Kenneth W 			continue;
44547da4d641SPeter Zijlstra 		}
4455a8bda28dSNaoya Horiguchi 		pte = huge_ptep_get(ptep);
4456a8bda28dSNaoya Horiguchi 		if (unlikely(is_hugetlb_entry_hwpoisoned(pte))) {
4457a8bda28dSNaoya Horiguchi 			spin_unlock(ptl);
4458a8bda28dSNaoya Horiguchi 			continue;
4459a8bda28dSNaoya Horiguchi 		}
4460a8bda28dSNaoya Horiguchi 		if (unlikely(is_hugetlb_entry_migration(pte))) {
4461a8bda28dSNaoya Horiguchi 			swp_entry_t entry = pte_to_swp_entry(pte);
4462a8bda28dSNaoya Horiguchi 
4463a8bda28dSNaoya Horiguchi 			if (is_write_migration_entry(entry)) {
4464a8bda28dSNaoya Horiguchi 				pte_t newpte;
4465a8bda28dSNaoya Horiguchi 
4466a8bda28dSNaoya Horiguchi 				make_migration_entry_read(&entry);
4467a8bda28dSNaoya Horiguchi 				newpte = swp_entry_to_pte(entry);
4468e5251fd4SPunit Agrawal 				set_huge_swap_pte_at(mm, address, ptep,
4469e5251fd4SPunit Agrawal 						     newpte, huge_page_size(h));
4470a8bda28dSNaoya Horiguchi 				pages++;
4471a8bda28dSNaoya Horiguchi 			}
4472a8bda28dSNaoya Horiguchi 			spin_unlock(ptl);
4473a8bda28dSNaoya Horiguchi 			continue;
4474a8bda28dSNaoya Horiguchi 		}
4475a8bda28dSNaoya Horiguchi 		if (!huge_pte_none(pte)) {
4476023bdd00SAneesh Kumar K.V 			pte_t old_pte;
4477023bdd00SAneesh Kumar K.V 
4478023bdd00SAneesh Kumar K.V 			old_pte = huge_ptep_modify_prot_start(vma, address, ptep);
4479023bdd00SAneesh Kumar K.V 			pte = pte_mkhuge(huge_pte_modify(old_pte, newprot));
4480be7517d6STony Lu 			pte = arch_make_huge_pte(pte, vma, NULL, 0);
4481023bdd00SAneesh Kumar K.V 			huge_ptep_modify_prot_commit(vma, address, ptep, old_pte, pte);
44827da4d641SPeter Zijlstra 			pages++;
44838f860591SZhang, Yanmin 		}
4484cb900f41SKirill A. Shutemov 		spin_unlock(ptl);
44858f860591SZhang, Yanmin 	}
4486d833352aSMel Gorman 	/*
4487c8c06efaSDavidlohr Bueso 	 * Must flush TLB before releasing i_mmap_rwsem: x86's huge_pmd_unshare
4488d833352aSMel Gorman 	 * may have cleared our pud entry and done put_page on the page table:
4489c8c06efaSDavidlohr Bueso 	 * once we release i_mmap_rwsem, another task can do the final put_page
4490dff11abeSMike Kravetz 	 * and that page table be reused and filled with junk.  If we actually
4491dff11abeSMike Kravetz 	 * did unshare a page of pmds, flush the range corresponding to the pud.
4492d833352aSMel Gorman 	 */
4493dff11abeSMike Kravetz 	if (shared_pmd)
4494ac46d4f3SJérôme Glisse 		flush_hugetlb_tlb_range(vma, range.start, range.end);
4495dff11abeSMike Kravetz 	else
44965491ae7bSAneesh Kumar K.V 		flush_hugetlb_tlb_range(vma, start, end);
44970f10851eSJérôme Glisse 	/*
44980f10851eSJérôme Glisse 	 * No need to call mmu_notifier_invalidate_range() we are downgrading
44990f10851eSJérôme Glisse 	 * page table protection not changing it to point to a new page.
45000f10851eSJérôme Glisse 	 *
4501ad56b738SMike Rapoport 	 * See Documentation/vm/mmu_notifier.rst
45020f10851eSJérôme Glisse 	 */
450383cde9e8SDavidlohr Bueso 	i_mmap_unlock_write(vma->vm_file->f_mapping);
4504ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
45057da4d641SPeter Zijlstra 
45067da4d641SPeter Zijlstra 	return pages << h->order;
45078f860591SZhang, Yanmin }
45088f860591SZhang, Yanmin 
4509a1e78772SMel Gorman int hugetlb_reserve_pages(struct inode *inode,
4510a1e78772SMel Gorman 					long from, long to,
45115a6fe125SMel Gorman 					struct vm_area_struct *vma,
4512ca16d140SKOSAKI Motohiro 					vm_flags_t vm_flags)
4513e4e574b7SAdam Litke {
451417c9d12eSMel Gorman 	long ret, chg;
4515a5516438SAndi Kleen 	struct hstate *h = hstate_inode(inode);
451690481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_inode(inode);
45179119a41eSJoonsoo Kim 	struct resv_map *resv_map;
45181c5ecae3SMike Kravetz 	long gbl_reserve;
4519e4e574b7SAdam Litke 
452063489f8eSMike Kravetz 	/* This should never happen */
452163489f8eSMike Kravetz 	if (from > to) {
452263489f8eSMike Kravetz 		VM_WARN(1, "%s called with a negative range\n", __func__);
452363489f8eSMike Kravetz 		return -EINVAL;
452463489f8eSMike Kravetz 	}
452563489f8eSMike Kravetz 
4526a1e78772SMel Gorman 	/*
452717c9d12eSMel Gorman 	 * Only apply hugepage reservation if asked. At fault time, an
452817c9d12eSMel Gorman 	 * attempt will be made for VM_NORESERVE to allocate a page
452990481622SDavid Gibson 	 * without using reserves
453017c9d12eSMel Gorman 	 */
4531ca16d140SKOSAKI Motohiro 	if (vm_flags & VM_NORESERVE)
453217c9d12eSMel Gorman 		return 0;
453317c9d12eSMel Gorman 
453417c9d12eSMel Gorman 	/*
4535a1e78772SMel Gorman 	 * Shared mappings base their reservation on the number of pages that
4536a1e78772SMel Gorman 	 * are already allocated on behalf of the file. Private mappings need
4537a1e78772SMel Gorman 	 * to reserve the full area even if read-only as mprotect() may be
4538a1e78772SMel Gorman 	 * called to make the mapping read-write. Assume !vma is a shm mapping
4539a1e78772SMel Gorman 	 */
45409119a41eSJoonsoo Kim 	if (!vma || vma->vm_flags & VM_MAYSHARE) {
4541f27a5136SMike Kravetz 		/*
4542f27a5136SMike Kravetz 		 * resv_map can not be NULL as hugetlb_reserve_pages is only
4543f27a5136SMike Kravetz 		 * called for inodes for which resv_maps were created (see
4544f27a5136SMike Kravetz 		 * hugetlbfs_get_inode).
4545f27a5136SMike Kravetz 		 */
45464e35f483SJoonsoo Kim 		resv_map = inode_resv_map(inode);
45479119a41eSJoonsoo Kim 
45481406ec9bSJoonsoo Kim 		chg = region_chg(resv_map, from, to);
45499119a41eSJoonsoo Kim 
45509119a41eSJoonsoo Kim 	} else {
45519119a41eSJoonsoo Kim 		resv_map = resv_map_alloc();
45525a6fe125SMel Gorman 		if (!resv_map)
45535a6fe125SMel Gorman 			return -ENOMEM;
45545a6fe125SMel Gorman 
455517c9d12eSMel Gorman 		chg = to - from;
455617c9d12eSMel Gorman 
45575a6fe125SMel Gorman 		set_vma_resv_map(vma, resv_map);
45585a6fe125SMel Gorman 		set_vma_resv_flags(vma, HPAGE_RESV_OWNER);
45595a6fe125SMel Gorman 	}
45605a6fe125SMel Gorman 
4561c50ac050SDave Hansen 	if (chg < 0) {
4562c50ac050SDave Hansen 		ret = chg;
4563c50ac050SDave Hansen 		goto out_err;
4564c50ac050SDave Hansen 	}
456517c9d12eSMel Gorman 
45661c5ecae3SMike Kravetz 	/*
45671c5ecae3SMike Kravetz 	 * There must be enough pages in the subpool for the mapping. If
45681c5ecae3SMike Kravetz 	 * the subpool has a minimum size, there may be some global
45691c5ecae3SMike Kravetz 	 * reservations already in place (gbl_reserve).
45701c5ecae3SMike Kravetz 	 */
45711c5ecae3SMike Kravetz 	gbl_reserve = hugepage_subpool_get_pages(spool, chg);
45721c5ecae3SMike Kravetz 	if (gbl_reserve < 0) {
4573c50ac050SDave Hansen 		ret = -ENOSPC;
4574c50ac050SDave Hansen 		goto out_err;
4575c50ac050SDave Hansen 	}
457617c9d12eSMel Gorman 
457717c9d12eSMel Gorman 	/*
457817c9d12eSMel Gorman 	 * Check enough hugepages are available for the reservation.
457990481622SDavid Gibson 	 * Hand the pages back to the subpool if there are not
458017c9d12eSMel Gorman 	 */
45811c5ecae3SMike Kravetz 	ret = hugetlb_acct_memory(h, gbl_reserve);
458217c9d12eSMel Gorman 	if (ret < 0) {
45831c5ecae3SMike Kravetz 		/* put back original number of pages, chg */
45841c5ecae3SMike Kravetz 		(void)hugepage_subpool_put_pages(spool, chg);
4585c50ac050SDave Hansen 		goto out_err;
458617c9d12eSMel Gorman 	}
458717c9d12eSMel Gorman 
458817c9d12eSMel Gorman 	/*
458917c9d12eSMel Gorman 	 * Account for the reservations made. Shared mappings record regions
459017c9d12eSMel Gorman 	 * that have reservations as they are shared by multiple VMAs.
459117c9d12eSMel Gorman 	 * When the last VMA disappears, the region map says how much
459217c9d12eSMel Gorman 	 * the reservation was and the page cache tells how much of
459317c9d12eSMel Gorman 	 * the reservation was consumed. Private mappings are per-VMA and
459417c9d12eSMel Gorman 	 * only the consumed reservations are tracked. When the VMA
459517c9d12eSMel Gorman 	 * disappears, the original reservation is the VMA size and the
459617c9d12eSMel Gorman 	 * consumed reservations are stored in the map. Hence, nothing
459717c9d12eSMel Gorman 	 * else has to be done for private mappings here
459817c9d12eSMel Gorman 	 */
459933039678SMike Kravetz 	if (!vma || vma->vm_flags & VM_MAYSHARE) {
460033039678SMike Kravetz 		long add = region_add(resv_map, from, to);
460133039678SMike Kravetz 
460233039678SMike Kravetz 		if (unlikely(chg > add)) {
460333039678SMike Kravetz 			/*
460433039678SMike Kravetz 			 * pages in this range were added to the reserve
460533039678SMike Kravetz 			 * map between region_chg and region_add.  This
460633039678SMike Kravetz 			 * indicates a race with alloc_huge_page.  Adjust
460733039678SMike Kravetz 			 * the subpool and reserve counts modified above
460833039678SMike Kravetz 			 * based on the difference.
460933039678SMike Kravetz 			 */
461033039678SMike Kravetz 			long rsv_adjust;
461133039678SMike Kravetz 
461233039678SMike Kravetz 			rsv_adjust = hugepage_subpool_put_pages(spool,
461333039678SMike Kravetz 								chg - add);
461433039678SMike Kravetz 			hugetlb_acct_memory(h, -rsv_adjust);
461533039678SMike Kravetz 		}
461633039678SMike Kravetz 	}
4617a43a8c39SChen, Kenneth W 	return 0;
4618c50ac050SDave Hansen out_err:
46195e911373SMike Kravetz 	if (!vma || vma->vm_flags & VM_MAYSHARE)
4620ff8c0c53SMike Kravetz 		/* Don't call region_abort if region_chg failed */
4621ff8c0c53SMike Kravetz 		if (chg >= 0)
46225e911373SMike Kravetz 			region_abort(resv_map, from, to);
4623f031dd27SJoonsoo Kim 	if (vma && is_vma_resv_set(vma, HPAGE_RESV_OWNER))
4624f031dd27SJoonsoo Kim 		kref_put(&resv_map->refs, resv_map_release);
4625c50ac050SDave Hansen 	return ret;
4626a43a8c39SChen, Kenneth W }
4627a43a8c39SChen, Kenneth W 
4628b5cec28dSMike Kravetz long hugetlb_unreserve_pages(struct inode *inode, long start, long end,
4629b5cec28dSMike Kravetz 								long freed)
4630a43a8c39SChen, Kenneth W {
4631a5516438SAndi Kleen 	struct hstate *h = hstate_inode(inode);
46324e35f483SJoonsoo Kim 	struct resv_map *resv_map = inode_resv_map(inode);
46339119a41eSJoonsoo Kim 	long chg = 0;
463490481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_inode(inode);
46351c5ecae3SMike Kravetz 	long gbl_reserve;
463645c682a6SKen Chen 
4637f27a5136SMike Kravetz 	/*
4638f27a5136SMike Kravetz 	 * Since this routine can be called in the evict inode path for all
4639f27a5136SMike Kravetz 	 * hugetlbfs inodes, resv_map could be NULL.
4640f27a5136SMike Kravetz 	 */
4641b5cec28dSMike Kravetz 	if (resv_map) {
4642b5cec28dSMike Kravetz 		chg = region_del(resv_map, start, end);
4643b5cec28dSMike Kravetz 		/*
4644b5cec28dSMike Kravetz 		 * region_del() can fail in the rare case where a region
4645b5cec28dSMike Kravetz 		 * must be split and another region descriptor can not be
4646b5cec28dSMike Kravetz 		 * allocated.  If end == LONG_MAX, it will not fail.
4647b5cec28dSMike Kravetz 		 */
4648b5cec28dSMike Kravetz 		if (chg < 0)
4649b5cec28dSMike Kravetz 			return chg;
4650b5cec28dSMike Kravetz 	}
4651b5cec28dSMike Kravetz 
465245c682a6SKen Chen 	spin_lock(&inode->i_lock);
4653e4c6f8beSEric Sandeen 	inode->i_blocks -= (blocks_per_huge_page(h) * freed);
465445c682a6SKen Chen 	spin_unlock(&inode->i_lock);
465545c682a6SKen Chen 
46561c5ecae3SMike Kravetz 	/*
46571c5ecae3SMike Kravetz 	 * If the subpool has a minimum size, the number of global
46581c5ecae3SMike Kravetz 	 * reservations to be released may be adjusted.
46591c5ecae3SMike Kravetz 	 */
46601c5ecae3SMike Kravetz 	gbl_reserve = hugepage_subpool_put_pages(spool, (chg - freed));
46611c5ecae3SMike Kravetz 	hugetlb_acct_memory(h, -gbl_reserve);
4662b5cec28dSMike Kravetz 
4663b5cec28dSMike Kravetz 	return 0;
4664a43a8c39SChen, Kenneth W }
466593f70f90SNaoya Horiguchi 
46663212b535SSteve Capper #ifdef CONFIG_ARCH_WANT_HUGE_PMD_SHARE
46673212b535SSteve Capper static unsigned long page_table_shareable(struct vm_area_struct *svma,
46683212b535SSteve Capper 				struct vm_area_struct *vma,
46693212b535SSteve Capper 				unsigned long addr, pgoff_t idx)
46703212b535SSteve Capper {
46713212b535SSteve Capper 	unsigned long saddr = ((idx - svma->vm_pgoff) << PAGE_SHIFT) +
46723212b535SSteve Capper 				svma->vm_start;
46733212b535SSteve Capper 	unsigned long sbase = saddr & PUD_MASK;
46743212b535SSteve Capper 	unsigned long s_end = sbase + PUD_SIZE;
46753212b535SSteve Capper 
46763212b535SSteve Capper 	/* Allow segments to share if only one is marked locked */
4677de60f5f1SEric B Munson 	unsigned long vm_flags = vma->vm_flags & VM_LOCKED_CLEAR_MASK;
4678de60f5f1SEric B Munson 	unsigned long svm_flags = svma->vm_flags & VM_LOCKED_CLEAR_MASK;
46793212b535SSteve Capper 
46803212b535SSteve Capper 	/*
46813212b535SSteve Capper 	 * match the virtual addresses, permission and the alignment of the
46823212b535SSteve Capper 	 * page table page.
46833212b535SSteve Capper 	 */
46843212b535SSteve Capper 	if (pmd_index(addr) != pmd_index(saddr) ||
46853212b535SSteve Capper 	    vm_flags != svm_flags ||
46863212b535SSteve Capper 	    sbase < svma->vm_start || svma->vm_end < s_end)
46873212b535SSteve Capper 		return 0;
46883212b535SSteve Capper 
46893212b535SSteve Capper 	return saddr;
46903212b535SSteve Capper }
46913212b535SSteve Capper 
469231aafb45SNicholas Krause static bool vma_shareable(struct vm_area_struct *vma, unsigned long addr)
46933212b535SSteve Capper {
46943212b535SSteve Capper 	unsigned long base = addr & PUD_MASK;
46953212b535SSteve Capper 	unsigned long end = base + PUD_SIZE;
46963212b535SSteve Capper 
46973212b535SSteve Capper 	/*
46983212b535SSteve Capper 	 * check on proper vm_flags and page table alignment
46993212b535SSteve Capper 	 */
4700017b1660SMike Kravetz 	if (vma->vm_flags & VM_MAYSHARE && range_in_vma(vma, base, end))
470131aafb45SNicholas Krause 		return true;
470231aafb45SNicholas Krause 	return false;
47033212b535SSteve Capper }
47043212b535SSteve Capper 
47053212b535SSteve Capper /*
4706017b1660SMike Kravetz  * Determine if start,end range within vma could be mapped by shared pmd.
4707017b1660SMike Kravetz  * If yes, adjust start and end to cover range associated with possible
4708017b1660SMike Kravetz  * shared pmd mappings.
4709017b1660SMike Kravetz  */
4710017b1660SMike Kravetz void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
4711017b1660SMike Kravetz 				unsigned long *start, unsigned long *end)
4712017b1660SMike Kravetz {
4713017b1660SMike Kravetz 	unsigned long check_addr = *start;
4714017b1660SMike Kravetz 
4715017b1660SMike Kravetz 	if (!(vma->vm_flags & VM_MAYSHARE))
4716017b1660SMike Kravetz 		return;
4717017b1660SMike Kravetz 
4718017b1660SMike Kravetz 	for (check_addr = *start; check_addr < *end; check_addr += PUD_SIZE) {
4719017b1660SMike Kravetz 		unsigned long a_start = check_addr & PUD_MASK;
4720017b1660SMike Kravetz 		unsigned long a_end = a_start + PUD_SIZE;
4721017b1660SMike Kravetz 
4722017b1660SMike Kravetz 		/*
4723017b1660SMike Kravetz 		 * If sharing is possible, adjust start/end if necessary.
4724017b1660SMike Kravetz 		 */
4725017b1660SMike Kravetz 		if (range_in_vma(vma, a_start, a_end)) {
4726017b1660SMike Kravetz 			if (a_start < *start)
4727017b1660SMike Kravetz 				*start = a_start;
4728017b1660SMike Kravetz 			if (a_end > *end)
4729017b1660SMike Kravetz 				*end = a_end;
4730017b1660SMike Kravetz 		}
4731017b1660SMike Kravetz 	}
4732017b1660SMike Kravetz }
4733017b1660SMike Kravetz 
4734017b1660SMike Kravetz /*
47353212b535SSteve Capper  * Search for a shareable pmd page for hugetlb. In any case calls pmd_alloc()
47363212b535SSteve Capper  * and returns the corresponding pte. While this is not necessary for the
47373212b535SSteve Capper  * !shared pmd case because we can allocate the pmd later as well, it makes the
4738ddeaab32SMike Kravetz  * code much cleaner. pmd allocation is essential for the shared case because
4739ddeaab32SMike Kravetz  * pud has to be populated inside the same i_mmap_rwsem section - otherwise
4740ddeaab32SMike Kravetz  * racing tasks could either miss the sharing (see huge_pte_offset) or select a
4741ddeaab32SMike Kravetz  * bad pmd for sharing.
47423212b535SSteve Capper  */
47433212b535SSteve Capper pte_t *huge_pmd_share(struct mm_struct *mm, unsigned long addr, pud_t *pud)
47443212b535SSteve Capper {
47453212b535SSteve Capper 	struct vm_area_struct *vma = find_vma(mm, addr);
47463212b535SSteve Capper 	struct address_space *mapping = vma->vm_file->f_mapping;
47473212b535SSteve Capper 	pgoff_t idx = ((addr - vma->vm_start) >> PAGE_SHIFT) +
47483212b535SSteve Capper 			vma->vm_pgoff;
47493212b535SSteve Capper 	struct vm_area_struct *svma;
47503212b535SSteve Capper 	unsigned long saddr;
47513212b535SSteve Capper 	pte_t *spte = NULL;
47523212b535SSteve Capper 	pte_t *pte;
4753cb900f41SKirill A. Shutemov 	spinlock_t *ptl;
47543212b535SSteve Capper 
47553212b535SSteve Capper 	if (!vma_shareable(vma, addr))
47563212b535SSteve Capper 		return (pte_t *)pmd_alloc(mm, pud, addr);
47573212b535SSteve Capper 
4758ddeaab32SMike Kravetz 	i_mmap_lock_write(mapping);
47593212b535SSteve Capper 	vma_interval_tree_foreach(svma, &mapping->i_mmap, idx, idx) {
47603212b535SSteve Capper 		if (svma == vma)
47613212b535SSteve Capper 			continue;
47623212b535SSteve Capper 
47633212b535SSteve Capper 		saddr = page_table_shareable(svma, vma, addr, idx);
47643212b535SSteve Capper 		if (saddr) {
47657868a208SPunit Agrawal 			spte = huge_pte_offset(svma->vm_mm, saddr,
47667868a208SPunit Agrawal 					       vma_mmu_pagesize(svma));
47673212b535SSteve Capper 			if (spte) {
47683212b535SSteve Capper 				get_page(virt_to_page(spte));
47693212b535SSteve Capper 				break;
47703212b535SSteve Capper 			}
47713212b535SSteve Capper 		}
47723212b535SSteve Capper 	}
47733212b535SSteve Capper 
47743212b535SSteve Capper 	if (!spte)
47753212b535SSteve Capper 		goto out;
47763212b535SSteve Capper 
47778bea8052SAneesh Kumar K.V 	ptl = huge_pte_lock(hstate_vma(vma), mm, spte);
4778dc6c9a35SKirill A. Shutemov 	if (pud_none(*pud)) {
47793212b535SSteve Capper 		pud_populate(mm, pud,
47803212b535SSteve Capper 				(pmd_t *)((unsigned long)spte & PAGE_MASK));
4781c17b1f42SKirill A. Shutemov 		mm_inc_nr_pmds(mm);
4782dc6c9a35SKirill A. Shutemov 	} else {
47833212b535SSteve Capper 		put_page(virt_to_page(spte));
4784dc6c9a35SKirill A. Shutemov 	}
4785cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
47863212b535SSteve Capper out:
47873212b535SSteve Capper 	pte = (pte_t *)pmd_alloc(mm, pud, addr);
4788ddeaab32SMike Kravetz 	i_mmap_unlock_write(mapping);
47893212b535SSteve Capper 	return pte;
47903212b535SSteve Capper }
47913212b535SSteve Capper 
47923212b535SSteve Capper /*
47933212b535SSteve Capper  * unmap huge page backed by shared pte.
47943212b535SSteve Capper  *
47953212b535SSteve Capper  * Hugetlb pte page is ref counted at the time of mapping.  If pte is shared
47963212b535SSteve Capper  * indicated by page_count > 1, unmap is achieved by clearing pud and
47973212b535SSteve Capper  * decrementing the ref count. If count == 1, the pte page is not shared.
47983212b535SSteve Capper  *
4799ddeaab32SMike Kravetz  * called with page table lock held.
48003212b535SSteve Capper  *
48013212b535SSteve Capper  * returns: 1 successfully unmapped a shared pte page
48023212b535SSteve Capper  *	    0 the underlying pte page is not shared, or it is the last user
48033212b535SSteve Capper  */
48043212b535SSteve Capper int huge_pmd_unshare(struct mm_struct *mm, unsigned long *addr, pte_t *ptep)
48053212b535SSteve Capper {
48063212b535SSteve Capper 	pgd_t *pgd = pgd_offset(mm, *addr);
4807c2febafcSKirill A. Shutemov 	p4d_t *p4d = p4d_offset(pgd, *addr);
4808c2febafcSKirill A. Shutemov 	pud_t *pud = pud_offset(p4d, *addr);
48093212b535SSteve Capper 
48103212b535SSteve Capper 	BUG_ON(page_count(virt_to_page(ptep)) == 0);
48113212b535SSteve Capper 	if (page_count(virt_to_page(ptep)) == 1)
48123212b535SSteve Capper 		return 0;
48133212b535SSteve Capper 
48143212b535SSteve Capper 	pud_clear(pud);
48153212b535SSteve Capper 	put_page(virt_to_page(ptep));
4816dc6c9a35SKirill A. Shutemov 	mm_dec_nr_pmds(mm);
48173212b535SSteve Capper 	*addr = ALIGN(*addr, HPAGE_SIZE * PTRS_PER_PTE) - HPAGE_SIZE;
48183212b535SSteve Capper 	return 1;
48193212b535SSteve Capper }
48209e5fc74cSSteve Capper #define want_pmd_share()	(1)
48219e5fc74cSSteve Capper #else /* !CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
48229e5fc74cSSteve Capper pte_t *huge_pmd_share(struct mm_struct *mm, unsigned long addr, pud_t *pud)
48239e5fc74cSSteve Capper {
48249e5fc74cSSteve Capper 	return NULL;
48259e5fc74cSSteve Capper }
4826e81f2d22SZhang Zhen 
4827e81f2d22SZhang Zhen int huge_pmd_unshare(struct mm_struct *mm, unsigned long *addr, pte_t *ptep)
4828e81f2d22SZhang Zhen {
4829e81f2d22SZhang Zhen 	return 0;
4830e81f2d22SZhang Zhen }
4831017b1660SMike Kravetz 
4832017b1660SMike Kravetz void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
4833017b1660SMike Kravetz 				unsigned long *start, unsigned long *end)
4834017b1660SMike Kravetz {
4835017b1660SMike Kravetz }
48369e5fc74cSSteve Capper #define want_pmd_share()	(0)
48373212b535SSteve Capper #endif /* CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
48383212b535SSteve Capper 
48399e5fc74cSSteve Capper #ifdef CONFIG_ARCH_WANT_GENERAL_HUGETLB
48409e5fc74cSSteve Capper pte_t *huge_pte_alloc(struct mm_struct *mm,
48419e5fc74cSSteve Capper 			unsigned long addr, unsigned long sz)
48429e5fc74cSSteve Capper {
48439e5fc74cSSteve Capper 	pgd_t *pgd;
4844c2febafcSKirill A. Shutemov 	p4d_t *p4d;
48459e5fc74cSSteve Capper 	pud_t *pud;
48469e5fc74cSSteve Capper 	pte_t *pte = NULL;
48479e5fc74cSSteve Capper 
48489e5fc74cSSteve Capper 	pgd = pgd_offset(mm, addr);
4849f4f0a3d8SKirill A. Shutemov 	p4d = p4d_alloc(mm, pgd, addr);
4850f4f0a3d8SKirill A. Shutemov 	if (!p4d)
4851f4f0a3d8SKirill A. Shutemov 		return NULL;
4852c2febafcSKirill A. Shutemov 	pud = pud_alloc(mm, p4d, addr);
48539e5fc74cSSteve Capper 	if (pud) {
48549e5fc74cSSteve Capper 		if (sz == PUD_SIZE) {
48559e5fc74cSSteve Capper 			pte = (pte_t *)pud;
48569e5fc74cSSteve Capper 		} else {
48579e5fc74cSSteve Capper 			BUG_ON(sz != PMD_SIZE);
48589e5fc74cSSteve Capper 			if (want_pmd_share() && pud_none(*pud))
48599e5fc74cSSteve Capper 				pte = huge_pmd_share(mm, addr, pud);
48609e5fc74cSSteve Capper 			else
48619e5fc74cSSteve Capper 				pte = (pte_t *)pmd_alloc(mm, pud, addr);
48629e5fc74cSSteve Capper 		}
48639e5fc74cSSteve Capper 	}
48644e666314SMichal Hocko 	BUG_ON(pte && pte_present(*pte) && !pte_huge(*pte));
48659e5fc74cSSteve Capper 
48669e5fc74cSSteve Capper 	return pte;
48679e5fc74cSSteve Capper }
48689e5fc74cSSteve Capper 
48699b19df29SPunit Agrawal /*
48709b19df29SPunit Agrawal  * huge_pte_offset() - Walk the page table to resolve the hugepage
48719b19df29SPunit Agrawal  * entry at address @addr
48729b19df29SPunit Agrawal  *
48739b19df29SPunit Agrawal  * Return: Pointer to page table or swap entry (PUD or PMD) for
48749b19df29SPunit Agrawal  * address @addr, or NULL if a p*d_none() entry is encountered and the
48759b19df29SPunit Agrawal  * size @sz doesn't match the hugepage size at this level of the page
48769b19df29SPunit Agrawal  * table.
48779b19df29SPunit Agrawal  */
48787868a208SPunit Agrawal pte_t *huge_pte_offset(struct mm_struct *mm,
48797868a208SPunit Agrawal 		       unsigned long addr, unsigned long sz)
48809e5fc74cSSteve Capper {
48819e5fc74cSSteve Capper 	pgd_t *pgd;
4882c2febafcSKirill A. Shutemov 	p4d_t *p4d;
48839e5fc74cSSteve Capper 	pud_t *pud;
4884c2febafcSKirill A. Shutemov 	pmd_t *pmd;
48859e5fc74cSSteve Capper 
48869e5fc74cSSteve Capper 	pgd = pgd_offset(mm, addr);
4887c2febafcSKirill A. Shutemov 	if (!pgd_present(*pgd))
4888c2febafcSKirill A. Shutemov 		return NULL;
4889c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, addr);
4890c2febafcSKirill A. Shutemov 	if (!p4d_present(*p4d))
4891c2febafcSKirill A. Shutemov 		return NULL;
48929b19df29SPunit Agrawal 
4893c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, addr);
48949b19df29SPunit Agrawal 	if (sz != PUD_SIZE && pud_none(*pud))
4895c2febafcSKirill A. Shutemov 		return NULL;
48969b19df29SPunit Agrawal 	/* hugepage or swap? */
48979b19df29SPunit Agrawal 	if (pud_huge(*pud) || !pud_present(*pud))
48989e5fc74cSSteve Capper 		return (pte_t *)pud;
48999b19df29SPunit Agrawal 
49009e5fc74cSSteve Capper 	pmd = pmd_offset(pud, addr);
49019b19df29SPunit Agrawal 	if (sz != PMD_SIZE && pmd_none(*pmd))
49029b19df29SPunit Agrawal 		return NULL;
49039b19df29SPunit Agrawal 	/* hugepage or swap? */
49049b19df29SPunit Agrawal 	if (pmd_huge(*pmd) || !pmd_present(*pmd))
49059e5fc74cSSteve Capper 		return (pte_t *)pmd;
49069b19df29SPunit Agrawal 
49079b19df29SPunit Agrawal 	return NULL;
49089e5fc74cSSteve Capper }
49099e5fc74cSSteve Capper 
491061f77edaSNaoya Horiguchi #endif /* CONFIG_ARCH_WANT_GENERAL_HUGETLB */
491161f77edaSNaoya Horiguchi 
491261f77edaSNaoya Horiguchi /*
491361f77edaSNaoya Horiguchi  * These functions are overwritable if your architecture needs its own
491461f77edaSNaoya Horiguchi  * behavior.
491561f77edaSNaoya Horiguchi  */
491661f77edaSNaoya Horiguchi struct page * __weak
491761f77edaSNaoya Horiguchi follow_huge_addr(struct mm_struct *mm, unsigned long address,
491861f77edaSNaoya Horiguchi 			      int write)
491961f77edaSNaoya Horiguchi {
492061f77edaSNaoya Horiguchi 	return ERR_PTR(-EINVAL);
492161f77edaSNaoya Horiguchi }
492261f77edaSNaoya Horiguchi 
492361f77edaSNaoya Horiguchi struct page * __weak
49244dc71451SAneesh Kumar K.V follow_huge_pd(struct vm_area_struct *vma,
49254dc71451SAneesh Kumar K.V 	       unsigned long address, hugepd_t hpd, int flags, int pdshift)
49264dc71451SAneesh Kumar K.V {
49274dc71451SAneesh Kumar K.V 	WARN(1, "hugepd follow called with no support for hugepage directory format\n");
49284dc71451SAneesh Kumar K.V 	return NULL;
49294dc71451SAneesh Kumar K.V }
49304dc71451SAneesh Kumar K.V 
49314dc71451SAneesh Kumar K.V struct page * __weak
49329e5fc74cSSteve Capper follow_huge_pmd(struct mm_struct *mm, unsigned long address,
4933e66f17ffSNaoya Horiguchi 		pmd_t *pmd, int flags)
49349e5fc74cSSteve Capper {
4935e66f17ffSNaoya Horiguchi 	struct page *page = NULL;
4936e66f17ffSNaoya Horiguchi 	spinlock_t *ptl;
4937c9d398faSNaoya Horiguchi 	pte_t pte;
4938e66f17ffSNaoya Horiguchi retry:
4939e66f17ffSNaoya Horiguchi 	ptl = pmd_lockptr(mm, pmd);
4940e66f17ffSNaoya Horiguchi 	spin_lock(ptl);
4941e66f17ffSNaoya Horiguchi 	/*
4942e66f17ffSNaoya Horiguchi 	 * make sure that the address range covered by this pmd is not
4943e66f17ffSNaoya Horiguchi 	 * unmapped from other threads.
4944e66f17ffSNaoya Horiguchi 	 */
4945e66f17ffSNaoya Horiguchi 	if (!pmd_huge(*pmd))
4946e66f17ffSNaoya Horiguchi 		goto out;
4947c9d398faSNaoya Horiguchi 	pte = huge_ptep_get((pte_t *)pmd);
4948c9d398faSNaoya Horiguchi 	if (pte_present(pte)) {
494997534127SGerald Schaefer 		page = pmd_page(*pmd) + ((address & ~PMD_MASK) >> PAGE_SHIFT);
4950e66f17ffSNaoya Horiguchi 		if (flags & FOLL_GET)
4951e66f17ffSNaoya Horiguchi 			get_page(page);
4952e66f17ffSNaoya Horiguchi 	} else {
4953c9d398faSNaoya Horiguchi 		if (is_hugetlb_entry_migration(pte)) {
4954e66f17ffSNaoya Horiguchi 			spin_unlock(ptl);
4955e66f17ffSNaoya Horiguchi 			__migration_entry_wait(mm, (pte_t *)pmd, ptl);
4956e66f17ffSNaoya Horiguchi 			goto retry;
4957e66f17ffSNaoya Horiguchi 		}
4958e66f17ffSNaoya Horiguchi 		/*
4959e66f17ffSNaoya Horiguchi 		 * hwpoisoned entry is treated as no_page_table in
4960e66f17ffSNaoya Horiguchi 		 * follow_page_mask().
4961e66f17ffSNaoya Horiguchi 		 */
4962e66f17ffSNaoya Horiguchi 	}
4963e66f17ffSNaoya Horiguchi out:
4964e66f17ffSNaoya Horiguchi 	spin_unlock(ptl);
49659e5fc74cSSteve Capper 	return page;
49669e5fc74cSSteve Capper }
49679e5fc74cSSteve Capper 
496861f77edaSNaoya Horiguchi struct page * __weak
49699e5fc74cSSteve Capper follow_huge_pud(struct mm_struct *mm, unsigned long address,
4970e66f17ffSNaoya Horiguchi 		pud_t *pud, int flags)
49719e5fc74cSSteve Capper {
4972e66f17ffSNaoya Horiguchi 	if (flags & FOLL_GET)
4973e66f17ffSNaoya Horiguchi 		return NULL;
49749e5fc74cSSteve Capper 
4975e66f17ffSNaoya Horiguchi 	return pte_page(*(pte_t *)pud) + ((address & ~PUD_MASK) >> PAGE_SHIFT);
49769e5fc74cSSteve Capper }
49779e5fc74cSSteve Capper 
4978faaa5b62SAnshuman Khandual struct page * __weak
4979faaa5b62SAnshuman Khandual follow_huge_pgd(struct mm_struct *mm, unsigned long address, pgd_t *pgd, int flags)
4980faaa5b62SAnshuman Khandual {
4981faaa5b62SAnshuman Khandual 	if (flags & FOLL_GET)
4982faaa5b62SAnshuman Khandual 		return NULL;
4983faaa5b62SAnshuman Khandual 
4984faaa5b62SAnshuman Khandual 	return pte_page(*(pte_t *)pgd) + ((address & ~PGDIR_MASK) >> PAGE_SHIFT);
4985faaa5b62SAnshuman Khandual }
4986faaa5b62SAnshuman Khandual 
498731caf665SNaoya Horiguchi bool isolate_huge_page(struct page *page, struct list_head *list)
498831caf665SNaoya Horiguchi {
4989bcc54222SNaoya Horiguchi 	bool ret = true;
4990bcc54222SNaoya Horiguchi 
4991309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageHead(page), page);
499231caf665SNaoya Horiguchi 	spin_lock(&hugetlb_lock);
4993bcc54222SNaoya Horiguchi 	if (!page_huge_active(page) || !get_page_unless_zero(page)) {
4994bcc54222SNaoya Horiguchi 		ret = false;
4995bcc54222SNaoya Horiguchi 		goto unlock;
4996bcc54222SNaoya Horiguchi 	}
4997bcc54222SNaoya Horiguchi 	clear_page_huge_active(page);
499831caf665SNaoya Horiguchi 	list_move_tail(&page->lru, list);
4999bcc54222SNaoya Horiguchi unlock:
500031caf665SNaoya Horiguchi 	spin_unlock(&hugetlb_lock);
5001bcc54222SNaoya Horiguchi 	return ret;
500231caf665SNaoya Horiguchi }
500331caf665SNaoya Horiguchi 
500431caf665SNaoya Horiguchi void putback_active_hugepage(struct page *page)
500531caf665SNaoya Horiguchi {
5006309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageHead(page), page);
500731caf665SNaoya Horiguchi 	spin_lock(&hugetlb_lock);
5008bcc54222SNaoya Horiguchi 	set_page_huge_active(page);
500931caf665SNaoya Horiguchi 	list_move_tail(&page->lru, &(page_hstate(page))->hugepage_activelist);
501031caf665SNaoya Horiguchi 	spin_unlock(&hugetlb_lock);
501131caf665SNaoya Horiguchi 	put_page(page);
501231caf665SNaoya Horiguchi }
5013ab5ac90aSMichal Hocko 
5014ab5ac90aSMichal Hocko void move_hugetlb_state(struct page *oldpage, struct page *newpage, int reason)
5015ab5ac90aSMichal Hocko {
5016ab5ac90aSMichal Hocko 	struct hstate *h = page_hstate(oldpage);
5017ab5ac90aSMichal Hocko 
5018ab5ac90aSMichal Hocko 	hugetlb_cgroup_migrate(oldpage, newpage);
5019ab5ac90aSMichal Hocko 	set_page_owner_migrate_reason(newpage, reason);
5020ab5ac90aSMichal Hocko 
5021ab5ac90aSMichal Hocko 	/*
5022ab5ac90aSMichal Hocko 	 * transfer temporary state of the new huge page. This is
5023ab5ac90aSMichal Hocko 	 * reverse to other transitions because the newpage is going to
5024ab5ac90aSMichal Hocko 	 * be final while the old one will be freed so it takes over
5025ab5ac90aSMichal Hocko 	 * the temporary status.
5026ab5ac90aSMichal Hocko 	 *
5027ab5ac90aSMichal Hocko 	 * Also note that we have to transfer the per-node surplus state
5028ab5ac90aSMichal Hocko 	 * here as well otherwise the global surplus count will not match
5029ab5ac90aSMichal Hocko 	 * the per-node's.
5030ab5ac90aSMichal Hocko 	 */
5031ab5ac90aSMichal Hocko 	if (PageHugeTemporary(newpage)) {
5032ab5ac90aSMichal Hocko 		int old_nid = page_to_nid(oldpage);
5033ab5ac90aSMichal Hocko 		int new_nid = page_to_nid(newpage);
5034ab5ac90aSMichal Hocko 
5035ab5ac90aSMichal Hocko 		SetPageHugeTemporary(oldpage);
5036ab5ac90aSMichal Hocko 		ClearPageHugeTemporary(newpage);
5037ab5ac90aSMichal Hocko 
5038ab5ac90aSMichal Hocko 		spin_lock(&hugetlb_lock);
5039ab5ac90aSMichal Hocko 		if (h->surplus_huge_pages_node[old_nid]) {
5040ab5ac90aSMichal Hocko 			h->surplus_huge_pages_node[old_nid]--;
5041ab5ac90aSMichal Hocko 			h->surplus_huge_pages_node[new_nid]++;
5042ab5ac90aSMichal Hocko 		}
5043ab5ac90aSMichal Hocko 		spin_unlock(&hugetlb_lock);
5044ab5ac90aSMichal Hocko 	}
5045ab5ac90aSMichal Hocko }
5046