xref: /openbmc/linux/mm/hugetlb.c (revision e9fe92ae)
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>
30c77c0a8aSWaiman Long #include <linux/llist.h>
31d6606683SLinus Torvalds 
3263551ae0SDavid Gibson #include <asm/page.h>
3363551ae0SDavid Gibson #include <asm/pgtable.h>
3424669e58SAneesh Kumar K.V #include <asm/tlb.h>
3563551ae0SDavid Gibson 
3624669e58SAneesh Kumar K.V #include <linux/io.h>
3763551ae0SDavid Gibson #include <linux/hugetlb.h>
389dd540e2SAneesh Kumar K.V #include <linux/hugetlb_cgroup.h>
399a305230SLee Schermerhorn #include <linux/node.h>
401a1aad8aSMike Kravetz #include <linux/userfaultfd_k.h>
41ab5ac90aSMichal Hocko #include <linux/page_owner.h>
427835e98bSNick Piggin #include "internal.h"
431da177e4SLinus Torvalds 
44c3f38a38SAneesh Kumar K.V int hugetlb_max_hstate __read_mostly;
45e5ff2159SAndi Kleen unsigned int default_hstate_idx;
46e5ff2159SAndi Kleen struct hstate hstates[HUGE_MAX_HSTATE];
47641844f5SNaoya Horiguchi /*
48641844f5SNaoya Horiguchi  * Minimum page order among possible hugepage sizes, set to a proper value
49641844f5SNaoya Horiguchi  * at boot time.
50641844f5SNaoya Horiguchi  */
51641844f5SNaoya Horiguchi static unsigned int minimum_order __read_mostly = UINT_MAX;
52e5ff2159SAndi Kleen 
5353ba51d2SJon Tollefson __initdata LIST_HEAD(huge_boot_pages);
5453ba51d2SJon Tollefson 
55e5ff2159SAndi Kleen /* for command line parsing */
56e5ff2159SAndi Kleen static struct hstate * __initdata parsed_hstate;
57e5ff2159SAndi Kleen static unsigned long __initdata default_hstate_max_huge_pages;
58e11bfbfcSNick Piggin static unsigned long __initdata default_hstate_size;
599fee021dSVaishali Thakkar static bool __initdata parsed_valid_hugepagesz = true;
60e5ff2159SAndi Kleen 
613935baa9SDavid Gibson /*
6231caf665SNaoya Horiguchi  * Protects updates to hugepage_freelists, hugepage_activelist, nr_huge_pages,
6331caf665SNaoya Horiguchi  * free_huge_pages, and surplus_huge_pages.
643935baa9SDavid Gibson  */
65c3f38a38SAneesh Kumar K.V DEFINE_SPINLOCK(hugetlb_lock);
660bd0f9fbSEric Paris 
678382d914SDavidlohr Bueso /*
688382d914SDavidlohr Bueso  * Serializes faults on the same logical page.  This is used to
698382d914SDavidlohr Bueso  * prevent spurious OOMs when the hugepage pool is fully utilized.
708382d914SDavidlohr Bueso  */
718382d914SDavidlohr Bueso static int num_fault_mutexes;
72c672c7f2SMike Kravetz struct mutex *hugetlb_fault_mutex_table ____cacheline_aligned_in_smp;
738382d914SDavidlohr Bueso 
747ca02d0aSMike Kravetz /* Forward declaration */
757ca02d0aSMike Kravetz static int hugetlb_acct_memory(struct hstate *h, long delta);
767ca02d0aSMike Kravetz 
7790481622SDavid Gibson static inline void unlock_or_release_subpool(struct hugepage_subpool *spool)
7890481622SDavid Gibson {
7990481622SDavid Gibson 	bool free = (spool->count == 0) && (spool->used_hpages == 0);
8090481622SDavid Gibson 
8190481622SDavid Gibson 	spin_unlock(&spool->lock);
8290481622SDavid Gibson 
8390481622SDavid Gibson 	/* If no pages are used, and no other handles to the subpool
847ca02d0aSMike Kravetz 	 * remain, give up any reservations mased on minimum size and
857ca02d0aSMike Kravetz 	 * free the subpool */
867ca02d0aSMike Kravetz 	if (free) {
877ca02d0aSMike Kravetz 		if (spool->min_hpages != -1)
887ca02d0aSMike Kravetz 			hugetlb_acct_memory(spool->hstate,
897ca02d0aSMike Kravetz 						-spool->min_hpages);
9090481622SDavid Gibson 		kfree(spool);
9190481622SDavid Gibson 	}
927ca02d0aSMike Kravetz }
9390481622SDavid Gibson 
947ca02d0aSMike Kravetz struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages,
957ca02d0aSMike Kravetz 						long min_hpages)
9690481622SDavid Gibson {
9790481622SDavid Gibson 	struct hugepage_subpool *spool;
9890481622SDavid Gibson 
99c6a91820SMike Kravetz 	spool = kzalloc(sizeof(*spool), GFP_KERNEL);
10090481622SDavid Gibson 	if (!spool)
10190481622SDavid Gibson 		return NULL;
10290481622SDavid Gibson 
10390481622SDavid Gibson 	spin_lock_init(&spool->lock);
10490481622SDavid Gibson 	spool->count = 1;
1057ca02d0aSMike Kravetz 	spool->max_hpages = max_hpages;
1067ca02d0aSMike Kravetz 	spool->hstate = h;
1077ca02d0aSMike Kravetz 	spool->min_hpages = min_hpages;
1087ca02d0aSMike Kravetz 
1097ca02d0aSMike Kravetz 	if (min_hpages != -1 && hugetlb_acct_memory(h, min_hpages)) {
1107ca02d0aSMike Kravetz 		kfree(spool);
1117ca02d0aSMike Kravetz 		return NULL;
1127ca02d0aSMike Kravetz 	}
1137ca02d0aSMike Kravetz 	spool->rsv_hpages = min_hpages;
11490481622SDavid Gibson 
11590481622SDavid Gibson 	return spool;
11690481622SDavid Gibson }
11790481622SDavid Gibson 
11890481622SDavid Gibson void hugepage_put_subpool(struct hugepage_subpool *spool)
11990481622SDavid Gibson {
12090481622SDavid Gibson 	spin_lock(&spool->lock);
12190481622SDavid Gibson 	BUG_ON(!spool->count);
12290481622SDavid Gibson 	spool->count--;
12390481622SDavid Gibson 	unlock_or_release_subpool(spool);
12490481622SDavid Gibson }
12590481622SDavid Gibson 
1261c5ecae3SMike Kravetz /*
1271c5ecae3SMike Kravetz  * Subpool accounting for allocating and reserving pages.
1281c5ecae3SMike Kravetz  * Return -ENOMEM if there are not enough resources to satisfy the
1291c5ecae3SMike Kravetz  * the request.  Otherwise, return the number of pages by which the
1301c5ecae3SMike Kravetz  * global pools must be adjusted (upward).  The returned value may
1311c5ecae3SMike Kravetz  * only be different than the passed value (delta) in the case where
1321c5ecae3SMike Kravetz  * a subpool minimum size must be manitained.
1331c5ecae3SMike Kravetz  */
1341c5ecae3SMike Kravetz static long hugepage_subpool_get_pages(struct hugepage_subpool *spool,
13590481622SDavid Gibson 				      long delta)
13690481622SDavid Gibson {
1371c5ecae3SMike Kravetz 	long ret = delta;
13890481622SDavid Gibson 
13990481622SDavid Gibson 	if (!spool)
1401c5ecae3SMike Kravetz 		return ret;
14190481622SDavid Gibson 
14290481622SDavid Gibson 	spin_lock(&spool->lock);
14390481622SDavid Gibson 
1441c5ecae3SMike Kravetz 	if (spool->max_hpages != -1) {		/* maximum size accounting */
1451c5ecae3SMike Kravetz 		if ((spool->used_hpages + delta) <= spool->max_hpages)
1461c5ecae3SMike Kravetz 			spool->used_hpages += delta;
1471c5ecae3SMike Kravetz 		else {
1481c5ecae3SMike Kravetz 			ret = -ENOMEM;
1491c5ecae3SMike Kravetz 			goto unlock_ret;
1501c5ecae3SMike Kravetz 		}
1511c5ecae3SMike Kravetz 	}
1521c5ecae3SMike Kravetz 
15309a95e29SMike Kravetz 	/* minimum size accounting */
15409a95e29SMike Kravetz 	if (spool->min_hpages != -1 && spool->rsv_hpages) {
1551c5ecae3SMike Kravetz 		if (delta > spool->rsv_hpages) {
1561c5ecae3SMike Kravetz 			/*
1571c5ecae3SMike Kravetz 			 * Asking for more reserves than those already taken on
1581c5ecae3SMike Kravetz 			 * behalf of subpool.  Return difference.
1591c5ecae3SMike Kravetz 			 */
1601c5ecae3SMike Kravetz 			ret = delta - spool->rsv_hpages;
1611c5ecae3SMike Kravetz 			spool->rsv_hpages = 0;
1621c5ecae3SMike Kravetz 		} else {
1631c5ecae3SMike Kravetz 			ret = 0;	/* reserves already accounted for */
1641c5ecae3SMike Kravetz 			spool->rsv_hpages -= delta;
1651c5ecae3SMike Kravetz 		}
1661c5ecae3SMike Kravetz 	}
1671c5ecae3SMike Kravetz 
1681c5ecae3SMike Kravetz unlock_ret:
1691c5ecae3SMike Kravetz 	spin_unlock(&spool->lock);
17090481622SDavid Gibson 	return ret;
17190481622SDavid Gibson }
17290481622SDavid Gibson 
1731c5ecae3SMike Kravetz /*
1741c5ecae3SMike Kravetz  * Subpool accounting for freeing and unreserving pages.
1751c5ecae3SMike Kravetz  * Return the number of global page reservations that must be dropped.
1761c5ecae3SMike Kravetz  * The return value may only be different than the passed value (delta)
1771c5ecae3SMike Kravetz  * in the case where a subpool minimum size must be maintained.
1781c5ecae3SMike Kravetz  */
1791c5ecae3SMike Kravetz static long hugepage_subpool_put_pages(struct hugepage_subpool *spool,
18090481622SDavid Gibson 				       long delta)
18190481622SDavid Gibson {
1821c5ecae3SMike Kravetz 	long ret = delta;
1831c5ecae3SMike Kravetz 
18490481622SDavid Gibson 	if (!spool)
1851c5ecae3SMike Kravetz 		return delta;
18690481622SDavid Gibson 
18790481622SDavid Gibson 	spin_lock(&spool->lock);
1881c5ecae3SMike Kravetz 
1891c5ecae3SMike Kravetz 	if (spool->max_hpages != -1)		/* maximum size accounting */
19090481622SDavid Gibson 		spool->used_hpages -= delta;
1911c5ecae3SMike Kravetz 
19209a95e29SMike Kravetz 	 /* minimum size accounting */
19309a95e29SMike Kravetz 	if (spool->min_hpages != -1 && spool->used_hpages < spool->min_hpages) {
1941c5ecae3SMike Kravetz 		if (spool->rsv_hpages + delta <= spool->min_hpages)
1951c5ecae3SMike Kravetz 			ret = 0;
1961c5ecae3SMike Kravetz 		else
1971c5ecae3SMike Kravetz 			ret = spool->rsv_hpages + delta - spool->min_hpages;
1981c5ecae3SMike Kravetz 
1991c5ecae3SMike Kravetz 		spool->rsv_hpages += delta;
2001c5ecae3SMike Kravetz 		if (spool->rsv_hpages > spool->min_hpages)
2011c5ecae3SMike Kravetz 			spool->rsv_hpages = spool->min_hpages;
2021c5ecae3SMike Kravetz 	}
2031c5ecae3SMike Kravetz 
2041c5ecae3SMike Kravetz 	/*
2051c5ecae3SMike Kravetz 	 * If hugetlbfs_put_super couldn't free spool due to an outstanding
2061c5ecae3SMike Kravetz 	 * quota reference, free it now.
2071c5ecae3SMike Kravetz 	 */
20890481622SDavid Gibson 	unlock_or_release_subpool(spool);
2091c5ecae3SMike Kravetz 
2101c5ecae3SMike Kravetz 	return ret;
21190481622SDavid Gibson }
21290481622SDavid Gibson 
21390481622SDavid Gibson static inline struct hugepage_subpool *subpool_inode(struct inode *inode)
21490481622SDavid Gibson {
21590481622SDavid Gibson 	return HUGETLBFS_SB(inode->i_sb)->spool;
21690481622SDavid Gibson }
21790481622SDavid Gibson 
21890481622SDavid Gibson static inline struct hugepage_subpool *subpool_vma(struct vm_area_struct *vma)
21990481622SDavid Gibson {
220496ad9aaSAl Viro 	return subpool_inode(file_inode(vma->vm_file));
22190481622SDavid Gibson }
22290481622SDavid Gibson 
223e7c4b0bfSAndy Whitcroft /*
22496822904SAndy Whitcroft  * Region tracking -- allows tracking of reservations and instantiated pages
22596822904SAndy Whitcroft  *                    across the pages in a mapping.
22684afd99bSAndy Whitcroft  *
2271dd308a7SMike Kravetz  * The region data structures are embedded into a resv_map and protected
2281dd308a7SMike Kravetz  * by a resv_map's lock.  The set of regions within the resv_map represent
2291dd308a7SMike Kravetz  * reservations for huge pages, or huge pages that have already been
2301dd308a7SMike Kravetz  * instantiated within the map.  The from and to elements are huge page
2311dd308a7SMike Kravetz  * indicies into the associated mapping.  from indicates the starting index
2321dd308a7SMike Kravetz  * of the region.  to represents the first index past the end of  the region.
2331dd308a7SMike Kravetz  *
2341dd308a7SMike Kravetz  * For example, a file region structure with from == 0 and to == 4 represents
2351dd308a7SMike Kravetz  * four huge pages in a mapping.  It is important to note that the to element
2361dd308a7SMike Kravetz  * represents the first element past the end of the region. This is used in
2371dd308a7SMike Kravetz  * arithmetic as 4(to) - 0(from) = 4 huge pages in the region.
2381dd308a7SMike Kravetz  *
2391dd308a7SMike Kravetz  * Interval notation of the form [from, to) will be used to indicate that
2401dd308a7SMike Kravetz  * the endpoint from is inclusive and to is exclusive.
24196822904SAndy Whitcroft  */
24296822904SAndy Whitcroft struct file_region {
24396822904SAndy Whitcroft 	struct list_head link;
24496822904SAndy Whitcroft 	long from;
24596822904SAndy Whitcroft 	long to;
24696822904SAndy Whitcroft };
24796822904SAndy Whitcroft 
248d75c6af9SMina Almasry /* Must be called with resv->lock held. Calling this with count_only == true
249d75c6af9SMina Almasry  * will count the number of pages to be added but will not modify the linked
250d75c6af9SMina Almasry  * list.
251d75c6af9SMina Almasry  */
252d75c6af9SMina Almasry static long add_reservation_in_range(struct resv_map *resv, long f, long t,
253d75c6af9SMina Almasry 				     bool count_only)
254d75c6af9SMina Almasry {
255d75c6af9SMina Almasry 	long chg = 0;
256d75c6af9SMina Almasry 	struct list_head *head = &resv->regions;
257d75c6af9SMina Almasry 	struct file_region *rg = NULL, *trg = NULL, *nrg = NULL;
258d75c6af9SMina Almasry 
259d75c6af9SMina Almasry 	/* Locate the region we are before or in. */
260d75c6af9SMina Almasry 	list_for_each_entry(rg, head, link)
261d75c6af9SMina Almasry 		if (f <= rg->to)
262d75c6af9SMina Almasry 			break;
263d75c6af9SMina Almasry 
264d75c6af9SMina Almasry 	/* Round our left edge to the current segment if it encloses us. */
265d75c6af9SMina Almasry 	if (f > rg->from)
266d75c6af9SMina Almasry 		f = rg->from;
267d75c6af9SMina Almasry 
268d75c6af9SMina Almasry 	chg = t - f;
269d75c6af9SMina Almasry 
270d75c6af9SMina Almasry 	/* Check for and consume any regions we now overlap with. */
271d75c6af9SMina Almasry 	nrg = rg;
272d75c6af9SMina Almasry 	list_for_each_entry_safe(rg, trg, rg->link.prev, link) {
273d75c6af9SMina Almasry 		if (&rg->link == head)
274d75c6af9SMina Almasry 			break;
275d75c6af9SMina Almasry 		if (rg->from > t)
276d75c6af9SMina Almasry 			break;
277d75c6af9SMina Almasry 
278d75c6af9SMina Almasry 		/* We overlap with this area, if it extends further than
279d75c6af9SMina Almasry 		 * us then we must extend ourselves.  Account for its
280d75c6af9SMina Almasry 		 * existing reservation.
281d75c6af9SMina Almasry 		 */
282d75c6af9SMina Almasry 		if (rg->to > t) {
283d75c6af9SMina Almasry 			chg += rg->to - t;
284d75c6af9SMina Almasry 			t = rg->to;
285d75c6af9SMina Almasry 		}
286d75c6af9SMina Almasry 		chg -= rg->to - rg->from;
287d75c6af9SMina Almasry 
288d75c6af9SMina Almasry 		if (!count_only && rg != nrg) {
289d75c6af9SMina Almasry 			list_del(&rg->link);
290d75c6af9SMina Almasry 			kfree(rg);
291d75c6af9SMina Almasry 		}
292d75c6af9SMina Almasry 	}
293d75c6af9SMina Almasry 
294d75c6af9SMina Almasry 	if (!count_only) {
295d75c6af9SMina Almasry 		nrg->from = f;
296d75c6af9SMina Almasry 		nrg->to = t;
297d75c6af9SMina Almasry 	}
298d75c6af9SMina Almasry 
299d75c6af9SMina Almasry 	return chg;
300d75c6af9SMina Almasry }
301d75c6af9SMina Almasry 
3021dd308a7SMike Kravetz /*
3031dd308a7SMike Kravetz  * Add the huge page range represented by [f, t) to the reserve
3045c911954SMina Almasry  * map.  Existing regions will be expanded to accommodate the specified
3055c911954SMina Almasry  * range, or a region will be taken from the cache.  Sufficient regions
3065c911954SMina Almasry  * must exist in the cache due to the previous call to region_chg with
3075c911954SMina Almasry  * the same range.
308cf3ad20bSMike Kravetz  *
309cf3ad20bSMike Kravetz  * Return the number of new huge pages added to the map.  This
310cf3ad20bSMike Kravetz  * number is greater than or equal to zero.
3111dd308a7SMike Kravetz  */
3121406ec9bSJoonsoo Kim static long region_add(struct resv_map *resv, long f, long t)
31396822904SAndy Whitcroft {
3141406ec9bSJoonsoo Kim 	struct list_head *head = &resv->regions;
315d75c6af9SMina Almasry 	struct file_region *rg, *nrg;
316cf3ad20bSMike Kravetz 	long add = 0;
31796822904SAndy Whitcroft 
3187b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
31996822904SAndy Whitcroft 	/* Locate the region we are either in or before. */
32096822904SAndy Whitcroft 	list_for_each_entry(rg, head, link)
32196822904SAndy Whitcroft 		if (f <= rg->to)
32296822904SAndy Whitcroft 			break;
32396822904SAndy Whitcroft 
3245e911373SMike Kravetz 	/*
3255e911373SMike Kravetz 	 * If no region exists which can be expanded to include the
3265c911954SMina Almasry 	 * specified range, pull a region descriptor from the cache
3275c911954SMina Almasry 	 * and use it for this range.
3285e911373SMike Kravetz 	 */
3295e911373SMike Kravetz 	if (&rg->link == head || t < rg->from) {
3305e911373SMike Kravetz 		VM_BUG_ON(resv->region_cache_count <= 0);
3315e911373SMike Kravetz 
3325e911373SMike Kravetz 		resv->region_cache_count--;
3335e911373SMike Kravetz 		nrg = list_first_entry(&resv->region_cache, struct file_region,
3345e911373SMike Kravetz 					link);
3355e911373SMike Kravetz 		list_del(&nrg->link);
3365e911373SMike Kravetz 
3375e911373SMike Kravetz 		nrg->from = f;
3385e911373SMike Kravetz 		nrg->to = t;
3395e911373SMike Kravetz 		list_add(&nrg->link, rg->link.prev);
3405e911373SMike Kravetz 
3415e911373SMike Kravetz 		add += t - f;
3425e911373SMike Kravetz 		goto out_locked;
3435e911373SMike Kravetz 	}
3445e911373SMike Kravetz 
345d75c6af9SMina Almasry 	add = add_reservation_in_range(resv, f, t, false);
346cf3ad20bSMike Kravetz 
3475e911373SMike Kravetz out_locked:
3485e911373SMike Kravetz 	resv->adds_in_progress--;
3497b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
350cf3ad20bSMike Kravetz 	VM_BUG_ON(add < 0);
351cf3ad20bSMike Kravetz 	return add;
35296822904SAndy Whitcroft }
35396822904SAndy Whitcroft 
3541dd308a7SMike Kravetz /*
3551dd308a7SMike Kravetz  * Examine the existing reserve map and determine how many
3561dd308a7SMike Kravetz  * huge pages in the specified range [f, t) are NOT currently
3571dd308a7SMike Kravetz  * represented.  This routine is called before a subsequent
3581dd308a7SMike Kravetz  * call to region_add that will actually modify the reserve
3591dd308a7SMike Kravetz  * map to add the specified range [f, t).  region_chg does
3601dd308a7SMike Kravetz  * not change the number of huge pages represented by the
3615c911954SMina Almasry  * map.  A new file_region structure is added to the cache
3625c911954SMina Almasry  * as a placeholder, so that the subsequent region_add
3635c911954SMina Almasry  * call will have all the regions it needs and will not fail.
3645e911373SMike Kravetz  *
3655e911373SMike Kravetz  * Returns the number of huge pages that need to be added to the existing
3665e911373SMike Kravetz  * reservation map for the range [f, t).  This number is greater or equal to
3675e911373SMike Kravetz  * zero.  -ENOMEM is returned if a new file_region structure or cache entry
3685e911373SMike Kravetz  * is needed and can not be allocated.
3691dd308a7SMike Kravetz  */
3701406ec9bSJoonsoo Kim static long region_chg(struct resv_map *resv, long f, long t)
37196822904SAndy Whitcroft {
37296822904SAndy Whitcroft 	long chg = 0;
37396822904SAndy Whitcroft 
3747b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
3755e911373SMike Kravetz retry_locked:
3765e911373SMike Kravetz 	resv->adds_in_progress++;
3775e911373SMike Kravetz 
3785e911373SMike Kravetz 	/*
3795e911373SMike Kravetz 	 * Check for sufficient descriptors in the cache to accommodate
3805e911373SMike Kravetz 	 * the number of in progress add operations.
3815e911373SMike Kravetz 	 */
3825e911373SMike Kravetz 	if (resv->adds_in_progress > resv->region_cache_count) {
3835e911373SMike Kravetz 		struct file_region *trg;
3845e911373SMike Kravetz 
3855e911373SMike Kravetz 		VM_BUG_ON(resv->adds_in_progress - resv->region_cache_count > 1);
3865e911373SMike Kravetz 		/* Must drop lock to allocate a new descriptor. */
3875e911373SMike Kravetz 		resv->adds_in_progress--;
3885e911373SMike Kravetz 		spin_unlock(&resv->lock);
3895e911373SMike Kravetz 
3905e911373SMike Kravetz 		trg = kmalloc(sizeof(*trg), GFP_KERNEL);
3915c911954SMina Almasry 		if (!trg)
3925e911373SMike Kravetz 			return -ENOMEM;
3935e911373SMike Kravetz 
3945e911373SMike Kravetz 		spin_lock(&resv->lock);
3955e911373SMike Kravetz 		list_add(&trg->link, &resv->region_cache);
3965e911373SMike Kravetz 		resv->region_cache_count++;
3975e911373SMike Kravetz 		goto retry_locked;
3985e911373SMike Kravetz 	}
3995e911373SMike Kravetz 
400d75c6af9SMina Almasry 	chg = add_reservation_in_range(resv, f, t, true);
40196822904SAndy Whitcroft 
4027b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
40396822904SAndy Whitcroft 	return chg;
40496822904SAndy Whitcroft }
40596822904SAndy Whitcroft 
4061dd308a7SMike Kravetz /*
4075e911373SMike Kravetz  * Abort the in progress add operation.  The adds_in_progress field
4085e911373SMike Kravetz  * of the resv_map keeps track of the operations in progress between
4095e911373SMike Kravetz  * calls to region_chg and region_add.  Operations are sometimes
4105e911373SMike Kravetz  * aborted after the call to region_chg.  In such cases, region_abort
4115e911373SMike Kravetz  * is called to decrement the adds_in_progress counter.
4125e911373SMike Kravetz  *
4135e911373SMike Kravetz  * NOTE: The range arguments [f, t) are not needed or used in this
4145e911373SMike Kravetz  * routine.  They are kept to make reading the calling code easier as
4155e911373SMike Kravetz  * arguments will match the associated region_chg call.
4165e911373SMike Kravetz  */
4175e911373SMike Kravetz static void region_abort(struct resv_map *resv, long f, long t)
4185e911373SMike Kravetz {
4195e911373SMike Kravetz 	spin_lock(&resv->lock);
4205e911373SMike Kravetz 	VM_BUG_ON(!resv->region_cache_count);
4215e911373SMike Kravetz 	resv->adds_in_progress--;
4225e911373SMike Kravetz 	spin_unlock(&resv->lock);
4235e911373SMike Kravetz }
4245e911373SMike Kravetz 
4255e911373SMike Kravetz /*
426feba16e2SMike Kravetz  * Delete the specified range [f, t) from the reserve map.  If the
427feba16e2SMike Kravetz  * t parameter is LONG_MAX, this indicates that ALL regions after f
428feba16e2SMike Kravetz  * should be deleted.  Locate the regions which intersect [f, t)
429feba16e2SMike Kravetz  * and either trim, delete or split the existing regions.
430feba16e2SMike Kravetz  *
431feba16e2SMike Kravetz  * Returns the number of huge pages deleted from the reserve map.
432feba16e2SMike Kravetz  * In the normal case, the return value is zero or more.  In the
433feba16e2SMike Kravetz  * case where a region must be split, a new region descriptor must
434feba16e2SMike Kravetz  * be allocated.  If the allocation fails, -ENOMEM will be returned.
435feba16e2SMike Kravetz  * NOTE: If the parameter t == LONG_MAX, then we will never split
436feba16e2SMike Kravetz  * a region and possibly return -ENOMEM.  Callers specifying
437feba16e2SMike Kravetz  * t == LONG_MAX do not need to check for -ENOMEM error.
4381dd308a7SMike Kravetz  */
439feba16e2SMike Kravetz static long region_del(struct resv_map *resv, long f, long t)
44096822904SAndy Whitcroft {
4411406ec9bSJoonsoo Kim 	struct list_head *head = &resv->regions;
44296822904SAndy Whitcroft 	struct file_region *rg, *trg;
443feba16e2SMike Kravetz 	struct file_region *nrg = NULL;
444feba16e2SMike Kravetz 	long del = 0;
44596822904SAndy Whitcroft 
446feba16e2SMike Kravetz retry:
4477b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
448feba16e2SMike Kravetz 	list_for_each_entry_safe(rg, trg, head, link) {
449dbe409e4SMike Kravetz 		/*
450dbe409e4SMike Kravetz 		 * Skip regions before the range to be deleted.  file_region
451dbe409e4SMike Kravetz 		 * ranges are normally of the form [from, to).  However, there
452dbe409e4SMike Kravetz 		 * may be a "placeholder" entry in the map which is of the form
453dbe409e4SMike Kravetz 		 * (from, to) with from == to.  Check for placeholder entries
454dbe409e4SMike Kravetz 		 * at the beginning of the range to be deleted.
455dbe409e4SMike Kravetz 		 */
456dbe409e4SMike Kravetz 		if (rg->to <= f && (rg->to != rg->from || rg->to != f))
457feba16e2SMike Kravetz 			continue;
458dbe409e4SMike Kravetz 
459feba16e2SMike Kravetz 		if (rg->from >= t)
46096822904SAndy Whitcroft 			break;
46196822904SAndy Whitcroft 
462feba16e2SMike Kravetz 		if (f > rg->from && t < rg->to) { /* Must split region */
463feba16e2SMike Kravetz 			/*
464feba16e2SMike Kravetz 			 * Check for an entry in the cache before dropping
465feba16e2SMike Kravetz 			 * lock and attempting allocation.
466feba16e2SMike Kravetz 			 */
467feba16e2SMike Kravetz 			if (!nrg &&
468feba16e2SMike Kravetz 			    resv->region_cache_count > resv->adds_in_progress) {
469feba16e2SMike Kravetz 				nrg = list_first_entry(&resv->region_cache,
470feba16e2SMike Kravetz 							struct file_region,
471feba16e2SMike Kravetz 							link);
472feba16e2SMike Kravetz 				list_del(&nrg->link);
473feba16e2SMike Kravetz 				resv->region_cache_count--;
47496822904SAndy Whitcroft 			}
47596822904SAndy Whitcroft 
476feba16e2SMike Kravetz 			if (!nrg) {
477feba16e2SMike Kravetz 				spin_unlock(&resv->lock);
478feba16e2SMike Kravetz 				nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
479feba16e2SMike Kravetz 				if (!nrg)
480feba16e2SMike Kravetz 					return -ENOMEM;
481feba16e2SMike Kravetz 				goto retry;
482feba16e2SMike Kravetz 			}
483feba16e2SMike Kravetz 
484feba16e2SMike Kravetz 			del += t - f;
485feba16e2SMike Kravetz 
486feba16e2SMike Kravetz 			/* New entry for end of split region */
487feba16e2SMike Kravetz 			nrg->from = t;
488feba16e2SMike Kravetz 			nrg->to = rg->to;
489feba16e2SMike Kravetz 			INIT_LIST_HEAD(&nrg->link);
490feba16e2SMike Kravetz 
491feba16e2SMike Kravetz 			/* Original entry is trimmed */
492feba16e2SMike Kravetz 			rg->to = f;
493feba16e2SMike Kravetz 
494feba16e2SMike Kravetz 			list_add(&nrg->link, &rg->link);
495feba16e2SMike Kravetz 			nrg = NULL;
49696822904SAndy Whitcroft 			break;
497feba16e2SMike Kravetz 		}
498feba16e2SMike Kravetz 
499feba16e2SMike Kravetz 		if (f <= rg->from && t >= rg->to) { /* Remove entire region */
500feba16e2SMike Kravetz 			del += rg->to - rg->from;
50196822904SAndy Whitcroft 			list_del(&rg->link);
50296822904SAndy Whitcroft 			kfree(rg);
503feba16e2SMike Kravetz 			continue;
50496822904SAndy Whitcroft 		}
5057b24d861SDavidlohr Bueso 
506feba16e2SMike Kravetz 		if (f <= rg->from) {	/* Trim beginning of region */
507feba16e2SMike Kravetz 			del += t - rg->from;
508feba16e2SMike Kravetz 			rg->from = t;
509feba16e2SMike Kravetz 		} else {		/* Trim end of region */
510feba16e2SMike Kravetz 			del += rg->to - f;
511feba16e2SMike Kravetz 			rg->to = f;
512feba16e2SMike Kravetz 		}
513feba16e2SMike Kravetz 	}
514feba16e2SMike Kravetz 
5157b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
516feba16e2SMike Kravetz 	kfree(nrg);
517feba16e2SMike Kravetz 	return del;
51896822904SAndy Whitcroft }
51996822904SAndy Whitcroft 
5201dd308a7SMike Kravetz /*
521b5cec28dSMike Kravetz  * A rare out of memory error was encountered which prevented removal of
522b5cec28dSMike Kravetz  * the reserve map region for a page.  The huge page itself was free'ed
523b5cec28dSMike Kravetz  * and removed from the page cache.  This routine will adjust the subpool
524b5cec28dSMike Kravetz  * usage count, and the global reserve count if needed.  By incrementing
525b5cec28dSMike Kravetz  * these counts, the reserve map entry which could not be deleted will
526b5cec28dSMike Kravetz  * appear as a "reserved" entry instead of simply dangling with incorrect
527b5cec28dSMike Kravetz  * counts.
528b5cec28dSMike Kravetz  */
52972e2936cSzhong jiang void hugetlb_fix_reserve_counts(struct inode *inode)
530b5cec28dSMike Kravetz {
531b5cec28dSMike Kravetz 	struct hugepage_subpool *spool = subpool_inode(inode);
532b5cec28dSMike Kravetz 	long rsv_adjust;
533b5cec28dSMike Kravetz 
534b5cec28dSMike Kravetz 	rsv_adjust = hugepage_subpool_get_pages(spool, 1);
53572e2936cSzhong jiang 	if (rsv_adjust) {
536b5cec28dSMike Kravetz 		struct hstate *h = hstate_inode(inode);
537b5cec28dSMike Kravetz 
538b5cec28dSMike Kravetz 		hugetlb_acct_memory(h, 1);
539b5cec28dSMike Kravetz 	}
540b5cec28dSMike Kravetz }
541b5cec28dSMike Kravetz 
542b5cec28dSMike Kravetz /*
5431dd308a7SMike Kravetz  * Count and return the number of huge pages in the reserve map
5441dd308a7SMike Kravetz  * that intersect with the range [f, t).
5451dd308a7SMike Kravetz  */
5461406ec9bSJoonsoo Kim static long region_count(struct resv_map *resv, long f, long t)
54784afd99bSAndy Whitcroft {
5481406ec9bSJoonsoo Kim 	struct list_head *head = &resv->regions;
54984afd99bSAndy Whitcroft 	struct file_region *rg;
55084afd99bSAndy Whitcroft 	long chg = 0;
55184afd99bSAndy Whitcroft 
5527b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
55384afd99bSAndy Whitcroft 	/* Locate each segment we overlap with, and count that overlap. */
55484afd99bSAndy Whitcroft 	list_for_each_entry(rg, head, link) {
555f2135a4aSWang Sheng-Hui 		long seg_from;
556f2135a4aSWang Sheng-Hui 		long seg_to;
55784afd99bSAndy Whitcroft 
55884afd99bSAndy Whitcroft 		if (rg->to <= f)
55984afd99bSAndy Whitcroft 			continue;
56084afd99bSAndy Whitcroft 		if (rg->from >= t)
56184afd99bSAndy Whitcroft 			break;
56284afd99bSAndy Whitcroft 
56384afd99bSAndy Whitcroft 		seg_from = max(rg->from, f);
56484afd99bSAndy Whitcroft 		seg_to = min(rg->to, t);
56584afd99bSAndy Whitcroft 
56684afd99bSAndy Whitcroft 		chg += seg_to - seg_from;
56784afd99bSAndy Whitcroft 	}
5687b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
56984afd99bSAndy Whitcroft 
57084afd99bSAndy Whitcroft 	return chg;
57184afd99bSAndy Whitcroft }
57284afd99bSAndy Whitcroft 
57396822904SAndy Whitcroft /*
574e7c4b0bfSAndy Whitcroft  * Convert the address within this vma to the page offset within
575e7c4b0bfSAndy Whitcroft  * the mapping, in pagecache page units; huge pages here.
576e7c4b0bfSAndy Whitcroft  */
577a5516438SAndi Kleen static pgoff_t vma_hugecache_offset(struct hstate *h,
578a5516438SAndi Kleen 			struct vm_area_struct *vma, unsigned long address)
579e7c4b0bfSAndy Whitcroft {
580a5516438SAndi Kleen 	return ((address - vma->vm_start) >> huge_page_shift(h)) +
581a5516438SAndi Kleen 			(vma->vm_pgoff >> huge_page_order(h));
582e7c4b0bfSAndy Whitcroft }
583e7c4b0bfSAndy Whitcroft 
5840fe6e20bSNaoya Horiguchi pgoff_t linear_hugepage_index(struct vm_area_struct *vma,
5850fe6e20bSNaoya Horiguchi 				     unsigned long address)
5860fe6e20bSNaoya Horiguchi {
5870fe6e20bSNaoya Horiguchi 	return vma_hugecache_offset(hstate_vma(vma), vma, address);
5880fe6e20bSNaoya Horiguchi }
589dee41079SDan Williams EXPORT_SYMBOL_GPL(linear_hugepage_index);
5900fe6e20bSNaoya Horiguchi 
59184afd99bSAndy Whitcroft /*
59208fba699SMel Gorman  * Return the size of the pages allocated when backing a VMA. In the majority
59308fba699SMel Gorman  * cases this will be same size as used by the page table entries.
59408fba699SMel Gorman  */
59508fba699SMel Gorman unsigned long vma_kernel_pagesize(struct vm_area_struct *vma)
59608fba699SMel Gorman {
59705ea8860SDan Williams 	if (vma->vm_ops && vma->vm_ops->pagesize)
59805ea8860SDan Williams 		return vma->vm_ops->pagesize(vma);
59908fba699SMel Gorman 	return PAGE_SIZE;
60008fba699SMel Gorman }
601f340ca0fSJoerg Roedel EXPORT_SYMBOL_GPL(vma_kernel_pagesize);
60208fba699SMel Gorman 
60308fba699SMel Gorman /*
6043340289dSMel Gorman  * Return the page size being used by the MMU to back a VMA. In the majority
6053340289dSMel Gorman  * of cases, the page size used by the kernel matches the MMU size. On
60609135cc5SDan Williams  * architectures where it differs, an architecture-specific 'strong'
60709135cc5SDan Williams  * version of this symbol is required.
6083340289dSMel Gorman  */
60909135cc5SDan Williams __weak unsigned long vma_mmu_pagesize(struct vm_area_struct *vma)
6103340289dSMel Gorman {
6113340289dSMel Gorman 	return vma_kernel_pagesize(vma);
6123340289dSMel Gorman }
6133340289dSMel Gorman 
6143340289dSMel Gorman /*
61584afd99bSAndy Whitcroft  * Flags for MAP_PRIVATE reservations.  These are stored in the bottom
61684afd99bSAndy Whitcroft  * bits of the reservation map pointer, which are always clear due to
61784afd99bSAndy Whitcroft  * alignment.
61884afd99bSAndy Whitcroft  */
61984afd99bSAndy Whitcroft #define HPAGE_RESV_OWNER    (1UL << 0)
62084afd99bSAndy Whitcroft #define HPAGE_RESV_UNMAPPED (1UL << 1)
62104f2cbe3SMel Gorman #define HPAGE_RESV_MASK (HPAGE_RESV_OWNER | HPAGE_RESV_UNMAPPED)
62284afd99bSAndy Whitcroft 
623a1e78772SMel Gorman /*
624a1e78772SMel Gorman  * These helpers are used to track how many pages are reserved for
625a1e78772SMel Gorman  * faults in a MAP_PRIVATE mapping. Only the process that called mmap()
626a1e78772SMel Gorman  * is guaranteed to have their future faults succeed.
627a1e78772SMel Gorman  *
628a1e78772SMel Gorman  * With the exception of reset_vma_resv_huge_pages() which is called at fork(),
629a1e78772SMel Gorman  * the reserve counters are updated with the hugetlb_lock held. It is safe
630a1e78772SMel Gorman  * to reset the VMA at fork() time as it is not in use yet and there is no
631a1e78772SMel Gorman  * chance of the global counters getting corrupted as a result of the values.
63284afd99bSAndy Whitcroft  *
63384afd99bSAndy Whitcroft  * The private mapping reservation is represented in a subtly different
63484afd99bSAndy Whitcroft  * manner to a shared mapping.  A shared mapping has a region map associated
63584afd99bSAndy Whitcroft  * with the underlying file, this region map represents the backing file
63684afd99bSAndy Whitcroft  * pages which have ever had a reservation assigned which this persists even
63784afd99bSAndy Whitcroft  * after the page is instantiated.  A private mapping has a region map
63884afd99bSAndy Whitcroft  * associated with the original mmap which is attached to all VMAs which
63984afd99bSAndy Whitcroft  * reference it, this region map represents those offsets which have consumed
64084afd99bSAndy Whitcroft  * reservation ie. where pages have been instantiated.
641a1e78772SMel Gorman  */
642e7c4b0bfSAndy Whitcroft static unsigned long get_vma_private_data(struct vm_area_struct *vma)
643e7c4b0bfSAndy Whitcroft {
644e7c4b0bfSAndy Whitcroft 	return (unsigned long)vma->vm_private_data;
645e7c4b0bfSAndy Whitcroft }
646e7c4b0bfSAndy Whitcroft 
647e7c4b0bfSAndy Whitcroft static void set_vma_private_data(struct vm_area_struct *vma,
648e7c4b0bfSAndy Whitcroft 							unsigned long value)
649e7c4b0bfSAndy Whitcroft {
650e7c4b0bfSAndy Whitcroft 	vma->vm_private_data = (void *)value;
651e7c4b0bfSAndy Whitcroft }
652e7c4b0bfSAndy Whitcroft 
653e9fe92aeSMina Almasry static void
654e9fe92aeSMina Almasry resv_map_set_hugetlb_cgroup_uncharge_info(struct resv_map *resv_map,
655e9fe92aeSMina Almasry 					  struct hugetlb_cgroup *h_cg,
656e9fe92aeSMina Almasry 					  struct hstate *h)
657e9fe92aeSMina Almasry {
658e9fe92aeSMina Almasry #ifdef CONFIG_CGROUP_HUGETLB
659e9fe92aeSMina Almasry 	if (!h_cg || !h) {
660e9fe92aeSMina Almasry 		resv_map->reservation_counter = NULL;
661e9fe92aeSMina Almasry 		resv_map->pages_per_hpage = 0;
662e9fe92aeSMina Almasry 		resv_map->css = NULL;
663e9fe92aeSMina Almasry 	} else {
664e9fe92aeSMina Almasry 		resv_map->reservation_counter =
665e9fe92aeSMina Almasry 			&h_cg->rsvd_hugepage[hstate_index(h)];
666e9fe92aeSMina Almasry 		resv_map->pages_per_hpage = pages_per_huge_page(h);
667e9fe92aeSMina Almasry 		resv_map->css = &h_cg->css;
668e9fe92aeSMina Almasry 	}
669e9fe92aeSMina Almasry #endif
670e9fe92aeSMina Almasry }
671e9fe92aeSMina Almasry 
6729119a41eSJoonsoo Kim struct resv_map *resv_map_alloc(void)
67384afd99bSAndy Whitcroft {
67484afd99bSAndy Whitcroft 	struct resv_map *resv_map = kmalloc(sizeof(*resv_map), GFP_KERNEL);
6755e911373SMike Kravetz 	struct file_region *rg = kmalloc(sizeof(*rg), GFP_KERNEL);
6765e911373SMike Kravetz 
6775e911373SMike Kravetz 	if (!resv_map || !rg) {
6785e911373SMike Kravetz 		kfree(resv_map);
6795e911373SMike Kravetz 		kfree(rg);
68084afd99bSAndy Whitcroft 		return NULL;
6815e911373SMike Kravetz 	}
68284afd99bSAndy Whitcroft 
68384afd99bSAndy Whitcroft 	kref_init(&resv_map->refs);
6847b24d861SDavidlohr Bueso 	spin_lock_init(&resv_map->lock);
68584afd99bSAndy Whitcroft 	INIT_LIST_HEAD(&resv_map->regions);
68684afd99bSAndy Whitcroft 
6875e911373SMike Kravetz 	resv_map->adds_in_progress = 0;
688e9fe92aeSMina Almasry 	/*
689e9fe92aeSMina Almasry 	 * Initialize these to 0. On shared mappings, 0's here indicate these
690e9fe92aeSMina Almasry 	 * fields don't do cgroup accounting. On private mappings, these will be
691e9fe92aeSMina Almasry 	 * re-initialized to the proper values, to indicate that hugetlb cgroup
692e9fe92aeSMina Almasry 	 * reservations are to be un-charged from here.
693e9fe92aeSMina Almasry 	 */
694e9fe92aeSMina Almasry 	resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, NULL, NULL);
6955e911373SMike Kravetz 
6965e911373SMike Kravetz 	INIT_LIST_HEAD(&resv_map->region_cache);
6975e911373SMike Kravetz 	list_add(&rg->link, &resv_map->region_cache);
6985e911373SMike Kravetz 	resv_map->region_cache_count = 1;
6995e911373SMike Kravetz 
70084afd99bSAndy Whitcroft 	return resv_map;
70184afd99bSAndy Whitcroft }
70284afd99bSAndy Whitcroft 
7039119a41eSJoonsoo Kim void resv_map_release(struct kref *ref)
70484afd99bSAndy Whitcroft {
70584afd99bSAndy Whitcroft 	struct resv_map *resv_map = container_of(ref, struct resv_map, refs);
7065e911373SMike Kravetz 	struct list_head *head = &resv_map->region_cache;
7075e911373SMike Kravetz 	struct file_region *rg, *trg;
70884afd99bSAndy Whitcroft 
70984afd99bSAndy Whitcroft 	/* Clear out any active regions before we release the map. */
710feba16e2SMike Kravetz 	region_del(resv_map, 0, LONG_MAX);
7115e911373SMike Kravetz 
7125e911373SMike Kravetz 	/* ... and any entries left in the cache */
7135e911373SMike Kravetz 	list_for_each_entry_safe(rg, trg, head, link) {
7145e911373SMike Kravetz 		list_del(&rg->link);
7155e911373SMike Kravetz 		kfree(rg);
7165e911373SMike Kravetz 	}
7175e911373SMike Kravetz 
7185e911373SMike Kravetz 	VM_BUG_ON(resv_map->adds_in_progress);
7195e911373SMike Kravetz 
72084afd99bSAndy Whitcroft 	kfree(resv_map);
72184afd99bSAndy Whitcroft }
72284afd99bSAndy Whitcroft 
7234e35f483SJoonsoo Kim static inline struct resv_map *inode_resv_map(struct inode *inode)
7244e35f483SJoonsoo Kim {
725f27a5136SMike Kravetz 	/*
726f27a5136SMike Kravetz 	 * At inode evict time, i_mapping may not point to the original
727f27a5136SMike Kravetz 	 * address space within the inode.  This original address space
728f27a5136SMike Kravetz 	 * contains the pointer to the resv_map.  So, always use the
729f27a5136SMike Kravetz 	 * address space embedded within the inode.
730f27a5136SMike Kravetz 	 * The VERY common case is inode->mapping == &inode->i_data but,
731f27a5136SMike Kravetz 	 * this may not be true for device special inodes.
732f27a5136SMike Kravetz 	 */
733f27a5136SMike Kravetz 	return (struct resv_map *)(&inode->i_data)->private_data;
7344e35f483SJoonsoo Kim }
7354e35f483SJoonsoo Kim 
73684afd99bSAndy Whitcroft static struct resv_map *vma_resv_map(struct vm_area_struct *vma)
737a1e78772SMel Gorman {
73881d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
7394e35f483SJoonsoo Kim 	if (vma->vm_flags & VM_MAYSHARE) {
7404e35f483SJoonsoo Kim 		struct address_space *mapping = vma->vm_file->f_mapping;
7414e35f483SJoonsoo Kim 		struct inode *inode = mapping->host;
7424e35f483SJoonsoo Kim 
7434e35f483SJoonsoo Kim 		return inode_resv_map(inode);
7444e35f483SJoonsoo Kim 
7454e35f483SJoonsoo Kim 	} else {
74684afd99bSAndy Whitcroft 		return (struct resv_map *)(get_vma_private_data(vma) &
74784afd99bSAndy Whitcroft 							~HPAGE_RESV_MASK);
7484e35f483SJoonsoo Kim 	}
749a1e78772SMel Gorman }
750a1e78772SMel Gorman 
75184afd99bSAndy Whitcroft static void set_vma_resv_map(struct vm_area_struct *vma, struct resv_map *map)
752a1e78772SMel Gorman {
75381d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
75481d1b09cSSasha Levin 	VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
755a1e78772SMel Gorman 
75684afd99bSAndy Whitcroft 	set_vma_private_data(vma, (get_vma_private_data(vma) &
75784afd99bSAndy Whitcroft 				HPAGE_RESV_MASK) | (unsigned long)map);
75804f2cbe3SMel Gorman }
75904f2cbe3SMel Gorman 
76004f2cbe3SMel Gorman static void set_vma_resv_flags(struct vm_area_struct *vma, unsigned long flags)
76104f2cbe3SMel Gorman {
76281d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
76381d1b09cSSasha Levin 	VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
764e7c4b0bfSAndy Whitcroft 
765e7c4b0bfSAndy Whitcroft 	set_vma_private_data(vma, get_vma_private_data(vma) | flags);
76604f2cbe3SMel Gorman }
76704f2cbe3SMel Gorman 
76804f2cbe3SMel Gorman static int is_vma_resv_set(struct vm_area_struct *vma, unsigned long flag)
76904f2cbe3SMel Gorman {
77081d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
771e7c4b0bfSAndy Whitcroft 
772e7c4b0bfSAndy Whitcroft 	return (get_vma_private_data(vma) & flag) != 0;
773a1e78772SMel Gorman }
774a1e78772SMel Gorman 
77504f2cbe3SMel Gorman /* Reset counters to 0 and clear all HPAGE_RESV_* flags */
776a1e78772SMel Gorman void reset_vma_resv_huge_pages(struct vm_area_struct *vma)
777a1e78772SMel Gorman {
77881d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
779f83a275dSMel Gorman 	if (!(vma->vm_flags & VM_MAYSHARE))
780a1e78772SMel Gorman 		vma->vm_private_data = (void *)0;
781a1e78772SMel Gorman }
782a1e78772SMel Gorman 
783a1e78772SMel Gorman /* Returns true if the VMA has associated reserve pages */
784559ec2f8SNicholas Krause static bool vma_has_reserves(struct vm_area_struct *vma, long chg)
785a1e78772SMel Gorman {
786af0ed73eSJoonsoo Kim 	if (vma->vm_flags & VM_NORESERVE) {
787af0ed73eSJoonsoo Kim 		/*
788af0ed73eSJoonsoo Kim 		 * This address is already reserved by other process(chg == 0),
789af0ed73eSJoonsoo Kim 		 * so, we should decrement reserved count. Without decrementing,
790af0ed73eSJoonsoo Kim 		 * reserve count remains after releasing inode, because this
791af0ed73eSJoonsoo Kim 		 * allocated page will go into page cache and is regarded as
792af0ed73eSJoonsoo Kim 		 * coming from reserved pool in releasing step.  Currently, we
793af0ed73eSJoonsoo Kim 		 * don't have any other solution to deal with this situation
794af0ed73eSJoonsoo Kim 		 * properly, so add work-around here.
795af0ed73eSJoonsoo Kim 		 */
796af0ed73eSJoonsoo Kim 		if (vma->vm_flags & VM_MAYSHARE && chg == 0)
797559ec2f8SNicholas Krause 			return true;
798af0ed73eSJoonsoo Kim 		else
799559ec2f8SNicholas Krause 			return false;
800af0ed73eSJoonsoo Kim 	}
801a63884e9SJoonsoo Kim 
802a63884e9SJoonsoo Kim 	/* Shared mappings always use reserves */
8031fb1b0e9SMike Kravetz 	if (vma->vm_flags & VM_MAYSHARE) {
8041fb1b0e9SMike Kravetz 		/*
8051fb1b0e9SMike Kravetz 		 * We know VM_NORESERVE is not set.  Therefore, there SHOULD
8061fb1b0e9SMike Kravetz 		 * be a region map for all pages.  The only situation where
8071fb1b0e9SMike Kravetz 		 * there is no region map is if a hole was punched via
8081fb1b0e9SMike Kravetz 		 * fallocate.  In this case, there really are no reverves to
8091fb1b0e9SMike Kravetz 		 * use.  This situation is indicated if chg != 0.
8101fb1b0e9SMike Kravetz 		 */
8111fb1b0e9SMike Kravetz 		if (chg)
8121fb1b0e9SMike Kravetz 			return false;
8131fb1b0e9SMike Kravetz 		else
814559ec2f8SNicholas Krause 			return true;
8151fb1b0e9SMike Kravetz 	}
816a63884e9SJoonsoo Kim 
817a63884e9SJoonsoo Kim 	/*
818a63884e9SJoonsoo Kim 	 * Only the process that called mmap() has reserves for
819a63884e9SJoonsoo Kim 	 * private mappings.
820a63884e9SJoonsoo Kim 	 */
82167961f9dSMike Kravetz 	if (is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
82267961f9dSMike Kravetz 		/*
82367961f9dSMike Kravetz 		 * Like the shared case above, a hole punch or truncate
82467961f9dSMike Kravetz 		 * could have been performed on the private mapping.
82567961f9dSMike Kravetz 		 * Examine the value of chg to determine if reserves
82667961f9dSMike Kravetz 		 * actually exist or were previously consumed.
82767961f9dSMike Kravetz 		 * Very Subtle - The value of chg comes from a previous
82867961f9dSMike Kravetz 		 * call to vma_needs_reserves().  The reserve map for
82967961f9dSMike Kravetz 		 * private mappings has different (opposite) semantics
83067961f9dSMike Kravetz 		 * than that of shared mappings.  vma_needs_reserves()
83167961f9dSMike Kravetz 		 * has already taken this difference in semantics into
83267961f9dSMike Kravetz 		 * account.  Therefore, the meaning of chg is the same
83367961f9dSMike Kravetz 		 * as in the shared case above.  Code could easily be
83467961f9dSMike Kravetz 		 * combined, but keeping it separate draws attention to
83567961f9dSMike Kravetz 		 * subtle differences.
83667961f9dSMike Kravetz 		 */
83767961f9dSMike Kravetz 		if (chg)
83867961f9dSMike Kravetz 			return false;
83967961f9dSMike Kravetz 		else
840559ec2f8SNicholas Krause 			return true;
84167961f9dSMike Kravetz 	}
842a63884e9SJoonsoo Kim 
843559ec2f8SNicholas Krause 	return false;
844a1e78772SMel Gorman }
845a1e78772SMel Gorman 
846a5516438SAndi Kleen static void enqueue_huge_page(struct hstate *h, struct page *page)
8471da177e4SLinus Torvalds {
8481da177e4SLinus Torvalds 	int nid = page_to_nid(page);
8490edaecfaSAneesh Kumar K.V 	list_move(&page->lru, &h->hugepage_freelists[nid]);
850a5516438SAndi Kleen 	h->free_huge_pages++;
851a5516438SAndi Kleen 	h->free_huge_pages_node[nid]++;
8521da177e4SLinus Torvalds }
8531da177e4SLinus Torvalds 
85494310cbcSAnshuman Khandual static struct page *dequeue_huge_page_node_exact(struct hstate *h, int nid)
855bf50bab2SNaoya Horiguchi {
856bf50bab2SNaoya Horiguchi 	struct page *page;
857bf50bab2SNaoya Horiguchi 
858c8721bbbSNaoya Horiguchi 	list_for_each_entry(page, &h->hugepage_freelists[nid], lru)
859243abd5bSNaoya Horiguchi 		if (!PageHWPoison(page))
860c8721bbbSNaoya Horiguchi 			break;
861c8721bbbSNaoya Horiguchi 	/*
862c8721bbbSNaoya Horiguchi 	 * if 'non-isolated free hugepage' not found on the list,
863c8721bbbSNaoya Horiguchi 	 * the allocation fails.
864c8721bbbSNaoya Horiguchi 	 */
865c8721bbbSNaoya Horiguchi 	if (&h->hugepage_freelists[nid] == &page->lru)
866bf50bab2SNaoya Horiguchi 		return NULL;
8670edaecfaSAneesh Kumar K.V 	list_move(&page->lru, &h->hugepage_activelist);
868a9869b83SNaoya Horiguchi 	set_page_refcounted(page);
869bf50bab2SNaoya Horiguchi 	h->free_huge_pages--;
870bf50bab2SNaoya Horiguchi 	h->free_huge_pages_node[nid]--;
871bf50bab2SNaoya Horiguchi 	return page;
872bf50bab2SNaoya Horiguchi }
873bf50bab2SNaoya Horiguchi 
8743e59fcb0SMichal Hocko static struct page *dequeue_huge_page_nodemask(struct hstate *h, gfp_t gfp_mask, int nid,
8753e59fcb0SMichal Hocko 		nodemask_t *nmask)
87694310cbcSAnshuman Khandual {
8773e59fcb0SMichal Hocko 	unsigned int cpuset_mems_cookie;
8783e59fcb0SMichal Hocko 	struct zonelist *zonelist;
8793e59fcb0SMichal Hocko 	struct zone *zone;
8803e59fcb0SMichal Hocko 	struct zoneref *z;
88198fa15f3SAnshuman Khandual 	int node = NUMA_NO_NODE;
8823e59fcb0SMichal Hocko 
8833e59fcb0SMichal Hocko 	zonelist = node_zonelist(nid, gfp_mask);
8843e59fcb0SMichal Hocko 
8853e59fcb0SMichal Hocko retry_cpuset:
8863e59fcb0SMichal Hocko 	cpuset_mems_cookie = read_mems_allowed_begin();
8873e59fcb0SMichal Hocko 	for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nmask) {
88894310cbcSAnshuman Khandual 		struct page *page;
88994310cbcSAnshuman Khandual 
8903e59fcb0SMichal Hocko 		if (!cpuset_zone_allowed(zone, gfp_mask))
8913e59fcb0SMichal Hocko 			continue;
8923e59fcb0SMichal Hocko 		/*
8933e59fcb0SMichal Hocko 		 * no need to ask again on the same node. Pool is node rather than
8943e59fcb0SMichal Hocko 		 * zone aware
8953e59fcb0SMichal Hocko 		 */
8963e59fcb0SMichal Hocko 		if (zone_to_nid(zone) == node)
8973e59fcb0SMichal Hocko 			continue;
8983e59fcb0SMichal Hocko 		node = zone_to_nid(zone);
89994310cbcSAnshuman Khandual 
90094310cbcSAnshuman Khandual 		page = dequeue_huge_page_node_exact(h, node);
90194310cbcSAnshuman Khandual 		if (page)
90294310cbcSAnshuman Khandual 			return page;
90394310cbcSAnshuman Khandual 	}
9043e59fcb0SMichal Hocko 	if (unlikely(read_mems_allowed_retry(cpuset_mems_cookie)))
9053e59fcb0SMichal Hocko 		goto retry_cpuset;
9063e59fcb0SMichal Hocko 
90794310cbcSAnshuman Khandual 	return NULL;
90894310cbcSAnshuman Khandual }
90994310cbcSAnshuman Khandual 
91086cdb465SNaoya Horiguchi /* Movability of hugepages depends on migration support. */
91186cdb465SNaoya Horiguchi static inline gfp_t htlb_alloc_mask(struct hstate *h)
91286cdb465SNaoya Horiguchi {
9137ed2c31dSAnshuman Khandual 	if (hugepage_movable_supported(h))
91486cdb465SNaoya Horiguchi 		return GFP_HIGHUSER_MOVABLE;
91586cdb465SNaoya Horiguchi 	else
91686cdb465SNaoya Horiguchi 		return GFP_HIGHUSER;
91786cdb465SNaoya Horiguchi }
91886cdb465SNaoya Horiguchi 
919a5516438SAndi Kleen static struct page *dequeue_huge_page_vma(struct hstate *h,
920a5516438SAndi Kleen 				struct vm_area_struct *vma,
921af0ed73eSJoonsoo Kim 				unsigned long address, int avoid_reserve,
922af0ed73eSJoonsoo Kim 				long chg)
9231da177e4SLinus Torvalds {
9243e59fcb0SMichal Hocko 	struct page *page;
925480eccf9SLee Schermerhorn 	struct mempolicy *mpol;
92604ec6264SVlastimil Babka 	gfp_t gfp_mask;
9273e59fcb0SMichal Hocko 	nodemask_t *nodemask;
92804ec6264SVlastimil Babka 	int nid;
9291da177e4SLinus Torvalds 
930a1e78772SMel Gorman 	/*
931a1e78772SMel Gorman 	 * A child process with MAP_PRIVATE mappings created by their parent
932a1e78772SMel Gorman 	 * have no page reserves. This check ensures that reservations are
933a1e78772SMel Gorman 	 * not "stolen". The child may still get SIGKILLed
934a1e78772SMel Gorman 	 */
935af0ed73eSJoonsoo Kim 	if (!vma_has_reserves(vma, chg) &&
936a5516438SAndi Kleen 			h->free_huge_pages - h->resv_huge_pages == 0)
937c0ff7453SMiao Xie 		goto err;
938a1e78772SMel Gorman 
93904f2cbe3SMel Gorman 	/* If reserves cannot be used, ensure enough pages are in the pool */
940a5516438SAndi Kleen 	if (avoid_reserve && h->free_huge_pages - h->resv_huge_pages == 0)
9416eab04a8SJustin P. Mattock 		goto err;
94204f2cbe3SMel Gorman 
94304ec6264SVlastimil Babka 	gfp_mask = htlb_alloc_mask(h);
94404ec6264SVlastimil Babka 	nid = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
9453e59fcb0SMichal Hocko 	page = dequeue_huge_page_nodemask(h, gfp_mask, nid, nodemask);
9463e59fcb0SMichal Hocko 	if (page && !avoid_reserve && vma_has_reserves(vma, chg)) {
94707443a85SJoonsoo Kim 		SetPagePrivate(page);
948a63884e9SJoonsoo Kim 		h->resv_huge_pages--;
949bf50bab2SNaoya Horiguchi 	}
950cc9a6c87SMel Gorman 
951cc9a6c87SMel Gorman 	mpol_cond_put(mpol);
952cc9a6c87SMel Gorman 	return page;
953cc9a6c87SMel Gorman 
954c0ff7453SMiao Xie err:
955cc9a6c87SMel Gorman 	return NULL;
9561da177e4SLinus Torvalds }
9571da177e4SLinus Torvalds 
9581cac6f2cSLuiz Capitulino /*
9591cac6f2cSLuiz Capitulino  * common helper functions for hstate_next_node_to_{alloc|free}.
9601cac6f2cSLuiz Capitulino  * We may have allocated or freed a huge page based on a different
9611cac6f2cSLuiz Capitulino  * nodes_allowed previously, so h->next_node_to_{alloc|free} might
9621cac6f2cSLuiz Capitulino  * be outside of *nodes_allowed.  Ensure that we use an allowed
9631cac6f2cSLuiz Capitulino  * node for alloc or free.
9641cac6f2cSLuiz Capitulino  */
9651cac6f2cSLuiz Capitulino static int next_node_allowed(int nid, nodemask_t *nodes_allowed)
9661cac6f2cSLuiz Capitulino {
9670edaf86cSAndrew Morton 	nid = next_node_in(nid, *nodes_allowed);
9681cac6f2cSLuiz Capitulino 	VM_BUG_ON(nid >= MAX_NUMNODES);
9691cac6f2cSLuiz Capitulino 
9701cac6f2cSLuiz Capitulino 	return nid;
9711cac6f2cSLuiz Capitulino }
9721cac6f2cSLuiz Capitulino 
9731cac6f2cSLuiz Capitulino static int get_valid_node_allowed(int nid, nodemask_t *nodes_allowed)
9741cac6f2cSLuiz Capitulino {
9751cac6f2cSLuiz Capitulino 	if (!node_isset(nid, *nodes_allowed))
9761cac6f2cSLuiz Capitulino 		nid = next_node_allowed(nid, nodes_allowed);
9771cac6f2cSLuiz Capitulino 	return nid;
9781cac6f2cSLuiz Capitulino }
9791cac6f2cSLuiz Capitulino 
9801cac6f2cSLuiz Capitulino /*
9811cac6f2cSLuiz Capitulino  * returns the previously saved node ["this node"] from which to
9821cac6f2cSLuiz Capitulino  * allocate a persistent huge page for the pool and advance the
9831cac6f2cSLuiz Capitulino  * next node from which to allocate, handling wrap at end of node
9841cac6f2cSLuiz Capitulino  * mask.
9851cac6f2cSLuiz Capitulino  */
9861cac6f2cSLuiz Capitulino static int hstate_next_node_to_alloc(struct hstate *h,
9871cac6f2cSLuiz Capitulino 					nodemask_t *nodes_allowed)
9881cac6f2cSLuiz Capitulino {
9891cac6f2cSLuiz Capitulino 	int nid;
9901cac6f2cSLuiz Capitulino 
9911cac6f2cSLuiz Capitulino 	VM_BUG_ON(!nodes_allowed);
9921cac6f2cSLuiz Capitulino 
9931cac6f2cSLuiz Capitulino 	nid = get_valid_node_allowed(h->next_nid_to_alloc, nodes_allowed);
9941cac6f2cSLuiz Capitulino 	h->next_nid_to_alloc = next_node_allowed(nid, nodes_allowed);
9951cac6f2cSLuiz Capitulino 
9961cac6f2cSLuiz Capitulino 	return nid;
9971cac6f2cSLuiz Capitulino }
9981cac6f2cSLuiz Capitulino 
9991cac6f2cSLuiz Capitulino /*
10001cac6f2cSLuiz Capitulino  * helper for free_pool_huge_page() - return the previously saved
10011cac6f2cSLuiz Capitulino  * node ["this node"] from which to free a huge page.  Advance the
10021cac6f2cSLuiz Capitulino  * next node id whether or not we find a free huge page to free so
10031cac6f2cSLuiz Capitulino  * that the next attempt to free addresses the next node.
10041cac6f2cSLuiz Capitulino  */
10051cac6f2cSLuiz Capitulino static int hstate_next_node_to_free(struct hstate *h, nodemask_t *nodes_allowed)
10061cac6f2cSLuiz Capitulino {
10071cac6f2cSLuiz Capitulino 	int nid;
10081cac6f2cSLuiz Capitulino 
10091cac6f2cSLuiz Capitulino 	VM_BUG_ON(!nodes_allowed);
10101cac6f2cSLuiz Capitulino 
10111cac6f2cSLuiz Capitulino 	nid = get_valid_node_allowed(h->next_nid_to_free, nodes_allowed);
10121cac6f2cSLuiz Capitulino 	h->next_nid_to_free = next_node_allowed(nid, nodes_allowed);
10131cac6f2cSLuiz Capitulino 
10141cac6f2cSLuiz Capitulino 	return nid;
10151cac6f2cSLuiz Capitulino }
10161cac6f2cSLuiz Capitulino 
10171cac6f2cSLuiz Capitulino #define for_each_node_mask_to_alloc(hs, nr_nodes, node, mask)		\
10181cac6f2cSLuiz Capitulino 	for (nr_nodes = nodes_weight(*mask);				\
10191cac6f2cSLuiz Capitulino 		nr_nodes > 0 &&						\
10201cac6f2cSLuiz Capitulino 		((node = hstate_next_node_to_alloc(hs, mask)) || 1);	\
10211cac6f2cSLuiz Capitulino 		nr_nodes--)
10221cac6f2cSLuiz Capitulino 
10231cac6f2cSLuiz Capitulino #define for_each_node_mask_to_free(hs, nr_nodes, node, mask)		\
10241cac6f2cSLuiz Capitulino 	for (nr_nodes = nodes_weight(*mask);				\
10251cac6f2cSLuiz Capitulino 		nr_nodes > 0 &&						\
10261cac6f2cSLuiz Capitulino 		((node = hstate_next_node_to_free(hs, mask)) || 1);	\
10271cac6f2cSLuiz Capitulino 		nr_nodes--)
10281cac6f2cSLuiz Capitulino 
1029e1073d1eSAneesh Kumar K.V #ifdef CONFIG_ARCH_HAS_GIGANTIC_PAGE
1030944d9fecSLuiz Capitulino static void destroy_compound_gigantic_page(struct page *page,
1031d00181b9SKirill A. Shutemov 					unsigned int order)
1032944d9fecSLuiz Capitulino {
1033944d9fecSLuiz Capitulino 	int i;
1034944d9fecSLuiz Capitulino 	int nr_pages = 1 << order;
1035944d9fecSLuiz Capitulino 	struct page *p = page + 1;
1036944d9fecSLuiz Capitulino 
1037c8cc708aSGerald Schaefer 	atomic_set(compound_mapcount_ptr(page), 0);
103847e29d32SJohn Hubbard 	if (hpage_pincount_available(page))
103947e29d32SJohn Hubbard 		atomic_set(compound_pincount_ptr(page), 0);
104047e29d32SJohn Hubbard 
1041944d9fecSLuiz Capitulino 	for (i = 1; i < nr_pages; i++, p = mem_map_next(p, page, i)) {
10421d798ca3SKirill A. Shutemov 		clear_compound_head(p);
1043944d9fecSLuiz Capitulino 		set_page_refcounted(p);
1044944d9fecSLuiz Capitulino 	}
1045944d9fecSLuiz Capitulino 
1046944d9fecSLuiz Capitulino 	set_compound_order(page, 0);
1047944d9fecSLuiz Capitulino 	__ClearPageHead(page);
1048944d9fecSLuiz Capitulino }
1049944d9fecSLuiz Capitulino 
1050d00181b9SKirill A. Shutemov static void free_gigantic_page(struct page *page, unsigned int order)
1051944d9fecSLuiz Capitulino {
1052944d9fecSLuiz Capitulino 	free_contig_range(page_to_pfn(page), 1 << order);
1053944d9fecSLuiz Capitulino }
1054944d9fecSLuiz Capitulino 
10554eb0716eSAlexandre Ghiti #ifdef CONFIG_CONTIG_ALLOC
1056d9cc948fSMichal Hocko static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
1057d9cc948fSMichal Hocko 		int nid, nodemask_t *nodemask)
1058944d9fecSLuiz Capitulino {
10595e27a2dfSAnshuman Khandual 	unsigned long nr_pages = 1UL << huge_page_order(h);
1060944d9fecSLuiz Capitulino 
10615e27a2dfSAnshuman Khandual 	return alloc_contig_pages(nr_pages, gfp_mask, nid, nodemask);
1062944d9fecSLuiz Capitulino }
1063944d9fecSLuiz Capitulino 
1064944d9fecSLuiz Capitulino static void prep_new_huge_page(struct hstate *h, struct page *page, int nid);
1065d00181b9SKirill A. Shutemov static void prep_compound_gigantic_page(struct page *page, unsigned int order);
10664eb0716eSAlexandre Ghiti #else /* !CONFIG_CONTIG_ALLOC */
10674eb0716eSAlexandre Ghiti static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
10684eb0716eSAlexandre Ghiti 					int nid, nodemask_t *nodemask)
10694eb0716eSAlexandre Ghiti {
10704eb0716eSAlexandre Ghiti 	return NULL;
10714eb0716eSAlexandre Ghiti }
10724eb0716eSAlexandre Ghiti #endif /* CONFIG_CONTIG_ALLOC */
1073944d9fecSLuiz Capitulino 
1074e1073d1eSAneesh Kumar K.V #else /* !CONFIG_ARCH_HAS_GIGANTIC_PAGE */
1075d9cc948fSMichal Hocko static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
10764eb0716eSAlexandre Ghiti 					int nid, nodemask_t *nodemask)
10774eb0716eSAlexandre Ghiti {
10784eb0716eSAlexandre Ghiti 	return NULL;
10794eb0716eSAlexandre Ghiti }
1080d00181b9SKirill A. Shutemov static inline void free_gigantic_page(struct page *page, unsigned int order) { }
1081944d9fecSLuiz Capitulino static inline void destroy_compound_gigantic_page(struct page *page,
1082d00181b9SKirill A. Shutemov 						unsigned int order) { }
1083944d9fecSLuiz Capitulino #endif
1084944d9fecSLuiz Capitulino 
1085a5516438SAndi Kleen static void update_and_free_page(struct hstate *h, struct page *page)
10866af2acb6SAdam Litke {
10876af2acb6SAdam Litke 	int i;
1088a5516438SAndi Kleen 
10894eb0716eSAlexandre Ghiti 	if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
1090944d9fecSLuiz Capitulino 		return;
109118229df5SAndy Whitcroft 
1092a5516438SAndi Kleen 	h->nr_huge_pages--;
1093a5516438SAndi Kleen 	h->nr_huge_pages_node[page_to_nid(page)]--;
1094a5516438SAndi Kleen 	for (i = 0; i < pages_per_huge_page(h); i++) {
109532f84528SChris Forbes 		page[i].flags &= ~(1 << PG_locked | 1 << PG_error |
109632f84528SChris Forbes 				1 << PG_referenced | 1 << PG_dirty |
1097a7407a27SLuiz Capitulino 				1 << PG_active | 1 << PG_private |
1098a7407a27SLuiz Capitulino 				1 << PG_writeback);
10996af2acb6SAdam Litke 	}
1100309381feSSasha Levin 	VM_BUG_ON_PAGE(hugetlb_cgroup_from_page(page), page);
11011adc4d41SMina Almasry 	VM_BUG_ON_PAGE(hugetlb_cgroup_from_page_rsvd(page), page);
1102f1e61557SKirill A. Shutemov 	set_compound_page_dtor(page, NULL_COMPOUND_DTOR);
11036af2acb6SAdam Litke 	set_page_refcounted(page);
1104944d9fecSLuiz Capitulino 	if (hstate_is_gigantic(h)) {
1105944d9fecSLuiz Capitulino 		destroy_compound_gigantic_page(page, huge_page_order(h));
1106944d9fecSLuiz Capitulino 		free_gigantic_page(page, huge_page_order(h));
1107944d9fecSLuiz Capitulino 	} else {
1108a5516438SAndi Kleen 		__free_pages(page, huge_page_order(h));
11096af2acb6SAdam Litke 	}
1110944d9fecSLuiz Capitulino }
11116af2acb6SAdam Litke 
1112e5ff2159SAndi Kleen struct hstate *size_to_hstate(unsigned long size)
1113e5ff2159SAndi Kleen {
1114e5ff2159SAndi Kleen 	struct hstate *h;
1115e5ff2159SAndi Kleen 
1116e5ff2159SAndi Kleen 	for_each_hstate(h) {
1117e5ff2159SAndi Kleen 		if (huge_page_size(h) == size)
1118e5ff2159SAndi Kleen 			return h;
1119e5ff2159SAndi Kleen 	}
1120e5ff2159SAndi Kleen 	return NULL;
1121e5ff2159SAndi Kleen }
1122e5ff2159SAndi Kleen 
1123bcc54222SNaoya Horiguchi /*
1124bcc54222SNaoya Horiguchi  * Test to determine whether the hugepage is "active/in-use" (i.e. being linked
1125bcc54222SNaoya Horiguchi  * to hstate->hugepage_activelist.)
1126bcc54222SNaoya Horiguchi  *
1127bcc54222SNaoya Horiguchi  * This function can be called for tail pages, but never returns true for them.
1128bcc54222SNaoya Horiguchi  */
1129bcc54222SNaoya Horiguchi bool page_huge_active(struct page *page)
1130bcc54222SNaoya Horiguchi {
1131bcc54222SNaoya Horiguchi 	VM_BUG_ON_PAGE(!PageHuge(page), page);
1132bcc54222SNaoya Horiguchi 	return PageHead(page) && PagePrivate(&page[1]);
1133bcc54222SNaoya Horiguchi }
1134bcc54222SNaoya Horiguchi 
1135bcc54222SNaoya Horiguchi /* never called for tail page */
1136bcc54222SNaoya Horiguchi static void set_page_huge_active(struct page *page)
1137bcc54222SNaoya Horiguchi {
1138bcc54222SNaoya Horiguchi 	VM_BUG_ON_PAGE(!PageHeadHuge(page), page);
1139bcc54222SNaoya Horiguchi 	SetPagePrivate(&page[1]);
1140bcc54222SNaoya Horiguchi }
1141bcc54222SNaoya Horiguchi 
1142bcc54222SNaoya Horiguchi static void clear_page_huge_active(struct page *page)
1143bcc54222SNaoya Horiguchi {
1144bcc54222SNaoya Horiguchi 	VM_BUG_ON_PAGE(!PageHeadHuge(page), page);
1145bcc54222SNaoya Horiguchi 	ClearPagePrivate(&page[1]);
1146bcc54222SNaoya Horiguchi }
1147bcc54222SNaoya Horiguchi 
1148ab5ac90aSMichal Hocko /*
1149ab5ac90aSMichal Hocko  * Internal hugetlb specific page flag. Do not use outside of the hugetlb
1150ab5ac90aSMichal Hocko  * code
1151ab5ac90aSMichal Hocko  */
1152ab5ac90aSMichal Hocko static inline bool PageHugeTemporary(struct page *page)
1153ab5ac90aSMichal Hocko {
1154ab5ac90aSMichal Hocko 	if (!PageHuge(page))
1155ab5ac90aSMichal Hocko 		return false;
1156ab5ac90aSMichal Hocko 
1157ab5ac90aSMichal Hocko 	return (unsigned long)page[2].mapping == -1U;
1158ab5ac90aSMichal Hocko }
1159ab5ac90aSMichal Hocko 
1160ab5ac90aSMichal Hocko static inline void SetPageHugeTemporary(struct page *page)
1161ab5ac90aSMichal Hocko {
1162ab5ac90aSMichal Hocko 	page[2].mapping = (void *)-1U;
1163ab5ac90aSMichal Hocko }
1164ab5ac90aSMichal Hocko 
1165ab5ac90aSMichal Hocko static inline void ClearPageHugeTemporary(struct page *page)
1166ab5ac90aSMichal Hocko {
1167ab5ac90aSMichal Hocko 	page[2].mapping = NULL;
1168ab5ac90aSMichal Hocko }
1169ab5ac90aSMichal Hocko 
1170c77c0a8aSWaiman Long static void __free_huge_page(struct page *page)
117127a85ef1SDavid Gibson {
1172a5516438SAndi Kleen 	/*
1173a5516438SAndi Kleen 	 * Can't pass hstate in here because it is called from the
1174a5516438SAndi Kleen 	 * compound page destructor.
1175a5516438SAndi Kleen 	 */
1176e5ff2159SAndi Kleen 	struct hstate *h = page_hstate(page);
11777893d1d5SAdam Litke 	int nid = page_to_nid(page);
117890481622SDavid Gibson 	struct hugepage_subpool *spool =
117990481622SDavid Gibson 		(struct hugepage_subpool *)page_private(page);
118007443a85SJoonsoo Kim 	bool restore_reserve;
118127a85ef1SDavid Gibson 
1182b4330afbSMike Kravetz 	VM_BUG_ON_PAGE(page_count(page), page);
1183b4330afbSMike Kravetz 	VM_BUG_ON_PAGE(page_mapcount(page), page);
11848ace22bcSYongkai Wu 
11858ace22bcSYongkai Wu 	set_page_private(page, 0);
11868ace22bcSYongkai Wu 	page->mapping = NULL;
118707443a85SJoonsoo Kim 	restore_reserve = PagePrivate(page);
118816c794b4SJoonsoo Kim 	ClearPagePrivate(page);
118927a85ef1SDavid Gibson 
11901c5ecae3SMike Kravetz 	/*
11910919e1b6SMike Kravetz 	 * If PagePrivate() was set on page, page allocation consumed a
11920919e1b6SMike Kravetz 	 * reservation.  If the page was associated with a subpool, there
11930919e1b6SMike Kravetz 	 * would have been a page reserved in the subpool before allocation
11940919e1b6SMike Kravetz 	 * via hugepage_subpool_get_pages().  Since we are 'restoring' the
11950919e1b6SMike Kravetz 	 * reservtion, do not call hugepage_subpool_put_pages() as this will
11960919e1b6SMike Kravetz 	 * remove the reserved page from the subpool.
11970919e1b6SMike Kravetz 	 */
11980919e1b6SMike Kravetz 	if (!restore_reserve) {
11990919e1b6SMike Kravetz 		/*
12000919e1b6SMike Kravetz 		 * A return code of zero implies that the subpool will be
12010919e1b6SMike Kravetz 		 * under its minimum size if the reservation is not restored
12020919e1b6SMike Kravetz 		 * after page is free.  Therefore, force restore_reserve
12030919e1b6SMike Kravetz 		 * operation.
12041c5ecae3SMike Kravetz 		 */
12051c5ecae3SMike Kravetz 		if (hugepage_subpool_put_pages(spool, 1) == 0)
12061c5ecae3SMike Kravetz 			restore_reserve = true;
12070919e1b6SMike Kravetz 	}
12081c5ecae3SMike Kravetz 
120927a85ef1SDavid Gibson 	spin_lock(&hugetlb_lock);
1210bcc54222SNaoya Horiguchi 	clear_page_huge_active(page);
12116d76dcf4SAneesh Kumar K.V 	hugetlb_cgroup_uncharge_page(hstate_index(h),
12126d76dcf4SAneesh Kumar K.V 				     pages_per_huge_page(h), page);
121307443a85SJoonsoo Kim 	if (restore_reserve)
121407443a85SJoonsoo Kim 		h->resv_huge_pages++;
121507443a85SJoonsoo Kim 
1216ab5ac90aSMichal Hocko 	if (PageHugeTemporary(page)) {
1217ab5ac90aSMichal Hocko 		list_del(&page->lru);
1218ab5ac90aSMichal Hocko 		ClearPageHugeTemporary(page);
1219ab5ac90aSMichal Hocko 		update_and_free_page(h, page);
1220ab5ac90aSMichal Hocko 	} else if (h->surplus_huge_pages_node[nid]) {
12210edaecfaSAneesh Kumar K.V 		/* remove the page from active list */
12220edaecfaSAneesh Kumar K.V 		list_del(&page->lru);
1223a5516438SAndi Kleen 		update_and_free_page(h, page);
1224a5516438SAndi Kleen 		h->surplus_huge_pages--;
1225a5516438SAndi Kleen 		h->surplus_huge_pages_node[nid]--;
12267893d1d5SAdam Litke 	} else {
12275d3a551cSWill Deacon 		arch_clear_hugepage_flags(page);
1228a5516438SAndi Kleen 		enqueue_huge_page(h, page);
12297893d1d5SAdam Litke 	}
123027a85ef1SDavid Gibson 	spin_unlock(&hugetlb_lock);
123127a85ef1SDavid Gibson }
123227a85ef1SDavid Gibson 
1233c77c0a8aSWaiman Long /*
1234c77c0a8aSWaiman Long  * As free_huge_page() can be called from a non-task context, we have
1235c77c0a8aSWaiman Long  * to defer the actual freeing in a workqueue to prevent potential
1236c77c0a8aSWaiman Long  * hugetlb_lock deadlock.
1237c77c0a8aSWaiman Long  *
1238c77c0a8aSWaiman Long  * free_hpage_workfn() locklessly retrieves the linked list of pages to
1239c77c0a8aSWaiman Long  * be freed and frees them one-by-one. As the page->mapping pointer is
1240c77c0a8aSWaiman Long  * going to be cleared in __free_huge_page() anyway, it is reused as the
1241c77c0a8aSWaiman Long  * llist_node structure of a lockless linked list of huge pages to be freed.
1242c77c0a8aSWaiman Long  */
1243c77c0a8aSWaiman Long static LLIST_HEAD(hpage_freelist);
1244c77c0a8aSWaiman Long 
1245c77c0a8aSWaiman Long static void free_hpage_workfn(struct work_struct *work)
1246c77c0a8aSWaiman Long {
1247c77c0a8aSWaiman Long 	struct llist_node *node;
1248c77c0a8aSWaiman Long 	struct page *page;
1249c77c0a8aSWaiman Long 
1250c77c0a8aSWaiman Long 	node = llist_del_all(&hpage_freelist);
1251c77c0a8aSWaiman Long 
1252c77c0a8aSWaiman Long 	while (node) {
1253c77c0a8aSWaiman Long 		page = container_of((struct address_space **)node,
1254c77c0a8aSWaiman Long 				     struct page, mapping);
1255c77c0a8aSWaiman Long 		node = node->next;
1256c77c0a8aSWaiman Long 		__free_huge_page(page);
1257c77c0a8aSWaiman Long 	}
1258c77c0a8aSWaiman Long }
1259c77c0a8aSWaiman Long static DECLARE_WORK(free_hpage_work, free_hpage_workfn);
1260c77c0a8aSWaiman Long 
1261c77c0a8aSWaiman Long void free_huge_page(struct page *page)
1262c77c0a8aSWaiman Long {
1263c77c0a8aSWaiman Long 	/*
1264c77c0a8aSWaiman Long 	 * Defer freeing if in non-task context to avoid hugetlb_lock deadlock.
1265c77c0a8aSWaiman Long 	 */
1266c77c0a8aSWaiman Long 	if (!in_task()) {
1267c77c0a8aSWaiman Long 		/*
1268c77c0a8aSWaiman Long 		 * Only call schedule_work() if hpage_freelist is previously
1269c77c0a8aSWaiman Long 		 * empty. Otherwise, schedule_work() had been called but the
1270c77c0a8aSWaiman Long 		 * workfn hasn't retrieved the list yet.
1271c77c0a8aSWaiman Long 		 */
1272c77c0a8aSWaiman Long 		if (llist_add((struct llist_node *)&page->mapping,
1273c77c0a8aSWaiman Long 			      &hpage_freelist))
1274c77c0a8aSWaiman Long 			schedule_work(&free_hpage_work);
1275c77c0a8aSWaiman Long 		return;
1276c77c0a8aSWaiman Long 	}
1277c77c0a8aSWaiman Long 
1278c77c0a8aSWaiman Long 	__free_huge_page(page);
1279c77c0a8aSWaiman Long }
1280c77c0a8aSWaiman Long 
1281a5516438SAndi Kleen static void prep_new_huge_page(struct hstate *h, struct page *page, int nid)
1282b7ba30c6SAndi Kleen {
12830edaecfaSAneesh Kumar K.V 	INIT_LIST_HEAD(&page->lru);
1284f1e61557SKirill A. Shutemov 	set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
1285b7ba30c6SAndi Kleen 	spin_lock(&hugetlb_lock);
12869dd540e2SAneesh Kumar K.V 	set_hugetlb_cgroup(page, NULL);
12871adc4d41SMina Almasry 	set_hugetlb_cgroup_rsvd(page, NULL);
1288a5516438SAndi Kleen 	h->nr_huge_pages++;
1289a5516438SAndi Kleen 	h->nr_huge_pages_node[nid]++;
1290b7ba30c6SAndi Kleen 	spin_unlock(&hugetlb_lock);
1291b7ba30c6SAndi Kleen }
1292b7ba30c6SAndi Kleen 
1293d00181b9SKirill A. Shutemov static void prep_compound_gigantic_page(struct page *page, unsigned int order)
129420a0307cSWu Fengguang {
129520a0307cSWu Fengguang 	int i;
129620a0307cSWu Fengguang 	int nr_pages = 1 << order;
129720a0307cSWu Fengguang 	struct page *p = page + 1;
129820a0307cSWu Fengguang 
129920a0307cSWu Fengguang 	/* we rely on prep_new_huge_page to set the destructor */
130020a0307cSWu Fengguang 	set_compound_order(page, order);
1301ef5a22beSAndrea Arcangeli 	__ClearPageReserved(page);
1302de09d31dSKirill A. Shutemov 	__SetPageHead(page);
130320a0307cSWu Fengguang 	for (i = 1; i < nr_pages; i++, p = mem_map_next(p, page, i)) {
1304ef5a22beSAndrea Arcangeli 		/*
1305ef5a22beSAndrea Arcangeli 		 * For gigantic hugepages allocated through bootmem at
1306ef5a22beSAndrea Arcangeli 		 * boot, it's safer to be consistent with the not-gigantic
1307ef5a22beSAndrea Arcangeli 		 * hugepages and clear the PG_reserved bit from all tail pages
1308ef5a22beSAndrea Arcangeli 		 * too.  Otherwse drivers using get_user_pages() to access tail
1309ef5a22beSAndrea Arcangeli 		 * pages may get the reference counting wrong if they see
1310ef5a22beSAndrea Arcangeli 		 * PG_reserved set on a tail page (despite the head page not
1311ef5a22beSAndrea Arcangeli 		 * having PG_reserved set).  Enforcing this consistency between
1312ef5a22beSAndrea Arcangeli 		 * head and tail pages allows drivers to optimize away a check
1313ef5a22beSAndrea Arcangeli 		 * on the head page when they need know if put_page() is needed
1314ef5a22beSAndrea Arcangeli 		 * after get_user_pages().
1315ef5a22beSAndrea Arcangeli 		 */
1316ef5a22beSAndrea Arcangeli 		__ClearPageReserved(p);
131758a84aa9SYouquan Song 		set_page_count(p, 0);
13181d798ca3SKirill A. Shutemov 		set_compound_head(p, page);
131920a0307cSWu Fengguang 	}
1320b4330afbSMike Kravetz 	atomic_set(compound_mapcount_ptr(page), -1);
132147e29d32SJohn Hubbard 
132247e29d32SJohn Hubbard 	if (hpage_pincount_available(page))
132347e29d32SJohn Hubbard 		atomic_set(compound_pincount_ptr(page), 0);
132420a0307cSWu Fengguang }
132520a0307cSWu Fengguang 
13267795912cSAndrew Morton /*
13277795912cSAndrew Morton  * PageHuge() only returns true for hugetlbfs pages, but not for normal or
13287795912cSAndrew Morton  * transparent huge pages.  See the PageTransHuge() documentation for more
13297795912cSAndrew Morton  * details.
13307795912cSAndrew Morton  */
133120a0307cSWu Fengguang int PageHuge(struct page *page)
133220a0307cSWu Fengguang {
133320a0307cSWu Fengguang 	if (!PageCompound(page))
133420a0307cSWu Fengguang 		return 0;
133520a0307cSWu Fengguang 
133620a0307cSWu Fengguang 	page = compound_head(page);
1337f1e61557SKirill A. Shutemov 	return page[1].compound_dtor == HUGETLB_PAGE_DTOR;
133820a0307cSWu Fengguang }
133943131e14SNaoya Horiguchi EXPORT_SYMBOL_GPL(PageHuge);
134043131e14SNaoya Horiguchi 
134127c73ae7SAndrea Arcangeli /*
134227c73ae7SAndrea Arcangeli  * PageHeadHuge() only returns true for hugetlbfs head page, but not for
134327c73ae7SAndrea Arcangeli  * normal or transparent huge pages.
134427c73ae7SAndrea Arcangeli  */
134527c73ae7SAndrea Arcangeli int PageHeadHuge(struct page *page_head)
134627c73ae7SAndrea Arcangeli {
134727c73ae7SAndrea Arcangeli 	if (!PageHead(page_head))
134827c73ae7SAndrea Arcangeli 		return 0;
134927c73ae7SAndrea Arcangeli 
1350758f66a2SAndrew Morton 	return get_compound_page_dtor(page_head) == free_huge_page;
135127c73ae7SAndrea Arcangeli }
135227c73ae7SAndrea Arcangeli 
1353c0d0381aSMike Kravetz /*
1354c0d0381aSMike Kravetz  * Find address_space associated with hugetlbfs page.
1355c0d0381aSMike Kravetz  * Upon entry page is locked and page 'was' mapped although mapped state
1356c0d0381aSMike Kravetz  * could change.  If necessary, use anon_vma to find vma and associated
1357c0d0381aSMike Kravetz  * address space.  The returned mapping may be stale, but it can not be
1358c0d0381aSMike Kravetz  * invalid as page lock (which is held) is required to destroy mapping.
1359c0d0381aSMike Kravetz  */
1360c0d0381aSMike Kravetz static struct address_space *_get_hugetlb_page_mapping(struct page *hpage)
1361c0d0381aSMike Kravetz {
1362c0d0381aSMike Kravetz 	struct anon_vma *anon_vma;
1363c0d0381aSMike Kravetz 	pgoff_t pgoff_start, pgoff_end;
1364c0d0381aSMike Kravetz 	struct anon_vma_chain *avc;
1365c0d0381aSMike Kravetz 	struct address_space *mapping = page_mapping(hpage);
1366c0d0381aSMike Kravetz 
1367c0d0381aSMike Kravetz 	/* Simple file based mapping */
1368c0d0381aSMike Kravetz 	if (mapping)
1369c0d0381aSMike Kravetz 		return mapping;
1370c0d0381aSMike Kravetz 
1371c0d0381aSMike Kravetz 	/*
1372c0d0381aSMike Kravetz 	 * Even anonymous hugetlbfs mappings are associated with an
1373c0d0381aSMike Kravetz 	 * underlying hugetlbfs file (see hugetlb_file_setup in mmap
1374c0d0381aSMike Kravetz 	 * code).  Find a vma associated with the anonymous vma, and
1375c0d0381aSMike Kravetz 	 * use the file pointer to get address_space.
1376c0d0381aSMike Kravetz 	 */
1377c0d0381aSMike Kravetz 	anon_vma = page_lock_anon_vma_read(hpage);
1378c0d0381aSMike Kravetz 	if (!anon_vma)
1379c0d0381aSMike Kravetz 		return mapping;  /* NULL */
1380c0d0381aSMike Kravetz 
1381c0d0381aSMike Kravetz 	/* Use first found vma */
1382c0d0381aSMike Kravetz 	pgoff_start = page_to_pgoff(hpage);
1383c0d0381aSMike Kravetz 	pgoff_end = pgoff_start + hpage_nr_pages(hpage) - 1;
1384c0d0381aSMike Kravetz 	anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root,
1385c0d0381aSMike Kravetz 					pgoff_start, pgoff_end) {
1386c0d0381aSMike Kravetz 		struct vm_area_struct *vma = avc->vma;
1387c0d0381aSMike Kravetz 
1388c0d0381aSMike Kravetz 		mapping = vma->vm_file->f_mapping;
1389c0d0381aSMike Kravetz 		break;
1390c0d0381aSMike Kravetz 	}
1391c0d0381aSMike Kravetz 
1392c0d0381aSMike Kravetz 	anon_vma_unlock_read(anon_vma);
1393c0d0381aSMike Kravetz 	return mapping;
1394c0d0381aSMike Kravetz }
1395c0d0381aSMike Kravetz 
1396c0d0381aSMike Kravetz /*
1397c0d0381aSMike Kravetz  * Find and lock address space (mapping) in write mode.
1398c0d0381aSMike Kravetz  *
1399c0d0381aSMike Kravetz  * Upon entry, the page is locked which allows us to find the mapping
1400c0d0381aSMike Kravetz  * even in the case of an anon page.  However, locking order dictates
1401c0d0381aSMike Kravetz  * the i_mmap_rwsem be acquired BEFORE the page lock.  This is hugetlbfs
1402c0d0381aSMike Kravetz  * specific.  So, we first try to lock the sema while still holding the
1403c0d0381aSMike Kravetz  * page lock.  If this works, great!  If not, then we need to drop the
1404c0d0381aSMike Kravetz  * page lock and then acquire i_mmap_rwsem and reacquire page lock.  Of
1405c0d0381aSMike Kravetz  * course, need to revalidate state along the way.
1406c0d0381aSMike Kravetz  */
1407c0d0381aSMike Kravetz struct address_space *hugetlb_page_mapping_lock_write(struct page *hpage)
1408c0d0381aSMike Kravetz {
1409c0d0381aSMike Kravetz 	struct address_space *mapping, *mapping2;
1410c0d0381aSMike Kravetz 
1411c0d0381aSMike Kravetz 	mapping = _get_hugetlb_page_mapping(hpage);
1412c0d0381aSMike Kravetz retry:
1413c0d0381aSMike Kravetz 	if (!mapping)
1414c0d0381aSMike Kravetz 		return mapping;
1415c0d0381aSMike Kravetz 
1416c0d0381aSMike Kravetz 	/*
1417c0d0381aSMike Kravetz 	 * If no contention, take lock and return
1418c0d0381aSMike Kravetz 	 */
1419c0d0381aSMike Kravetz 	if (i_mmap_trylock_write(mapping))
1420c0d0381aSMike Kravetz 		return mapping;
1421c0d0381aSMike Kravetz 
1422c0d0381aSMike Kravetz 	/*
1423c0d0381aSMike Kravetz 	 * Must drop page lock and wait on mapping sema.
1424c0d0381aSMike Kravetz 	 * Note:  Once page lock is dropped, mapping could become invalid.
1425c0d0381aSMike Kravetz 	 * As a hack, increase map count until we lock page again.
1426c0d0381aSMike Kravetz 	 */
1427c0d0381aSMike Kravetz 	atomic_inc(&hpage->_mapcount);
1428c0d0381aSMike Kravetz 	unlock_page(hpage);
1429c0d0381aSMike Kravetz 	i_mmap_lock_write(mapping);
1430c0d0381aSMike Kravetz 	lock_page(hpage);
1431c0d0381aSMike Kravetz 	atomic_add_negative(-1, &hpage->_mapcount);
1432c0d0381aSMike Kravetz 
1433c0d0381aSMike Kravetz 	/* verify page is still mapped */
1434c0d0381aSMike Kravetz 	if (!page_mapped(hpage)) {
1435c0d0381aSMike Kravetz 		i_mmap_unlock_write(mapping);
1436c0d0381aSMike Kravetz 		return NULL;
1437c0d0381aSMike Kravetz 	}
1438c0d0381aSMike Kravetz 
1439c0d0381aSMike Kravetz 	/*
1440c0d0381aSMike Kravetz 	 * Get address space again and verify it is the same one
1441c0d0381aSMike Kravetz 	 * we locked.  If not, drop lock and retry.
1442c0d0381aSMike Kravetz 	 */
1443c0d0381aSMike Kravetz 	mapping2 = _get_hugetlb_page_mapping(hpage);
1444c0d0381aSMike Kravetz 	if (mapping2 != mapping) {
1445c0d0381aSMike Kravetz 		i_mmap_unlock_write(mapping);
1446c0d0381aSMike Kravetz 		mapping = mapping2;
1447c0d0381aSMike Kravetz 		goto retry;
1448c0d0381aSMike Kravetz 	}
1449c0d0381aSMike Kravetz 
1450c0d0381aSMike Kravetz 	return mapping;
1451c0d0381aSMike Kravetz }
1452c0d0381aSMike Kravetz 
145313d60f4bSZhang Yi pgoff_t __basepage_index(struct page *page)
145413d60f4bSZhang Yi {
145513d60f4bSZhang Yi 	struct page *page_head = compound_head(page);
145613d60f4bSZhang Yi 	pgoff_t index = page_index(page_head);
145713d60f4bSZhang Yi 	unsigned long compound_idx;
145813d60f4bSZhang Yi 
145913d60f4bSZhang Yi 	if (!PageHuge(page_head))
146013d60f4bSZhang Yi 		return page_index(page);
146113d60f4bSZhang Yi 
146213d60f4bSZhang Yi 	if (compound_order(page_head) >= MAX_ORDER)
146313d60f4bSZhang Yi 		compound_idx = page_to_pfn(page) - page_to_pfn(page_head);
146413d60f4bSZhang Yi 	else
146513d60f4bSZhang Yi 		compound_idx = page - page_head;
146613d60f4bSZhang Yi 
146713d60f4bSZhang Yi 	return (index << compound_order(page_head)) + compound_idx;
146813d60f4bSZhang Yi }
146913d60f4bSZhang Yi 
14700c397daeSMichal Hocko static struct page *alloc_buddy_huge_page(struct hstate *h,
1471f60858f9SMike Kravetz 		gfp_t gfp_mask, int nid, nodemask_t *nmask,
1472f60858f9SMike Kravetz 		nodemask_t *node_alloc_noretry)
14731da177e4SLinus Torvalds {
1474af0fb9dfSMichal Hocko 	int order = huge_page_order(h);
14751da177e4SLinus Torvalds 	struct page *page;
1476f60858f9SMike Kravetz 	bool alloc_try_hard = true;
1477f96efd58SJoe Jin 
1478f60858f9SMike Kravetz 	/*
1479f60858f9SMike Kravetz 	 * By default we always try hard to allocate the page with
1480f60858f9SMike Kravetz 	 * __GFP_RETRY_MAYFAIL flag.  However, if we are allocating pages in
1481f60858f9SMike Kravetz 	 * a loop (to adjust global huge page counts) and previous allocation
1482f60858f9SMike Kravetz 	 * failed, do not continue to try hard on the same node.  Use the
1483f60858f9SMike Kravetz 	 * node_alloc_noretry bitmap to manage this state information.
1484f60858f9SMike Kravetz 	 */
1485f60858f9SMike Kravetz 	if (node_alloc_noretry && node_isset(nid, *node_alloc_noretry))
1486f60858f9SMike Kravetz 		alloc_try_hard = false;
1487f60858f9SMike Kravetz 	gfp_mask |= __GFP_COMP|__GFP_NOWARN;
1488f60858f9SMike Kravetz 	if (alloc_try_hard)
1489f60858f9SMike Kravetz 		gfp_mask |= __GFP_RETRY_MAYFAIL;
1490af0fb9dfSMichal Hocko 	if (nid == NUMA_NO_NODE)
1491af0fb9dfSMichal Hocko 		nid = numa_mem_id();
1492af0fb9dfSMichal Hocko 	page = __alloc_pages_nodemask(gfp_mask, order, nid, nmask);
1493af0fb9dfSMichal Hocko 	if (page)
1494af0fb9dfSMichal Hocko 		__count_vm_event(HTLB_BUDDY_PGALLOC);
1495af0fb9dfSMichal Hocko 	else
1496af0fb9dfSMichal Hocko 		__count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
149763b4613cSNishanth Aravamudan 
1498f60858f9SMike Kravetz 	/*
1499f60858f9SMike Kravetz 	 * If we did not specify __GFP_RETRY_MAYFAIL, but still got a page this
1500f60858f9SMike Kravetz 	 * indicates an overall state change.  Clear bit so that we resume
1501f60858f9SMike Kravetz 	 * normal 'try hard' allocations.
1502f60858f9SMike Kravetz 	 */
1503f60858f9SMike Kravetz 	if (node_alloc_noretry && page && !alloc_try_hard)
1504f60858f9SMike Kravetz 		node_clear(nid, *node_alloc_noretry);
1505f60858f9SMike Kravetz 
1506f60858f9SMike Kravetz 	/*
1507f60858f9SMike Kravetz 	 * If we tried hard to get a page but failed, set bit so that
1508f60858f9SMike Kravetz 	 * subsequent attempts will not try as hard until there is an
1509f60858f9SMike Kravetz 	 * overall state change.
1510f60858f9SMike Kravetz 	 */
1511f60858f9SMike Kravetz 	if (node_alloc_noretry && !page && alloc_try_hard)
1512f60858f9SMike Kravetz 		node_set(nid, *node_alloc_noretry);
1513f60858f9SMike Kravetz 
151463b4613cSNishanth Aravamudan 	return page;
151563b4613cSNishanth Aravamudan }
151663b4613cSNishanth Aravamudan 
1517af0fb9dfSMichal Hocko /*
15180c397daeSMichal Hocko  * Common helper to allocate a fresh hugetlb page. All specific allocators
15190c397daeSMichal Hocko  * should use this function to get new hugetlb pages
15200c397daeSMichal Hocko  */
15210c397daeSMichal Hocko static struct page *alloc_fresh_huge_page(struct hstate *h,
1522f60858f9SMike Kravetz 		gfp_t gfp_mask, int nid, nodemask_t *nmask,
1523f60858f9SMike Kravetz 		nodemask_t *node_alloc_noretry)
15240c397daeSMichal Hocko {
15250c397daeSMichal Hocko 	struct page *page;
15260c397daeSMichal Hocko 
15270c397daeSMichal Hocko 	if (hstate_is_gigantic(h))
15280c397daeSMichal Hocko 		page = alloc_gigantic_page(h, gfp_mask, nid, nmask);
15290c397daeSMichal Hocko 	else
15300c397daeSMichal Hocko 		page = alloc_buddy_huge_page(h, gfp_mask,
1531f60858f9SMike Kravetz 				nid, nmask, node_alloc_noretry);
15320c397daeSMichal Hocko 	if (!page)
15330c397daeSMichal Hocko 		return NULL;
15340c397daeSMichal Hocko 
15350c397daeSMichal Hocko 	if (hstate_is_gigantic(h))
15360c397daeSMichal Hocko 		prep_compound_gigantic_page(page, huge_page_order(h));
15370c397daeSMichal Hocko 	prep_new_huge_page(h, page, page_to_nid(page));
15380c397daeSMichal Hocko 
15390c397daeSMichal Hocko 	return page;
15400c397daeSMichal Hocko }
15410c397daeSMichal Hocko 
15420c397daeSMichal Hocko /*
1543af0fb9dfSMichal Hocko  * Allocates a fresh page to the hugetlb allocator pool in the node interleaved
1544af0fb9dfSMichal Hocko  * manner.
1545af0fb9dfSMichal Hocko  */
1546f60858f9SMike Kravetz static int alloc_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed,
1547f60858f9SMike Kravetz 				nodemask_t *node_alloc_noretry)
1548b2261026SJoonsoo Kim {
1549b2261026SJoonsoo Kim 	struct page *page;
1550b2261026SJoonsoo Kim 	int nr_nodes, node;
1551af0fb9dfSMichal Hocko 	gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
1552b2261026SJoonsoo Kim 
1553b2261026SJoonsoo Kim 	for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
1554f60858f9SMike Kravetz 		page = alloc_fresh_huge_page(h, gfp_mask, node, nodes_allowed,
1555f60858f9SMike Kravetz 						node_alloc_noretry);
1556af0fb9dfSMichal Hocko 		if (page)
1557b2261026SJoonsoo Kim 			break;
1558b2261026SJoonsoo Kim 	}
1559b2261026SJoonsoo Kim 
1560af0fb9dfSMichal Hocko 	if (!page)
1561af0fb9dfSMichal Hocko 		return 0;
1562b2261026SJoonsoo Kim 
1563af0fb9dfSMichal Hocko 	put_page(page); /* free it into the hugepage allocator */
1564af0fb9dfSMichal Hocko 
1565af0fb9dfSMichal Hocko 	return 1;
1566b2261026SJoonsoo Kim }
1567b2261026SJoonsoo Kim 
1568e8c5c824SLee Schermerhorn /*
1569e8c5c824SLee Schermerhorn  * Free huge page from pool from next node to free.
1570e8c5c824SLee Schermerhorn  * Attempt to keep persistent huge pages more or less
1571e8c5c824SLee Schermerhorn  * balanced over allowed nodes.
1572e8c5c824SLee Schermerhorn  * Called with hugetlb_lock locked.
1573e8c5c824SLee Schermerhorn  */
15746ae11b27SLee Schermerhorn static int free_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed,
15756ae11b27SLee Schermerhorn 							 bool acct_surplus)
1576e8c5c824SLee Schermerhorn {
1577b2261026SJoonsoo Kim 	int nr_nodes, node;
1578e8c5c824SLee Schermerhorn 	int ret = 0;
1579e8c5c824SLee Schermerhorn 
1580b2261026SJoonsoo Kim 	for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
1581685f3457SLee Schermerhorn 		/*
1582685f3457SLee Schermerhorn 		 * If we're returning unused surplus pages, only examine
1583685f3457SLee Schermerhorn 		 * nodes with surplus pages.
1584685f3457SLee Schermerhorn 		 */
1585b2261026SJoonsoo Kim 		if ((!acct_surplus || h->surplus_huge_pages_node[node]) &&
1586b2261026SJoonsoo Kim 		    !list_empty(&h->hugepage_freelists[node])) {
1587e8c5c824SLee Schermerhorn 			struct page *page =
1588b2261026SJoonsoo Kim 				list_entry(h->hugepage_freelists[node].next,
1589e8c5c824SLee Schermerhorn 					  struct page, lru);
1590e8c5c824SLee Schermerhorn 			list_del(&page->lru);
1591e8c5c824SLee Schermerhorn 			h->free_huge_pages--;
1592b2261026SJoonsoo Kim 			h->free_huge_pages_node[node]--;
1593685f3457SLee Schermerhorn 			if (acct_surplus) {
1594685f3457SLee Schermerhorn 				h->surplus_huge_pages--;
1595b2261026SJoonsoo Kim 				h->surplus_huge_pages_node[node]--;
1596685f3457SLee Schermerhorn 			}
1597e8c5c824SLee Schermerhorn 			update_and_free_page(h, page);
1598e8c5c824SLee Schermerhorn 			ret = 1;
15999a76db09SLee Schermerhorn 			break;
1600e8c5c824SLee Schermerhorn 		}
1601b2261026SJoonsoo Kim 	}
1602e8c5c824SLee Schermerhorn 
1603e8c5c824SLee Schermerhorn 	return ret;
1604e8c5c824SLee Schermerhorn }
1605e8c5c824SLee Schermerhorn 
1606c8721bbbSNaoya Horiguchi /*
1607c8721bbbSNaoya Horiguchi  * Dissolve a given free hugepage into free buddy pages. This function does
1608faf53defSNaoya Horiguchi  * nothing for in-use hugepages and non-hugepages.
1609faf53defSNaoya Horiguchi  * This function returns values like below:
1610faf53defSNaoya Horiguchi  *
1611faf53defSNaoya Horiguchi  *  -EBUSY: failed to dissolved free hugepages or the hugepage is in-use
1612faf53defSNaoya Horiguchi  *          (allocated or reserved.)
1613faf53defSNaoya Horiguchi  *       0: successfully dissolved free hugepages or the page is not a
1614faf53defSNaoya Horiguchi  *          hugepage (considered as already dissolved)
1615c8721bbbSNaoya Horiguchi  */
1616c3114a84SAnshuman Khandual int dissolve_free_huge_page(struct page *page)
1617c8721bbbSNaoya Horiguchi {
16186bc9b564SNaoya Horiguchi 	int rc = -EBUSY;
1619082d5b6bSGerald Schaefer 
1620faf53defSNaoya Horiguchi 	/* Not to disrupt normal path by vainly holding hugetlb_lock */
1621faf53defSNaoya Horiguchi 	if (!PageHuge(page))
1622faf53defSNaoya Horiguchi 		return 0;
1623faf53defSNaoya Horiguchi 
1624c8721bbbSNaoya Horiguchi 	spin_lock(&hugetlb_lock);
1625faf53defSNaoya Horiguchi 	if (!PageHuge(page)) {
1626faf53defSNaoya Horiguchi 		rc = 0;
1627faf53defSNaoya Horiguchi 		goto out;
1628faf53defSNaoya Horiguchi 	}
1629faf53defSNaoya Horiguchi 
1630faf53defSNaoya Horiguchi 	if (!page_count(page)) {
16312247bb33SGerald Schaefer 		struct page *head = compound_head(page);
16322247bb33SGerald Schaefer 		struct hstate *h = page_hstate(head);
16332247bb33SGerald Schaefer 		int nid = page_to_nid(head);
16346bc9b564SNaoya Horiguchi 		if (h->free_huge_pages - h->resv_huge_pages == 0)
1635082d5b6bSGerald Schaefer 			goto out;
1636c3114a84SAnshuman Khandual 		/*
1637c3114a84SAnshuman Khandual 		 * Move PageHWPoison flag from head page to the raw error page,
1638c3114a84SAnshuman Khandual 		 * which makes any subpages rather than the error page reusable.
1639c3114a84SAnshuman Khandual 		 */
1640c3114a84SAnshuman Khandual 		if (PageHWPoison(head) && page != head) {
1641c3114a84SAnshuman Khandual 			SetPageHWPoison(page);
1642c3114a84SAnshuman Khandual 			ClearPageHWPoison(head);
1643c3114a84SAnshuman Khandual 		}
16442247bb33SGerald Schaefer 		list_del(&head->lru);
1645c8721bbbSNaoya Horiguchi 		h->free_huge_pages--;
1646c8721bbbSNaoya Horiguchi 		h->free_huge_pages_node[nid]--;
1647c1470b33Szhong jiang 		h->max_huge_pages--;
16482247bb33SGerald Schaefer 		update_and_free_page(h, head);
16496bc9b564SNaoya Horiguchi 		rc = 0;
1650c8721bbbSNaoya Horiguchi 	}
1651082d5b6bSGerald Schaefer out:
1652c8721bbbSNaoya Horiguchi 	spin_unlock(&hugetlb_lock);
1653082d5b6bSGerald Schaefer 	return rc;
1654c8721bbbSNaoya Horiguchi }
1655c8721bbbSNaoya Horiguchi 
1656c8721bbbSNaoya Horiguchi /*
1657c8721bbbSNaoya Horiguchi  * Dissolve free hugepages in a given pfn range. Used by memory hotplug to
1658c8721bbbSNaoya Horiguchi  * make specified memory blocks removable from the system.
16592247bb33SGerald Schaefer  * Note that this will dissolve a free gigantic hugepage completely, if any
16602247bb33SGerald Schaefer  * part of it lies within the given range.
1661082d5b6bSGerald Schaefer  * Also note that if dissolve_free_huge_page() returns with an error, all
1662082d5b6bSGerald Schaefer  * free hugepages that were dissolved before that error are lost.
1663c8721bbbSNaoya Horiguchi  */
1664082d5b6bSGerald Schaefer int dissolve_free_huge_pages(unsigned long start_pfn, unsigned long end_pfn)
1665c8721bbbSNaoya Horiguchi {
1666c8721bbbSNaoya Horiguchi 	unsigned long pfn;
1667eb03aa00SGerald Schaefer 	struct page *page;
1668082d5b6bSGerald Schaefer 	int rc = 0;
1669c8721bbbSNaoya Horiguchi 
1670d0177639SLi Zhong 	if (!hugepages_supported())
1671082d5b6bSGerald Schaefer 		return rc;
1672d0177639SLi Zhong 
1673eb03aa00SGerald Schaefer 	for (pfn = start_pfn; pfn < end_pfn; pfn += 1 << minimum_order) {
1674eb03aa00SGerald Schaefer 		page = pfn_to_page(pfn);
1675eb03aa00SGerald Schaefer 		rc = dissolve_free_huge_page(page);
1676eb03aa00SGerald Schaefer 		if (rc)
1677082d5b6bSGerald Schaefer 			break;
1678eb03aa00SGerald Schaefer 	}
1679082d5b6bSGerald Schaefer 
1680082d5b6bSGerald Schaefer 	return rc;
1681c8721bbbSNaoya Horiguchi }
1682c8721bbbSNaoya Horiguchi 
1683ab5ac90aSMichal Hocko /*
1684ab5ac90aSMichal Hocko  * Allocates a fresh surplus page from the page allocator.
1685ab5ac90aSMichal Hocko  */
16860c397daeSMichal Hocko static struct page *alloc_surplus_huge_page(struct hstate *h, gfp_t gfp_mask,
1687aaf14e40SMichal Hocko 		int nid, nodemask_t *nmask)
16887893d1d5SAdam Litke {
16899980d744SMichal Hocko 	struct page *page = NULL;
16907893d1d5SAdam Litke 
1691bae7f4aeSLuiz Capitulino 	if (hstate_is_gigantic(h))
1692aa888a74SAndi Kleen 		return NULL;
1693aa888a74SAndi Kleen 
1694d1c3fb1fSNishanth Aravamudan 	spin_lock(&hugetlb_lock);
16959980d744SMichal Hocko 	if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages)
16969980d744SMichal Hocko 		goto out_unlock;
1697d1c3fb1fSNishanth Aravamudan 	spin_unlock(&hugetlb_lock);
1698d1c3fb1fSNishanth Aravamudan 
1699f60858f9SMike Kravetz 	page = alloc_fresh_huge_page(h, gfp_mask, nid, nmask, NULL);
17009980d744SMichal Hocko 	if (!page)
17010c397daeSMichal Hocko 		return NULL;
1702d1c3fb1fSNishanth Aravamudan 
17037893d1d5SAdam Litke 	spin_lock(&hugetlb_lock);
17049980d744SMichal Hocko 	/*
17059980d744SMichal Hocko 	 * We could have raced with the pool size change.
17069980d744SMichal Hocko 	 * Double check that and simply deallocate the new page
17079980d744SMichal Hocko 	 * if we would end up overcommiting the surpluses. Abuse
17089980d744SMichal Hocko 	 * temporary page to workaround the nasty free_huge_page
17099980d744SMichal Hocko 	 * codeflow
17109980d744SMichal Hocko 	 */
17119980d744SMichal Hocko 	if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) {
17129980d744SMichal Hocko 		SetPageHugeTemporary(page);
17132bf753e6SKai Shen 		spin_unlock(&hugetlb_lock);
17149980d744SMichal Hocko 		put_page(page);
17152bf753e6SKai Shen 		return NULL;
17169980d744SMichal Hocko 	} else {
17179980d744SMichal Hocko 		h->surplus_huge_pages++;
17184704dea3SMichal Hocko 		h->surplus_huge_pages_node[page_to_nid(page)]++;
17197893d1d5SAdam Litke 	}
17209980d744SMichal Hocko 
17219980d744SMichal Hocko out_unlock:
1722d1c3fb1fSNishanth Aravamudan 	spin_unlock(&hugetlb_lock);
17237893d1d5SAdam Litke 
17247893d1d5SAdam Litke 	return page;
17257893d1d5SAdam Litke }
17267893d1d5SAdam Litke 
17279a4e9f3bSAneesh Kumar K.V struct page *alloc_migrate_huge_page(struct hstate *h, gfp_t gfp_mask,
1728ab5ac90aSMichal Hocko 				     int nid, nodemask_t *nmask)
1729ab5ac90aSMichal Hocko {
1730ab5ac90aSMichal Hocko 	struct page *page;
1731ab5ac90aSMichal Hocko 
1732ab5ac90aSMichal Hocko 	if (hstate_is_gigantic(h))
1733ab5ac90aSMichal Hocko 		return NULL;
1734ab5ac90aSMichal Hocko 
1735f60858f9SMike Kravetz 	page = alloc_fresh_huge_page(h, gfp_mask, nid, nmask, NULL);
1736ab5ac90aSMichal Hocko 	if (!page)
1737ab5ac90aSMichal Hocko 		return NULL;
1738ab5ac90aSMichal Hocko 
1739ab5ac90aSMichal Hocko 	/*
1740ab5ac90aSMichal Hocko 	 * We do not account these pages as surplus because they are only
1741ab5ac90aSMichal Hocko 	 * temporary and will be released properly on the last reference
1742ab5ac90aSMichal Hocko 	 */
1743ab5ac90aSMichal Hocko 	SetPageHugeTemporary(page);
1744ab5ac90aSMichal Hocko 
1745ab5ac90aSMichal Hocko 	return page;
1746ab5ac90aSMichal Hocko }
1747ab5ac90aSMichal Hocko 
1748e4e574b7SAdam Litke /*
1749099730d6SDave Hansen  * Use the VMA's mpolicy to allocate a huge page from the buddy.
1750099730d6SDave Hansen  */
1751e0ec90eeSDave Hansen static
17520c397daeSMichal Hocko struct page *alloc_buddy_huge_page_with_mpol(struct hstate *h,
1753099730d6SDave Hansen 		struct vm_area_struct *vma, unsigned long addr)
1754099730d6SDave Hansen {
1755aaf14e40SMichal Hocko 	struct page *page;
1756aaf14e40SMichal Hocko 	struct mempolicy *mpol;
1757aaf14e40SMichal Hocko 	gfp_t gfp_mask = htlb_alloc_mask(h);
1758aaf14e40SMichal Hocko 	int nid;
1759aaf14e40SMichal Hocko 	nodemask_t *nodemask;
1760aaf14e40SMichal Hocko 
1761aaf14e40SMichal Hocko 	nid = huge_node(vma, addr, gfp_mask, &mpol, &nodemask);
17620c397daeSMichal Hocko 	page = alloc_surplus_huge_page(h, gfp_mask, nid, nodemask);
1763aaf14e40SMichal Hocko 	mpol_cond_put(mpol);
1764aaf14e40SMichal Hocko 
1765aaf14e40SMichal Hocko 	return page;
1766099730d6SDave Hansen }
1767099730d6SDave Hansen 
1768ab5ac90aSMichal Hocko /* page migration callback function */
1769bf50bab2SNaoya Horiguchi struct page *alloc_huge_page_node(struct hstate *h, int nid)
1770bf50bab2SNaoya Horiguchi {
1771aaf14e40SMichal Hocko 	gfp_t gfp_mask = htlb_alloc_mask(h);
17724ef91848SJoonsoo Kim 	struct page *page = NULL;
1773bf50bab2SNaoya Horiguchi 
1774aaf14e40SMichal Hocko 	if (nid != NUMA_NO_NODE)
1775aaf14e40SMichal Hocko 		gfp_mask |= __GFP_THISNODE;
1776aaf14e40SMichal Hocko 
1777bf50bab2SNaoya Horiguchi 	spin_lock(&hugetlb_lock);
17784ef91848SJoonsoo Kim 	if (h->free_huge_pages - h->resv_huge_pages > 0)
17793e59fcb0SMichal Hocko 		page = dequeue_huge_page_nodemask(h, gfp_mask, nid, NULL);
1780bf50bab2SNaoya Horiguchi 	spin_unlock(&hugetlb_lock);
1781bf50bab2SNaoya Horiguchi 
178294ae8ba7SAneesh Kumar K.V 	if (!page)
17830c397daeSMichal Hocko 		page = alloc_migrate_huge_page(h, gfp_mask, nid, NULL);
1784bf50bab2SNaoya Horiguchi 
1785bf50bab2SNaoya Horiguchi 	return page;
1786bf50bab2SNaoya Horiguchi }
1787bf50bab2SNaoya Horiguchi 
1788ab5ac90aSMichal Hocko /* page migration callback function */
17893e59fcb0SMichal Hocko struct page *alloc_huge_page_nodemask(struct hstate *h, int preferred_nid,
17903e59fcb0SMichal Hocko 		nodemask_t *nmask)
17914db9b2efSMichal Hocko {
1792aaf14e40SMichal Hocko 	gfp_t gfp_mask = htlb_alloc_mask(h);
17934db9b2efSMichal Hocko 
17944db9b2efSMichal Hocko 	spin_lock(&hugetlb_lock);
17954db9b2efSMichal Hocko 	if (h->free_huge_pages - h->resv_huge_pages > 0) {
17963e59fcb0SMichal Hocko 		struct page *page;
17973e59fcb0SMichal Hocko 
17983e59fcb0SMichal Hocko 		page = dequeue_huge_page_nodemask(h, gfp_mask, preferred_nid, nmask);
17993e59fcb0SMichal Hocko 		if (page) {
18003e59fcb0SMichal Hocko 			spin_unlock(&hugetlb_lock);
18013e59fcb0SMichal Hocko 			return page;
18024db9b2efSMichal Hocko 		}
18034db9b2efSMichal Hocko 	}
18044db9b2efSMichal Hocko 	spin_unlock(&hugetlb_lock);
18054db9b2efSMichal Hocko 
18060c397daeSMichal Hocko 	return alloc_migrate_huge_page(h, gfp_mask, preferred_nid, nmask);
18074db9b2efSMichal Hocko }
18084db9b2efSMichal Hocko 
1809ebd63723SMichal Hocko /* mempolicy aware migration callback */
1810389c8178SMichal Hocko struct page *alloc_huge_page_vma(struct hstate *h, struct vm_area_struct *vma,
1811389c8178SMichal Hocko 		unsigned long address)
1812ebd63723SMichal Hocko {
1813ebd63723SMichal Hocko 	struct mempolicy *mpol;
1814ebd63723SMichal Hocko 	nodemask_t *nodemask;
1815ebd63723SMichal Hocko 	struct page *page;
1816ebd63723SMichal Hocko 	gfp_t gfp_mask;
1817ebd63723SMichal Hocko 	int node;
1818ebd63723SMichal Hocko 
1819ebd63723SMichal Hocko 	gfp_mask = htlb_alloc_mask(h);
1820ebd63723SMichal Hocko 	node = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
1821ebd63723SMichal Hocko 	page = alloc_huge_page_nodemask(h, node, nodemask);
1822ebd63723SMichal Hocko 	mpol_cond_put(mpol);
1823ebd63723SMichal Hocko 
1824ebd63723SMichal Hocko 	return page;
1825ebd63723SMichal Hocko }
1826ebd63723SMichal Hocko 
1827bf50bab2SNaoya Horiguchi /*
182825985edcSLucas De Marchi  * Increase the hugetlb pool such that it can accommodate a reservation
1829e4e574b7SAdam Litke  * of size 'delta'.
1830e4e574b7SAdam Litke  */
1831a5516438SAndi Kleen static int gather_surplus_pages(struct hstate *h, int delta)
1832e4e574b7SAdam Litke {
1833e4e574b7SAdam Litke 	struct list_head surplus_list;
1834e4e574b7SAdam Litke 	struct page *page, *tmp;
1835e4e574b7SAdam Litke 	int ret, i;
1836e4e574b7SAdam Litke 	int needed, allocated;
183728073b02SHillf Danton 	bool alloc_ok = true;
1838e4e574b7SAdam Litke 
1839a5516438SAndi Kleen 	needed = (h->resv_huge_pages + delta) - h->free_huge_pages;
1840ac09b3a1SAdam Litke 	if (needed <= 0) {
1841a5516438SAndi Kleen 		h->resv_huge_pages += delta;
1842e4e574b7SAdam Litke 		return 0;
1843ac09b3a1SAdam Litke 	}
1844e4e574b7SAdam Litke 
1845e4e574b7SAdam Litke 	allocated = 0;
1846e4e574b7SAdam Litke 	INIT_LIST_HEAD(&surplus_list);
1847e4e574b7SAdam Litke 
1848e4e574b7SAdam Litke 	ret = -ENOMEM;
1849e4e574b7SAdam Litke retry:
1850e4e574b7SAdam Litke 	spin_unlock(&hugetlb_lock);
1851e4e574b7SAdam Litke 	for (i = 0; i < needed; i++) {
18520c397daeSMichal Hocko 		page = alloc_surplus_huge_page(h, htlb_alloc_mask(h),
1853aaf14e40SMichal Hocko 				NUMA_NO_NODE, NULL);
185428073b02SHillf Danton 		if (!page) {
185528073b02SHillf Danton 			alloc_ok = false;
185628073b02SHillf Danton 			break;
185728073b02SHillf Danton 		}
1858e4e574b7SAdam Litke 		list_add(&page->lru, &surplus_list);
185969ed779aSDavid Rientjes 		cond_resched();
1860e4e574b7SAdam Litke 	}
186128073b02SHillf Danton 	allocated += i;
1862e4e574b7SAdam Litke 
1863e4e574b7SAdam Litke 	/*
1864e4e574b7SAdam Litke 	 * After retaking hugetlb_lock, we need to recalculate 'needed'
1865e4e574b7SAdam Litke 	 * because either resv_huge_pages or free_huge_pages may have changed.
1866e4e574b7SAdam Litke 	 */
1867e4e574b7SAdam Litke 	spin_lock(&hugetlb_lock);
1868a5516438SAndi Kleen 	needed = (h->resv_huge_pages + delta) -
1869a5516438SAndi Kleen 			(h->free_huge_pages + allocated);
187028073b02SHillf Danton 	if (needed > 0) {
187128073b02SHillf Danton 		if (alloc_ok)
1872e4e574b7SAdam Litke 			goto retry;
187328073b02SHillf Danton 		/*
187428073b02SHillf Danton 		 * We were not able to allocate enough pages to
187528073b02SHillf Danton 		 * satisfy the entire reservation so we free what
187628073b02SHillf Danton 		 * we've allocated so far.
187728073b02SHillf Danton 		 */
187828073b02SHillf Danton 		goto free;
187928073b02SHillf Danton 	}
1880e4e574b7SAdam Litke 	/*
1881e4e574b7SAdam Litke 	 * The surplus_list now contains _at_least_ the number of extra pages
188225985edcSLucas De Marchi 	 * needed to accommodate the reservation.  Add the appropriate number
1883e4e574b7SAdam Litke 	 * of pages to the hugetlb pool and free the extras back to the buddy
1884ac09b3a1SAdam Litke 	 * allocator.  Commit the entire reservation here to prevent another
1885ac09b3a1SAdam Litke 	 * process from stealing the pages as they are added to the pool but
1886ac09b3a1SAdam Litke 	 * before they are reserved.
1887e4e574b7SAdam Litke 	 */
1888e4e574b7SAdam Litke 	needed += allocated;
1889a5516438SAndi Kleen 	h->resv_huge_pages += delta;
1890e4e574b7SAdam Litke 	ret = 0;
1891a9869b83SNaoya Horiguchi 
189219fc3f0aSAdam Litke 	/* Free the needed pages to the hugetlb pool */
189319fc3f0aSAdam Litke 	list_for_each_entry_safe(page, tmp, &surplus_list, lru) {
189419fc3f0aSAdam Litke 		if ((--needed) < 0)
189519fc3f0aSAdam Litke 			break;
1896a9869b83SNaoya Horiguchi 		/*
1897a9869b83SNaoya Horiguchi 		 * This page is now managed by the hugetlb allocator and has
1898a9869b83SNaoya Horiguchi 		 * no users -- drop the buddy allocator's reference.
1899a9869b83SNaoya Horiguchi 		 */
1900a9869b83SNaoya Horiguchi 		put_page_testzero(page);
1901309381feSSasha Levin 		VM_BUG_ON_PAGE(page_count(page), page);
1902a5516438SAndi Kleen 		enqueue_huge_page(h, page);
190319fc3f0aSAdam Litke 	}
190428073b02SHillf Danton free:
1905b0365c8dSHillf Danton 	spin_unlock(&hugetlb_lock);
190619fc3f0aSAdam Litke 
190719fc3f0aSAdam Litke 	/* Free unnecessary surplus pages to the buddy allocator */
1908c0d934baSJoonsoo Kim 	list_for_each_entry_safe(page, tmp, &surplus_list, lru)
1909a9869b83SNaoya Horiguchi 		put_page(page);
191019fc3f0aSAdam Litke 	spin_lock(&hugetlb_lock);
1911e4e574b7SAdam Litke 
1912e4e574b7SAdam Litke 	return ret;
1913e4e574b7SAdam Litke }
1914e4e574b7SAdam Litke 
1915e4e574b7SAdam Litke /*
1916e5bbc8a6SMike Kravetz  * This routine has two main purposes:
1917e5bbc8a6SMike Kravetz  * 1) Decrement the reservation count (resv_huge_pages) by the value passed
1918e5bbc8a6SMike Kravetz  *    in unused_resv_pages.  This corresponds to the prior adjustments made
1919e5bbc8a6SMike Kravetz  *    to the associated reservation map.
1920e5bbc8a6SMike Kravetz  * 2) Free any unused surplus pages that may have been allocated to satisfy
1921e5bbc8a6SMike Kravetz  *    the reservation.  As many as unused_resv_pages may be freed.
1922e5bbc8a6SMike Kravetz  *
1923e5bbc8a6SMike Kravetz  * Called with hugetlb_lock held.  However, the lock could be dropped (and
1924e5bbc8a6SMike Kravetz  * reacquired) during calls to cond_resched_lock.  Whenever dropping the lock,
1925e5bbc8a6SMike Kravetz  * we must make sure nobody else can claim pages we are in the process of
1926e5bbc8a6SMike Kravetz  * freeing.  Do this by ensuring resv_huge_page always is greater than the
1927e5bbc8a6SMike Kravetz  * number of huge pages we plan to free when dropping the lock.
1928e4e574b7SAdam Litke  */
1929a5516438SAndi Kleen static void return_unused_surplus_pages(struct hstate *h,
1930a5516438SAndi Kleen 					unsigned long unused_resv_pages)
1931e4e574b7SAdam Litke {
1932e4e574b7SAdam Litke 	unsigned long nr_pages;
1933e4e574b7SAdam Litke 
1934aa888a74SAndi Kleen 	/* Cannot return gigantic pages currently */
1935bae7f4aeSLuiz Capitulino 	if (hstate_is_gigantic(h))
1936e5bbc8a6SMike Kravetz 		goto out;
1937aa888a74SAndi Kleen 
1938e5bbc8a6SMike Kravetz 	/*
1939e5bbc8a6SMike Kravetz 	 * Part (or even all) of the reservation could have been backed
1940e5bbc8a6SMike Kravetz 	 * by pre-allocated pages. Only free surplus pages.
1941e5bbc8a6SMike Kravetz 	 */
1942a5516438SAndi Kleen 	nr_pages = min(unused_resv_pages, h->surplus_huge_pages);
1943e4e574b7SAdam Litke 
1944685f3457SLee Schermerhorn 	/*
1945685f3457SLee Schermerhorn 	 * We want to release as many surplus pages as possible, spread
19469b5e5d0fSLee Schermerhorn 	 * evenly across all nodes with memory. Iterate across these nodes
19479b5e5d0fSLee Schermerhorn 	 * until we can no longer free unreserved surplus pages. This occurs
19489b5e5d0fSLee Schermerhorn 	 * when the nodes with surplus pages have no free pages.
19499b5e5d0fSLee Schermerhorn 	 * free_pool_huge_page() will balance the the freed pages across the
19509b5e5d0fSLee Schermerhorn 	 * on-line nodes with memory and will handle the hstate accounting.
1951e5bbc8a6SMike Kravetz 	 *
1952e5bbc8a6SMike Kravetz 	 * Note that we decrement resv_huge_pages as we free the pages.  If
1953e5bbc8a6SMike Kravetz 	 * we drop the lock, resv_huge_pages will still be sufficiently large
1954e5bbc8a6SMike Kravetz 	 * to cover subsequent pages we may free.
1955685f3457SLee Schermerhorn 	 */
1956685f3457SLee Schermerhorn 	while (nr_pages--) {
1957e5bbc8a6SMike Kravetz 		h->resv_huge_pages--;
1958e5bbc8a6SMike Kravetz 		unused_resv_pages--;
19598cebfcd0SLai Jiangshan 		if (!free_pool_huge_page(h, &node_states[N_MEMORY], 1))
1960e5bbc8a6SMike Kravetz 			goto out;
19617848a4bfSMizuma, Masayoshi 		cond_resched_lock(&hugetlb_lock);
1962e4e574b7SAdam Litke 	}
1963e5bbc8a6SMike Kravetz 
1964e5bbc8a6SMike Kravetz out:
1965e5bbc8a6SMike Kravetz 	/* Fully uncommit the reservation */
1966e5bbc8a6SMike Kravetz 	h->resv_huge_pages -= unused_resv_pages;
1967e4e574b7SAdam Litke }
1968e4e574b7SAdam Litke 
19695e911373SMike Kravetz 
1970c37f9fb1SAndy Whitcroft /*
1971feba16e2SMike Kravetz  * vma_needs_reservation, vma_commit_reservation and vma_end_reservation
19725e911373SMike Kravetz  * are used by the huge page allocation routines to manage reservations.
1973cf3ad20bSMike Kravetz  *
1974cf3ad20bSMike Kravetz  * vma_needs_reservation is called to determine if the huge page at addr
1975cf3ad20bSMike Kravetz  * within the vma has an associated reservation.  If a reservation is
1976cf3ad20bSMike Kravetz  * needed, the value 1 is returned.  The caller is then responsible for
1977cf3ad20bSMike Kravetz  * managing the global reservation and subpool usage counts.  After
1978cf3ad20bSMike Kravetz  * the huge page has been allocated, vma_commit_reservation is called
1979feba16e2SMike Kravetz  * to add the page to the reservation map.  If the page allocation fails,
1980feba16e2SMike Kravetz  * the reservation must be ended instead of committed.  vma_end_reservation
1981feba16e2SMike Kravetz  * is called in such cases.
1982cf3ad20bSMike Kravetz  *
1983cf3ad20bSMike Kravetz  * In the normal case, vma_commit_reservation returns the same value
1984cf3ad20bSMike Kravetz  * as the preceding vma_needs_reservation call.  The only time this
1985cf3ad20bSMike Kravetz  * is not the case is if a reserve map was changed between calls.  It
1986cf3ad20bSMike Kravetz  * is the responsibility of the caller to notice the difference and
1987cf3ad20bSMike Kravetz  * take appropriate action.
198896b96a96SMike Kravetz  *
198996b96a96SMike Kravetz  * vma_add_reservation is used in error paths where a reservation must
199096b96a96SMike Kravetz  * be restored when a newly allocated huge page must be freed.  It is
199196b96a96SMike Kravetz  * to be called after calling vma_needs_reservation to determine if a
199296b96a96SMike Kravetz  * reservation exists.
1993c37f9fb1SAndy Whitcroft  */
19945e911373SMike Kravetz enum vma_resv_mode {
19955e911373SMike Kravetz 	VMA_NEEDS_RESV,
19965e911373SMike Kravetz 	VMA_COMMIT_RESV,
1997feba16e2SMike Kravetz 	VMA_END_RESV,
199896b96a96SMike Kravetz 	VMA_ADD_RESV,
19995e911373SMike Kravetz };
2000cf3ad20bSMike Kravetz static long __vma_reservation_common(struct hstate *h,
2001cf3ad20bSMike Kravetz 				struct vm_area_struct *vma, unsigned long addr,
20025e911373SMike Kravetz 				enum vma_resv_mode mode)
2003c37f9fb1SAndy Whitcroft {
20044e35f483SJoonsoo Kim 	struct resv_map *resv;
20054e35f483SJoonsoo Kim 	pgoff_t idx;
2006cf3ad20bSMike Kravetz 	long ret;
2007c37f9fb1SAndy Whitcroft 
20084e35f483SJoonsoo Kim 	resv = vma_resv_map(vma);
20094e35f483SJoonsoo Kim 	if (!resv)
2010c37f9fb1SAndy Whitcroft 		return 1;
2011c37f9fb1SAndy Whitcroft 
20124e35f483SJoonsoo Kim 	idx = vma_hugecache_offset(h, vma, addr);
20135e911373SMike Kravetz 	switch (mode) {
20145e911373SMike Kravetz 	case VMA_NEEDS_RESV:
2015cf3ad20bSMike Kravetz 		ret = region_chg(resv, idx, idx + 1);
20165e911373SMike Kravetz 		break;
20175e911373SMike Kravetz 	case VMA_COMMIT_RESV:
20185e911373SMike Kravetz 		ret = region_add(resv, idx, idx + 1);
20195e911373SMike Kravetz 		break;
2020feba16e2SMike Kravetz 	case VMA_END_RESV:
20215e911373SMike Kravetz 		region_abort(resv, idx, idx + 1);
20225e911373SMike Kravetz 		ret = 0;
20235e911373SMike Kravetz 		break;
202496b96a96SMike Kravetz 	case VMA_ADD_RESV:
202596b96a96SMike Kravetz 		if (vma->vm_flags & VM_MAYSHARE)
202696b96a96SMike Kravetz 			ret = region_add(resv, idx, idx + 1);
202796b96a96SMike Kravetz 		else {
202896b96a96SMike Kravetz 			region_abort(resv, idx, idx + 1);
202996b96a96SMike Kravetz 			ret = region_del(resv, idx, idx + 1);
203096b96a96SMike Kravetz 		}
203196b96a96SMike Kravetz 		break;
20325e911373SMike Kravetz 	default:
20335e911373SMike Kravetz 		BUG();
20345e911373SMike Kravetz 	}
203584afd99bSAndy Whitcroft 
20364e35f483SJoonsoo Kim 	if (vma->vm_flags & VM_MAYSHARE)
2037cf3ad20bSMike Kravetz 		return ret;
203867961f9dSMike Kravetz 	else if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) && ret >= 0) {
203967961f9dSMike Kravetz 		/*
204067961f9dSMike Kravetz 		 * In most cases, reserves always exist for private mappings.
204167961f9dSMike Kravetz 		 * However, a file associated with mapping could have been
204267961f9dSMike Kravetz 		 * hole punched or truncated after reserves were consumed.
204367961f9dSMike Kravetz 		 * As subsequent fault on such a range will not use reserves.
204467961f9dSMike Kravetz 		 * Subtle - The reserve map for private mappings has the
204567961f9dSMike Kravetz 		 * opposite meaning than that of shared mappings.  If NO
204667961f9dSMike Kravetz 		 * entry is in the reserve map, it means a reservation exists.
204767961f9dSMike Kravetz 		 * If an entry exists in the reserve map, it means the
204867961f9dSMike Kravetz 		 * reservation has already been consumed.  As a result, the
204967961f9dSMike Kravetz 		 * return value of this routine is the opposite of the
205067961f9dSMike Kravetz 		 * value returned from reserve map manipulation routines above.
205167961f9dSMike Kravetz 		 */
205267961f9dSMike Kravetz 		if (ret)
205367961f9dSMike Kravetz 			return 0;
205467961f9dSMike Kravetz 		else
205567961f9dSMike Kravetz 			return 1;
205667961f9dSMike Kravetz 	}
20574e35f483SJoonsoo Kim 	else
2058cf3ad20bSMike Kravetz 		return ret < 0 ? ret : 0;
205984afd99bSAndy Whitcroft }
2060cf3ad20bSMike Kravetz 
2061cf3ad20bSMike Kravetz static long vma_needs_reservation(struct hstate *h,
2062a5516438SAndi Kleen 			struct vm_area_struct *vma, unsigned long addr)
2063c37f9fb1SAndy Whitcroft {
20645e911373SMike Kravetz 	return __vma_reservation_common(h, vma, addr, VMA_NEEDS_RESV);
2065cf3ad20bSMike Kravetz }
2066c37f9fb1SAndy Whitcroft 
2067cf3ad20bSMike Kravetz static long vma_commit_reservation(struct hstate *h,
2068cf3ad20bSMike Kravetz 			struct vm_area_struct *vma, unsigned long addr)
2069cf3ad20bSMike Kravetz {
20705e911373SMike Kravetz 	return __vma_reservation_common(h, vma, addr, VMA_COMMIT_RESV);
20715e911373SMike Kravetz }
20725e911373SMike Kravetz 
2073feba16e2SMike Kravetz static void vma_end_reservation(struct hstate *h,
20745e911373SMike Kravetz 			struct vm_area_struct *vma, unsigned long addr)
20755e911373SMike Kravetz {
2076feba16e2SMike Kravetz 	(void)__vma_reservation_common(h, vma, addr, VMA_END_RESV);
2077c37f9fb1SAndy Whitcroft }
2078c37f9fb1SAndy Whitcroft 
207996b96a96SMike Kravetz static long vma_add_reservation(struct hstate *h,
208096b96a96SMike Kravetz 			struct vm_area_struct *vma, unsigned long addr)
208196b96a96SMike Kravetz {
208296b96a96SMike Kravetz 	return __vma_reservation_common(h, vma, addr, VMA_ADD_RESV);
208396b96a96SMike Kravetz }
208496b96a96SMike Kravetz 
208596b96a96SMike Kravetz /*
208696b96a96SMike Kravetz  * This routine is called to restore a reservation on error paths.  In the
208796b96a96SMike Kravetz  * specific error paths, a huge page was allocated (via alloc_huge_page)
208896b96a96SMike Kravetz  * and is about to be freed.  If a reservation for the page existed,
208996b96a96SMike Kravetz  * alloc_huge_page would have consumed the reservation and set PagePrivate
209096b96a96SMike Kravetz  * in the newly allocated page.  When the page is freed via free_huge_page,
209196b96a96SMike Kravetz  * the global reservation count will be incremented if PagePrivate is set.
209296b96a96SMike Kravetz  * However, free_huge_page can not adjust the reserve map.  Adjust the
209396b96a96SMike Kravetz  * reserve map here to be consistent with global reserve count adjustments
209496b96a96SMike Kravetz  * to be made by free_huge_page.
209596b96a96SMike Kravetz  */
209696b96a96SMike Kravetz static void restore_reserve_on_error(struct hstate *h,
209796b96a96SMike Kravetz 			struct vm_area_struct *vma, unsigned long address,
209896b96a96SMike Kravetz 			struct page *page)
209996b96a96SMike Kravetz {
210096b96a96SMike Kravetz 	if (unlikely(PagePrivate(page))) {
210196b96a96SMike Kravetz 		long rc = vma_needs_reservation(h, vma, address);
210296b96a96SMike Kravetz 
210396b96a96SMike Kravetz 		if (unlikely(rc < 0)) {
210496b96a96SMike Kravetz 			/*
210596b96a96SMike Kravetz 			 * Rare out of memory condition in reserve map
210696b96a96SMike Kravetz 			 * manipulation.  Clear PagePrivate so that
210796b96a96SMike Kravetz 			 * global reserve count will not be incremented
210896b96a96SMike Kravetz 			 * by free_huge_page.  This will make it appear
210996b96a96SMike Kravetz 			 * as though the reservation for this page was
211096b96a96SMike Kravetz 			 * consumed.  This may prevent the task from
211196b96a96SMike Kravetz 			 * faulting in the page at a later time.  This
211296b96a96SMike Kravetz 			 * is better than inconsistent global huge page
211396b96a96SMike Kravetz 			 * accounting of reserve counts.
211496b96a96SMike Kravetz 			 */
211596b96a96SMike Kravetz 			ClearPagePrivate(page);
211696b96a96SMike Kravetz 		} else if (rc) {
211796b96a96SMike Kravetz 			rc = vma_add_reservation(h, vma, address);
211896b96a96SMike Kravetz 			if (unlikely(rc < 0))
211996b96a96SMike Kravetz 				/*
212096b96a96SMike Kravetz 				 * See above comment about rare out of
212196b96a96SMike Kravetz 				 * memory condition.
212296b96a96SMike Kravetz 				 */
212396b96a96SMike Kravetz 				ClearPagePrivate(page);
212496b96a96SMike Kravetz 		} else
212596b96a96SMike Kravetz 			vma_end_reservation(h, vma, address);
212696b96a96SMike Kravetz 	}
212796b96a96SMike Kravetz }
212896b96a96SMike Kravetz 
212970c3547eSMike Kravetz struct page *alloc_huge_page(struct vm_area_struct *vma,
213004f2cbe3SMel Gorman 				    unsigned long addr, int avoid_reserve)
2131348ea204SAdam Litke {
213290481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_vma(vma);
2133a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
2134348ea204SAdam Litke 	struct page *page;
2135d85f69b0SMike Kravetz 	long map_chg, map_commit;
2136d85f69b0SMike Kravetz 	long gbl_chg;
21376d76dcf4SAneesh Kumar K.V 	int ret, idx;
21386d76dcf4SAneesh Kumar K.V 	struct hugetlb_cgroup *h_cg;
21392fc39cecSAdam Litke 
21406d76dcf4SAneesh Kumar K.V 	idx = hstate_index(h);
2141a1e78772SMel Gorman 	/*
2142d85f69b0SMike Kravetz 	 * Examine the region/reserve map to determine if the process
2143d85f69b0SMike Kravetz 	 * has a reservation for the page to be allocated.  A return
2144d85f69b0SMike Kravetz 	 * code of zero indicates a reservation exists (no change).
2145a1e78772SMel Gorman 	 */
2146d85f69b0SMike Kravetz 	map_chg = gbl_chg = vma_needs_reservation(h, vma, addr);
2147d85f69b0SMike Kravetz 	if (map_chg < 0)
214876dcee75SAneesh Kumar K.V 		return ERR_PTR(-ENOMEM);
2149d85f69b0SMike Kravetz 
2150d85f69b0SMike Kravetz 	/*
2151d85f69b0SMike Kravetz 	 * Processes that did not create the mapping will have no
2152d85f69b0SMike Kravetz 	 * reserves as indicated by the region/reserve map. Check
2153d85f69b0SMike Kravetz 	 * that the allocation will not exceed the subpool limit.
2154d85f69b0SMike Kravetz 	 * Allocations for MAP_NORESERVE mappings also need to be
2155d85f69b0SMike Kravetz 	 * checked against any subpool limit.
2156d85f69b0SMike Kravetz 	 */
2157d85f69b0SMike Kravetz 	if (map_chg || avoid_reserve) {
2158d85f69b0SMike Kravetz 		gbl_chg = hugepage_subpool_get_pages(spool, 1);
2159d85f69b0SMike Kravetz 		if (gbl_chg < 0) {
2160feba16e2SMike Kravetz 			vma_end_reservation(h, vma, addr);
216176dcee75SAneesh Kumar K.V 			return ERR_PTR(-ENOSPC);
21625e911373SMike Kravetz 		}
216390d8b7e6SAdam Litke 
2164d85f69b0SMike Kravetz 		/*
2165d85f69b0SMike Kravetz 		 * Even though there was no reservation in the region/reserve
2166d85f69b0SMike Kravetz 		 * map, there could be reservations associated with the
2167d85f69b0SMike Kravetz 		 * subpool that can be used.  This would be indicated if the
2168d85f69b0SMike Kravetz 		 * return value of hugepage_subpool_get_pages() is zero.
2169d85f69b0SMike Kravetz 		 * However, if avoid_reserve is specified we still avoid even
2170d85f69b0SMike Kravetz 		 * the subpool reservations.
2171d85f69b0SMike Kravetz 		 */
2172d85f69b0SMike Kravetz 		if (avoid_reserve)
2173d85f69b0SMike Kravetz 			gbl_chg = 1;
2174d85f69b0SMike Kravetz 	}
2175d85f69b0SMike Kravetz 
21766d76dcf4SAneesh Kumar K.V 	ret = hugetlb_cgroup_charge_cgroup(idx, pages_per_huge_page(h), &h_cg);
21778f34af6fSJianyu Zhan 	if (ret)
21788f34af6fSJianyu Zhan 		goto out_subpool_put;
21798f34af6fSJianyu Zhan 
2180a1e78772SMel Gorman 	spin_lock(&hugetlb_lock);
2181d85f69b0SMike Kravetz 	/*
2182d85f69b0SMike Kravetz 	 * glb_chg is passed to indicate whether or not a page must be taken
2183d85f69b0SMike Kravetz 	 * from the global free pool (global change).  gbl_chg == 0 indicates
2184d85f69b0SMike Kravetz 	 * a reservation exists for the allocation.
2185d85f69b0SMike Kravetz 	 */
2186d85f69b0SMike Kravetz 	page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve, gbl_chg);
218781a6fcaeSJoonsoo Kim 	if (!page) {
218894ae8ba7SAneesh Kumar K.V 		spin_unlock(&hugetlb_lock);
21890c397daeSMichal Hocko 		page = alloc_buddy_huge_page_with_mpol(h, vma, addr);
21908f34af6fSJianyu Zhan 		if (!page)
21918f34af6fSJianyu Zhan 			goto out_uncharge_cgroup;
2192a88c7695SNaoya Horiguchi 		if (!avoid_reserve && vma_has_reserves(vma, gbl_chg)) {
2193a88c7695SNaoya Horiguchi 			SetPagePrivate(page);
2194a88c7695SNaoya Horiguchi 			h->resv_huge_pages--;
2195a88c7695SNaoya Horiguchi 		}
219679dbb236SAneesh Kumar K.V 		spin_lock(&hugetlb_lock);
219779dbb236SAneesh Kumar K.V 		list_move(&page->lru, &h->hugepage_activelist);
219881a6fcaeSJoonsoo Kim 		/* Fall through */
2199a1e78772SMel Gorman 	}
220081a6fcaeSJoonsoo Kim 	hugetlb_cgroup_commit_charge(idx, pages_per_huge_page(h), h_cg, page);
220181a6fcaeSJoonsoo Kim 	spin_unlock(&hugetlb_lock);
2202a1e78772SMel Gorman 
220390481622SDavid Gibson 	set_page_private(page, (unsigned long)spool);
2204a1e78772SMel Gorman 
2205d85f69b0SMike Kravetz 	map_commit = vma_commit_reservation(h, vma, addr);
2206d85f69b0SMike Kravetz 	if (unlikely(map_chg > map_commit)) {
220733039678SMike Kravetz 		/*
220833039678SMike Kravetz 		 * The page was added to the reservation map between
220933039678SMike Kravetz 		 * vma_needs_reservation and vma_commit_reservation.
221033039678SMike Kravetz 		 * This indicates a race with hugetlb_reserve_pages.
221133039678SMike Kravetz 		 * Adjust for the subpool count incremented above AND
221233039678SMike Kravetz 		 * in hugetlb_reserve_pages for the same page.  Also,
221333039678SMike Kravetz 		 * the reservation count added in hugetlb_reserve_pages
221433039678SMike Kravetz 		 * no longer applies.
221533039678SMike Kravetz 		 */
221633039678SMike Kravetz 		long rsv_adjust;
221733039678SMike Kravetz 
221833039678SMike Kravetz 		rsv_adjust = hugepage_subpool_put_pages(spool, 1);
221933039678SMike Kravetz 		hugetlb_acct_memory(h, -rsv_adjust);
222033039678SMike Kravetz 	}
22217893d1d5SAdam Litke 	return page;
22228f34af6fSJianyu Zhan 
22238f34af6fSJianyu Zhan out_uncharge_cgroup:
22248f34af6fSJianyu Zhan 	hugetlb_cgroup_uncharge_cgroup(idx, pages_per_huge_page(h), h_cg);
22258f34af6fSJianyu Zhan out_subpool_put:
2226d85f69b0SMike Kravetz 	if (map_chg || avoid_reserve)
22278f34af6fSJianyu Zhan 		hugepage_subpool_put_pages(spool, 1);
2228feba16e2SMike Kravetz 	vma_end_reservation(h, vma, addr);
22298f34af6fSJianyu Zhan 	return ERR_PTR(-ENOSPC);
2230b45b5bd6SDavid Gibson }
2231b45b5bd6SDavid Gibson 
2232e24a1307SAneesh Kumar K.V int alloc_bootmem_huge_page(struct hstate *h)
2233e24a1307SAneesh Kumar K.V 	__attribute__ ((weak, alias("__alloc_bootmem_huge_page")));
2234e24a1307SAneesh Kumar K.V int __alloc_bootmem_huge_page(struct hstate *h)
2235aa888a74SAndi Kleen {
2236aa888a74SAndi Kleen 	struct huge_bootmem_page *m;
2237b2261026SJoonsoo Kim 	int nr_nodes, node;
2238aa888a74SAndi Kleen 
2239b2261026SJoonsoo Kim 	for_each_node_mask_to_alloc(h, nr_nodes, node, &node_states[N_MEMORY]) {
2240aa888a74SAndi Kleen 		void *addr;
2241aa888a74SAndi Kleen 
2242eb31d559SMike Rapoport 		addr = memblock_alloc_try_nid_raw(
22438b89a116SGrygorii Strashko 				huge_page_size(h), huge_page_size(h),
224497ad1087SMike Rapoport 				0, MEMBLOCK_ALLOC_ACCESSIBLE, node);
2245aa888a74SAndi Kleen 		if (addr) {
2246aa888a74SAndi Kleen 			/*
2247aa888a74SAndi Kleen 			 * Use the beginning of the huge page to store the
2248aa888a74SAndi Kleen 			 * huge_bootmem_page struct (until gather_bootmem
2249aa888a74SAndi Kleen 			 * puts them into the mem_map).
2250aa888a74SAndi Kleen 			 */
2251aa888a74SAndi Kleen 			m = addr;
2252aa888a74SAndi Kleen 			goto found;
2253aa888a74SAndi Kleen 		}
2254aa888a74SAndi Kleen 	}
2255aa888a74SAndi Kleen 	return 0;
2256aa888a74SAndi Kleen 
2257aa888a74SAndi Kleen found:
2258df994eadSLuiz Capitulino 	BUG_ON(!IS_ALIGNED(virt_to_phys(m), huge_page_size(h)));
2259aa888a74SAndi Kleen 	/* Put them into a private list first because mem_map is not up yet */
2260330d6e48SCannon Matthews 	INIT_LIST_HEAD(&m->list);
2261aa888a74SAndi Kleen 	list_add(&m->list, &huge_boot_pages);
2262aa888a74SAndi Kleen 	m->hstate = h;
2263aa888a74SAndi Kleen 	return 1;
2264aa888a74SAndi Kleen }
2265aa888a74SAndi Kleen 
2266d00181b9SKirill A. Shutemov static void __init prep_compound_huge_page(struct page *page,
2267d00181b9SKirill A. Shutemov 		unsigned int order)
226818229df5SAndy Whitcroft {
226918229df5SAndy Whitcroft 	if (unlikely(order > (MAX_ORDER - 1)))
227018229df5SAndy Whitcroft 		prep_compound_gigantic_page(page, order);
227118229df5SAndy Whitcroft 	else
227218229df5SAndy Whitcroft 		prep_compound_page(page, order);
227318229df5SAndy Whitcroft }
227418229df5SAndy Whitcroft 
2275aa888a74SAndi Kleen /* Put bootmem huge pages into the standard lists after mem_map is up */
2276aa888a74SAndi Kleen static void __init gather_bootmem_prealloc(void)
2277aa888a74SAndi Kleen {
2278aa888a74SAndi Kleen 	struct huge_bootmem_page *m;
2279aa888a74SAndi Kleen 
2280aa888a74SAndi Kleen 	list_for_each_entry(m, &huge_boot_pages, list) {
228140d18ebfSMike Kravetz 		struct page *page = virt_to_page(m);
2282aa888a74SAndi Kleen 		struct hstate *h = m->hstate;
2283ee8f248dSBecky Bruce 
2284aa888a74SAndi Kleen 		WARN_ON(page_count(page) != 1);
228518229df5SAndy Whitcroft 		prep_compound_huge_page(page, h->order);
2286ef5a22beSAndrea Arcangeli 		WARN_ON(PageReserved(page));
2287aa888a74SAndi Kleen 		prep_new_huge_page(h, page, page_to_nid(page));
2288af0fb9dfSMichal Hocko 		put_page(page); /* free it into the hugepage allocator */
2289af0fb9dfSMichal Hocko 
2290b0320c7bSRafael Aquini 		/*
2291b0320c7bSRafael Aquini 		 * If we had gigantic hugepages allocated at boot time, we need
2292b0320c7bSRafael Aquini 		 * to restore the 'stolen' pages to totalram_pages in order to
2293b0320c7bSRafael Aquini 		 * fix confusing memory reports from free(1) and another
2294b0320c7bSRafael Aquini 		 * side-effects, like CommitLimit going negative.
2295b0320c7bSRafael Aquini 		 */
2296bae7f4aeSLuiz Capitulino 		if (hstate_is_gigantic(h))
22973dcc0571SJiang Liu 			adjust_managed_page_count(page, 1 << h->order);
2298520495feSCannon Matthews 		cond_resched();
2299aa888a74SAndi Kleen 	}
2300aa888a74SAndi Kleen }
2301aa888a74SAndi Kleen 
23028faa8b07SAndi Kleen static void __init hugetlb_hstate_alloc_pages(struct hstate *h)
23031da177e4SLinus Torvalds {
23041da177e4SLinus Torvalds 	unsigned long i;
2305f60858f9SMike Kravetz 	nodemask_t *node_alloc_noretry;
2306f60858f9SMike Kravetz 
2307f60858f9SMike Kravetz 	if (!hstate_is_gigantic(h)) {
2308f60858f9SMike Kravetz 		/*
2309f60858f9SMike Kravetz 		 * Bit mask controlling how hard we retry per-node allocations.
2310f60858f9SMike Kravetz 		 * Ignore errors as lower level routines can deal with
2311f60858f9SMike Kravetz 		 * node_alloc_noretry == NULL.  If this kmalloc fails at boot
2312f60858f9SMike Kravetz 		 * time, we are likely in bigger trouble.
2313f60858f9SMike Kravetz 		 */
2314f60858f9SMike Kravetz 		node_alloc_noretry = kmalloc(sizeof(*node_alloc_noretry),
2315f60858f9SMike Kravetz 						GFP_KERNEL);
2316f60858f9SMike Kravetz 	} else {
2317f60858f9SMike Kravetz 		/* allocations done at boot time */
2318f60858f9SMike Kravetz 		node_alloc_noretry = NULL;
2319f60858f9SMike Kravetz 	}
2320f60858f9SMike Kravetz 
2321f60858f9SMike Kravetz 	/* bit mask controlling how hard we retry per-node allocations */
2322f60858f9SMike Kravetz 	if (node_alloc_noretry)
2323f60858f9SMike Kravetz 		nodes_clear(*node_alloc_noretry);
23241da177e4SLinus Torvalds 
2325e5ff2159SAndi Kleen 	for (i = 0; i < h->max_huge_pages; ++i) {
2326bae7f4aeSLuiz Capitulino 		if (hstate_is_gigantic(h)) {
2327aa888a74SAndi Kleen 			if (!alloc_bootmem_huge_page(h))
2328aa888a74SAndi Kleen 				break;
23290c397daeSMichal Hocko 		} else if (!alloc_pool_huge_page(h,
2330f60858f9SMike Kravetz 					 &node_states[N_MEMORY],
2331f60858f9SMike Kravetz 					 node_alloc_noretry))
23321da177e4SLinus Torvalds 			break;
233369ed779aSDavid Rientjes 		cond_resched();
23341da177e4SLinus Torvalds 	}
2335d715cf80SLiam R. Howlett 	if (i < h->max_huge_pages) {
2336d715cf80SLiam R. Howlett 		char buf[32];
2337d715cf80SLiam R. Howlett 
2338c6247f72SMatthew Wilcox 		string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
2339d715cf80SLiam R. Howlett 		pr_warn("HugeTLB: allocating %lu of page size %s failed.  Only allocated %lu hugepages.\n",
2340d715cf80SLiam R. Howlett 			h->max_huge_pages, buf, i);
23418faa8b07SAndi Kleen 		h->max_huge_pages = i;
2342e5ff2159SAndi Kleen 	}
2343f60858f9SMike Kravetz 
2344f60858f9SMike Kravetz 	kfree(node_alloc_noretry);
2345d715cf80SLiam R. Howlett }
2346e5ff2159SAndi Kleen 
2347e5ff2159SAndi Kleen static void __init hugetlb_init_hstates(void)
2348e5ff2159SAndi Kleen {
2349e5ff2159SAndi Kleen 	struct hstate *h;
2350e5ff2159SAndi Kleen 
2351e5ff2159SAndi Kleen 	for_each_hstate(h) {
2352641844f5SNaoya Horiguchi 		if (minimum_order > huge_page_order(h))
2353641844f5SNaoya Horiguchi 			minimum_order = huge_page_order(h);
2354641844f5SNaoya Horiguchi 
23558faa8b07SAndi Kleen 		/* oversize hugepages were init'ed in early boot */
2356bae7f4aeSLuiz Capitulino 		if (!hstate_is_gigantic(h))
23578faa8b07SAndi Kleen 			hugetlb_hstate_alloc_pages(h);
2358e5ff2159SAndi Kleen 	}
2359641844f5SNaoya Horiguchi 	VM_BUG_ON(minimum_order == UINT_MAX);
2360e5ff2159SAndi Kleen }
2361e5ff2159SAndi Kleen 
2362e5ff2159SAndi Kleen static void __init report_hugepages(void)
2363e5ff2159SAndi Kleen {
2364e5ff2159SAndi Kleen 	struct hstate *h;
2365e5ff2159SAndi Kleen 
2366e5ff2159SAndi Kleen 	for_each_hstate(h) {
23674abd32dbSAndi Kleen 		char buf[32];
2368c6247f72SMatthew Wilcox 
2369c6247f72SMatthew Wilcox 		string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
2370ffb22af5SAndrew Morton 		pr_info("HugeTLB registered %s page size, pre-allocated %ld pages\n",
2371c6247f72SMatthew Wilcox 			buf, h->free_huge_pages);
2372e5ff2159SAndi Kleen 	}
2373e5ff2159SAndi Kleen }
2374e5ff2159SAndi Kleen 
23751da177e4SLinus Torvalds #ifdef CONFIG_HIGHMEM
23766ae11b27SLee Schermerhorn static void try_to_free_low(struct hstate *h, unsigned long count,
23776ae11b27SLee Schermerhorn 						nodemask_t *nodes_allowed)
23781da177e4SLinus Torvalds {
23794415cc8dSChristoph Lameter 	int i;
23804415cc8dSChristoph Lameter 
2381bae7f4aeSLuiz Capitulino 	if (hstate_is_gigantic(h))
2382aa888a74SAndi Kleen 		return;
2383aa888a74SAndi Kleen 
23846ae11b27SLee Schermerhorn 	for_each_node_mask(i, *nodes_allowed) {
23851da177e4SLinus Torvalds 		struct page *page, *next;
2386a5516438SAndi Kleen 		struct list_head *freel = &h->hugepage_freelists[i];
2387a5516438SAndi Kleen 		list_for_each_entry_safe(page, next, freel, lru) {
2388a5516438SAndi Kleen 			if (count >= h->nr_huge_pages)
23896b0c880dSAdam Litke 				return;
23901da177e4SLinus Torvalds 			if (PageHighMem(page))
23911da177e4SLinus Torvalds 				continue;
23921da177e4SLinus Torvalds 			list_del(&page->lru);
2393e5ff2159SAndi Kleen 			update_and_free_page(h, page);
2394a5516438SAndi Kleen 			h->free_huge_pages--;
2395a5516438SAndi Kleen 			h->free_huge_pages_node[page_to_nid(page)]--;
23961da177e4SLinus Torvalds 		}
23971da177e4SLinus Torvalds 	}
23981da177e4SLinus Torvalds }
23991da177e4SLinus Torvalds #else
24006ae11b27SLee Schermerhorn static inline void try_to_free_low(struct hstate *h, unsigned long count,
24016ae11b27SLee Schermerhorn 						nodemask_t *nodes_allowed)
24021da177e4SLinus Torvalds {
24031da177e4SLinus Torvalds }
24041da177e4SLinus Torvalds #endif
24051da177e4SLinus Torvalds 
240620a0307cSWu Fengguang /*
240720a0307cSWu Fengguang  * Increment or decrement surplus_huge_pages.  Keep node-specific counters
240820a0307cSWu Fengguang  * balanced by operating on them in a round-robin fashion.
240920a0307cSWu Fengguang  * Returns 1 if an adjustment was made.
241020a0307cSWu Fengguang  */
24116ae11b27SLee Schermerhorn static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed,
24126ae11b27SLee Schermerhorn 				int delta)
241320a0307cSWu Fengguang {
2414b2261026SJoonsoo Kim 	int nr_nodes, node;
241520a0307cSWu Fengguang 
241620a0307cSWu Fengguang 	VM_BUG_ON(delta != -1 && delta != 1);
241720a0307cSWu Fengguang 
2418e8c5c824SLee Schermerhorn 	if (delta < 0) {
2419b2261026SJoonsoo Kim 		for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
2420b2261026SJoonsoo Kim 			if (h->surplus_huge_pages_node[node])
2421b2261026SJoonsoo Kim 				goto found;
2422b2261026SJoonsoo Kim 		}
2423b2261026SJoonsoo Kim 	} else {
2424b2261026SJoonsoo Kim 		for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
2425b2261026SJoonsoo Kim 			if (h->surplus_huge_pages_node[node] <
2426b2261026SJoonsoo Kim 					h->nr_huge_pages_node[node])
2427b2261026SJoonsoo Kim 				goto found;
2428e8c5c824SLee Schermerhorn 		}
24299a76db09SLee Schermerhorn 	}
2430b2261026SJoonsoo Kim 	return 0;
243120a0307cSWu Fengguang 
2432b2261026SJoonsoo Kim found:
243320a0307cSWu Fengguang 	h->surplus_huge_pages += delta;
2434b2261026SJoonsoo Kim 	h->surplus_huge_pages_node[node] += delta;
2435b2261026SJoonsoo Kim 	return 1;
243620a0307cSWu Fengguang }
243720a0307cSWu Fengguang 
2438a5516438SAndi Kleen #define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages)
2439fd875dcaSMike Kravetz static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,
24406ae11b27SLee Schermerhorn 			      nodemask_t *nodes_allowed)
24411da177e4SLinus Torvalds {
24427893d1d5SAdam Litke 	unsigned long min_count, ret;
2443f60858f9SMike Kravetz 	NODEMASK_ALLOC(nodemask_t, node_alloc_noretry, GFP_KERNEL);
2444f60858f9SMike Kravetz 
2445f60858f9SMike Kravetz 	/*
2446f60858f9SMike Kravetz 	 * Bit mask controlling how hard we retry per-node allocations.
2447f60858f9SMike Kravetz 	 * If we can not allocate the bit mask, do not attempt to allocate
2448f60858f9SMike Kravetz 	 * the requested huge pages.
2449f60858f9SMike Kravetz 	 */
2450f60858f9SMike Kravetz 	if (node_alloc_noretry)
2451f60858f9SMike Kravetz 		nodes_clear(*node_alloc_noretry);
2452f60858f9SMike Kravetz 	else
2453f60858f9SMike Kravetz 		return -ENOMEM;
24541da177e4SLinus Torvalds 
24554eb0716eSAlexandre Ghiti 	spin_lock(&hugetlb_lock);
24564eb0716eSAlexandre Ghiti 
24574eb0716eSAlexandre Ghiti 	/*
2458fd875dcaSMike Kravetz 	 * Check for a node specific request.
2459fd875dcaSMike Kravetz 	 * Changing node specific huge page count may require a corresponding
2460fd875dcaSMike Kravetz 	 * change to the global count.  In any case, the passed node mask
2461fd875dcaSMike Kravetz 	 * (nodes_allowed) will restrict alloc/free to the specified node.
2462fd875dcaSMike Kravetz 	 */
2463fd875dcaSMike Kravetz 	if (nid != NUMA_NO_NODE) {
2464fd875dcaSMike Kravetz 		unsigned long old_count = count;
2465fd875dcaSMike Kravetz 
2466fd875dcaSMike Kravetz 		count += h->nr_huge_pages - h->nr_huge_pages_node[nid];
2467fd875dcaSMike Kravetz 		/*
2468fd875dcaSMike Kravetz 		 * User may have specified a large count value which caused the
2469fd875dcaSMike Kravetz 		 * above calculation to overflow.  In this case, they wanted
2470fd875dcaSMike Kravetz 		 * to allocate as many huge pages as possible.  Set count to
2471fd875dcaSMike Kravetz 		 * largest possible value to align with their intention.
2472fd875dcaSMike Kravetz 		 */
2473fd875dcaSMike Kravetz 		if (count < old_count)
2474fd875dcaSMike Kravetz 			count = ULONG_MAX;
2475fd875dcaSMike Kravetz 	}
2476fd875dcaSMike Kravetz 
2477fd875dcaSMike Kravetz 	/*
24784eb0716eSAlexandre Ghiti 	 * Gigantic pages runtime allocation depend on the capability for large
24794eb0716eSAlexandre Ghiti 	 * page range allocation.
24804eb0716eSAlexandre Ghiti 	 * If the system does not provide this feature, return an error when
24814eb0716eSAlexandre Ghiti 	 * the user tries to allocate gigantic pages but let the user free the
24824eb0716eSAlexandre Ghiti 	 * boottime allocated gigantic pages.
24834eb0716eSAlexandre Ghiti 	 */
24844eb0716eSAlexandre Ghiti 	if (hstate_is_gigantic(h) && !IS_ENABLED(CONFIG_CONTIG_ALLOC)) {
24854eb0716eSAlexandre Ghiti 		if (count > persistent_huge_pages(h)) {
24864eb0716eSAlexandre Ghiti 			spin_unlock(&hugetlb_lock);
2487f60858f9SMike Kravetz 			NODEMASK_FREE(node_alloc_noretry);
24884eb0716eSAlexandre Ghiti 			return -EINVAL;
24894eb0716eSAlexandre Ghiti 		}
24904eb0716eSAlexandre Ghiti 		/* Fall through to decrease pool */
24914eb0716eSAlexandre Ghiti 	}
2492aa888a74SAndi Kleen 
24937893d1d5SAdam Litke 	/*
24947893d1d5SAdam Litke 	 * Increase the pool size
24957893d1d5SAdam Litke 	 * First take pages out of surplus state.  Then make up the
24967893d1d5SAdam Litke 	 * remaining difference by allocating fresh huge pages.
2497d1c3fb1fSNishanth Aravamudan 	 *
24980c397daeSMichal Hocko 	 * We might race with alloc_surplus_huge_page() here and be unable
2499d1c3fb1fSNishanth Aravamudan 	 * to convert a surplus huge page to a normal huge page. That is
2500d1c3fb1fSNishanth Aravamudan 	 * not critical, though, it just means the overall size of the
2501d1c3fb1fSNishanth Aravamudan 	 * pool might be one hugepage larger than it needs to be, but
2502d1c3fb1fSNishanth Aravamudan 	 * within all the constraints specified by the sysctls.
25037893d1d5SAdam Litke 	 */
2504a5516438SAndi Kleen 	while (h->surplus_huge_pages && count > persistent_huge_pages(h)) {
25056ae11b27SLee Schermerhorn 		if (!adjust_pool_surplus(h, nodes_allowed, -1))
25067893d1d5SAdam Litke 			break;
25077893d1d5SAdam Litke 	}
25087893d1d5SAdam Litke 
2509a5516438SAndi Kleen 	while (count > persistent_huge_pages(h)) {
25107893d1d5SAdam Litke 		/*
25117893d1d5SAdam Litke 		 * If this allocation races such that we no longer need the
25127893d1d5SAdam Litke 		 * page, free_huge_page will handle it by freeing the page
25137893d1d5SAdam Litke 		 * and reducing the surplus.
25147893d1d5SAdam Litke 		 */
25157893d1d5SAdam Litke 		spin_unlock(&hugetlb_lock);
2516649920c6SJia He 
2517649920c6SJia He 		/* yield cpu to avoid soft lockup */
2518649920c6SJia He 		cond_resched();
2519649920c6SJia He 
2520f60858f9SMike Kravetz 		ret = alloc_pool_huge_page(h, nodes_allowed,
2521f60858f9SMike Kravetz 						node_alloc_noretry);
25227893d1d5SAdam Litke 		spin_lock(&hugetlb_lock);
25237893d1d5SAdam Litke 		if (!ret)
25247893d1d5SAdam Litke 			goto out;
25257893d1d5SAdam Litke 
2526536240f2SMel Gorman 		/* Bail for signals. Probably ctrl-c from user */
2527536240f2SMel Gorman 		if (signal_pending(current))
2528536240f2SMel Gorman 			goto out;
25297893d1d5SAdam Litke 	}
25307893d1d5SAdam Litke 
25317893d1d5SAdam Litke 	/*
25327893d1d5SAdam Litke 	 * Decrease the pool size
25337893d1d5SAdam Litke 	 * First return free pages to the buddy allocator (being careful
25347893d1d5SAdam Litke 	 * to keep enough around to satisfy reservations).  Then place
25357893d1d5SAdam Litke 	 * pages into surplus state as needed so the pool will shrink
25367893d1d5SAdam Litke 	 * to the desired size as pages become free.
2537d1c3fb1fSNishanth Aravamudan 	 *
2538d1c3fb1fSNishanth Aravamudan 	 * By placing pages into the surplus state independent of the
2539d1c3fb1fSNishanth Aravamudan 	 * overcommit value, we are allowing the surplus pool size to
2540d1c3fb1fSNishanth Aravamudan 	 * exceed overcommit. There are few sane options here. Since
25410c397daeSMichal Hocko 	 * alloc_surplus_huge_page() is checking the global counter,
2542d1c3fb1fSNishanth Aravamudan 	 * though, we'll note that we're not allowed to exceed surplus
2543d1c3fb1fSNishanth Aravamudan 	 * and won't grow the pool anywhere else. Not until one of the
2544d1c3fb1fSNishanth Aravamudan 	 * sysctls are changed, or the surplus pages go out of use.
25457893d1d5SAdam Litke 	 */
2546a5516438SAndi Kleen 	min_count = h->resv_huge_pages + h->nr_huge_pages - h->free_huge_pages;
25476b0c880dSAdam Litke 	min_count = max(count, min_count);
25486ae11b27SLee Schermerhorn 	try_to_free_low(h, min_count, nodes_allowed);
2549a5516438SAndi Kleen 	while (min_count < persistent_huge_pages(h)) {
25506ae11b27SLee Schermerhorn 		if (!free_pool_huge_page(h, nodes_allowed, 0))
25511da177e4SLinus Torvalds 			break;
255255f67141SMizuma, Masayoshi 		cond_resched_lock(&hugetlb_lock);
25531da177e4SLinus Torvalds 	}
2554a5516438SAndi Kleen 	while (count < persistent_huge_pages(h)) {
25556ae11b27SLee Schermerhorn 		if (!adjust_pool_surplus(h, nodes_allowed, 1))
25567893d1d5SAdam Litke 			break;
25577893d1d5SAdam Litke 	}
25587893d1d5SAdam Litke out:
25594eb0716eSAlexandre Ghiti 	h->max_huge_pages = persistent_huge_pages(h);
25601da177e4SLinus Torvalds 	spin_unlock(&hugetlb_lock);
25614eb0716eSAlexandre Ghiti 
2562f60858f9SMike Kravetz 	NODEMASK_FREE(node_alloc_noretry);
2563f60858f9SMike Kravetz 
25644eb0716eSAlexandre Ghiti 	return 0;
25651da177e4SLinus Torvalds }
25661da177e4SLinus Torvalds 
2567a3437870SNishanth Aravamudan #define HSTATE_ATTR_RO(_name) \
2568a3437870SNishanth Aravamudan 	static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
2569a3437870SNishanth Aravamudan 
2570a3437870SNishanth Aravamudan #define HSTATE_ATTR(_name) \
2571a3437870SNishanth Aravamudan 	static struct kobj_attribute _name##_attr = \
2572a3437870SNishanth Aravamudan 		__ATTR(_name, 0644, _name##_show, _name##_store)
2573a3437870SNishanth Aravamudan 
2574a3437870SNishanth Aravamudan static struct kobject *hugepages_kobj;
2575a3437870SNishanth Aravamudan static struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
2576a3437870SNishanth Aravamudan 
25779a305230SLee Schermerhorn static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp);
25789a305230SLee Schermerhorn 
25799a305230SLee Schermerhorn static struct hstate *kobj_to_hstate(struct kobject *kobj, int *nidp)
2580a3437870SNishanth Aravamudan {
2581a3437870SNishanth Aravamudan 	int i;
25829a305230SLee Schermerhorn 
2583a3437870SNishanth Aravamudan 	for (i = 0; i < HUGE_MAX_HSTATE; i++)
25849a305230SLee Schermerhorn 		if (hstate_kobjs[i] == kobj) {
25859a305230SLee Schermerhorn 			if (nidp)
25869a305230SLee Schermerhorn 				*nidp = NUMA_NO_NODE;
2587a3437870SNishanth Aravamudan 			return &hstates[i];
25889a305230SLee Schermerhorn 		}
25899a305230SLee Schermerhorn 
25909a305230SLee Schermerhorn 	return kobj_to_node_hstate(kobj, nidp);
2591a3437870SNishanth Aravamudan }
2592a3437870SNishanth Aravamudan 
259306808b08SLee Schermerhorn static ssize_t nr_hugepages_show_common(struct kobject *kobj,
2594a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
2595a3437870SNishanth Aravamudan {
25969a305230SLee Schermerhorn 	struct hstate *h;
25979a305230SLee Schermerhorn 	unsigned long nr_huge_pages;
25989a305230SLee Schermerhorn 	int nid;
25999a305230SLee Schermerhorn 
26009a305230SLee Schermerhorn 	h = kobj_to_hstate(kobj, &nid);
26019a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE)
26029a305230SLee Schermerhorn 		nr_huge_pages = h->nr_huge_pages;
26039a305230SLee Schermerhorn 	else
26049a305230SLee Schermerhorn 		nr_huge_pages = h->nr_huge_pages_node[nid];
26059a305230SLee Schermerhorn 
26069a305230SLee Schermerhorn 	return sprintf(buf, "%lu\n", nr_huge_pages);
2607a3437870SNishanth Aravamudan }
2608adbe8726SEric B Munson 
2609238d3c13SDavid Rientjes static ssize_t __nr_hugepages_store_common(bool obey_mempolicy,
2610238d3c13SDavid Rientjes 					   struct hstate *h, int nid,
2611238d3c13SDavid Rientjes 					   unsigned long count, size_t len)
2612a3437870SNishanth Aravamudan {
2613a3437870SNishanth Aravamudan 	int err;
26142d0adf7eSOscar Salvador 	nodemask_t nodes_allowed, *n_mask;
2615a3437870SNishanth Aravamudan 
26162d0adf7eSOscar Salvador 	if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
26172d0adf7eSOscar Salvador 		return -EINVAL;
2618adbe8726SEric B Munson 
26199a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE) {
26209a305230SLee Schermerhorn 		/*
26219a305230SLee Schermerhorn 		 * global hstate attribute
26229a305230SLee Schermerhorn 		 */
26239a305230SLee Schermerhorn 		if (!(obey_mempolicy &&
26242d0adf7eSOscar Salvador 				init_nodemask_of_mempolicy(&nodes_allowed)))
26252d0adf7eSOscar Salvador 			n_mask = &node_states[N_MEMORY];
26262d0adf7eSOscar Salvador 		else
26272d0adf7eSOscar Salvador 			n_mask = &nodes_allowed;
26282d0adf7eSOscar Salvador 	} else {
26299a305230SLee Schermerhorn 		/*
2630fd875dcaSMike Kravetz 		 * Node specific request.  count adjustment happens in
2631fd875dcaSMike Kravetz 		 * set_max_huge_pages() after acquiring hugetlb_lock.
26329a305230SLee Schermerhorn 		 */
26332d0adf7eSOscar Salvador 		init_nodemask_of_node(&nodes_allowed, nid);
26342d0adf7eSOscar Salvador 		n_mask = &nodes_allowed;
2635fd875dcaSMike Kravetz 	}
26369a305230SLee Schermerhorn 
26372d0adf7eSOscar Salvador 	err = set_max_huge_pages(h, count, nid, n_mask);
263806808b08SLee Schermerhorn 
26394eb0716eSAlexandre Ghiti 	return err ? err : len;
264006808b08SLee Schermerhorn }
264106808b08SLee Schermerhorn 
2642238d3c13SDavid Rientjes static ssize_t nr_hugepages_store_common(bool obey_mempolicy,
2643238d3c13SDavid Rientjes 					 struct kobject *kobj, const char *buf,
2644238d3c13SDavid Rientjes 					 size_t len)
2645238d3c13SDavid Rientjes {
2646238d3c13SDavid Rientjes 	struct hstate *h;
2647238d3c13SDavid Rientjes 	unsigned long count;
2648238d3c13SDavid Rientjes 	int nid;
2649238d3c13SDavid Rientjes 	int err;
2650238d3c13SDavid Rientjes 
2651238d3c13SDavid Rientjes 	err = kstrtoul(buf, 10, &count);
2652238d3c13SDavid Rientjes 	if (err)
2653238d3c13SDavid Rientjes 		return err;
2654238d3c13SDavid Rientjes 
2655238d3c13SDavid Rientjes 	h = kobj_to_hstate(kobj, &nid);
2656238d3c13SDavid Rientjes 	return __nr_hugepages_store_common(obey_mempolicy, h, nid, count, len);
2657238d3c13SDavid Rientjes }
2658238d3c13SDavid Rientjes 
265906808b08SLee Schermerhorn static ssize_t nr_hugepages_show(struct kobject *kobj,
266006808b08SLee Schermerhorn 				       struct kobj_attribute *attr, char *buf)
266106808b08SLee Schermerhorn {
266206808b08SLee Schermerhorn 	return nr_hugepages_show_common(kobj, attr, buf);
266306808b08SLee Schermerhorn }
266406808b08SLee Schermerhorn 
266506808b08SLee Schermerhorn static ssize_t nr_hugepages_store(struct kobject *kobj,
266606808b08SLee Schermerhorn 	       struct kobj_attribute *attr, const char *buf, size_t len)
266706808b08SLee Schermerhorn {
2668238d3c13SDavid Rientjes 	return nr_hugepages_store_common(false, kobj, buf, len);
2669a3437870SNishanth Aravamudan }
2670a3437870SNishanth Aravamudan HSTATE_ATTR(nr_hugepages);
2671a3437870SNishanth Aravamudan 
267206808b08SLee Schermerhorn #ifdef CONFIG_NUMA
267306808b08SLee Schermerhorn 
267406808b08SLee Schermerhorn /*
267506808b08SLee Schermerhorn  * hstate attribute for optionally mempolicy-based constraint on persistent
267606808b08SLee Schermerhorn  * huge page alloc/free.
267706808b08SLee Schermerhorn  */
267806808b08SLee Schermerhorn static ssize_t nr_hugepages_mempolicy_show(struct kobject *kobj,
267906808b08SLee Schermerhorn 				       struct kobj_attribute *attr, char *buf)
268006808b08SLee Schermerhorn {
268106808b08SLee Schermerhorn 	return nr_hugepages_show_common(kobj, attr, buf);
268206808b08SLee Schermerhorn }
268306808b08SLee Schermerhorn 
268406808b08SLee Schermerhorn static ssize_t nr_hugepages_mempolicy_store(struct kobject *kobj,
268506808b08SLee Schermerhorn 	       struct kobj_attribute *attr, const char *buf, size_t len)
268606808b08SLee Schermerhorn {
2687238d3c13SDavid Rientjes 	return nr_hugepages_store_common(true, kobj, buf, len);
268806808b08SLee Schermerhorn }
268906808b08SLee Schermerhorn HSTATE_ATTR(nr_hugepages_mempolicy);
269006808b08SLee Schermerhorn #endif
269106808b08SLee Schermerhorn 
269206808b08SLee Schermerhorn 
2693a3437870SNishanth Aravamudan static ssize_t nr_overcommit_hugepages_show(struct kobject *kobj,
2694a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
2695a3437870SNishanth Aravamudan {
26969a305230SLee Schermerhorn 	struct hstate *h = kobj_to_hstate(kobj, NULL);
2697a3437870SNishanth Aravamudan 	return sprintf(buf, "%lu\n", h->nr_overcommit_huge_pages);
2698a3437870SNishanth Aravamudan }
2699adbe8726SEric B Munson 
2700a3437870SNishanth Aravamudan static ssize_t nr_overcommit_hugepages_store(struct kobject *kobj,
2701a3437870SNishanth Aravamudan 		struct kobj_attribute *attr, const char *buf, size_t count)
2702a3437870SNishanth Aravamudan {
2703a3437870SNishanth Aravamudan 	int err;
2704a3437870SNishanth Aravamudan 	unsigned long input;
27059a305230SLee Schermerhorn 	struct hstate *h = kobj_to_hstate(kobj, NULL);
2706a3437870SNishanth Aravamudan 
2707bae7f4aeSLuiz Capitulino 	if (hstate_is_gigantic(h))
2708adbe8726SEric B Munson 		return -EINVAL;
2709adbe8726SEric B Munson 
27103dbb95f7SJingoo Han 	err = kstrtoul(buf, 10, &input);
2711a3437870SNishanth Aravamudan 	if (err)
271273ae31e5SEric B Munson 		return err;
2713a3437870SNishanth Aravamudan 
2714a3437870SNishanth Aravamudan 	spin_lock(&hugetlb_lock);
2715a3437870SNishanth Aravamudan 	h->nr_overcommit_huge_pages = input;
2716a3437870SNishanth Aravamudan 	spin_unlock(&hugetlb_lock);
2717a3437870SNishanth Aravamudan 
2718a3437870SNishanth Aravamudan 	return count;
2719a3437870SNishanth Aravamudan }
2720a3437870SNishanth Aravamudan HSTATE_ATTR(nr_overcommit_hugepages);
2721a3437870SNishanth Aravamudan 
2722a3437870SNishanth Aravamudan static ssize_t free_hugepages_show(struct kobject *kobj,
2723a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
2724a3437870SNishanth Aravamudan {
27259a305230SLee Schermerhorn 	struct hstate *h;
27269a305230SLee Schermerhorn 	unsigned long free_huge_pages;
27279a305230SLee Schermerhorn 	int nid;
27289a305230SLee Schermerhorn 
27299a305230SLee Schermerhorn 	h = kobj_to_hstate(kobj, &nid);
27309a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE)
27319a305230SLee Schermerhorn 		free_huge_pages = h->free_huge_pages;
27329a305230SLee Schermerhorn 	else
27339a305230SLee Schermerhorn 		free_huge_pages = h->free_huge_pages_node[nid];
27349a305230SLee Schermerhorn 
27359a305230SLee Schermerhorn 	return sprintf(buf, "%lu\n", free_huge_pages);
2736a3437870SNishanth Aravamudan }
2737a3437870SNishanth Aravamudan HSTATE_ATTR_RO(free_hugepages);
2738a3437870SNishanth Aravamudan 
2739a3437870SNishanth Aravamudan static ssize_t resv_hugepages_show(struct kobject *kobj,
2740a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
2741a3437870SNishanth Aravamudan {
27429a305230SLee Schermerhorn 	struct hstate *h = kobj_to_hstate(kobj, NULL);
2743a3437870SNishanth Aravamudan 	return sprintf(buf, "%lu\n", h->resv_huge_pages);
2744a3437870SNishanth Aravamudan }
2745a3437870SNishanth Aravamudan HSTATE_ATTR_RO(resv_hugepages);
2746a3437870SNishanth Aravamudan 
2747a3437870SNishanth Aravamudan static ssize_t surplus_hugepages_show(struct kobject *kobj,
2748a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
2749a3437870SNishanth Aravamudan {
27509a305230SLee Schermerhorn 	struct hstate *h;
27519a305230SLee Schermerhorn 	unsigned long surplus_huge_pages;
27529a305230SLee Schermerhorn 	int nid;
27539a305230SLee Schermerhorn 
27549a305230SLee Schermerhorn 	h = kobj_to_hstate(kobj, &nid);
27559a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE)
27569a305230SLee Schermerhorn 		surplus_huge_pages = h->surplus_huge_pages;
27579a305230SLee Schermerhorn 	else
27589a305230SLee Schermerhorn 		surplus_huge_pages = h->surplus_huge_pages_node[nid];
27599a305230SLee Schermerhorn 
27609a305230SLee Schermerhorn 	return sprintf(buf, "%lu\n", surplus_huge_pages);
2761a3437870SNishanth Aravamudan }
2762a3437870SNishanth Aravamudan HSTATE_ATTR_RO(surplus_hugepages);
2763a3437870SNishanth Aravamudan 
2764a3437870SNishanth Aravamudan static struct attribute *hstate_attrs[] = {
2765a3437870SNishanth Aravamudan 	&nr_hugepages_attr.attr,
2766a3437870SNishanth Aravamudan 	&nr_overcommit_hugepages_attr.attr,
2767a3437870SNishanth Aravamudan 	&free_hugepages_attr.attr,
2768a3437870SNishanth Aravamudan 	&resv_hugepages_attr.attr,
2769a3437870SNishanth Aravamudan 	&surplus_hugepages_attr.attr,
277006808b08SLee Schermerhorn #ifdef CONFIG_NUMA
277106808b08SLee Schermerhorn 	&nr_hugepages_mempolicy_attr.attr,
277206808b08SLee Schermerhorn #endif
2773a3437870SNishanth Aravamudan 	NULL,
2774a3437870SNishanth Aravamudan };
2775a3437870SNishanth Aravamudan 
277667e5ed96SArvind Yadav static const struct attribute_group hstate_attr_group = {
2777a3437870SNishanth Aravamudan 	.attrs = hstate_attrs,
2778a3437870SNishanth Aravamudan };
2779a3437870SNishanth Aravamudan 
2780094e9539SJeff Mahoney static int hugetlb_sysfs_add_hstate(struct hstate *h, struct kobject *parent,
27819a305230SLee Schermerhorn 				    struct kobject **hstate_kobjs,
278267e5ed96SArvind Yadav 				    const struct attribute_group *hstate_attr_group)
2783a3437870SNishanth Aravamudan {
2784a3437870SNishanth Aravamudan 	int retval;
2785972dc4deSAneesh Kumar K.V 	int hi = hstate_index(h);
2786a3437870SNishanth Aravamudan 
27879a305230SLee Schermerhorn 	hstate_kobjs[hi] = kobject_create_and_add(h->name, parent);
27889a305230SLee Schermerhorn 	if (!hstate_kobjs[hi])
2789a3437870SNishanth Aravamudan 		return -ENOMEM;
2790a3437870SNishanth Aravamudan 
27919a305230SLee Schermerhorn 	retval = sysfs_create_group(hstate_kobjs[hi], hstate_attr_group);
2792a3437870SNishanth Aravamudan 	if (retval)
27939a305230SLee Schermerhorn 		kobject_put(hstate_kobjs[hi]);
2794a3437870SNishanth Aravamudan 
2795a3437870SNishanth Aravamudan 	return retval;
2796a3437870SNishanth Aravamudan }
2797a3437870SNishanth Aravamudan 
2798a3437870SNishanth Aravamudan static void __init hugetlb_sysfs_init(void)
2799a3437870SNishanth Aravamudan {
2800a3437870SNishanth Aravamudan 	struct hstate *h;
2801a3437870SNishanth Aravamudan 	int err;
2802a3437870SNishanth Aravamudan 
2803a3437870SNishanth Aravamudan 	hugepages_kobj = kobject_create_and_add("hugepages", mm_kobj);
2804a3437870SNishanth Aravamudan 	if (!hugepages_kobj)
2805a3437870SNishanth Aravamudan 		return;
2806a3437870SNishanth Aravamudan 
2807a3437870SNishanth Aravamudan 	for_each_hstate(h) {
28089a305230SLee Schermerhorn 		err = hugetlb_sysfs_add_hstate(h, hugepages_kobj,
28099a305230SLee Schermerhorn 					 hstate_kobjs, &hstate_attr_group);
2810a3437870SNishanth Aravamudan 		if (err)
2811ffb22af5SAndrew Morton 			pr_err("Hugetlb: Unable to add hstate %s", h->name);
2812a3437870SNishanth Aravamudan 	}
2813a3437870SNishanth Aravamudan }
2814a3437870SNishanth Aravamudan 
28159a305230SLee Schermerhorn #ifdef CONFIG_NUMA
28169a305230SLee Schermerhorn 
28179a305230SLee Schermerhorn /*
28189a305230SLee Schermerhorn  * node_hstate/s - associate per node hstate attributes, via their kobjects,
281910fbcf4cSKay Sievers  * with node devices in node_devices[] using a parallel array.  The array
282010fbcf4cSKay Sievers  * index of a node device or _hstate == node id.
282110fbcf4cSKay Sievers  * This is here to avoid any static dependency of the node device driver, in
28229a305230SLee Schermerhorn  * the base kernel, on the hugetlb module.
28239a305230SLee Schermerhorn  */
28249a305230SLee Schermerhorn struct node_hstate {
28259a305230SLee Schermerhorn 	struct kobject		*hugepages_kobj;
28269a305230SLee Schermerhorn 	struct kobject		*hstate_kobjs[HUGE_MAX_HSTATE];
28279a305230SLee Schermerhorn };
2828b4e289a6SAlexander Kuleshov static struct node_hstate node_hstates[MAX_NUMNODES];
28299a305230SLee Schermerhorn 
28309a305230SLee Schermerhorn /*
283110fbcf4cSKay Sievers  * A subset of global hstate attributes for node devices
28329a305230SLee Schermerhorn  */
28339a305230SLee Schermerhorn static struct attribute *per_node_hstate_attrs[] = {
28349a305230SLee Schermerhorn 	&nr_hugepages_attr.attr,
28359a305230SLee Schermerhorn 	&free_hugepages_attr.attr,
28369a305230SLee Schermerhorn 	&surplus_hugepages_attr.attr,
28379a305230SLee Schermerhorn 	NULL,
28389a305230SLee Schermerhorn };
28399a305230SLee Schermerhorn 
284067e5ed96SArvind Yadav static const struct attribute_group per_node_hstate_attr_group = {
28419a305230SLee Schermerhorn 	.attrs = per_node_hstate_attrs,
28429a305230SLee Schermerhorn };
28439a305230SLee Schermerhorn 
28449a305230SLee Schermerhorn /*
284510fbcf4cSKay Sievers  * kobj_to_node_hstate - lookup global hstate for node device hstate attr kobj.
28469a305230SLee Schermerhorn  * Returns node id via non-NULL nidp.
28479a305230SLee Schermerhorn  */
28489a305230SLee Schermerhorn static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
28499a305230SLee Schermerhorn {
28509a305230SLee Schermerhorn 	int nid;
28519a305230SLee Schermerhorn 
28529a305230SLee Schermerhorn 	for (nid = 0; nid < nr_node_ids; nid++) {
28539a305230SLee Schermerhorn 		struct node_hstate *nhs = &node_hstates[nid];
28549a305230SLee Schermerhorn 		int i;
28559a305230SLee Schermerhorn 		for (i = 0; i < HUGE_MAX_HSTATE; i++)
28569a305230SLee Schermerhorn 			if (nhs->hstate_kobjs[i] == kobj) {
28579a305230SLee Schermerhorn 				if (nidp)
28589a305230SLee Schermerhorn 					*nidp = nid;
28599a305230SLee Schermerhorn 				return &hstates[i];
28609a305230SLee Schermerhorn 			}
28619a305230SLee Schermerhorn 	}
28629a305230SLee Schermerhorn 
28639a305230SLee Schermerhorn 	BUG();
28649a305230SLee Schermerhorn 	return NULL;
28659a305230SLee Schermerhorn }
28669a305230SLee Schermerhorn 
28679a305230SLee Schermerhorn /*
286810fbcf4cSKay Sievers  * Unregister hstate attributes from a single node device.
28699a305230SLee Schermerhorn  * No-op if no hstate attributes attached.
28709a305230SLee Schermerhorn  */
28713cd8b44fSClaudiu Ghioc static void hugetlb_unregister_node(struct node *node)
28729a305230SLee Schermerhorn {
28739a305230SLee Schermerhorn 	struct hstate *h;
287410fbcf4cSKay Sievers 	struct node_hstate *nhs = &node_hstates[node->dev.id];
28759a305230SLee Schermerhorn 
28769a305230SLee Schermerhorn 	if (!nhs->hugepages_kobj)
28779b5e5d0fSLee Schermerhorn 		return;		/* no hstate attributes */
28789a305230SLee Schermerhorn 
2879972dc4deSAneesh Kumar K.V 	for_each_hstate(h) {
2880972dc4deSAneesh Kumar K.V 		int idx = hstate_index(h);
2881972dc4deSAneesh Kumar K.V 		if (nhs->hstate_kobjs[idx]) {
2882972dc4deSAneesh Kumar K.V 			kobject_put(nhs->hstate_kobjs[idx]);
2883972dc4deSAneesh Kumar K.V 			nhs->hstate_kobjs[idx] = NULL;
2884972dc4deSAneesh Kumar K.V 		}
28859a305230SLee Schermerhorn 	}
28869a305230SLee Schermerhorn 
28879a305230SLee Schermerhorn 	kobject_put(nhs->hugepages_kobj);
28889a305230SLee Schermerhorn 	nhs->hugepages_kobj = NULL;
28899a305230SLee Schermerhorn }
28909a305230SLee Schermerhorn 
28919a305230SLee Schermerhorn 
28929a305230SLee Schermerhorn /*
289310fbcf4cSKay Sievers  * Register hstate attributes for a single node device.
28949a305230SLee Schermerhorn  * No-op if attributes already registered.
28959a305230SLee Schermerhorn  */
28963cd8b44fSClaudiu Ghioc static void hugetlb_register_node(struct node *node)
28979a305230SLee Schermerhorn {
28989a305230SLee Schermerhorn 	struct hstate *h;
289910fbcf4cSKay Sievers 	struct node_hstate *nhs = &node_hstates[node->dev.id];
29009a305230SLee Schermerhorn 	int err;
29019a305230SLee Schermerhorn 
29029a305230SLee Schermerhorn 	if (nhs->hugepages_kobj)
29039a305230SLee Schermerhorn 		return;		/* already allocated */
29049a305230SLee Schermerhorn 
29059a305230SLee Schermerhorn 	nhs->hugepages_kobj = kobject_create_and_add("hugepages",
290610fbcf4cSKay Sievers 							&node->dev.kobj);
29079a305230SLee Schermerhorn 	if (!nhs->hugepages_kobj)
29089a305230SLee Schermerhorn 		return;
29099a305230SLee Schermerhorn 
29109a305230SLee Schermerhorn 	for_each_hstate(h) {
29119a305230SLee Schermerhorn 		err = hugetlb_sysfs_add_hstate(h, nhs->hugepages_kobj,
29129a305230SLee Schermerhorn 						nhs->hstate_kobjs,
29139a305230SLee Schermerhorn 						&per_node_hstate_attr_group);
29149a305230SLee Schermerhorn 		if (err) {
2915ffb22af5SAndrew Morton 			pr_err("Hugetlb: Unable to add hstate %s for node %d\n",
291610fbcf4cSKay Sievers 				h->name, node->dev.id);
29179a305230SLee Schermerhorn 			hugetlb_unregister_node(node);
29189a305230SLee Schermerhorn 			break;
29199a305230SLee Schermerhorn 		}
29209a305230SLee Schermerhorn 	}
29219a305230SLee Schermerhorn }
29229a305230SLee Schermerhorn 
29239a305230SLee Schermerhorn /*
29249b5e5d0fSLee Schermerhorn  * hugetlb init time:  register hstate attributes for all registered node
292510fbcf4cSKay Sievers  * devices of nodes that have memory.  All on-line nodes should have
292610fbcf4cSKay Sievers  * registered their associated device by this time.
29279a305230SLee Schermerhorn  */
29287d9ca000SLuiz Capitulino static void __init hugetlb_register_all_nodes(void)
29299a305230SLee Schermerhorn {
29309a305230SLee Schermerhorn 	int nid;
29319a305230SLee Schermerhorn 
29328cebfcd0SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
29338732794bSWen Congyang 		struct node *node = node_devices[nid];
293410fbcf4cSKay Sievers 		if (node->dev.id == nid)
29359a305230SLee Schermerhorn 			hugetlb_register_node(node);
29369a305230SLee Schermerhorn 	}
29379a305230SLee Schermerhorn 
29389a305230SLee Schermerhorn 	/*
293910fbcf4cSKay Sievers 	 * Let the node device driver know we're here so it can
29409a305230SLee Schermerhorn 	 * [un]register hstate attributes on node hotplug.
29419a305230SLee Schermerhorn 	 */
29429a305230SLee Schermerhorn 	register_hugetlbfs_with_node(hugetlb_register_node,
29439a305230SLee Schermerhorn 				     hugetlb_unregister_node);
29449a305230SLee Schermerhorn }
29459a305230SLee Schermerhorn #else	/* !CONFIG_NUMA */
29469a305230SLee Schermerhorn 
29479a305230SLee Schermerhorn static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
29489a305230SLee Schermerhorn {
29499a305230SLee Schermerhorn 	BUG();
29509a305230SLee Schermerhorn 	if (nidp)
29519a305230SLee Schermerhorn 		*nidp = -1;
29529a305230SLee Schermerhorn 	return NULL;
29539a305230SLee Schermerhorn }
29549a305230SLee Schermerhorn 
29559a305230SLee Schermerhorn static void hugetlb_register_all_nodes(void) { }
29569a305230SLee Schermerhorn 
29579a305230SLee Schermerhorn #endif
29589a305230SLee Schermerhorn 
2959a3437870SNishanth Aravamudan static int __init hugetlb_init(void)
2960a3437870SNishanth Aravamudan {
29618382d914SDavidlohr Bueso 	int i;
29628382d914SDavidlohr Bueso 
2963457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
29640ef89d25SBenjamin Herrenschmidt 		return 0;
2965a3437870SNishanth Aravamudan 
2966e11bfbfcSNick Piggin 	if (!size_to_hstate(default_hstate_size)) {
2967d715cf80SLiam R. Howlett 		if (default_hstate_size != 0) {
2968d715cf80SLiam R. Howlett 			pr_err("HugeTLB: unsupported default_hugepagesz %lu. Reverting to %lu\n",
2969d715cf80SLiam R. Howlett 			       default_hstate_size, HPAGE_SIZE);
2970d715cf80SLiam R. Howlett 		}
2971d715cf80SLiam R. Howlett 
2972e11bfbfcSNick Piggin 		default_hstate_size = HPAGE_SIZE;
2973e11bfbfcSNick Piggin 		if (!size_to_hstate(default_hstate_size))
2974a3437870SNishanth Aravamudan 			hugetlb_add_hstate(HUGETLB_PAGE_ORDER);
2975a3437870SNishanth Aravamudan 	}
2976972dc4deSAneesh Kumar K.V 	default_hstate_idx = hstate_index(size_to_hstate(default_hstate_size));
2977f8b74815SVaishali Thakkar 	if (default_hstate_max_huge_pages) {
2978f8b74815SVaishali Thakkar 		if (!default_hstate.max_huge_pages)
2979e11bfbfcSNick Piggin 			default_hstate.max_huge_pages = default_hstate_max_huge_pages;
2980f8b74815SVaishali Thakkar 	}
2981a3437870SNishanth Aravamudan 
2982a3437870SNishanth Aravamudan 	hugetlb_init_hstates();
2983aa888a74SAndi Kleen 	gather_bootmem_prealloc();
2984a3437870SNishanth Aravamudan 	report_hugepages();
2985a3437870SNishanth Aravamudan 
2986a3437870SNishanth Aravamudan 	hugetlb_sysfs_init();
29879a305230SLee Schermerhorn 	hugetlb_register_all_nodes();
29887179e7bfSJianguo Wu 	hugetlb_cgroup_file_init();
29899a305230SLee Schermerhorn 
29908382d914SDavidlohr Bueso #ifdef CONFIG_SMP
29918382d914SDavidlohr Bueso 	num_fault_mutexes = roundup_pow_of_two(8 * num_possible_cpus());
29928382d914SDavidlohr Bueso #else
29938382d914SDavidlohr Bueso 	num_fault_mutexes = 1;
29948382d914SDavidlohr Bueso #endif
2995c672c7f2SMike Kravetz 	hugetlb_fault_mutex_table =
29966da2ec56SKees Cook 		kmalloc_array(num_fault_mutexes, sizeof(struct mutex),
29976da2ec56SKees Cook 			      GFP_KERNEL);
2998c672c7f2SMike Kravetz 	BUG_ON(!hugetlb_fault_mutex_table);
29998382d914SDavidlohr Bueso 
30008382d914SDavidlohr Bueso 	for (i = 0; i < num_fault_mutexes; i++)
3001c672c7f2SMike Kravetz 		mutex_init(&hugetlb_fault_mutex_table[i]);
3002a3437870SNishanth Aravamudan 	return 0;
3003a3437870SNishanth Aravamudan }
30043e89e1c5SPaul Gortmaker subsys_initcall(hugetlb_init);
3005a3437870SNishanth Aravamudan 
3006a3437870SNishanth Aravamudan /* Should be called on processing a hugepagesz=... option */
30079fee021dSVaishali Thakkar void __init hugetlb_bad_size(void)
30089fee021dSVaishali Thakkar {
30099fee021dSVaishali Thakkar 	parsed_valid_hugepagesz = false;
30109fee021dSVaishali Thakkar }
30119fee021dSVaishali Thakkar 
3012d00181b9SKirill A. Shutemov void __init hugetlb_add_hstate(unsigned int order)
3013a3437870SNishanth Aravamudan {
3014a3437870SNishanth Aravamudan 	struct hstate *h;
30158faa8b07SAndi Kleen 	unsigned long i;
30168faa8b07SAndi Kleen 
3017a3437870SNishanth Aravamudan 	if (size_to_hstate(PAGE_SIZE << order)) {
3018598d8091SJoe Perches 		pr_warn("hugepagesz= specified twice, ignoring\n");
3019a3437870SNishanth Aravamudan 		return;
3020a3437870SNishanth Aravamudan 	}
302147d38344SAneesh Kumar K.V 	BUG_ON(hugetlb_max_hstate >= HUGE_MAX_HSTATE);
3022a3437870SNishanth Aravamudan 	BUG_ON(order == 0);
302347d38344SAneesh Kumar K.V 	h = &hstates[hugetlb_max_hstate++];
3024a3437870SNishanth Aravamudan 	h->order = order;
3025a3437870SNishanth Aravamudan 	h->mask = ~((1ULL << (order + PAGE_SHIFT)) - 1);
30268faa8b07SAndi Kleen 	h->nr_huge_pages = 0;
30278faa8b07SAndi Kleen 	h->free_huge_pages = 0;
30288faa8b07SAndi Kleen 	for (i = 0; i < MAX_NUMNODES; ++i)
30298faa8b07SAndi Kleen 		INIT_LIST_HEAD(&h->hugepage_freelists[i]);
30300edaecfaSAneesh Kumar K.V 	INIT_LIST_HEAD(&h->hugepage_activelist);
303154f18d35SAndrew Morton 	h->next_nid_to_alloc = first_memory_node;
303254f18d35SAndrew Morton 	h->next_nid_to_free = first_memory_node;
3033a3437870SNishanth Aravamudan 	snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB",
3034a3437870SNishanth Aravamudan 					huge_page_size(h)/1024);
30358faa8b07SAndi Kleen 
3036a3437870SNishanth Aravamudan 	parsed_hstate = h;
3037a3437870SNishanth Aravamudan }
3038a3437870SNishanth Aravamudan 
3039e11bfbfcSNick Piggin static int __init hugetlb_nrpages_setup(char *s)
3040a3437870SNishanth Aravamudan {
3041a3437870SNishanth Aravamudan 	unsigned long *mhp;
30428faa8b07SAndi Kleen 	static unsigned long *last_mhp;
3043a3437870SNishanth Aravamudan 
30449fee021dSVaishali Thakkar 	if (!parsed_valid_hugepagesz) {
30459fee021dSVaishali Thakkar 		pr_warn("hugepages = %s preceded by "
30469fee021dSVaishali Thakkar 			"an unsupported hugepagesz, ignoring\n", s);
30479fee021dSVaishali Thakkar 		parsed_valid_hugepagesz = true;
30489fee021dSVaishali Thakkar 		return 1;
30499fee021dSVaishali Thakkar 	}
3050a3437870SNishanth Aravamudan 	/*
305147d38344SAneesh Kumar K.V 	 * !hugetlb_max_hstate means we haven't parsed a hugepagesz= parameter yet,
3052a3437870SNishanth Aravamudan 	 * so this hugepages= parameter goes to the "default hstate".
3053a3437870SNishanth Aravamudan 	 */
30549fee021dSVaishali Thakkar 	else if (!hugetlb_max_hstate)
3055a3437870SNishanth Aravamudan 		mhp = &default_hstate_max_huge_pages;
3056a3437870SNishanth Aravamudan 	else
3057a3437870SNishanth Aravamudan 		mhp = &parsed_hstate->max_huge_pages;
3058a3437870SNishanth Aravamudan 
30598faa8b07SAndi Kleen 	if (mhp == last_mhp) {
3060598d8091SJoe Perches 		pr_warn("hugepages= specified twice without interleaving hugepagesz=, ignoring\n");
30618faa8b07SAndi Kleen 		return 1;
30628faa8b07SAndi Kleen 	}
30638faa8b07SAndi Kleen 
3064a3437870SNishanth Aravamudan 	if (sscanf(s, "%lu", mhp) <= 0)
3065a3437870SNishanth Aravamudan 		*mhp = 0;
3066a3437870SNishanth Aravamudan 
30678faa8b07SAndi Kleen 	/*
30688faa8b07SAndi Kleen 	 * Global state is always initialized later in hugetlb_init.
30698faa8b07SAndi Kleen 	 * But we need to allocate >= MAX_ORDER hstates here early to still
30708faa8b07SAndi Kleen 	 * use the bootmem allocator.
30718faa8b07SAndi Kleen 	 */
307247d38344SAneesh Kumar K.V 	if (hugetlb_max_hstate && parsed_hstate->order >= MAX_ORDER)
30738faa8b07SAndi Kleen 		hugetlb_hstate_alloc_pages(parsed_hstate);
30748faa8b07SAndi Kleen 
30758faa8b07SAndi Kleen 	last_mhp = mhp;
30768faa8b07SAndi Kleen 
3077a3437870SNishanth Aravamudan 	return 1;
3078a3437870SNishanth Aravamudan }
3079e11bfbfcSNick Piggin __setup("hugepages=", hugetlb_nrpages_setup);
3080e11bfbfcSNick Piggin 
3081e11bfbfcSNick Piggin static int __init hugetlb_default_setup(char *s)
3082e11bfbfcSNick Piggin {
3083e11bfbfcSNick Piggin 	default_hstate_size = memparse(s, &s);
3084e11bfbfcSNick Piggin 	return 1;
3085e11bfbfcSNick Piggin }
3086e11bfbfcSNick Piggin __setup("default_hugepagesz=", hugetlb_default_setup);
3087a3437870SNishanth Aravamudan 
30888a213460SNishanth Aravamudan static unsigned int cpuset_mems_nr(unsigned int *array)
30898a213460SNishanth Aravamudan {
30908a213460SNishanth Aravamudan 	int node;
30918a213460SNishanth Aravamudan 	unsigned int nr = 0;
30928a213460SNishanth Aravamudan 
30938a213460SNishanth Aravamudan 	for_each_node_mask(node, cpuset_current_mems_allowed)
30948a213460SNishanth Aravamudan 		nr += array[node];
30958a213460SNishanth Aravamudan 
30968a213460SNishanth Aravamudan 	return nr;
30978a213460SNishanth Aravamudan }
30988a213460SNishanth Aravamudan 
30998a213460SNishanth Aravamudan #ifdef CONFIG_SYSCTL
310006808b08SLee Schermerhorn static int hugetlb_sysctl_handler_common(bool obey_mempolicy,
310106808b08SLee Schermerhorn 			 struct ctl_table *table, int write,
310206808b08SLee Schermerhorn 			 void __user *buffer, size_t *length, loff_t *ppos)
31031da177e4SLinus Torvalds {
3104e5ff2159SAndi Kleen 	struct hstate *h = &default_hstate;
3105238d3c13SDavid Rientjes 	unsigned long tmp = h->max_huge_pages;
310608d4a246SMichal Hocko 	int ret;
3107e5ff2159SAndi Kleen 
3108457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
310986613628SJan Stancek 		return -EOPNOTSUPP;
3110457c1b27SNishanth Aravamudan 
3111e5ff2159SAndi Kleen 	table->data = &tmp;
3112e5ff2159SAndi Kleen 	table->maxlen = sizeof(unsigned long);
311308d4a246SMichal Hocko 	ret = proc_doulongvec_minmax(table, write, buffer, length, ppos);
311408d4a246SMichal Hocko 	if (ret)
311508d4a246SMichal Hocko 		goto out;
3116e5ff2159SAndi Kleen 
3117238d3c13SDavid Rientjes 	if (write)
3118238d3c13SDavid Rientjes 		ret = __nr_hugepages_store_common(obey_mempolicy, h,
3119238d3c13SDavid Rientjes 						  NUMA_NO_NODE, tmp, *length);
312008d4a246SMichal Hocko out:
312108d4a246SMichal Hocko 	return ret;
31221da177e4SLinus Torvalds }
3123396faf03SMel Gorman 
312406808b08SLee Schermerhorn int hugetlb_sysctl_handler(struct ctl_table *table, int write,
312506808b08SLee Schermerhorn 			  void __user *buffer, size_t *length, loff_t *ppos)
312606808b08SLee Schermerhorn {
312706808b08SLee Schermerhorn 
312806808b08SLee Schermerhorn 	return hugetlb_sysctl_handler_common(false, table, write,
312906808b08SLee Schermerhorn 							buffer, length, ppos);
313006808b08SLee Schermerhorn }
313106808b08SLee Schermerhorn 
313206808b08SLee Schermerhorn #ifdef CONFIG_NUMA
313306808b08SLee Schermerhorn int hugetlb_mempolicy_sysctl_handler(struct ctl_table *table, int write,
313406808b08SLee Schermerhorn 			  void __user *buffer, size_t *length, loff_t *ppos)
313506808b08SLee Schermerhorn {
313606808b08SLee Schermerhorn 	return hugetlb_sysctl_handler_common(true, table, write,
313706808b08SLee Schermerhorn 							buffer, length, ppos);
313806808b08SLee Schermerhorn }
313906808b08SLee Schermerhorn #endif /* CONFIG_NUMA */
314006808b08SLee Schermerhorn 
3141a3d0c6aaSNishanth Aravamudan int hugetlb_overcommit_handler(struct ctl_table *table, int write,
31428d65af78SAlexey Dobriyan 			void __user *buffer,
3143a3d0c6aaSNishanth Aravamudan 			size_t *length, loff_t *ppos)
3144a3d0c6aaSNishanth Aravamudan {
3145a5516438SAndi Kleen 	struct hstate *h = &default_hstate;
3146e5ff2159SAndi Kleen 	unsigned long tmp;
314708d4a246SMichal Hocko 	int ret;
3148e5ff2159SAndi Kleen 
3149457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
315086613628SJan Stancek 		return -EOPNOTSUPP;
3151457c1b27SNishanth Aravamudan 
3152e5ff2159SAndi Kleen 	tmp = h->nr_overcommit_huge_pages;
3153e5ff2159SAndi Kleen 
3154bae7f4aeSLuiz Capitulino 	if (write && hstate_is_gigantic(h))
3155adbe8726SEric B Munson 		return -EINVAL;
3156adbe8726SEric B Munson 
3157e5ff2159SAndi Kleen 	table->data = &tmp;
3158e5ff2159SAndi Kleen 	table->maxlen = sizeof(unsigned long);
315908d4a246SMichal Hocko 	ret = proc_doulongvec_minmax(table, write, buffer, length, ppos);
316008d4a246SMichal Hocko 	if (ret)
316108d4a246SMichal Hocko 		goto out;
3162e5ff2159SAndi Kleen 
3163e5ff2159SAndi Kleen 	if (write) {
3164064d9efeSNishanth Aravamudan 		spin_lock(&hugetlb_lock);
3165e5ff2159SAndi Kleen 		h->nr_overcommit_huge_pages = tmp;
3166a3d0c6aaSNishanth Aravamudan 		spin_unlock(&hugetlb_lock);
3167e5ff2159SAndi Kleen 	}
316808d4a246SMichal Hocko out:
316908d4a246SMichal Hocko 	return ret;
3170a3d0c6aaSNishanth Aravamudan }
3171a3d0c6aaSNishanth Aravamudan 
31721da177e4SLinus Torvalds #endif /* CONFIG_SYSCTL */
31731da177e4SLinus Torvalds 
3174e1759c21SAlexey Dobriyan void hugetlb_report_meminfo(struct seq_file *m)
31751da177e4SLinus Torvalds {
3176fcb2b0c5SRoman Gushchin 	struct hstate *h;
3177fcb2b0c5SRoman Gushchin 	unsigned long total = 0;
3178fcb2b0c5SRoman Gushchin 
3179457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
3180457c1b27SNishanth Aravamudan 		return;
3181fcb2b0c5SRoman Gushchin 
3182fcb2b0c5SRoman Gushchin 	for_each_hstate(h) {
3183fcb2b0c5SRoman Gushchin 		unsigned long count = h->nr_huge_pages;
3184fcb2b0c5SRoman Gushchin 
3185fcb2b0c5SRoman Gushchin 		total += (PAGE_SIZE << huge_page_order(h)) * count;
3186fcb2b0c5SRoman Gushchin 
3187fcb2b0c5SRoman Gushchin 		if (h == &default_hstate)
3188e1759c21SAlexey Dobriyan 			seq_printf(m,
31891da177e4SLinus Torvalds 				   "HugePages_Total:   %5lu\n"
31901da177e4SLinus Torvalds 				   "HugePages_Free:    %5lu\n"
3191b45b5bd6SDavid Gibson 				   "HugePages_Rsvd:    %5lu\n"
31927893d1d5SAdam Litke 				   "HugePages_Surp:    %5lu\n"
31934f98a2feSRik van Riel 				   "Hugepagesize:   %8lu kB\n",
3194fcb2b0c5SRoman Gushchin 				   count,
3195a5516438SAndi Kleen 				   h->free_huge_pages,
3196a5516438SAndi Kleen 				   h->resv_huge_pages,
3197a5516438SAndi Kleen 				   h->surplus_huge_pages,
3198fcb2b0c5SRoman Gushchin 				   (PAGE_SIZE << huge_page_order(h)) / 1024);
3199fcb2b0c5SRoman Gushchin 	}
3200fcb2b0c5SRoman Gushchin 
3201fcb2b0c5SRoman Gushchin 	seq_printf(m, "Hugetlb:        %8lu kB\n", total / 1024);
32021da177e4SLinus Torvalds }
32031da177e4SLinus Torvalds 
32041da177e4SLinus Torvalds int hugetlb_report_node_meminfo(int nid, char *buf)
32051da177e4SLinus Torvalds {
3206a5516438SAndi Kleen 	struct hstate *h = &default_hstate;
3207457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
3208457c1b27SNishanth Aravamudan 		return 0;
32091da177e4SLinus Torvalds 	return sprintf(buf,
32101da177e4SLinus Torvalds 		"Node %d HugePages_Total: %5u\n"
3211a1de0919SNishanth Aravamudan 		"Node %d HugePages_Free:  %5u\n"
3212a1de0919SNishanth Aravamudan 		"Node %d HugePages_Surp:  %5u\n",
3213a5516438SAndi Kleen 		nid, h->nr_huge_pages_node[nid],
3214a5516438SAndi Kleen 		nid, h->free_huge_pages_node[nid],
3215a5516438SAndi Kleen 		nid, h->surplus_huge_pages_node[nid]);
32161da177e4SLinus Torvalds }
32171da177e4SLinus Torvalds 
3218949f7ec5SDavid Rientjes void hugetlb_show_meminfo(void)
3219949f7ec5SDavid Rientjes {
3220949f7ec5SDavid Rientjes 	struct hstate *h;
3221949f7ec5SDavid Rientjes 	int nid;
3222949f7ec5SDavid Rientjes 
3223457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
3224457c1b27SNishanth Aravamudan 		return;
3225457c1b27SNishanth Aravamudan 
3226949f7ec5SDavid Rientjes 	for_each_node_state(nid, N_MEMORY)
3227949f7ec5SDavid Rientjes 		for_each_hstate(h)
3228949f7ec5SDavid Rientjes 			pr_info("Node %d hugepages_total=%u hugepages_free=%u hugepages_surp=%u hugepages_size=%lukB\n",
3229949f7ec5SDavid Rientjes 				nid,
3230949f7ec5SDavid Rientjes 				h->nr_huge_pages_node[nid],
3231949f7ec5SDavid Rientjes 				h->free_huge_pages_node[nid],
3232949f7ec5SDavid Rientjes 				h->surplus_huge_pages_node[nid],
3233949f7ec5SDavid Rientjes 				1UL << (huge_page_order(h) + PAGE_SHIFT - 10));
3234949f7ec5SDavid Rientjes }
3235949f7ec5SDavid Rientjes 
32365d317b2bSNaoya Horiguchi void hugetlb_report_usage(struct seq_file *m, struct mm_struct *mm)
32375d317b2bSNaoya Horiguchi {
32385d317b2bSNaoya Horiguchi 	seq_printf(m, "HugetlbPages:\t%8lu kB\n",
32395d317b2bSNaoya Horiguchi 		   atomic_long_read(&mm->hugetlb_usage) << (PAGE_SHIFT - 10));
32405d317b2bSNaoya Horiguchi }
32415d317b2bSNaoya Horiguchi 
32421da177e4SLinus Torvalds /* Return the number pages of memory we physically have, in PAGE_SIZE units. */
32431da177e4SLinus Torvalds unsigned long hugetlb_total_pages(void)
32441da177e4SLinus Torvalds {
3245d0028588SWanpeng Li 	struct hstate *h;
3246d0028588SWanpeng Li 	unsigned long nr_total_pages = 0;
3247d0028588SWanpeng Li 
3248d0028588SWanpeng Li 	for_each_hstate(h)
3249d0028588SWanpeng Li 		nr_total_pages += h->nr_huge_pages * pages_per_huge_page(h);
3250d0028588SWanpeng Li 	return nr_total_pages;
32511da177e4SLinus Torvalds }
32521da177e4SLinus Torvalds 
3253a5516438SAndi Kleen static int hugetlb_acct_memory(struct hstate *h, long delta)
3254fc1b8a73SMel Gorman {
3255fc1b8a73SMel Gorman 	int ret = -ENOMEM;
3256fc1b8a73SMel Gorman 
3257fc1b8a73SMel Gorman 	spin_lock(&hugetlb_lock);
3258fc1b8a73SMel Gorman 	/*
3259fc1b8a73SMel Gorman 	 * When cpuset is configured, it breaks the strict hugetlb page
3260fc1b8a73SMel Gorman 	 * reservation as the accounting is done on a global variable. Such
3261fc1b8a73SMel Gorman 	 * reservation is completely rubbish in the presence of cpuset because
3262fc1b8a73SMel Gorman 	 * the reservation is not checked against page availability for the
3263fc1b8a73SMel Gorman 	 * current cpuset. Application can still potentially OOM'ed by kernel
3264fc1b8a73SMel Gorman 	 * with lack of free htlb page in cpuset that the task is in.
3265fc1b8a73SMel Gorman 	 * Attempt to enforce strict accounting with cpuset is almost
3266fc1b8a73SMel Gorman 	 * impossible (or too ugly) because cpuset is too fluid that
3267fc1b8a73SMel Gorman 	 * task or memory node can be dynamically moved between cpusets.
3268fc1b8a73SMel Gorman 	 *
3269fc1b8a73SMel Gorman 	 * The change of semantics for shared hugetlb mapping with cpuset is
3270fc1b8a73SMel Gorman 	 * undesirable. However, in order to preserve some of the semantics,
3271fc1b8a73SMel Gorman 	 * we fall back to check against current free page availability as
3272fc1b8a73SMel Gorman 	 * a best attempt and hopefully to minimize the impact of changing
3273fc1b8a73SMel Gorman 	 * semantics that cpuset has.
3274fc1b8a73SMel Gorman 	 */
3275fc1b8a73SMel Gorman 	if (delta > 0) {
3276a5516438SAndi Kleen 		if (gather_surplus_pages(h, delta) < 0)
3277fc1b8a73SMel Gorman 			goto out;
3278fc1b8a73SMel Gorman 
3279a5516438SAndi Kleen 		if (delta > cpuset_mems_nr(h->free_huge_pages_node)) {
3280a5516438SAndi Kleen 			return_unused_surplus_pages(h, delta);
3281fc1b8a73SMel Gorman 			goto out;
3282fc1b8a73SMel Gorman 		}
3283fc1b8a73SMel Gorman 	}
3284fc1b8a73SMel Gorman 
3285fc1b8a73SMel Gorman 	ret = 0;
3286fc1b8a73SMel Gorman 	if (delta < 0)
3287a5516438SAndi Kleen 		return_unused_surplus_pages(h, (unsigned long) -delta);
3288fc1b8a73SMel Gorman 
3289fc1b8a73SMel Gorman out:
3290fc1b8a73SMel Gorman 	spin_unlock(&hugetlb_lock);
3291fc1b8a73SMel Gorman 	return ret;
3292fc1b8a73SMel Gorman }
3293fc1b8a73SMel Gorman 
329484afd99bSAndy Whitcroft static void hugetlb_vm_op_open(struct vm_area_struct *vma)
329584afd99bSAndy Whitcroft {
3296f522c3acSJoonsoo Kim 	struct resv_map *resv = vma_resv_map(vma);
329784afd99bSAndy Whitcroft 
329884afd99bSAndy Whitcroft 	/*
329984afd99bSAndy Whitcroft 	 * This new VMA should share its siblings reservation map if present.
330084afd99bSAndy Whitcroft 	 * The VMA will only ever have a valid reservation map pointer where
330184afd99bSAndy Whitcroft 	 * it is being copied for another still existing VMA.  As that VMA
330225985edcSLucas De Marchi 	 * has a reference to the reservation map it cannot disappear until
330384afd99bSAndy Whitcroft 	 * after this open call completes.  It is therefore safe to take a
330484afd99bSAndy Whitcroft 	 * new reference here without additional locking.
330584afd99bSAndy Whitcroft 	 */
33064e35f483SJoonsoo Kim 	if (resv && is_vma_resv_set(vma, HPAGE_RESV_OWNER))
3307f522c3acSJoonsoo Kim 		kref_get(&resv->refs);
330884afd99bSAndy Whitcroft }
330984afd99bSAndy Whitcroft 
3310a1e78772SMel Gorman static void hugetlb_vm_op_close(struct vm_area_struct *vma)
3311a1e78772SMel Gorman {
3312a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
3313f522c3acSJoonsoo Kim 	struct resv_map *resv = vma_resv_map(vma);
331490481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_vma(vma);
33154e35f483SJoonsoo Kim 	unsigned long reserve, start, end;
33161c5ecae3SMike Kravetz 	long gbl_reserve;
331784afd99bSAndy Whitcroft 
33184e35f483SJoonsoo Kim 	if (!resv || !is_vma_resv_set(vma, HPAGE_RESV_OWNER))
33194e35f483SJoonsoo Kim 		return;
33204e35f483SJoonsoo Kim 
3321a5516438SAndi Kleen 	start = vma_hugecache_offset(h, vma, vma->vm_start);
3322a5516438SAndi Kleen 	end = vma_hugecache_offset(h, vma, vma->vm_end);
332384afd99bSAndy Whitcroft 
33244e35f483SJoonsoo Kim 	reserve = (end - start) - region_count(resv, start, end);
3325e9fe92aeSMina Almasry 	hugetlb_cgroup_uncharge_counter(resv, start, end);
33267251ff78SAdam Litke 	if (reserve) {
33271c5ecae3SMike Kravetz 		/*
33281c5ecae3SMike Kravetz 		 * Decrement reserve counts.  The global reserve count may be
33291c5ecae3SMike Kravetz 		 * adjusted if the subpool has a minimum size.
33301c5ecae3SMike Kravetz 		 */
33311c5ecae3SMike Kravetz 		gbl_reserve = hugepage_subpool_put_pages(spool, reserve);
33321c5ecae3SMike Kravetz 		hugetlb_acct_memory(h, -gbl_reserve);
33337251ff78SAdam Litke 	}
3334e9fe92aeSMina Almasry 
3335e9fe92aeSMina Almasry 	kref_put(&resv->refs, resv_map_release);
3336a1e78772SMel Gorman }
3337a1e78772SMel Gorman 
333831383c68SDan Williams static int hugetlb_vm_op_split(struct vm_area_struct *vma, unsigned long addr)
333931383c68SDan Williams {
334031383c68SDan Williams 	if (addr & ~(huge_page_mask(hstate_vma(vma))))
334131383c68SDan Williams 		return -EINVAL;
334231383c68SDan Williams 	return 0;
334331383c68SDan Williams }
334431383c68SDan Williams 
334505ea8860SDan Williams static unsigned long hugetlb_vm_op_pagesize(struct vm_area_struct *vma)
334605ea8860SDan Williams {
334705ea8860SDan Williams 	struct hstate *hstate = hstate_vma(vma);
334805ea8860SDan Williams 
334905ea8860SDan Williams 	return 1UL << huge_page_shift(hstate);
335005ea8860SDan Williams }
335105ea8860SDan Williams 
33521da177e4SLinus Torvalds /*
33531da177e4SLinus Torvalds  * We cannot handle pagefaults against hugetlb pages at all.  They cause
33541da177e4SLinus Torvalds  * handle_mm_fault() to try to instantiate regular-sized pages in the
33551da177e4SLinus Torvalds  * hugegpage VMA.  do_page_fault() is supposed to trap this, so BUG is we get
33561da177e4SLinus Torvalds  * this far.
33571da177e4SLinus Torvalds  */
3358b3ec9f33SSouptick Joarder static vm_fault_t hugetlb_vm_op_fault(struct vm_fault *vmf)
33591da177e4SLinus Torvalds {
33601da177e4SLinus Torvalds 	BUG();
3361d0217ac0SNick Piggin 	return 0;
33621da177e4SLinus Torvalds }
33631da177e4SLinus Torvalds 
3364eec3636aSJane Chu /*
3365eec3636aSJane Chu  * When a new function is introduced to vm_operations_struct and added
3366eec3636aSJane Chu  * to hugetlb_vm_ops, please consider adding the function to shm_vm_ops.
3367eec3636aSJane Chu  * This is because under System V memory model, mappings created via
3368eec3636aSJane Chu  * shmget/shmat with "huge page" specified are backed by hugetlbfs files,
3369eec3636aSJane Chu  * their original vm_ops are overwritten with shm_vm_ops.
3370eec3636aSJane Chu  */
3371f0f37e2fSAlexey Dobriyan const struct vm_operations_struct hugetlb_vm_ops = {
3372d0217ac0SNick Piggin 	.fault = hugetlb_vm_op_fault,
337384afd99bSAndy Whitcroft 	.open = hugetlb_vm_op_open,
3374a1e78772SMel Gorman 	.close = hugetlb_vm_op_close,
337531383c68SDan Williams 	.split = hugetlb_vm_op_split,
337605ea8860SDan Williams 	.pagesize = hugetlb_vm_op_pagesize,
33771da177e4SLinus Torvalds };
33781da177e4SLinus Torvalds 
33791e8f889bSDavid Gibson static pte_t make_huge_pte(struct vm_area_struct *vma, struct page *page,
33801e8f889bSDavid Gibson 				int writable)
338163551ae0SDavid Gibson {
338263551ae0SDavid Gibson 	pte_t entry;
338363551ae0SDavid Gibson 
33841e8f889bSDavid Gibson 	if (writable) {
3385106c992aSGerald Schaefer 		entry = huge_pte_mkwrite(huge_pte_mkdirty(mk_huge_pte(page,
3386106c992aSGerald Schaefer 					 vma->vm_page_prot)));
338763551ae0SDavid Gibson 	} else {
3388106c992aSGerald Schaefer 		entry = huge_pte_wrprotect(mk_huge_pte(page,
3389106c992aSGerald Schaefer 					   vma->vm_page_prot));
339063551ae0SDavid Gibson 	}
339163551ae0SDavid Gibson 	entry = pte_mkyoung(entry);
339263551ae0SDavid Gibson 	entry = pte_mkhuge(entry);
3393d9ed9faaSChris Metcalf 	entry = arch_make_huge_pte(entry, vma, page, writable);
339463551ae0SDavid Gibson 
339563551ae0SDavid Gibson 	return entry;
339663551ae0SDavid Gibson }
339763551ae0SDavid Gibson 
33981e8f889bSDavid Gibson static void set_huge_ptep_writable(struct vm_area_struct *vma,
33991e8f889bSDavid Gibson 				   unsigned long address, pte_t *ptep)
34001e8f889bSDavid Gibson {
34011e8f889bSDavid Gibson 	pte_t entry;
34021e8f889bSDavid Gibson 
3403106c992aSGerald Schaefer 	entry = huge_pte_mkwrite(huge_pte_mkdirty(huge_ptep_get(ptep)));
340432f84528SChris Forbes 	if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1))
34054b3073e1SRussell King 		update_mmu_cache(vma, address, ptep);
34061e8f889bSDavid Gibson }
34071e8f889bSDavid Gibson 
3408d5ed7444SAneesh Kumar K.V bool is_hugetlb_entry_migration(pte_t pte)
34094a705fefSNaoya Horiguchi {
34104a705fefSNaoya Horiguchi 	swp_entry_t swp;
34114a705fefSNaoya Horiguchi 
34124a705fefSNaoya Horiguchi 	if (huge_pte_none(pte) || pte_present(pte))
3413d5ed7444SAneesh Kumar K.V 		return false;
34144a705fefSNaoya Horiguchi 	swp = pte_to_swp_entry(pte);
34154a705fefSNaoya Horiguchi 	if (non_swap_entry(swp) && is_migration_entry(swp))
3416d5ed7444SAneesh Kumar K.V 		return true;
34174a705fefSNaoya Horiguchi 	else
3418d5ed7444SAneesh Kumar K.V 		return false;
34194a705fefSNaoya Horiguchi }
34204a705fefSNaoya Horiguchi 
34214a705fefSNaoya Horiguchi static int is_hugetlb_entry_hwpoisoned(pte_t pte)
34224a705fefSNaoya Horiguchi {
34234a705fefSNaoya Horiguchi 	swp_entry_t swp;
34244a705fefSNaoya Horiguchi 
34254a705fefSNaoya Horiguchi 	if (huge_pte_none(pte) || pte_present(pte))
34264a705fefSNaoya Horiguchi 		return 0;
34274a705fefSNaoya Horiguchi 	swp = pte_to_swp_entry(pte);
34284a705fefSNaoya Horiguchi 	if (non_swap_entry(swp) && is_hwpoison_entry(swp))
34294a705fefSNaoya Horiguchi 		return 1;
34304a705fefSNaoya Horiguchi 	else
34314a705fefSNaoya Horiguchi 		return 0;
34324a705fefSNaoya Horiguchi }
34331e8f889bSDavid Gibson 
343463551ae0SDavid Gibson int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src,
343563551ae0SDavid Gibson 			    struct vm_area_struct *vma)
343663551ae0SDavid Gibson {
34375e41540cSMike Kravetz 	pte_t *src_pte, *dst_pte, entry, dst_entry;
343863551ae0SDavid Gibson 	struct page *ptepage;
34391c59827dSHugh Dickins 	unsigned long addr;
34401e8f889bSDavid Gibson 	int cow;
3441a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
3442a5516438SAndi Kleen 	unsigned long sz = huge_page_size(h);
3443c0d0381aSMike Kravetz 	struct address_space *mapping = vma->vm_file->f_mapping;
3444ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
3445e8569dd2SAndreas Sandberg 	int ret = 0;
34461e8f889bSDavid Gibson 
34471e8f889bSDavid Gibson 	cow = (vma->vm_flags & (VM_SHARED | VM_MAYWRITE)) == VM_MAYWRITE;
344863551ae0SDavid Gibson 
3449ac46d4f3SJérôme Glisse 	if (cow) {
34507269f999SJérôme Glisse 		mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, src,
34516f4f13e8SJérôme Glisse 					vma->vm_start,
3452ac46d4f3SJérôme Glisse 					vma->vm_end);
3453ac46d4f3SJérôme Glisse 		mmu_notifier_invalidate_range_start(&range);
3454c0d0381aSMike Kravetz 	} else {
3455c0d0381aSMike Kravetz 		/*
3456c0d0381aSMike Kravetz 		 * For shared mappings i_mmap_rwsem must be held to call
3457c0d0381aSMike Kravetz 		 * huge_pte_alloc, otherwise the returned ptep could go
3458c0d0381aSMike Kravetz 		 * away if part of a shared pmd and another thread calls
3459c0d0381aSMike Kravetz 		 * huge_pmd_unshare.
3460c0d0381aSMike Kravetz 		 */
3461c0d0381aSMike Kravetz 		i_mmap_lock_read(mapping);
3462ac46d4f3SJérôme Glisse 	}
3463e8569dd2SAndreas Sandberg 
3464a5516438SAndi Kleen 	for (addr = vma->vm_start; addr < vma->vm_end; addr += sz) {
3465cb900f41SKirill A. Shutemov 		spinlock_t *src_ptl, *dst_ptl;
34667868a208SPunit Agrawal 		src_pte = huge_pte_offset(src, addr, sz);
3467c74df32cSHugh Dickins 		if (!src_pte)
3468c74df32cSHugh Dickins 			continue;
3469a5516438SAndi Kleen 		dst_pte = huge_pte_alloc(dst, addr, sz);
3470e8569dd2SAndreas Sandberg 		if (!dst_pte) {
3471e8569dd2SAndreas Sandberg 			ret = -ENOMEM;
3472e8569dd2SAndreas Sandberg 			break;
3473e8569dd2SAndreas Sandberg 		}
3474c5c99429SLarry Woodman 
34755e41540cSMike Kravetz 		/*
34765e41540cSMike Kravetz 		 * If the pagetables are shared don't copy or take references.
34775e41540cSMike Kravetz 		 * dst_pte == src_pte is the common case of src/dest sharing.
34785e41540cSMike Kravetz 		 *
34795e41540cSMike Kravetz 		 * However, src could have 'unshared' and dst shares with
34805e41540cSMike Kravetz 		 * another vma.  If dst_pte !none, this implies sharing.
34815e41540cSMike Kravetz 		 * Check here before taking page table lock, and once again
34825e41540cSMike Kravetz 		 * after taking the lock below.
34835e41540cSMike Kravetz 		 */
34845e41540cSMike Kravetz 		dst_entry = huge_ptep_get(dst_pte);
34855e41540cSMike Kravetz 		if ((dst_pte == src_pte) || !huge_pte_none(dst_entry))
3486c5c99429SLarry Woodman 			continue;
3487c5c99429SLarry Woodman 
3488cb900f41SKirill A. Shutemov 		dst_ptl = huge_pte_lock(h, dst, dst_pte);
3489cb900f41SKirill A. Shutemov 		src_ptl = huge_pte_lockptr(h, src, src_pte);
3490cb900f41SKirill A. Shutemov 		spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
34914a705fefSNaoya Horiguchi 		entry = huge_ptep_get(src_pte);
34925e41540cSMike Kravetz 		dst_entry = huge_ptep_get(dst_pte);
34935e41540cSMike Kravetz 		if (huge_pte_none(entry) || !huge_pte_none(dst_entry)) {
34945e41540cSMike Kravetz 			/*
34955e41540cSMike Kravetz 			 * Skip if src entry none.  Also, skip in the
34965e41540cSMike Kravetz 			 * unlikely case dst entry !none as this implies
34975e41540cSMike Kravetz 			 * sharing with another vma.
34985e41540cSMike Kravetz 			 */
34994a705fefSNaoya Horiguchi 			;
35004a705fefSNaoya Horiguchi 		} else if (unlikely(is_hugetlb_entry_migration(entry) ||
35014a705fefSNaoya Horiguchi 				    is_hugetlb_entry_hwpoisoned(entry))) {
35024a705fefSNaoya Horiguchi 			swp_entry_t swp_entry = pte_to_swp_entry(entry);
35034a705fefSNaoya Horiguchi 
35044a705fefSNaoya Horiguchi 			if (is_write_migration_entry(swp_entry) && cow) {
35054a705fefSNaoya Horiguchi 				/*
35064a705fefSNaoya Horiguchi 				 * COW mappings require pages in both
35074a705fefSNaoya Horiguchi 				 * parent and child to be set to read.
35084a705fefSNaoya Horiguchi 				 */
35094a705fefSNaoya Horiguchi 				make_migration_entry_read(&swp_entry);
35104a705fefSNaoya Horiguchi 				entry = swp_entry_to_pte(swp_entry);
3511e5251fd4SPunit Agrawal 				set_huge_swap_pte_at(src, addr, src_pte,
3512e5251fd4SPunit Agrawal 						     entry, sz);
35134a705fefSNaoya Horiguchi 			}
3514e5251fd4SPunit Agrawal 			set_huge_swap_pte_at(dst, addr, dst_pte, entry, sz);
35154a705fefSNaoya Horiguchi 		} else {
351634ee645eSJoerg Roedel 			if (cow) {
35170f10851eSJérôme Glisse 				/*
35180f10851eSJérôme Glisse 				 * No need to notify as we are downgrading page
35190f10851eSJérôme Glisse 				 * table protection not changing it to point
35200f10851eSJérôme Glisse 				 * to a new page.
35210f10851eSJérôme Glisse 				 *
3522ad56b738SMike Rapoport 				 * See Documentation/vm/mmu_notifier.rst
35230f10851eSJérôme Glisse 				 */
35247f2e9525SGerald Schaefer 				huge_ptep_set_wrprotect(src, addr, src_pte);
352534ee645eSJoerg Roedel 			}
35260253d634SNaoya Horiguchi 			entry = huge_ptep_get(src_pte);
352763551ae0SDavid Gibson 			ptepage = pte_page(entry);
352863551ae0SDavid Gibson 			get_page(ptepage);
352953f9263bSKirill A. Shutemov 			page_dup_rmap(ptepage, true);
353063551ae0SDavid Gibson 			set_huge_pte_at(dst, addr, dst_pte, entry);
35315d317b2bSNaoya Horiguchi 			hugetlb_count_add(pages_per_huge_page(h), dst);
35321c59827dSHugh Dickins 		}
3533cb900f41SKirill A. Shutemov 		spin_unlock(src_ptl);
3534cb900f41SKirill A. Shutemov 		spin_unlock(dst_ptl);
353563551ae0SDavid Gibson 	}
353663551ae0SDavid Gibson 
3537e8569dd2SAndreas Sandberg 	if (cow)
3538ac46d4f3SJérôme Glisse 		mmu_notifier_invalidate_range_end(&range);
3539c0d0381aSMike Kravetz 	else
3540c0d0381aSMike Kravetz 		i_mmap_unlock_read(mapping);
3541e8569dd2SAndreas Sandberg 
3542e8569dd2SAndreas Sandberg 	return ret;
354363551ae0SDavid Gibson }
354463551ae0SDavid Gibson 
354524669e58SAneesh Kumar K.V void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
354624669e58SAneesh Kumar K.V 			    unsigned long start, unsigned long end,
354724669e58SAneesh Kumar K.V 			    struct page *ref_page)
354863551ae0SDavid Gibson {
354963551ae0SDavid Gibson 	struct mm_struct *mm = vma->vm_mm;
355063551ae0SDavid Gibson 	unsigned long address;
3551c7546f8fSDavid Gibson 	pte_t *ptep;
355263551ae0SDavid Gibson 	pte_t pte;
3553cb900f41SKirill A. Shutemov 	spinlock_t *ptl;
355463551ae0SDavid Gibson 	struct page *page;
3555a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
3556a5516438SAndi Kleen 	unsigned long sz = huge_page_size(h);
3557ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
3558a5516438SAndi Kleen 
355963551ae0SDavid Gibson 	WARN_ON(!is_vm_hugetlb_page(vma));
3560a5516438SAndi Kleen 	BUG_ON(start & ~huge_page_mask(h));
3561a5516438SAndi Kleen 	BUG_ON(end & ~huge_page_mask(h));
356263551ae0SDavid Gibson 
356307e32661SAneesh Kumar K.V 	/*
356407e32661SAneesh Kumar K.V 	 * This is a hugetlb vma, all the pte entries should point
356507e32661SAneesh Kumar K.V 	 * to huge page.
356607e32661SAneesh Kumar K.V 	 */
3567ed6a7935SPeter Zijlstra 	tlb_change_page_size(tlb, sz);
356824669e58SAneesh Kumar K.V 	tlb_start_vma(tlb, vma);
3569dff11abeSMike Kravetz 
3570dff11abeSMike Kravetz 	/*
3571dff11abeSMike Kravetz 	 * If sharing possible, alert mmu notifiers of worst case.
3572dff11abeSMike Kravetz 	 */
35736f4f13e8SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, mm, start,
35746f4f13e8SJérôme Glisse 				end);
3575ac46d4f3SJérôme Glisse 	adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
3576ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
3577569f48b8SHillf Danton 	address = start;
3578569f48b8SHillf Danton 	for (; address < end; address += sz) {
35797868a208SPunit Agrawal 		ptep = huge_pte_offset(mm, address, sz);
3580c7546f8fSDavid Gibson 		if (!ptep)
3581c7546f8fSDavid Gibson 			continue;
3582c7546f8fSDavid Gibson 
3583cb900f41SKirill A. Shutemov 		ptl = huge_pte_lock(h, mm, ptep);
358431d49da5SAneesh Kumar K.V 		if (huge_pmd_unshare(mm, &address, ptep)) {
358531d49da5SAneesh Kumar K.V 			spin_unlock(ptl);
3586dff11abeSMike Kravetz 			/*
3587dff11abeSMike Kravetz 			 * We just unmapped a page of PMDs by clearing a PUD.
3588dff11abeSMike Kravetz 			 * The caller's TLB flush range should cover this area.
3589dff11abeSMike Kravetz 			 */
359031d49da5SAneesh Kumar K.V 			continue;
359131d49da5SAneesh Kumar K.V 		}
359239dde65cSChen, Kenneth W 
35936629326bSHillf Danton 		pte = huge_ptep_get(ptep);
359431d49da5SAneesh Kumar K.V 		if (huge_pte_none(pte)) {
359531d49da5SAneesh Kumar K.V 			spin_unlock(ptl);
359631d49da5SAneesh Kumar K.V 			continue;
359731d49da5SAneesh Kumar K.V 		}
35986629326bSHillf Danton 
35996629326bSHillf Danton 		/*
36009fbc1f63SNaoya Horiguchi 		 * Migrating hugepage or HWPoisoned hugepage is already
36019fbc1f63SNaoya Horiguchi 		 * unmapped and its refcount is dropped, so just clear pte here.
36026629326bSHillf Danton 		 */
36039fbc1f63SNaoya Horiguchi 		if (unlikely(!pte_present(pte))) {
36049386fac3SPunit Agrawal 			huge_pte_clear(mm, address, ptep, sz);
360531d49da5SAneesh Kumar K.V 			spin_unlock(ptl);
360631d49da5SAneesh Kumar K.V 			continue;
36078c4894c6SNaoya Horiguchi 		}
36086629326bSHillf Danton 
36096629326bSHillf Danton 		page = pte_page(pte);
361004f2cbe3SMel Gorman 		/*
361104f2cbe3SMel Gorman 		 * If a reference page is supplied, it is because a specific
361204f2cbe3SMel Gorman 		 * page is being unmapped, not a range. Ensure the page we
361304f2cbe3SMel Gorman 		 * are about to unmap is the actual page of interest.
361404f2cbe3SMel Gorman 		 */
361504f2cbe3SMel Gorman 		if (ref_page) {
361631d49da5SAneesh Kumar K.V 			if (page != ref_page) {
361731d49da5SAneesh Kumar K.V 				spin_unlock(ptl);
361831d49da5SAneesh Kumar K.V 				continue;
361931d49da5SAneesh Kumar K.V 			}
362004f2cbe3SMel Gorman 			/*
362104f2cbe3SMel Gorman 			 * Mark the VMA as having unmapped its page so that
362204f2cbe3SMel Gorman 			 * future faults in this VMA will fail rather than
362304f2cbe3SMel Gorman 			 * looking like data was lost
362404f2cbe3SMel Gorman 			 */
362504f2cbe3SMel Gorman 			set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED);
362604f2cbe3SMel Gorman 		}
362704f2cbe3SMel Gorman 
3628c7546f8fSDavid Gibson 		pte = huge_ptep_get_and_clear(mm, address, ptep);
3629b528e4b6SAneesh Kumar K.V 		tlb_remove_huge_tlb_entry(h, tlb, ptep, address);
3630106c992aSGerald Schaefer 		if (huge_pte_dirty(pte))
36316649a386SKen Chen 			set_page_dirty(page);
36329e81130bSHillf Danton 
36335d317b2bSNaoya Horiguchi 		hugetlb_count_sub(pages_per_huge_page(h), mm);
3634d281ee61SKirill A. Shutemov 		page_remove_rmap(page, true);
363531d49da5SAneesh Kumar K.V 
3636cb900f41SKirill A. Shutemov 		spin_unlock(ptl);
3637e77b0852SAneesh Kumar K.V 		tlb_remove_page_size(tlb, page, huge_page_size(h));
363824669e58SAneesh Kumar K.V 		/*
363931d49da5SAneesh Kumar K.V 		 * Bail out after unmapping reference page if supplied
364024669e58SAneesh Kumar K.V 		 */
364131d49da5SAneesh Kumar K.V 		if (ref_page)
364231d49da5SAneesh Kumar K.V 			break;
3643fe1668aeSChen, Kenneth W 	}
3644ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
364524669e58SAneesh Kumar K.V 	tlb_end_vma(tlb, vma);
36461da177e4SLinus Torvalds }
364763551ae0SDavid Gibson 
3648d833352aSMel Gorman void __unmap_hugepage_range_final(struct mmu_gather *tlb,
3649d833352aSMel Gorman 			  struct vm_area_struct *vma, unsigned long start,
3650d833352aSMel Gorman 			  unsigned long end, struct page *ref_page)
3651d833352aSMel Gorman {
3652d833352aSMel Gorman 	__unmap_hugepage_range(tlb, vma, start, end, ref_page);
3653d833352aSMel Gorman 
3654d833352aSMel Gorman 	/*
3655d833352aSMel Gorman 	 * Clear this flag so that x86's huge_pmd_share page_table_shareable
3656d833352aSMel Gorman 	 * test will fail on a vma being torn down, and not grab a page table
3657d833352aSMel Gorman 	 * on its way out.  We're lucky that the flag has such an appropriate
3658d833352aSMel Gorman 	 * name, and can in fact be safely cleared here. We could clear it
3659d833352aSMel Gorman 	 * before the __unmap_hugepage_range above, but all that's necessary
3660c8c06efaSDavidlohr Bueso 	 * is to clear it before releasing the i_mmap_rwsem. This works
3661d833352aSMel Gorman 	 * because in the context this is called, the VMA is about to be
3662c8c06efaSDavidlohr Bueso 	 * destroyed and the i_mmap_rwsem is held.
3663d833352aSMel Gorman 	 */
3664d833352aSMel Gorman 	vma->vm_flags &= ~VM_MAYSHARE;
3665d833352aSMel Gorman }
3666d833352aSMel Gorman 
3667502717f4SChen, Kenneth W void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
366804f2cbe3SMel Gorman 			  unsigned long end, struct page *ref_page)
3669502717f4SChen, Kenneth W {
367024669e58SAneesh Kumar K.V 	struct mm_struct *mm;
367124669e58SAneesh Kumar K.V 	struct mmu_gather tlb;
3672dff11abeSMike Kravetz 	unsigned long tlb_start = start;
3673dff11abeSMike Kravetz 	unsigned long tlb_end = end;
3674dff11abeSMike Kravetz 
3675dff11abeSMike Kravetz 	/*
3676dff11abeSMike Kravetz 	 * If shared PMDs were possibly used within this vma range, adjust
3677dff11abeSMike Kravetz 	 * start/end for worst case tlb flushing.
3678dff11abeSMike Kravetz 	 * Note that we can not be sure if PMDs are shared until we try to
3679dff11abeSMike Kravetz 	 * unmap pages.  However, we want to make sure TLB flushing covers
3680dff11abeSMike Kravetz 	 * the largest possible range.
3681dff11abeSMike Kravetz 	 */
3682dff11abeSMike Kravetz 	adjust_range_if_pmd_sharing_possible(vma, &tlb_start, &tlb_end);
368324669e58SAneesh Kumar K.V 
368424669e58SAneesh Kumar K.V 	mm = vma->vm_mm;
368524669e58SAneesh Kumar K.V 
3686dff11abeSMike Kravetz 	tlb_gather_mmu(&tlb, mm, tlb_start, tlb_end);
368724669e58SAneesh Kumar K.V 	__unmap_hugepage_range(&tlb, vma, start, end, ref_page);
3688dff11abeSMike Kravetz 	tlb_finish_mmu(&tlb, tlb_start, tlb_end);
3689502717f4SChen, Kenneth W }
3690502717f4SChen, Kenneth W 
369104f2cbe3SMel Gorman /*
369204f2cbe3SMel Gorman  * This is called when the original mapper is failing to COW a MAP_PRIVATE
369304f2cbe3SMel Gorman  * mappping it owns the reserve page for. The intention is to unmap the page
369404f2cbe3SMel Gorman  * from other VMAs and let the children be SIGKILLed if they are faulting the
369504f2cbe3SMel Gorman  * same region.
369604f2cbe3SMel Gorman  */
36972f4612afSDavidlohr Bueso static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,
36982a4b3dedSHarvey Harrison 			      struct page *page, unsigned long address)
369904f2cbe3SMel Gorman {
37007526674dSAdam Litke 	struct hstate *h = hstate_vma(vma);
370104f2cbe3SMel Gorman 	struct vm_area_struct *iter_vma;
370204f2cbe3SMel Gorman 	struct address_space *mapping;
370304f2cbe3SMel Gorman 	pgoff_t pgoff;
370404f2cbe3SMel Gorman 
370504f2cbe3SMel Gorman 	/*
370604f2cbe3SMel Gorman 	 * vm_pgoff is in PAGE_SIZE units, hence the different calculation
370704f2cbe3SMel Gorman 	 * from page cache lookup which is in HPAGE_SIZE units.
370804f2cbe3SMel Gorman 	 */
37097526674dSAdam Litke 	address = address & huge_page_mask(h);
371036e4f20aSMichal Hocko 	pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) +
371136e4f20aSMichal Hocko 			vma->vm_pgoff;
371293c76a3dSAl Viro 	mapping = vma->vm_file->f_mapping;
371304f2cbe3SMel Gorman 
37144eb2b1dcSMel Gorman 	/*
37154eb2b1dcSMel Gorman 	 * Take the mapping lock for the duration of the table walk. As
37164eb2b1dcSMel Gorman 	 * this mapping should be shared between all the VMAs,
37174eb2b1dcSMel Gorman 	 * __unmap_hugepage_range() is called as the lock is already held
37184eb2b1dcSMel Gorman 	 */
371983cde9e8SDavidlohr Bueso 	i_mmap_lock_write(mapping);
37206b2dbba8SMichel Lespinasse 	vma_interval_tree_foreach(iter_vma, &mapping->i_mmap, pgoff, pgoff) {
372104f2cbe3SMel Gorman 		/* Do not unmap the current VMA */
372204f2cbe3SMel Gorman 		if (iter_vma == vma)
372304f2cbe3SMel Gorman 			continue;
372404f2cbe3SMel Gorman 
372504f2cbe3SMel Gorman 		/*
37262f84a899SMel Gorman 		 * Shared VMAs have their own reserves and do not affect
37272f84a899SMel Gorman 		 * MAP_PRIVATE accounting but it is possible that a shared
37282f84a899SMel Gorman 		 * VMA is using the same page so check and skip such VMAs.
37292f84a899SMel Gorman 		 */
37302f84a899SMel Gorman 		if (iter_vma->vm_flags & VM_MAYSHARE)
37312f84a899SMel Gorman 			continue;
37322f84a899SMel Gorman 
37332f84a899SMel Gorman 		/*
373404f2cbe3SMel Gorman 		 * Unmap the page from other VMAs without their own reserves.
373504f2cbe3SMel Gorman 		 * They get marked to be SIGKILLed if they fault in these
373604f2cbe3SMel Gorman 		 * areas. This is because a future no-page fault on this VMA
373704f2cbe3SMel Gorman 		 * could insert a zeroed page instead of the data existing
373804f2cbe3SMel Gorman 		 * from the time of fork. This would look like data corruption
373904f2cbe3SMel Gorman 		 */
374004f2cbe3SMel Gorman 		if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER))
374124669e58SAneesh Kumar K.V 			unmap_hugepage_range(iter_vma, address,
374224669e58SAneesh Kumar K.V 					     address + huge_page_size(h), page);
374304f2cbe3SMel Gorman 	}
374483cde9e8SDavidlohr Bueso 	i_mmap_unlock_write(mapping);
374504f2cbe3SMel Gorman }
374604f2cbe3SMel Gorman 
37470fe6e20bSNaoya Horiguchi /*
37480fe6e20bSNaoya Horiguchi  * Hugetlb_cow() should be called with page lock of the original hugepage held.
3749ef009b25SMichal Hocko  * Called with hugetlb_instantiation_mutex held and pte_page locked so we
3750ef009b25SMichal Hocko  * cannot race with other handlers or page migration.
3751ef009b25SMichal Hocko  * Keep the pte_same checks anyway to make transition from the mutex easier.
37520fe6e20bSNaoya Horiguchi  */
37532b740303SSouptick Joarder static vm_fault_t hugetlb_cow(struct mm_struct *mm, struct vm_area_struct *vma,
3754974e6d66SHuang Ying 		       unsigned long address, pte_t *ptep,
3755cb900f41SKirill A. Shutemov 		       struct page *pagecache_page, spinlock_t *ptl)
37561e8f889bSDavid Gibson {
37573999f52eSAneesh Kumar K.V 	pte_t pte;
3758a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
37591e8f889bSDavid Gibson 	struct page *old_page, *new_page;
37602b740303SSouptick Joarder 	int outside_reserve = 0;
37612b740303SSouptick Joarder 	vm_fault_t ret = 0;
3762974e6d66SHuang Ying 	unsigned long haddr = address & huge_page_mask(h);
3763ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
37641e8f889bSDavid Gibson 
37653999f52eSAneesh Kumar K.V 	pte = huge_ptep_get(ptep);
37661e8f889bSDavid Gibson 	old_page = pte_page(pte);
37671e8f889bSDavid Gibson 
376804f2cbe3SMel Gorman retry_avoidcopy:
37691e8f889bSDavid Gibson 	/* If no-one else is actually using this page, avoid the copy
37701e8f889bSDavid Gibson 	 * and just make the page writable */
377137a2140dSJoonsoo Kim 	if (page_mapcount(old_page) == 1 && PageAnon(old_page)) {
37725a49973dSHugh Dickins 		page_move_anon_rmap(old_page, vma);
37735b7a1d40SHuang Ying 		set_huge_ptep_writable(vma, haddr, ptep);
377483c54070SNick Piggin 		return 0;
37751e8f889bSDavid Gibson 	}
37761e8f889bSDavid Gibson 
377704f2cbe3SMel Gorman 	/*
377804f2cbe3SMel Gorman 	 * If the process that created a MAP_PRIVATE mapping is about to
377904f2cbe3SMel Gorman 	 * perform a COW due to a shared page count, attempt to satisfy
378004f2cbe3SMel Gorman 	 * the allocation without using the existing reserves. The pagecache
378104f2cbe3SMel Gorman 	 * page is used to determine if the reserve at this address was
378204f2cbe3SMel Gorman 	 * consumed or not. If reserves were used, a partial faulted mapping
378304f2cbe3SMel Gorman 	 * at the time of fork() could consume its reserves on COW instead
378404f2cbe3SMel Gorman 	 * of the full address range.
378504f2cbe3SMel Gorman 	 */
37865944d011SJoonsoo Kim 	if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) &&
378704f2cbe3SMel Gorman 			old_page != pagecache_page)
378804f2cbe3SMel Gorman 		outside_reserve = 1;
378904f2cbe3SMel Gorman 
379009cbfeafSKirill A. Shutemov 	get_page(old_page);
3791b76c8cfbSLarry Woodman 
3792ad4404a2SDavidlohr Bueso 	/*
3793ad4404a2SDavidlohr Bueso 	 * Drop page table lock as buddy allocator may be called. It will
3794ad4404a2SDavidlohr Bueso 	 * be acquired again before returning to the caller, as expected.
3795ad4404a2SDavidlohr Bueso 	 */
3796cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
37975b7a1d40SHuang Ying 	new_page = alloc_huge_page(vma, haddr, outside_reserve);
37981e8f889bSDavid Gibson 
37992fc39cecSAdam Litke 	if (IS_ERR(new_page)) {
380004f2cbe3SMel Gorman 		/*
380104f2cbe3SMel Gorman 		 * If a process owning a MAP_PRIVATE mapping fails to COW,
380204f2cbe3SMel Gorman 		 * it is due to references held by a child and an insufficient
380304f2cbe3SMel Gorman 		 * huge page pool. To guarantee the original mappers
380404f2cbe3SMel Gorman 		 * reliability, unmap the page from child processes. The child
380504f2cbe3SMel Gorman 		 * may get SIGKILLed if it later faults.
380604f2cbe3SMel Gorman 		 */
380704f2cbe3SMel Gorman 		if (outside_reserve) {
380809cbfeafSKirill A. Shutemov 			put_page(old_page);
380904f2cbe3SMel Gorman 			BUG_ON(huge_pte_none(pte));
38105b7a1d40SHuang Ying 			unmap_ref_private(mm, vma, old_page, haddr);
381104f2cbe3SMel Gorman 			BUG_ON(huge_pte_none(pte));
3812cb900f41SKirill A. Shutemov 			spin_lock(ptl);
38135b7a1d40SHuang Ying 			ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
3814a9af0c5dSNaoya Horiguchi 			if (likely(ptep &&
3815a9af0c5dSNaoya Horiguchi 				   pte_same(huge_ptep_get(ptep), pte)))
381604f2cbe3SMel Gorman 				goto retry_avoidcopy;
3817a734bcc8SHillf Danton 			/*
3818cb900f41SKirill A. Shutemov 			 * race occurs while re-acquiring page table
3819cb900f41SKirill A. Shutemov 			 * lock, and our job is done.
3820a734bcc8SHillf Danton 			 */
3821a734bcc8SHillf Danton 			return 0;
382204f2cbe3SMel Gorman 		}
382304f2cbe3SMel Gorman 
38242b740303SSouptick Joarder 		ret = vmf_error(PTR_ERR(new_page));
3825ad4404a2SDavidlohr Bueso 		goto out_release_old;
38261e8f889bSDavid Gibson 	}
38271e8f889bSDavid Gibson 
38280fe6e20bSNaoya Horiguchi 	/*
38290fe6e20bSNaoya Horiguchi 	 * When the original hugepage is shared one, it does not have
38300fe6e20bSNaoya Horiguchi 	 * anon_vma prepared.
38310fe6e20bSNaoya Horiguchi 	 */
383244e2aa93SDean Nelson 	if (unlikely(anon_vma_prepare(vma))) {
3833ad4404a2SDavidlohr Bueso 		ret = VM_FAULT_OOM;
3834ad4404a2SDavidlohr Bueso 		goto out_release_all;
383544e2aa93SDean Nelson 	}
38360fe6e20bSNaoya Horiguchi 
3837974e6d66SHuang Ying 	copy_user_huge_page(new_page, old_page, address, vma,
383847ad8475SAndrea Arcangeli 			    pages_per_huge_page(h));
38390ed361deSNick Piggin 	__SetPageUptodate(new_page);
38401e8f889bSDavid Gibson 
38417269f999SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm, haddr,
38426f4f13e8SJérôme Glisse 				haddr + huge_page_size(h));
3843ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
3844ad4404a2SDavidlohr Bueso 
3845b76c8cfbSLarry Woodman 	/*
3846cb900f41SKirill A. Shutemov 	 * Retake the page table lock to check for racing updates
3847b76c8cfbSLarry Woodman 	 * before the page tables are altered
3848b76c8cfbSLarry Woodman 	 */
3849cb900f41SKirill A. Shutemov 	spin_lock(ptl);
38505b7a1d40SHuang Ying 	ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
3851a9af0c5dSNaoya Horiguchi 	if (likely(ptep && pte_same(huge_ptep_get(ptep), pte))) {
385207443a85SJoonsoo Kim 		ClearPagePrivate(new_page);
385307443a85SJoonsoo Kim 
38541e8f889bSDavid Gibson 		/* Break COW */
38555b7a1d40SHuang Ying 		huge_ptep_clear_flush(vma, haddr, ptep);
3856ac46d4f3SJérôme Glisse 		mmu_notifier_invalidate_range(mm, range.start, range.end);
38575b7a1d40SHuang Ying 		set_huge_pte_at(mm, haddr, ptep,
38581e8f889bSDavid Gibson 				make_huge_pte(vma, new_page, 1));
3859d281ee61SKirill A. Shutemov 		page_remove_rmap(old_page, true);
38605b7a1d40SHuang Ying 		hugepage_add_new_anon_rmap(new_page, vma, haddr);
3861cb6acd01SMike Kravetz 		set_page_huge_active(new_page);
38621e8f889bSDavid Gibson 		/* Make the old page be freed below */
38631e8f889bSDavid Gibson 		new_page = old_page;
38641e8f889bSDavid Gibson 	}
3865cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
3866ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
3867ad4404a2SDavidlohr Bueso out_release_all:
38685b7a1d40SHuang Ying 	restore_reserve_on_error(h, vma, haddr, new_page);
386909cbfeafSKirill A. Shutemov 	put_page(new_page);
3870ad4404a2SDavidlohr Bueso out_release_old:
387109cbfeafSKirill A. Shutemov 	put_page(old_page);
38728312034fSJoonsoo Kim 
3873ad4404a2SDavidlohr Bueso 	spin_lock(ptl); /* Caller expects lock to be held */
3874ad4404a2SDavidlohr Bueso 	return ret;
38751e8f889bSDavid Gibson }
38761e8f889bSDavid Gibson 
387704f2cbe3SMel Gorman /* Return the pagecache page at a given address within a VMA */
3878a5516438SAndi Kleen static struct page *hugetlbfs_pagecache_page(struct hstate *h,
3879a5516438SAndi Kleen 			struct vm_area_struct *vma, unsigned long address)
388004f2cbe3SMel Gorman {
388104f2cbe3SMel Gorman 	struct address_space *mapping;
3882e7c4b0bfSAndy Whitcroft 	pgoff_t idx;
388304f2cbe3SMel Gorman 
388404f2cbe3SMel Gorman 	mapping = vma->vm_file->f_mapping;
3885a5516438SAndi Kleen 	idx = vma_hugecache_offset(h, vma, address);
388604f2cbe3SMel Gorman 
388704f2cbe3SMel Gorman 	return find_lock_page(mapping, idx);
388804f2cbe3SMel Gorman }
388904f2cbe3SMel Gorman 
38903ae77f43SHugh Dickins /*
38913ae77f43SHugh Dickins  * Return whether there is a pagecache page to back given address within VMA.
38923ae77f43SHugh Dickins  * Caller follow_hugetlb_page() holds page_table_lock so we cannot lock_page.
38933ae77f43SHugh Dickins  */
38943ae77f43SHugh Dickins static bool hugetlbfs_pagecache_present(struct hstate *h,
38952a15efc9SHugh Dickins 			struct vm_area_struct *vma, unsigned long address)
38962a15efc9SHugh Dickins {
38972a15efc9SHugh Dickins 	struct address_space *mapping;
38982a15efc9SHugh Dickins 	pgoff_t idx;
38992a15efc9SHugh Dickins 	struct page *page;
39002a15efc9SHugh Dickins 
39012a15efc9SHugh Dickins 	mapping = vma->vm_file->f_mapping;
39022a15efc9SHugh Dickins 	idx = vma_hugecache_offset(h, vma, address);
39032a15efc9SHugh Dickins 
39042a15efc9SHugh Dickins 	page = find_get_page(mapping, idx);
39052a15efc9SHugh Dickins 	if (page)
39062a15efc9SHugh Dickins 		put_page(page);
39072a15efc9SHugh Dickins 	return page != NULL;
39082a15efc9SHugh Dickins }
39092a15efc9SHugh Dickins 
3910ab76ad54SMike Kravetz int huge_add_to_page_cache(struct page *page, struct address_space *mapping,
3911ab76ad54SMike Kravetz 			   pgoff_t idx)
3912ab76ad54SMike Kravetz {
3913ab76ad54SMike Kravetz 	struct inode *inode = mapping->host;
3914ab76ad54SMike Kravetz 	struct hstate *h = hstate_inode(inode);
3915ab76ad54SMike Kravetz 	int err = add_to_page_cache(page, mapping, idx, GFP_KERNEL);
3916ab76ad54SMike Kravetz 
3917ab76ad54SMike Kravetz 	if (err)
3918ab76ad54SMike Kravetz 		return err;
3919ab76ad54SMike Kravetz 	ClearPagePrivate(page);
3920ab76ad54SMike Kravetz 
392122146c3cSMike Kravetz 	/*
392222146c3cSMike Kravetz 	 * set page dirty so that it will not be removed from cache/file
392322146c3cSMike Kravetz 	 * by non-hugetlbfs specific code paths.
392422146c3cSMike Kravetz 	 */
392522146c3cSMike Kravetz 	set_page_dirty(page);
392622146c3cSMike Kravetz 
3927ab76ad54SMike Kravetz 	spin_lock(&inode->i_lock);
3928ab76ad54SMike Kravetz 	inode->i_blocks += blocks_per_huge_page(h);
3929ab76ad54SMike Kravetz 	spin_unlock(&inode->i_lock);
3930ab76ad54SMike Kravetz 	return 0;
3931ab76ad54SMike Kravetz }
3932ab76ad54SMike Kravetz 
39332b740303SSouptick Joarder static vm_fault_t hugetlb_no_page(struct mm_struct *mm,
39342b740303SSouptick Joarder 			struct vm_area_struct *vma,
39358382d914SDavidlohr Bueso 			struct address_space *mapping, pgoff_t idx,
3936788c7df4SHugh Dickins 			unsigned long address, pte_t *ptep, unsigned int flags)
3937ac9b9c66SHugh Dickins {
3938a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
39392b740303SSouptick Joarder 	vm_fault_t ret = VM_FAULT_SIGBUS;
3940409eb8c2SHillf Danton 	int anon_rmap = 0;
39414c887265SAdam Litke 	unsigned long size;
39424c887265SAdam Litke 	struct page *page;
39431e8f889bSDavid Gibson 	pte_t new_pte;
3944cb900f41SKirill A. Shutemov 	spinlock_t *ptl;
3945285b8dcaSHuang Ying 	unsigned long haddr = address & huge_page_mask(h);
3946cb6acd01SMike Kravetz 	bool new_page = false;
39474c887265SAdam Litke 
394804f2cbe3SMel Gorman 	/*
394904f2cbe3SMel Gorman 	 * Currently, we are forced to kill the process in the event the
395004f2cbe3SMel Gorman 	 * original mapper has unmapped pages from the child due to a failed
395125985edcSLucas De Marchi 	 * COW. Warn that such a situation has occurred as it may not be obvious
395204f2cbe3SMel Gorman 	 */
395304f2cbe3SMel Gorman 	if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) {
3954910154d5SGeoffrey Thomas 		pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n",
395504f2cbe3SMel Gorman 			   current->pid);
395604f2cbe3SMel Gorman 		return ret;
395704f2cbe3SMel Gorman 	}
395804f2cbe3SMel Gorman 
39594c887265SAdam Litke 	/*
396087bf91d3SMike Kravetz 	 * We can not race with truncation due to holding i_mmap_rwsem.
396187bf91d3SMike Kravetz 	 * i_size is modified when holding i_mmap_rwsem, so check here
396287bf91d3SMike Kravetz 	 * once for faults beyond end of file.
39634c887265SAdam Litke 	 */
3964a5516438SAndi Kleen 	size = i_size_read(mapping->host) >> huge_page_shift(h);
3965ebed4bfcSHugh Dickins 	if (idx >= size)
3966ebed4bfcSHugh Dickins 		goto out;
39671a1aad8aSMike Kravetz 
396887bf91d3SMike Kravetz retry:
396987bf91d3SMike Kravetz 	page = find_lock_page(mapping, idx);
397087bf91d3SMike Kravetz 	if (!page) {
39711a1aad8aSMike Kravetz 		/*
39721a1aad8aSMike Kravetz 		 * Check for page in userfault range
39731a1aad8aSMike Kravetz 		 */
39741a1aad8aSMike Kravetz 		if (userfaultfd_missing(vma)) {
39751a1aad8aSMike Kravetz 			u32 hash;
39761a1aad8aSMike Kravetz 			struct vm_fault vmf = {
39771a1aad8aSMike Kravetz 				.vma = vma,
3978285b8dcaSHuang Ying 				.address = haddr,
39791a1aad8aSMike Kravetz 				.flags = flags,
39801a1aad8aSMike Kravetz 				/*
39811a1aad8aSMike Kravetz 				 * Hard to debug if it ends up being
39821a1aad8aSMike Kravetz 				 * used by a callee that assumes
39831a1aad8aSMike Kravetz 				 * something about the other
39841a1aad8aSMike Kravetz 				 * uninitialized fields... same as in
39851a1aad8aSMike Kravetz 				 * memory.c
39861a1aad8aSMike Kravetz 				 */
39871a1aad8aSMike Kravetz 			};
39881a1aad8aSMike Kravetz 
39891a1aad8aSMike Kravetz 			/*
3990c0d0381aSMike Kravetz 			 * hugetlb_fault_mutex and i_mmap_rwsem must be
3991c0d0381aSMike Kravetz 			 * dropped before handling userfault.  Reacquire
3992c0d0381aSMike Kravetz 			 * after handling fault to make calling code simpler.
39931a1aad8aSMike Kravetz 			 */
3994188b04a7SWei Yang 			hash = hugetlb_fault_mutex_hash(mapping, idx);
39951a1aad8aSMike Kravetz 			mutex_unlock(&hugetlb_fault_mutex_table[hash]);
3996c0d0381aSMike Kravetz 			i_mmap_unlock_read(mapping);
39971a1aad8aSMike Kravetz 			ret = handle_userfault(&vmf, VM_UFFD_MISSING);
3998c0d0381aSMike Kravetz 			i_mmap_lock_read(mapping);
39991a1aad8aSMike Kravetz 			mutex_lock(&hugetlb_fault_mutex_table[hash]);
40001a1aad8aSMike Kravetz 			goto out;
40011a1aad8aSMike Kravetz 		}
40021a1aad8aSMike Kravetz 
4003285b8dcaSHuang Ying 		page = alloc_huge_page(vma, haddr, 0);
40042fc39cecSAdam Litke 		if (IS_ERR(page)) {
40054643d67eSMike Kravetz 			/*
40064643d67eSMike Kravetz 			 * Returning error will result in faulting task being
40074643d67eSMike Kravetz 			 * sent SIGBUS.  The hugetlb fault mutex prevents two
40084643d67eSMike Kravetz 			 * tasks from racing to fault in the same page which
40094643d67eSMike Kravetz 			 * could result in false unable to allocate errors.
40104643d67eSMike Kravetz 			 * Page migration does not take the fault mutex, but
40114643d67eSMike Kravetz 			 * does a clear then write of pte's under page table
40124643d67eSMike Kravetz 			 * lock.  Page fault code could race with migration,
40134643d67eSMike Kravetz 			 * notice the clear pte and try to allocate a page
40144643d67eSMike Kravetz 			 * here.  Before returning error, get ptl and make
40154643d67eSMike Kravetz 			 * sure there really is no pte entry.
40164643d67eSMike Kravetz 			 */
40174643d67eSMike Kravetz 			ptl = huge_pte_lock(h, mm, ptep);
40184643d67eSMike Kravetz 			if (!huge_pte_none(huge_ptep_get(ptep))) {
40194643d67eSMike Kravetz 				ret = 0;
40204643d67eSMike Kravetz 				spin_unlock(ptl);
40214643d67eSMike Kravetz 				goto out;
40224643d67eSMike Kravetz 			}
40234643d67eSMike Kravetz 			spin_unlock(ptl);
40242b740303SSouptick Joarder 			ret = vmf_error(PTR_ERR(page));
40256bda666aSChristoph Lameter 			goto out;
40266bda666aSChristoph Lameter 		}
402747ad8475SAndrea Arcangeli 		clear_huge_page(page, address, pages_per_huge_page(h));
40280ed361deSNick Piggin 		__SetPageUptodate(page);
4029cb6acd01SMike Kravetz 		new_page = true;
4030ac9b9c66SHugh Dickins 
4031f83a275dSMel Gorman 		if (vma->vm_flags & VM_MAYSHARE) {
4032ab76ad54SMike Kravetz 			int err = huge_add_to_page_cache(page, mapping, idx);
40336bda666aSChristoph Lameter 			if (err) {
40346bda666aSChristoph Lameter 				put_page(page);
40356bda666aSChristoph Lameter 				if (err == -EEXIST)
40366bda666aSChristoph Lameter 					goto retry;
40376bda666aSChristoph Lameter 				goto out;
40386bda666aSChristoph Lameter 			}
403923be7468SMel Gorman 		} else {
40406bda666aSChristoph Lameter 			lock_page(page);
40410fe6e20bSNaoya Horiguchi 			if (unlikely(anon_vma_prepare(vma))) {
40420fe6e20bSNaoya Horiguchi 				ret = VM_FAULT_OOM;
40430fe6e20bSNaoya Horiguchi 				goto backout_unlocked;
404423be7468SMel Gorman 			}
4045409eb8c2SHillf Danton 			anon_rmap = 1;
40460fe6e20bSNaoya Horiguchi 		}
40470fe6e20bSNaoya Horiguchi 	} else {
404857303d80SAndy Whitcroft 		/*
4049998b4382SNaoya Horiguchi 		 * If memory error occurs between mmap() and fault, some process
4050998b4382SNaoya Horiguchi 		 * don't have hwpoisoned swap entry for errored virtual address.
4051998b4382SNaoya Horiguchi 		 * So we need to block hugepage fault by PG_hwpoison bit check.
4052fd6a03edSNaoya Horiguchi 		 */
4053fd6a03edSNaoya Horiguchi 		if (unlikely(PageHWPoison(page))) {
4054aa50d3a7SAndi Kleen 			ret = VM_FAULT_HWPOISON |
4055972dc4deSAneesh Kumar K.V 				VM_FAULT_SET_HINDEX(hstate_index(h));
4056fd6a03edSNaoya Horiguchi 			goto backout_unlocked;
40576bda666aSChristoph Lameter 		}
4058998b4382SNaoya Horiguchi 	}
40591e8f889bSDavid Gibson 
406057303d80SAndy Whitcroft 	/*
406157303d80SAndy Whitcroft 	 * If we are going to COW a private mapping later, we examine the
406257303d80SAndy Whitcroft 	 * pending reservations for this page now. This will ensure that
406357303d80SAndy Whitcroft 	 * any allocations necessary to record that reservation occur outside
406457303d80SAndy Whitcroft 	 * the spinlock.
406557303d80SAndy Whitcroft 	 */
40665e911373SMike Kravetz 	if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
4067285b8dcaSHuang Ying 		if (vma_needs_reservation(h, vma, haddr) < 0) {
40682b26736cSAndy Whitcroft 			ret = VM_FAULT_OOM;
40692b26736cSAndy Whitcroft 			goto backout_unlocked;
40702b26736cSAndy Whitcroft 		}
40715e911373SMike Kravetz 		/* Just decrements count, does not deallocate */
4072285b8dcaSHuang Ying 		vma_end_reservation(h, vma, haddr);
40735e911373SMike Kravetz 	}
407457303d80SAndy Whitcroft 
40758bea8052SAneesh Kumar K.V 	ptl = huge_pte_lock(h, mm, ptep);
407683c54070SNick Piggin 	ret = 0;
40777f2e9525SGerald Schaefer 	if (!huge_pte_none(huge_ptep_get(ptep)))
40784c887265SAdam Litke 		goto backout;
40794c887265SAdam Litke 
408007443a85SJoonsoo Kim 	if (anon_rmap) {
408107443a85SJoonsoo Kim 		ClearPagePrivate(page);
4082285b8dcaSHuang Ying 		hugepage_add_new_anon_rmap(page, vma, haddr);
4083ac714904SChoi Gi-yong 	} else
408453f9263bSKirill A. Shutemov 		page_dup_rmap(page, true);
40851e8f889bSDavid Gibson 	new_pte = make_huge_pte(vma, page, ((vma->vm_flags & VM_WRITE)
40861e8f889bSDavid Gibson 				&& (vma->vm_flags & VM_SHARED)));
4087285b8dcaSHuang Ying 	set_huge_pte_at(mm, haddr, ptep, new_pte);
40881e8f889bSDavid Gibson 
40895d317b2bSNaoya Horiguchi 	hugetlb_count_add(pages_per_huge_page(h), mm);
4090788c7df4SHugh Dickins 	if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
40911e8f889bSDavid Gibson 		/* Optimization, do the COW without a second fault */
4092974e6d66SHuang Ying 		ret = hugetlb_cow(mm, vma, address, ptep, page, ptl);
40931e8f889bSDavid Gibson 	}
40941e8f889bSDavid Gibson 
4095cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
4096cb6acd01SMike Kravetz 
4097cb6acd01SMike Kravetz 	/*
4098cb6acd01SMike Kravetz 	 * Only make newly allocated pages active.  Existing pages found
4099cb6acd01SMike Kravetz 	 * in the pagecache could be !page_huge_active() if they have been
4100cb6acd01SMike Kravetz 	 * isolated for migration.
4101cb6acd01SMike Kravetz 	 */
4102cb6acd01SMike Kravetz 	if (new_page)
4103cb6acd01SMike Kravetz 		set_page_huge_active(page);
4104cb6acd01SMike Kravetz 
41054c887265SAdam Litke 	unlock_page(page);
41064c887265SAdam Litke out:
4107ac9b9c66SHugh Dickins 	return ret;
41084c887265SAdam Litke 
41094c887265SAdam Litke backout:
4110cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
41112b26736cSAndy Whitcroft backout_unlocked:
41124c887265SAdam Litke 	unlock_page(page);
4113285b8dcaSHuang Ying 	restore_reserve_on_error(h, vma, haddr, page);
41144c887265SAdam Litke 	put_page(page);
41154c887265SAdam Litke 	goto out;
4116ac9b9c66SHugh Dickins }
4117ac9b9c66SHugh Dickins 
41188382d914SDavidlohr Bueso #ifdef CONFIG_SMP
4119188b04a7SWei Yang u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
41208382d914SDavidlohr Bueso {
41218382d914SDavidlohr Bueso 	unsigned long key[2];
41228382d914SDavidlohr Bueso 	u32 hash;
41238382d914SDavidlohr Bueso 
41248382d914SDavidlohr Bueso 	key[0] = (unsigned long) mapping;
41258382d914SDavidlohr Bueso 	key[1] = idx;
41268382d914SDavidlohr Bueso 
412755254636SMike Kravetz 	hash = jhash2((u32 *)&key, sizeof(key)/(sizeof(u32)), 0);
41288382d914SDavidlohr Bueso 
41298382d914SDavidlohr Bueso 	return hash & (num_fault_mutexes - 1);
41308382d914SDavidlohr Bueso }
41318382d914SDavidlohr Bueso #else
41328382d914SDavidlohr Bueso /*
41338382d914SDavidlohr Bueso  * For uniprocesor systems we always use a single mutex, so just
41348382d914SDavidlohr Bueso  * return 0 and avoid the hashing overhead.
41358382d914SDavidlohr Bueso  */
4136188b04a7SWei Yang u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
41378382d914SDavidlohr Bueso {
41388382d914SDavidlohr Bueso 	return 0;
41398382d914SDavidlohr Bueso }
41408382d914SDavidlohr Bueso #endif
41418382d914SDavidlohr Bueso 
41422b740303SSouptick Joarder vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,
4143788c7df4SHugh Dickins 			unsigned long address, unsigned int flags)
414486e5216fSAdam Litke {
41458382d914SDavidlohr Bueso 	pte_t *ptep, entry;
4146cb900f41SKirill A. Shutemov 	spinlock_t *ptl;
41472b740303SSouptick Joarder 	vm_fault_t ret;
41488382d914SDavidlohr Bueso 	u32 hash;
41498382d914SDavidlohr Bueso 	pgoff_t idx;
41500fe6e20bSNaoya Horiguchi 	struct page *page = NULL;
415157303d80SAndy Whitcroft 	struct page *pagecache_page = NULL;
4152a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
41538382d914SDavidlohr Bueso 	struct address_space *mapping;
41540f792cf9SNaoya Horiguchi 	int need_wait_lock = 0;
4155285b8dcaSHuang Ying 	unsigned long haddr = address & huge_page_mask(h);
415686e5216fSAdam Litke 
4157285b8dcaSHuang Ying 	ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
4158fd6a03edSNaoya Horiguchi 	if (ptep) {
4159c0d0381aSMike Kravetz 		/*
4160c0d0381aSMike Kravetz 		 * Since we hold no locks, ptep could be stale.  That is
4161c0d0381aSMike Kravetz 		 * OK as we are only making decisions based on content and
4162c0d0381aSMike Kravetz 		 * not actually modifying content here.
4163c0d0381aSMike Kravetz 		 */
4164fd6a03edSNaoya Horiguchi 		entry = huge_ptep_get(ptep);
4165290408d4SNaoya Horiguchi 		if (unlikely(is_hugetlb_entry_migration(entry))) {
4166cb900f41SKirill A. Shutemov 			migration_entry_wait_huge(vma, mm, ptep);
4167290408d4SNaoya Horiguchi 			return 0;
4168290408d4SNaoya Horiguchi 		} else if (unlikely(is_hugetlb_entry_hwpoisoned(entry)))
4169aa50d3a7SAndi Kleen 			return VM_FAULT_HWPOISON_LARGE |
4170972dc4deSAneesh Kumar K.V 				VM_FAULT_SET_HINDEX(hstate_index(h));
4171ddeaab32SMike Kravetz 	} else {
4172b43a9990SMike Kravetz 		ptep = huge_pte_alloc(mm, haddr, huge_page_size(h));
4173ddeaab32SMike Kravetz 		if (!ptep)
4174b43a9990SMike Kravetz 			return VM_FAULT_OOM;
4175b43a9990SMike Kravetz 	}
41768382d914SDavidlohr Bueso 
4177c0d0381aSMike Kravetz 	/*
4178c0d0381aSMike Kravetz 	 * Acquire i_mmap_rwsem before calling huge_pte_alloc and hold
417987bf91d3SMike Kravetz 	 * until finished with ptep.  This serves two purposes:
418087bf91d3SMike Kravetz 	 * 1) It prevents huge_pmd_unshare from being called elsewhere
418187bf91d3SMike Kravetz 	 *    and making the ptep no longer valid.
418287bf91d3SMike Kravetz 	 * 2) It synchronizes us with i_size modifications during truncation.
4183c0d0381aSMike Kravetz 	 *
4184c0d0381aSMike Kravetz 	 * ptep could have already be assigned via huge_pte_offset.  That
4185c0d0381aSMike Kravetz 	 * is OK, as huge_pte_alloc will return the same value unless
4186c0d0381aSMike Kravetz 	 * something has changed.
4187c0d0381aSMike Kravetz 	 */
4188ddeaab32SMike Kravetz 	mapping = vma->vm_file->f_mapping;
4189c0d0381aSMike Kravetz 	i_mmap_lock_read(mapping);
4190c0d0381aSMike Kravetz 	ptep = huge_pte_alloc(mm, haddr, huge_page_size(h));
4191c0d0381aSMike Kravetz 	if (!ptep) {
4192c0d0381aSMike Kravetz 		i_mmap_unlock_read(mapping);
4193c0d0381aSMike Kravetz 		return VM_FAULT_OOM;
4194c0d0381aSMike Kravetz 	}
4195ddeaab32SMike Kravetz 
41963935baa9SDavid Gibson 	/*
41973935baa9SDavid Gibson 	 * Serialize hugepage allocation and instantiation, so that we don't
41983935baa9SDavid Gibson 	 * get spurious allocation failures if two CPUs race to instantiate
41993935baa9SDavid Gibson 	 * the same page in the page cache.
42003935baa9SDavid Gibson 	 */
4201c0d0381aSMike Kravetz 	idx = vma_hugecache_offset(h, vma, haddr);
4202188b04a7SWei Yang 	hash = hugetlb_fault_mutex_hash(mapping, idx);
4203c672c7f2SMike Kravetz 	mutex_lock(&hugetlb_fault_mutex_table[hash]);
42048382d914SDavidlohr Bueso 
42057f2e9525SGerald Schaefer 	entry = huge_ptep_get(ptep);
42067f2e9525SGerald Schaefer 	if (huge_pte_none(entry)) {
42078382d914SDavidlohr Bueso 		ret = hugetlb_no_page(mm, vma, mapping, idx, address, ptep, flags);
4208b4d1d99fSDavid Gibson 		goto out_mutex;
42093935baa9SDavid Gibson 	}
421086e5216fSAdam Litke 
421183c54070SNick Piggin 	ret = 0;
42121e8f889bSDavid Gibson 
421357303d80SAndy Whitcroft 	/*
42140f792cf9SNaoya Horiguchi 	 * entry could be a migration/hwpoison entry at this point, so this
42150f792cf9SNaoya Horiguchi 	 * check prevents the kernel from going below assuming that we have
42160f792cf9SNaoya Horiguchi 	 * a active hugepage in pagecache. This goto expects the 2nd page fault,
42170f792cf9SNaoya Horiguchi 	 * and is_hugetlb_entry_(migration|hwpoisoned) check will properly
42180f792cf9SNaoya Horiguchi 	 * handle it.
42190f792cf9SNaoya Horiguchi 	 */
42200f792cf9SNaoya Horiguchi 	if (!pte_present(entry))
42210f792cf9SNaoya Horiguchi 		goto out_mutex;
42220f792cf9SNaoya Horiguchi 
42230f792cf9SNaoya Horiguchi 	/*
422457303d80SAndy Whitcroft 	 * If we are going to COW the mapping later, we examine the pending
422557303d80SAndy Whitcroft 	 * reservations for this page now. This will ensure that any
422657303d80SAndy Whitcroft 	 * allocations necessary to record that reservation occur outside the
422757303d80SAndy Whitcroft 	 * spinlock. For private mappings, we also lookup the pagecache
422857303d80SAndy Whitcroft 	 * page now as it is used to determine if a reservation has been
422957303d80SAndy Whitcroft 	 * consumed.
423057303d80SAndy Whitcroft 	 */
4231106c992aSGerald Schaefer 	if ((flags & FAULT_FLAG_WRITE) && !huge_pte_write(entry)) {
4232285b8dcaSHuang Ying 		if (vma_needs_reservation(h, vma, haddr) < 0) {
42332b26736cSAndy Whitcroft 			ret = VM_FAULT_OOM;
4234b4d1d99fSDavid Gibson 			goto out_mutex;
42352b26736cSAndy Whitcroft 		}
42365e911373SMike Kravetz 		/* Just decrements count, does not deallocate */
4237285b8dcaSHuang Ying 		vma_end_reservation(h, vma, haddr);
423857303d80SAndy Whitcroft 
4239f83a275dSMel Gorman 		if (!(vma->vm_flags & VM_MAYSHARE))
424057303d80SAndy Whitcroft 			pagecache_page = hugetlbfs_pagecache_page(h,
4241285b8dcaSHuang Ying 								vma, haddr);
424257303d80SAndy Whitcroft 	}
424357303d80SAndy Whitcroft 
42440f792cf9SNaoya Horiguchi 	ptl = huge_pte_lock(h, mm, ptep);
42450fe6e20bSNaoya Horiguchi 
42461e8f889bSDavid Gibson 	/* Check for a racing update before calling hugetlb_cow */
4247b4d1d99fSDavid Gibson 	if (unlikely(!pte_same(entry, huge_ptep_get(ptep))))
4248cb900f41SKirill A. Shutemov 		goto out_ptl;
4249b4d1d99fSDavid Gibson 
42500f792cf9SNaoya Horiguchi 	/*
42510f792cf9SNaoya Horiguchi 	 * hugetlb_cow() requires page locks of pte_page(entry) and
42520f792cf9SNaoya Horiguchi 	 * pagecache_page, so here we need take the former one
42530f792cf9SNaoya Horiguchi 	 * when page != pagecache_page or !pagecache_page.
42540f792cf9SNaoya Horiguchi 	 */
42550f792cf9SNaoya Horiguchi 	page = pte_page(entry);
42560f792cf9SNaoya Horiguchi 	if (page != pagecache_page)
42570f792cf9SNaoya Horiguchi 		if (!trylock_page(page)) {
42580f792cf9SNaoya Horiguchi 			need_wait_lock = 1;
42590f792cf9SNaoya Horiguchi 			goto out_ptl;
42600f792cf9SNaoya Horiguchi 		}
42610f792cf9SNaoya Horiguchi 
42620f792cf9SNaoya Horiguchi 	get_page(page);
4263b4d1d99fSDavid Gibson 
4264788c7df4SHugh Dickins 	if (flags & FAULT_FLAG_WRITE) {
4265106c992aSGerald Schaefer 		if (!huge_pte_write(entry)) {
4266974e6d66SHuang Ying 			ret = hugetlb_cow(mm, vma, address, ptep,
4267cb900f41SKirill A. Shutemov 					  pagecache_page, ptl);
42680f792cf9SNaoya Horiguchi 			goto out_put_page;
4269b4d1d99fSDavid Gibson 		}
4270106c992aSGerald Schaefer 		entry = huge_pte_mkdirty(entry);
4271b4d1d99fSDavid Gibson 	}
4272b4d1d99fSDavid Gibson 	entry = pte_mkyoung(entry);
4273285b8dcaSHuang Ying 	if (huge_ptep_set_access_flags(vma, haddr, ptep, entry,
4274788c7df4SHugh Dickins 						flags & FAULT_FLAG_WRITE))
4275285b8dcaSHuang Ying 		update_mmu_cache(vma, haddr, ptep);
42760f792cf9SNaoya Horiguchi out_put_page:
42770f792cf9SNaoya Horiguchi 	if (page != pagecache_page)
42780f792cf9SNaoya Horiguchi 		unlock_page(page);
42790f792cf9SNaoya Horiguchi 	put_page(page);
4280cb900f41SKirill A. Shutemov out_ptl:
4281cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
428257303d80SAndy Whitcroft 
428357303d80SAndy Whitcroft 	if (pagecache_page) {
428457303d80SAndy Whitcroft 		unlock_page(pagecache_page);
428557303d80SAndy Whitcroft 		put_page(pagecache_page);
428657303d80SAndy Whitcroft 	}
4287b4d1d99fSDavid Gibson out_mutex:
4288c672c7f2SMike Kravetz 	mutex_unlock(&hugetlb_fault_mutex_table[hash]);
4289c0d0381aSMike Kravetz 	i_mmap_unlock_read(mapping);
42900f792cf9SNaoya Horiguchi 	/*
42910f792cf9SNaoya Horiguchi 	 * Generally it's safe to hold refcount during waiting page lock. But
42920f792cf9SNaoya Horiguchi 	 * here we just wait to defer the next page fault to avoid busy loop and
42930f792cf9SNaoya Horiguchi 	 * the page is not used after unlocked before returning from the current
42940f792cf9SNaoya Horiguchi 	 * page fault. So we are safe from accessing freed page, even if we wait
42950f792cf9SNaoya Horiguchi 	 * here without taking refcount.
42960f792cf9SNaoya Horiguchi 	 */
42970f792cf9SNaoya Horiguchi 	if (need_wait_lock)
42980f792cf9SNaoya Horiguchi 		wait_on_page_locked(page);
42991e8f889bSDavid Gibson 	return ret;
430086e5216fSAdam Litke }
430186e5216fSAdam Litke 
43028fb5debcSMike Kravetz /*
43038fb5debcSMike Kravetz  * Used by userfaultfd UFFDIO_COPY.  Based on mcopy_atomic_pte with
43048fb5debcSMike Kravetz  * modifications for huge pages.
43058fb5debcSMike Kravetz  */
43068fb5debcSMike Kravetz int hugetlb_mcopy_atomic_pte(struct mm_struct *dst_mm,
43078fb5debcSMike Kravetz 			    pte_t *dst_pte,
43088fb5debcSMike Kravetz 			    struct vm_area_struct *dst_vma,
43098fb5debcSMike Kravetz 			    unsigned long dst_addr,
43108fb5debcSMike Kravetz 			    unsigned long src_addr,
43118fb5debcSMike Kravetz 			    struct page **pagep)
43128fb5debcSMike Kravetz {
43131e392147SAndrea Arcangeli 	struct address_space *mapping;
43141e392147SAndrea Arcangeli 	pgoff_t idx;
43151e392147SAndrea Arcangeli 	unsigned long size;
43161c9e8defSMike Kravetz 	int vm_shared = dst_vma->vm_flags & VM_SHARED;
43178fb5debcSMike Kravetz 	struct hstate *h = hstate_vma(dst_vma);
43188fb5debcSMike Kravetz 	pte_t _dst_pte;
43198fb5debcSMike Kravetz 	spinlock_t *ptl;
43208fb5debcSMike Kravetz 	int ret;
43218fb5debcSMike Kravetz 	struct page *page;
43228fb5debcSMike Kravetz 
43238fb5debcSMike Kravetz 	if (!*pagep) {
43248fb5debcSMike Kravetz 		ret = -ENOMEM;
43258fb5debcSMike Kravetz 		page = alloc_huge_page(dst_vma, dst_addr, 0);
43268fb5debcSMike Kravetz 		if (IS_ERR(page))
43278fb5debcSMike Kravetz 			goto out;
43288fb5debcSMike Kravetz 
43298fb5debcSMike Kravetz 		ret = copy_huge_page_from_user(page,
43308fb5debcSMike Kravetz 						(const void __user *) src_addr,
4331810a56b9SMike Kravetz 						pages_per_huge_page(h), false);
43328fb5debcSMike Kravetz 
43338fb5debcSMike Kravetz 		/* fallback to copy_from_user outside mmap_sem */
43348fb5debcSMike Kravetz 		if (unlikely(ret)) {
43359e368259SAndrea Arcangeli 			ret = -ENOENT;
43368fb5debcSMike Kravetz 			*pagep = page;
43378fb5debcSMike Kravetz 			/* don't free the page */
43388fb5debcSMike Kravetz 			goto out;
43398fb5debcSMike Kravetz 		}
43408fb5debcSMike Kravetz 	} else {
43418fb5debcSMike Kravetz 		page = *pagep;
43428fb5debcSMike Kravetz 		*pagep = NULL;
43438fb5debcSMike Kravetz 	}
43448fb5debcSMike Kravetz 
43458fb5debcSMike Kravetz 	/*
43468fb5debcSMike Kravetz 	 * The memory barrier inside __SetPageUptodate makes sure that
43478fb5debcSMike Kravetz 	 * preceding stores to the page contents become visible before
43488fb5debcSMike Kravetz 	 * the set_pte_at() write.
43498fb5debcSMike Kravetz 	 */
43508fb5debcSMike Kravetz 	__SetPageUptodate(page);
43518fb5debcSMike Kravetz 
43521e392147SAndrea Arcangeli 	mapping = dst_vma->vm_file->f_mapping;
43531e392147SAndrea Arcangeli 	idx = vma_hugecache_offset(h, dst_vma, dst_addr);
43541e392147SAndrea Arcangeli 
43551c9e8defSMike Kravetz 	/*
43561c9e8defSMike Kravetz 	 * If shared, add to page cache
43571c9e8defSMike Kravetz 	 */
43581c9e8defSMike Kravetz 	if (vm_shared) {
43591e392147SAndrea Arcangeli 		size = i_size_read(mapping->host) >> huge_page_shift(h);
43601e392147SAndrea Arcangeli 		ret = -EFAULT;
43611e392147SAndrea Arcangeli 		if (idx >= size)
43621e392147SAndrea Arcangeli 			goto out_release_nounlock;
43631c9e8defSMike Kravetz 
43641e392147SAndrea Arcangeli 		/*
43651e392147SAndrea Arcangeli 		 * Serialization between remove_inode_hugepages() and
43661e392147SAndrea Arcangeli 		 * huge_add_to_page_cache() below happens through the
43671e392147SAndrea Arcangeli 		 * hugetlb_fault_mutex_table that here must be hold by
43681e392147SAndrea Arcangeli 		 * the caller.
43691e392147SAndrea Arcangeli 		 */
43701c9e8defSMike Kravetz 		ret = huge_add_to_page_cache(page, mapping, idx);
43711c9e8defSMike Kravetz 		if (ret)
43721c9e8defSMike Kravetz 			goto out_release_nounlock;
43731c9e8defSMike Kravetz 	}
43741c9e8defSMike Kravetz 
43758fb5debcSMike Kravetz 	ptl = huge_pte_lockptr(h, dst_mm, dst_pte);
43768fb5debcSMike Kravetz 	spin_lock(ptl);
43778fb5debcSMike Kravetz 
43781e392147SAndrea Arcangeli 	/*
43791e392147SAndrea Arcangeli 	 * Recheck the i_size after holding PT lock to make sure not
43801e392147SAndrea Arcangeli 	 * to leave any page mapped (as page_mapped()) beyond the end
43811e392147SAndrea Arcangeli 	 * of the i_size (remove_inode_hugepages() is strict about
43821e392147SAndrea Arcangeli 	 * enforcing that). If we bail out here, we'll also leave a
43831e392147SAndrea Arcangeli 	 * page in the radix tree in the vm_shared case beyond the end
43841e392147SAndrea Arcangeli 	 * of the i_size, but remove_inode_hugepages() will take care
43851e392147SAndrea Arcangeli 	 * of it as soon as we drop the hugetlb_fault_mutex_table.
43861e392147SAndrea Arcangeli 	 */
43871e392147SAndrea Arcangeli 	size = i_size_read(mapping->host) >> huge_page_shift(h);
43881e392147SAndrea Arcangeli 	ret = -EFAULT;
43891e392147SAndrea Arcangeli 	if (idx >= size)
43901e392147SAndrea Arcangeli 		goto out_release_unlock;
43911e392147SAndrea Arcangeli 
43928fb5debcSMike Kravetz 	ret = -EEXIST;
43938fb5debcSMike Kravetz 	if (!huge_pte_none(huge_ptep_get(dst_pte)))
43948fb5debcSMike Kravetz 		goto out_release_unlock;
43958fb5debcSMike Kravetz 
43961c9e8defSMike Kravetz 	if (vm_shared) {
43971c9e8defSMike Kravetz 		page_dup_rmap(page, true);
43981c9e8defSMike Kravetz 	} else {
43998fb5debcSMike Kravetz 		ClearPagePrivate(page);
44008fb5debcSMike Kravetz 		hugepage_add_new_anon_rmap(page, dst_vma, dst_addr);
44011c9e8defSMike Kravetz 	}
44028fb5debcSMike Kravetz 
44038fb5debcSMike Kravetz 	_dst_pte = make_huge_pte(dst_vma, page, dst_vma->vm_flags & VM_WRITE);
44048fb5debcSMike Kravetz 	if (dst_vma->vm_flags & VM_WRITE)
44058fb5debcSMike Kravetz 		_dst_pte = huge_pte_mkdirty(_dst_pte);
44068fb5debcSMike Kravetz 	_dst_pte = pte_mkyoung(_dst_pte);
44078fb5debcSMike Kravetz 
44088fb5debcSMike Kravetz 	set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
44098fb5debcSMike Kravetz 
44108fb5debcSMike Kravetz 	(void)huge_ptep_set_access_flags(dst_vma, dst_addr, dst_pte, _dst_pte,
44118fb5debcSMike Kravetz 					dst_vma->vm_flags & VM_WRITE);
44128fb5debcSMike Kravetz 	hugetlb_count_add(pages_per_huge_page(h), dst_mm);
44138fb5debcSMike Kravetz 
44148fb5debcSMike Kravetz 	/* No need to invalidate - it was non-present before */
44158fb5debcSMike Kravetz 	update_mmu_cache(dst_vma, dst_addr, dst_pte);
44168fb5debcSMike Kravetz 
44178fb5debcSMike Kravetz 	spin_unlock(ptl);
4418cb6acd01SMike Kravetz 	set_page_huge_active(page);
44191c9e8defSMike Kravetz 	if (vm_shared)
44201c9e8defSMike Kravetz 		unlock_page(page);
44218fb5debcSMike Kravetz 	ret = 0;
44228fb5debcSMike Kravetz out:
44238fb5debcSMike Kravetz 	return ret;
44248fb5debcSMike Kravetz out_release_unlock:
44258fb5debcSMike Kravetz 	spin_unlock(ptl);
44261c9e8defSMike Kravetz 	if (vm_shared)
44271c9e8defSMike Kravetz 		unlock_page(page);
44285af10dfdSAndrea Arcangeli out_release_nounlock:
44298fb5debcSMike Kravetz 	put_page(page);
44308fb5debcSMike Kravetz 	goto out;
44318fb5debcSMike Kravetz }
44328fb5debcSMike Kravetz 
443328a35716SMichel Lespinasse long follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma,
443463551ae0SDavid Gibson 			 struct page **pages, struct vm_area_struct **vmas,
443528a35716SMichel Lespinasse 			 unsigned long *position, unsigned long *nr_pages,
44364f6da934SPeter Xu 			 long i, unsigned int flags, int *locked)
443763551ae0SDavid Gibson {
4438d5d4b0aaSChen, Kenneth W 	unsigned long pfn_offset;
4439d5d4b0aaSChen, Kenneth W 	unsigned long vaddr = *position;
444028a35716SMichel Lespinasse 	unsigned long remainder = *nr_pages;
4441a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
44422be7cfedSDaniel Jordan 	int err = -EFAULT;
444363551ae0SDavid Gibson 
444463551ae0SDavid Gibson 	while (vaddr < vma->vm_end && remainder) {
444563551ae0SDavid Gibson 		pte_t *pte;
4446cb900f41SKirill A. Shutemov 		spinlock_t *ptl = NULL;
44472a15efc9SHugh Dickins 		int absent;
444863551ae0SDavid Gibson 		struct page *page;
444963551ae0SDavid Gibson 
44504c887265SAdam Litke 		/*
445102057967SDavid Rientjes 		 * If we have a pending SIGKILL, don't keep faulting pages and
445202057967SDavid Rientjes 		 * potentially allocating memory.
445302057967SDavid Rientjes 		 */
4454fa45f116SDavidlohr Bueso 		if (fatal_signal_pending(current)) {
445502057967SDavid Rientjes 			remainder = 0;
445602057967SDavid Rientjes 			break;
445702057967SDavid Rientjes 		}
445802057967SDavid Rientjes 
445902057967SDavid Rientjes 		/*
44604c887265SAdam Litke 		 * Some archs (sparc64, sh*) have multiple pte_ts to
44612a15efc9SHugh Dickins 		 * each hugepage.  We have to make sure we get the
44624c887265SAdam Litke 		 * first, for the page indexing below to work.
4463cb900f41SKirill A. Shutemov 		 *
4464cb900f41SKirill A. Shutemov 		 * Note that page table lock is not held when pte is null.
44654c887265SAdam Litke 		 */
44667868a208SPunit Agrawal 		pte = huge_pte_offset(mm, vaddr & huge_page_mask(h),
44677868a208SPunit Agrawal 				      huge_page_size(h));
4468cb900f41SKirill A. Shutemov 		if (pte)
4469cb900f41SKirill A. Shutemov 			ptl = huge_pte_lock(h, mm, pte);
44702a15efc9SHugh Dickins 		absent = !pte || huge_pte_none(huge_ptep_get(pte));
447163551ae0SDavid Gibson 
44722a15efc9SHugh Dickins 		/*
44732a15efc9SHugh Dickins 		 * When coredumping, it suits get_dump_page if we just return
44743ae77f43SHugh Dickins 		 * an error where there's an empty slot with no huge pagecache
44753ae77f43SHugh Dickins 		 * to back it.  This way, we avoid allocating a hugepage, and
44763ae77f43SHugh Dickins 		 * the sparse dumpfile avoids allocating disk blocks, but its
44773ae77f43SHugh Dickins 		 * huge holes still show up with zeroes where they need to be.
44782a15efc9SHugh Dickins 		 */
44793ae77f43SHugh Dickins 		if (absent && (flags & FOLL_DUMP) &&
44803ae77f43SHugh Dickins 		    !hugetlbfs_pagecache_present(h, vma, vaddr)) {
4481cb900f41SKirill A. Shutemov 			if (pte)
4482cb900f41SKirill A. Shutemov 				spin_unlock(ptl);
44832a15efc9SHugh Dickins 			remainder = 0;
44842a15efc9SHugh Dickins 			break;
44852a15efc9SHugh Dickins 		}
44862a15efc9SHugh Dickins 
44879cc3a5bdSNaoya Horiguchi 		/*
44889cc3a5bdSNaoya Horiguchi 		 * We need call hugetlb_fault for both hugepages under migration
44899cc3a5bdSNaoya Horiguchi 		 * (in which case hugetlb_fault waits for the migration,) and
44909cc3a5bdSNaoya Horiguchi 		 * hwpoisoned hugepages (in which case we need to prevent the
44919cc3a5bdSNaoya Horiguchi 		 * caller from accessing to them.) In order to do this, we use
44929cc3a5bdSNaoya Horiguchi 		 * here is_swap_pte instead of is_hugetlb_entry_migration and
44939cc3a5bdSNaoya Horiguchi 		 * is_hugetlb_entry_hwpoisoned. This is because it simply covers
44949cc3a5bdSNaoya Horiguchi 		 * both cases, and because we can't follow correct pages
44959cc3a5bdSNaoya Horiguchi 		 * directly from any kind of swap entries.
44969cc3a5bdSNaoya Horiguchi 		 */
44979cc3a5bdSNaoya Horiguchi 		if (absent || is_swap_pte(huge_ptep_get(pte)) ||
4498106c992aSGerald Schaefer 		    ((flags & FOLL_WRITE) &&
4499106c992aSGerald Schaefer 		      !huge_pte_write(huge_ptep_get(pte)))) {
45002b740303SSouptick Joarder 			vm_fault_t ret;
450187ffc118SAndrea Arcangeli 			unsigned int fault_flags = 0;
45024c887265SAdam Litke 
4503cb900f41SKirill A. Shutemov 			if (pte)
4504cb900f41SKirill A. Shutemov 				spin_unlock(ptl);
450587ffc118SAndrea Arcangeli 			if (flags & FOLL_WRITE)
450687ffc118SAndrea Arcangeli 				fault_flags |= FAULT_FLAG_WRITE;
45074f6da934SPeter Xu 			if (locked)
450871335f37SPeter Xu 				fault_flags |= FAULT_FLAG_ALLOW_RETRY |
450971335f37SPeter Xu 					FAULT_FLAG_KILLABLE;
451087ffc118SAndrea Arcangeli 			if (flags & FOLL_NOWAIT)
451187ffc118SAndrea Arcangeli 				fault_flags |= FAULT_FLAG_ALLOW_RETRY |
451287ffc118SAndrea Arcangeli 					FAULT_FLAG_RETRY_NOWAIT;
451387ffc118SAndrea Arcangeli 			if (flags & FOLL_TRIED) {
45144426e945SPeter Xu 				/*
45154426e945SPeter Xu 				 * Note: FAULT_FLAG_ALLOW_RETRY and
45164426e945SPeter Xu 				 * FAULT_FLAG_TRIED can co-exist
45174426e945SPeter Xu 				 */
451887ffc118SAndrea Arcangeli 				fault_flags |= FAULT_FLAG_TRIED;
451987ffc118SAndrea Arcangeli 			}
452087ffc118SAndrea Arcangeli 			ret = hugetlb_fault(mm, vma, vaddr, fault_flags);
452187ffc118SAndrea Arcangeli 			if (ret & VM_FAULT_ERROR) {
45222be7cfedSDaniel Jordan 				err = vm_fault_to_errno(ret, flags);
45231c59827dSHugh Dickins 				remainder = 0;
45241c59827dSHugh Dickins 				break;
45251c59827dSHugh Dickins 			}
452687ffc118SAndrea Arcangeli 			if (ret & VM_FAULT_RETRY) {
45274f6da934SPeter Xu 				if (locked &&
45281ac25013SAndrea Arcangeli 				    !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
45294f6da934SPeter Xu 					*locked = 0;
453087ffc118SAndrea Arcangeli 				*nr_pages = 0;
453187ffc118SAndrea Arcangeli 				/*
453287ffc118SAndrea Arcangeli 				 * VM_FAULT_RETRY must not return an
453387ffc118SAndrea Arcangeli 				 * error, it will return zero
453487ffc118SAndrea Arcangeli 				 * instead.
453587ffc118SAndrea Arcangeli 				 *
453687ffc118SAndrea Arcangeli 				 * No need to update "position" as the
453787ffc118SAndrea Arcangeli 				 * caller will not check it after
453887ffc118SAndrea Arcangeli 				 * *nr_pages is set to 0.
453987ffc118SAndrea Arcangeli 				 */
454087ffc118SAndrea Arcangeli 				return i;
454187ffc118SAndrea Arcangeli 			}
454287ffc118SAndrea Arcangeli 			continue;
454387ffc118SAndrea Arcangeli 		}
454463551ae0SDavid Gibson 
4545a5516438SAndi Kleen 		pfn_offset = (vaddr & ~huge_page_mask(h)) >> PAGE_SHIFT;
45467f2e9525SGerald Schaefer 		page = pte_page(huge_ptep_get(pte));
45478fde12caSLinus Torvalds 
45488fde12caSLinus Torvalds 		/*
4549acbfb087SZhigang Lu 		 * If subpage information not requested, update counters
4550acbfb087SZhigang Lu 		 * and skip the same_page loop below.
4551acbfb087SZhigang Lu 		 */
4552acbfb087SZhigang Lu 		if (!pages && !vmas && !pfn_offset &&
4553acbfb087SZhigang Lu 		    (vaddr + huge_page_size(h) < vma->vm_end) &&
4554acbfb087SZhigang Lu 		    (remainder >= pages_per_huge_page(h))) {
4555acbfb087SZhigang Lu 			vaddr += huge_page_size(h);
4556acbfb087SZhigang Lu 			remainder -= pages_per_huge_page(h);
4557acbfb087SZhigang Lu 			i += pages_per_huge_page(h);
4558acbfb087SZhigang Lu 			spin_unlock(ptl);
4559acbfb087SZhigang Lu 			continue;
4560acbfb087SZhigang Lu 		}
4561acbfb087SZhigang Lu 
4562d5d4b0aaSChen, Kenneth W same_page:
4563d6692183SChen, Kenneth W 		if (pages) {
456469d177c2SAndy Whitcroft 			pages[i] = mem_map_offset(page, pfn_offset);
45653faa52c0SJohn Hubbard 			/*
45663faa52c0SJohn Hubbard 			 * try_grab_page() should always succeed here, because:
45673faa52c0SJohn Hubbard 			 * a) we hold the ptl lock, and b) we've just checked
45683faa52c0SJohn Hubbard 			 * that the huge page is present in the page tables. If
45693faa52c0SJohn Hubbard 			 * the huge page is present, then the tail pages must
45703faa52c0SJohn Hubbard 			 * also be present. The ptl prevents the head page and
45713faa52c0SJohn Hubbard 			 * tail pages from being rearranged in any way. So this
45723faa52c0SJohn Hubbard 			 * page must be available at this point, unless the page
45733faa52c0SJohn Hubbard 			 * refcount overflowed:
45743faa52c0SJohn Hubbard 			 */
45753faa52c0SJohn Hubbard 			if (WARN_ON_ONCE(!try_grab_page(pages[i], flags))) {
45763faa52c0SJohn Hubbard 				spin_unlock(ptl);
45773faa52c0SJohn Hubbard 				remainder = 0;
45783faa52c0SJohn Hubbard 				err = -ENOMEM;
45793faa52c0SJohn Hubbard 				break;
45803faa52c0SJohn Hubbard 			}
4581d6692183SChen, Kenneth W 		}
458263551ae0SDavid Gibson 
458363551ae0SDavid Gibson 		if (vmas)
458463551ae0SDavid Gibson 			vmas[i] = vma;
458563551ae0SDavid Gibson 
458663551ae0SDavid Gibson 		vaddr += PAGE_SIZE;
4587d5d4b0aaSChen, Kenneth W 		++pfn_offset;
458863551ae0SDavid Gibson 		--remainder;
458963551ae0SDavid Gibson 		++i;
4590d5d4b0aaSChen, Kenneth W 		if (vaddr < vma->vm_end && remainder &&
4591a5516438SAndi Kleen 				pfn_offset < pages_per_huge_page(h)) {
4592d5d4b0aaSChen, Kenneth W 			/*
4593d5d4b0aaSChen, Kenneth W 			 * We use pfn_offset to avoid touching the pageframes
4594d5d4b0aaSChen, Kenneth W 			 * of this compound page.
4595d5d4b0aaSChen, Kenneth W 			 */
4596d5d4b0aaSChen, Kenneth W 			goto same_page;
4597d5d4b0aaSChen, Kenneth W 		}
4598cb900f41SKirill A. Shutemov 		spin_unlock(ptl);
459963551ae0SDavid Gibson 	}
460028a35716SMichel Lespinasse 	*nr_pages = remainder;
460187ffc118SAndrea Arcangeli 	/*
460287ffc118SAndrea Arcangeli 	 * setting position is actually required only if remainder is
460387ffc118SAndrea Arcangeli 	 * not zero but it's faster not to add a "if (remainder)"
460487ffc118SAndrea Arcangeli 	 * branch.
460587ffc118SAndrea Arcangeli 	 */
460663551ae0SDavid Gibson 	*position = vaddr;
460763551ae0SDavid Gibson 
46082be7cfedSDaniel Jordan 	return i ? i : err;
460963551ae0SDavid Gibson }
46108f860591SZhang, Yanmin 
46115491ae7bSAneesh Kumar K.V #ifndef __HAVE_ARCH_FLUSH_HUGETLB_TLB_RANGE
46125491ae7bSAneesh Kumar K.V /*
46135491ae7bSAneesh Kumar K.V  * ARCHes with special requirements for evicting HUGETLB backing TLB entries can
46145491ae7bSAneesh Kumar K.V  * implement this.
46155491ae7bSAneesh Kumar K.V  */
46165491ae7bSAneesh Kumar K.V #define flush_hugetlb_tlb_range(vma, addr, end)	flush_tlb_range(vma, addr, end)
46175491ae7bSAneesh Kumar K.V #endif
46185491ae7bSAneesh Kumar K.V 
46197da4d641SPeter Zijlstra unsigned long hugetlb_change_protection(struct vm_area_struct *vma,
46208f860591SZhang, Yanmin 		unsigned long address, unsigned long end, pgprot_t newprot)
46218f860591SZhang, Yanmin {
46228f860591SZhang, Yanmin 	struct mm_struct *mm = vma->vm_mm;
46238f860591SZhang, Yanmin 	unsigned long start = address;
46248f860591SZhang, Yanmin 	pte_t *ptep;
46258f860591SZhang, Yanmin 	pte_t pte;
4626a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
46277da4d641SPeter Zijlstra 	unsigned long pages = 0;
4628dff11abeSMike Kravetz 	bool shared_pmd = false;
4629ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
4630dff11abeSMike Kravetz 
4631dff11abeSMike Kravetz 	/*
4632dff11abeSMike Kravetz 	 * In the case of shared PMDs, the area to flush could be beyond
4633ac46d4f3SJérôme Glisse 	 * start/end.  Set range.start/range.end to cover the maximum possible
4634dff11abeSMike Kravetz 	 * range if PMD sharing is possible.
4635dff11abeSMike Kravetz 	 */
46367269f999SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_VMA,
46377269f999SJérôme Glisse 				0, vma, mm, start, end);
4638ac46d4f3SJérôme Glisse 	adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
46398f860591SZhang, Yanmin 
46408f860591SZhang, Yanmin 	BUG_ON(address >= end);
4641ac46d4f3SJérôme Glisse 	flush_cache_range(vma, range.start, range.end);
46428f860591SZhang, Yanmin 
4643ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
464483cde9e8SDavidlohr Bueso 	i_mmap_lock_write(vma->vm_file->f_mapping);
4645a5516438SAndi Kleen 	for (; address < end; address += huge_page_size(h)) {
4646cb900f41SKirill A. Shutemov 		spinlock_t *ptl;
46477868a208SPunit Agrawal 		ptep = huge_pte_offset(mm, address, huge_page_size(h));
46488f860591SZhang, Yanmin 		if (!ptep)
46498f860591SZhang, Yanmin 			continue;
4650cb900f41SKirill A. Shutemov 		ptl = huge_pte_lock(h, mm, ptep);
46517da4d641SPeter Zijlstra 		if (huge_pmd_unshare(mm, &address, ptep)) {
46527da4d641SPeter Zijlstra 			pages++;
4653cb900f41SKirill A. Shutemov 			spin_unlock(ptl);
4654dff11abeSMike Kravetz 			shared_pmd = true;
465539dde65cSChen, Kenneth W 			continue;
46567da4d641SPeter Zijlstra 		}
4657a8bda28dSNaoya Horiguchi 		pte = huge_ptep_get(ptep);
4658a8bda28dSNaoya Horiguchi 		if (unlikely(is_hugetlb_entry_hwpoisoned(pte))) {
4659a8bda28dSNaoya Horiguchi 			spin_unlock(ptl);
4660a8bda28dSNaoya Horiguchi 			continue;
4661a8bda28dSNaoya Horiguchi 		}
4662a8bda28dSNaoya Horiguchi 		if (unlikely(is_hugetlb_entry_migration(pte))) {
4663a8bda28dSNaoya Horiguchi 			swp_entry_t entry = pte_to_swp_entry(pte);
4664a8bda28dSNaoya Horiguchi 
4665a8bda28dSNaoya Horiguchi 			if (is_write_migration_entry(entry)) {
4666a8bda28dSNaoya Horiguchi 				pte_t newpte;
4667a8bda28dSNaoya Horiguchi 
4668a8bda28dSNaoya Horiguchi 				make_migration_entry_read(&entry);
4669a8bda28dSNaoya Horiguchi 				newpte = swp_entry_to_pte(entry);
4670e5251fd4SPunit Agrawal 				set_huge_swap_pte_at(mm, address, ptep,
4671e5251fd4SPunit Agrawal 						     newpte, huge_page_size(h));
4672a8bda28dSNaoya Horiguchi 				pages++;
4673a8bda28dSNaoya Horiguchi 			}
4674a8bda28dSNaoya Horiguchi 			spin_unlock(ptl);
4675a8bda28dSNaoya Horiguchi 			continue;
4676a8bda28dSNaoya Horiguchi 		}
4677a8bda28dSNaoya Horiguchi 		if (!huge_pte_none(pte)) {
4678023bdd00SAneesh Kumar K.V 			pte_t old_pte;
4679023bdd00SAneesh Kumar K.V 
4680023bdd00SAneesh Kumar K.V 			old_pte = huge_ptep_modify_prot_start(vma, address, ptep);
4681023bdd00SAneesh Kumar K.V 			pte = pte_mkhuge(huge_pte_modify(old_pte, newprot));
4682be7517d6STony Lu 			pte = arch_make_huge_pte(pte, vma, NULL, 0);
4683023bdd00SAneesh Kumar K.V 			huge_ptep_modify_prot_commit(vma, address, ptep, old_pte, pte);
46847da4d641SPeter Zijlstra 			pages++;
46858f860591SZhang, Yanmin 		}
4686cb900f41SKirill A. Shutemov 		spin_unlock(ptl);
46878f860591SZhang, Yanmin 	}
4688d833352aSMel Gorman 	/*
4689c8c06efaSDavidlohr Bueso 	 * Must flush TLB before releasing i_mmap_rwsem: x86's huge_pmd_unshare
4690d833352aSMel Gorman 	 * may have cleared our pud entry and done put_page on the page table:
4691c8c06efaSDavidlohr Bueso 	 * once we release i_mmap_rwsem, another task can do the final put_page
4692dff11abeSMike Kravetz 	 * and that page table be reused and filled with junk.  If we actually
4693dff11abeSMike Kravetz 	 * did unshare a page of pmds, flush the range corresponding to the pud.
4694d833352aSMel Gorman 	 */
4695dff11abeSMike Kravetz 	if (shared_pmd)
4696ac46d4f3SJérôme Glisse 		flush_hugetlb_tlb_range(vma, range.start, range.end);
4697dff11abeSMike Kravetz 	else
46985491ae7bSAneesh Kumar K.V 		flush_hugetlb_tlb_range(vma, start, end);
46990f10851eSJérôme Glisse 	/*
47000f10851eSJérôme Glisse 	 * No need to call mmu_notifier_invalidate_range() we are downgrading
47010f10851eSJérôme Glisse 	 * page table protection not changing it to point to a new page.
47020f10851eSJérôme Glisse 	 *
4703ad56b738SMike Rapoport 	 * See Documentation/vm/mmu_notifier.rst
47040f10851eSJérôme Glisse 	 */
470583cde9e8SDavidlohr Bueso 	i_mmap_unlock_write(vma->vm_file->f_mapping);
4706ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
47077da4d641SPeter Zijlstra 
47087da4d641SPeter Zijlstra 	return pages << h->order;
47098f860591SZhang, Yanmin }
47108f860591SZhang, Yanmin 
4711a1e78772SMel Gorman int hugetlb_reserve_pages(struct inode *inode,
4712a1e78772SMel Gorman 					long from, long to,
47135a6fe125SMel Gorman 					struct vm_area_struct *vma,
4714ca16d140SKOSAKI Motohiro 					vm_flags_t vm_flags)
4715e4e574b7SAdam Litke {
471617c9d12eSMel Gorman 	long ret, chg;
4717a5516438SAndi Kleen 	struct hstate *h = hstate_inode(inode);
471890481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_inode(inode);
47199119a41eSJoonsoo Kim 	struct resv_map *resv_map;
4720e9fe92aeSMina Almasry 	struct hugetlb_cgroup *h_cg;
47211c5ecae3SMike Kravetz 	long gbl_reserve;
4722e4e574b7SAdam Litke 
472363489f8eSMike Kravetz 	/* This should never happen */
472463489f8eSMike Kravetz 	if (from > to) {
472563489f8eSMike Kravetz 		VM_WARN(1, "%s called with a negative range\n", __func__);
472663489f8eSMike Kravetz 		return -EINVAL;
472763489f8eSMike Kravetz 	}
472863489f8eSMike Kravetz 
4729a1e78772SMel Gorman 	/*
473017c9d12eSMel Gorman 	 * Only apply hugepage reservation if asked. At fault time, an
473117c9d12eSMel Gorman 	 * attempt will be made for VM_NORESERVE to allocate a page
473290481622SDavid Gibson 	 * without using reserves
473317c9d12eSMel Gorman 	 */
4734ca16d140SKOSAKI Motohiro 	if (vm_flags & VM_NORESERVE)
473517c9d12eSMel Gorman 		return 0;
473617c9d12eSMel Gorman 
473717c9d12eSMel Gorman 	/*
4738a1e78772SMel Gorman 	 * Shared mappings base their reservation on the number of pages that
4739a1e78772SMel Gorman 	 * are already allocated on behalf of the file. Private mappings need
4740a1e78772SMel Gorman 	 * to reserve the full area even if read-only as mprotect() may be
4741a1e78772SMel Gorman 	 * called to make the mapping read-write. Assume !vma is a shm mapping
4742a1e78772SMel Gorman 	 */
47439119a41eSJoonsoo Kim 	if (!vma || vma->vm_flags & VM_MAYSHARE) {
4744f27a5136SMike Kravetz 		/*
4745f27a5136SMike Kravetz 		 * resv_map can not be NULL as hugetlb_reserve_pages is only
4746f27a5136SMike Kravetz 		 * called for inodes for which resv_maps were created (see
4747f27a5136SMike Kravetz 		 * hugetlbfs_get_inode).
4748f27a5136SMike Kravetz 		 */
47494e35f483SJoonsoo Kim 		resv_map = inode_resv_map(inode);
47509119a41eSJoonsoo Kim 
47511406ec9bSJoonsoo Kim 		chg = region_chg(resv_map, from, to);
47529119a41eSJoonsoo Kim 
47539119a41eSJoonsoo Kim 	} else {
4754e9fe92aeSMina Almasry 		/* Private mapping. */
47559119a41eSJoonsoo Kim 		resv_map = resv_map_alloc();
47565a6fe125SMel Gorman 		if (!resv_map)
47575a6fe125SMel Gorman 			return -ENOMEM;
47585a6fe125SMel Gorman 
475917c9d12eSMel Gorman 		chg = to - from;
476017c9d12eSMel Gorman 
4761e9fe92aeSMina Almasry 		if (hugetlb_cgroup_charge_cgroup_rsvd(
4762e9fe92aeSMina Almasry 			    hstate_index(h), chg * pages_per_huge_page(h),
4763e9fe92aeSMina Almasry 			    &h_cg)) {
4764e9fe92aeSMina Almasry 			kref_put(&resv_map->refs, resv_map_release);
4765e9fe92aeSMina Almasry 			return -ENOMEM;
4766e9fe92aeSMina Almasry 		}
4767e9fe92aeSMina Almasry 
4768e9fe92aeSMina Almasry 		/*
4769e9fe92aeSMina Almasry 		 * Since this branch handles private mappings, we attach the
4770e9fe92aeSMina Almasry 		 * counter to uncharge for this reservation off resv_map.
4771e9fe92aeSMina Almasry 		 */
4772e9fe92aeSMina Almasry 		resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, h_cg, h);
4773e9fe92aeSMina Almasry 
47745a6fe125SMel Gorman 		set_vma_resv_map(vma, resv_map);
47755a6fe125SMel Gorman 		set_vma_resv_flags(vma, HPAGE_RESV_OWNER);
47765a6fe125SMel Gorman 	}
47775a6fe125SMel Gorman 
4778c50ac050SDave Hansen 	if (chg < 0) {
4779c50ac050SDave Hansen 		ret = chg;
4780c50ac050SDave Hansen 		goto out_err;
4781c50ac050SDave Hansen 	}
478217c9d12eSMel Gorman 
47831c5ecae3SMike Kravetz 	/*
47841c5ecae3SMike Kravetz 	 * There must be enough pages in the subpool for the mapping. If
47851c5ecae3SMike Kravetz 	 * the subpool has a minimum size, there may be some global
47861c5ecae3SMike Kravetz 	 * reservations already in place (gbl_reserve).
47871c5ecae3SMike Kravetz 	 */
47881c5ecae3SMike Kravetz 	gbl_reserve = hugepage_subpool_get_pages(spool, chg);
47891c5ecae3SMike Kravetz 	if (gbl_reserve < 0) {
4790c50ac050SDave Hansen 		ret = -ENOSPC;
4791c50ac050SDave Hansen 		goto out_err;
4792c50ac050SDave Hansen 	}
479317c9d12eSMel Gorman 
479417c9d12eSMel Gorman 	/*
479517c9d12eSMel Gorman 	 * Check enough hugepages are available for the reservation.
479690481622SDavid Gibson 	 * Hand the pages back to the subpool if there are not
479717c9d12eSMel Gorman 	 */
47981c5ecae3SMike Kravetz 	ret = hugetlb_acct_memory(h, gbl_reserve);
479917c9d12eSMel Gorman 	if (ret < 0) {
48001c5ecae3SMike Kravetz 		/* put back original number of pages, chg */
48011c5ecae3SMike Kravetz 		(void)hugepage_subpool_put_pages(spool, chg);
4802c50ac050SDave Hansen 		goto out_err;
480317c9d12eSMel Gorman 	}
480417c9d12eSMel Gorman 
480517c9d12eSMel Gorman 	/*
480617c9d12eSMel Gorman 	 * Account for the reservations made. Shared mappings record regions
480717c9d12eSMel Gorman 	 * that have reservations as they are shared by multiple VMAs.
480817c9d12eSMel Gorman 	 * When the last VMA disappears, the region map says how much
480917c9d12eSMel Gorman 	 * the reservation was and the page cache tells how much of
481017c9d12eSMel Gorman 	 * the reservation was consumed. Private mappings are per-VMA and
481117c9d12eSMel Gorman 	 * only the consumed reservations are tracked. When the VMA
481217c9d12eSMel Gorman 	 * disappears, the original reservation is the VMA size and the
481317c9d12eSMel Gorman 	 * consumed reservations are stored in the map. Hence, nothing
481417c9d12eSMel Gorman 	 * else has to be done for private mappings here
481517c9d12eSMel Gorman 	 */
481633039678SMike Kravetz 	if (!vma || vma->vm_flags & VM_MAYSHARE) {
481733039678SMike Kravetz 		long add = region_add(resv_map, from, to);
481833039678SMike Kravetz 
481933039678SMike Kravetz 		if (unlikely(chg > add)) {
482033039678SMike Kravetz 			/*
482133039678SMike Kravetz 			 * pages in this range were added to the reserve
482233039678SMike Kravetz 			 * map between region_chg and region_add.  This
482333039678SMike Kravetz 			 * indicates a race with alloc_huge_page.  Adjust
482433039678SMike Kravetz 			 * the subpool and reserve counts modified above
482533039678SMike Kravetz 			 * based on the difference.
482633039678SMike Kravetz 			 */
482733039678SMike Kravetz 			long rsv_adjust;
482833039678SMike Kravetz 
482933039678SMike Kravetz 			rsv_adjust = hugepage_subpool_put_pages(spool,
483033039678SMike Kravetz 								chg - add);
483133039678SMike Kravetz 			hugetlb_acct_memory(h, -rsv_adjust);
483233039678SMike Kravetz 		}
483333039678SMike Kravetz 	}
4834a43a8c39SChen, Kenneth W 	return 0;
4835c50ac050SDave Hansen out_err:
48365e911373SMike Kravetz 	if (!vma || vma->vm_flags & VM_MAYSHARE)
4837ff8c0c53SMike Kravetz 		/* Don't call region_abort if region_chg failed */
4838ff8c0c53SMike Kravetz 		if (chg >= 0)
48395e911373SMike Kravetz 			region_abort(resv_map, from, to);
4840f031dd27SJoonsoo Kim 	if (vma && is_vma_resv_set(vma, HPAGE_RESV_OWNER))
4841f031dd27SJoonsoo Kim 		kref_put(&resv_map->refs, resv_map_release);
4842c50ac050SDave Hansen 	return ret;
4843a43a8c39SChen, Kenneth W }
4844a43a8c39SChen, Kenneth W 
4845b5cec28dSMike Kravetz long hugetlb_unreserve_pages(struct inode *inode, long start, long end,
4846b5cec28dSMike Kravetz 								long freed)
4847a43a8c39SChen, Kenneth W {
4848a5516438SAndi Kleen 	struct hstate *h = hstate_inode(inode);
48494e35f483SJoonsoo Kim 	struct resv_map *resv_map = inode_resv_map(inode);
48509119a41eSJoonsoo Kim 	long chg = 0;
485190481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_inode(inode);
48521c5ecae3SMike Kravetz 	long gbl_reserve;
485345c682a6SKen Chen 
4854f27a5136SMike Kravetz 	/*
4855f27a5136SMike Kravetz 	 * Since this routine can be called in the evict inode path for all
4856f27a5136SMike Kravetz 	 * hugetlbfs inodes, resv_map could be NULL.
4857f27a5136SMike Kravetz 	 */
4858b5cec28dSMike Kravetz 	if (resv_map) {
4859b5cec28dSMike Kravetz 		chg = region_del(resv_map, start, end);
4860b5cec28dSMike Kravetz 		/*
4861b5cec28dSMike Kravetz 		 * region_del() can fail in the rare case where a region
4862b5cec28dSMike Kravetz 		 * must be split and another region descriptor can not be
4863b5cec28dSMike Kravetz 		 * allocated.  If end == LONG_MAX, it will not fail.
4864b5cec28dSMike Kravetz 		 */
4865b5cec28dSMike Kravetz 		if (chg < 0)
4866b5cec28dSMike Kravetz 			return chg;
4867b5cec28dSMike Kravetz 	}
4868b5cec28dSMike Kravetz 
486945c682a6SKen Chen 	spin_lock(&inode->i_lock);
4870e4c6f8beSEric Sandeen 	inode->i_blocks -= (blocks_per_huge_page(h) * freed);
487145c682a6SKen Chen 	spin_unlock(&inode->i_lock);
487245c682a6SKen Chen 
48731c5ecae3SMike Kravetz 	/*
48741c5ecae3SMike Kravetz 	 * If the subpool has a minimum size, the number of global
48751c5ecae3SMike Kravetz 	 * reservations to be released may be adjusted.
48761c5ecae3SMike Kravetz 	 */
48771c5ecae3SMike Kravetz 	gbl_reserve = hugepage_subpool_put_pages(spool, (chg - freed));
48781c5ecae3SMike Kravetz 	hugetlb_acct_memory(h, -gbl_reserve);
4879b5cec28dSMike Kravetz 
4880b5cec28dSMike Kravetz 	return 0;
4881a43a8c39SChen, Kenneth W }
488293f70f90SNaoya Horiguchi 
48833212b535SSteve Capper #ifdef CONFIG_ARCH_WANT_HUGE_PMD_SHARE
48843212b535SSteve Capper static unsigned long page_table_shareable(struct vm_area_struct *svma,
48853212b535SSteve Capper 				struct vm_area_struct *vma,
48863212b535SSteve Capper 				unsigned long addr, pgoff_t idx)
48873212b535SSteve Capper {
48883212b535SSteve Capper 	unsigned long saddr = ((idx - svma->vm_pgoff) << PAGE_SHIFT) +
48893212b535SSteve Capper 				svma->vm_start;
48903212b535SSteve Capper 	unsigned long sbase = saddr & PUD_MASK;
48913212b535SSteve Capper 	unsigned long s_end = sbase + PUD_SIZE;
48923212b535SSteve Capper 
48933212b535SSteve Capper 	/* Allow segments to share if only one is marked locked */
4894de60f5f1SEric B Munson 	unsigned long vm_flags = vma->vm_flags & VM_LOCKED_CLEAR_MASK;
4895de60f5f1SEric B Munson 	unsigned long svm_flags = svma->vm_flags & VM_LOCKED_CLEAR_MASK;
48963212b535SSteve Capper 
48973212b535SSteve Capper 	/*
48983212b535SSteve Capper 	 * match the virtual addresses, permission and the alignment of the
48993212b535SSteve Capper 	 * page table page.
49003212b535SSteve Capper 	 */
49013212b535SSteve Capper 	if (pmd_index(addr) != pmd_index(saddr) ||
49023212b535SSteve Capper 	    vm_flags != svm_flags ||
49033212b535SSteve Capper 	    sbase < svma->vm_start || svma->vm_end < s_end)
49043212b535SSteve Capper 		return 0;
49053212b535SSteve Capper 
49063212b535SSteve Capper 	return saddr;
49073212b535SSteve Capper }
49083212b535SSteve Capper 
490931aafb45SNicholas Krause static bool vma_shareable(struct vm_area_struct *vma, unsigned long addr)
49103212b535SSteve Capper {
49113212b535SSteve Capper 	unsigned long base = addr & PUD_MASK;
49123212b535SSteve Capper 	unsigned long end = base + PUD_SIZE;
49133212b535SSteve Capper 
49143212b535SSteve Capper 	/*
49153212b535SSteve Capper 	 * check on proper vm_flags and page table alignment
49163212b535SSteve Capper 	 */
4917017b1660SMike Kravetz 	if (vma->vm_flags & VM_MAYSHARE && range_in_vma(vma, base, end))
491831aafb45SNicholas Krause 		return true;
491931aafb45SNicholas Krause 	return false;
49203212b535SSteve Capper }
49213212b535SSteve Capper 
49223212b535SSteve Capper /*
4923017b1660SMike Kravetz  * Determine if start,end range within vma could be mapped by shared pmd.
4924017b1660SMike Kravetz  * If yes, adjust start and end to cover range associated with possible
4925017b1660SMike Kravetz  * shared pmd mappings.
4926017b1660SMike Kravetz  */
4927017b1660SMike Kravetz void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
4928017b1660SMike Kravetz 				unsigned long *start, unsigned long *end)
4929017b1660SMike Kravetz {
4930017b1660SMike Kravetz 	unsigned long check_addr = *start;
4931017b1660SMike Kravetz 
4932017b1660SMike Kravetz 	if (!(vma->vm_flags & VM_MAYSHARE))
4933017b1660SMike Kravetz 		return;
4934017b1660SMike Kravetz 
4935017b1660SMike Kravetz 	for (check_addr = *start; check_addr < *end; check_addr += PUD_SIZE) {
4936017b1660SMike Kravetz 		unsigned long a_start = check_addr & PUD_MASK;
4937017b1660SMike Kravetz 		unsigned long a_end = a_start + PUD_SIZE;
4938017b1660SMike Kravetz 
4939017b1660SMike Kravetz 		/*
4940017b1660SMike Kravetz 		 * If sharing is possible, adjust start/end if necessary.
4941017b1660SMike Kravetz 		 */
4942017b1660SMike Kravetz 		if (range_in_vma(vma, a_start, a_end)) {
4943017b1660SMike Kravetz 			if (a_start < *start)
4944017b1660SMike Kravetz 				*start = a_start;
4945017b1660SMike Kravetz 			if (a_end > *end)
4946017b1660SMike Kravetz 				*end = a_end;
4947017b1660SMike Kravetz 		}
4948017b1660SMike Kravetz 	}
4949017b1660SMike Kravetz }
4950017b1660SMike Kravetz 
4951017b1660SMike Kravetz /*
49523212b535SSteve Capper  * Search for a shareable pmd page for hugetlb. In any case calls pmd_alloc()
49533212b535SSteve Capper  * and returns the corresponding pte. While this is not necessary for the
49543212b535SSteve Capper  * !shared pmd case because we can allocate the pmd later as well, it makes the
4955c0d0381aSMike Kravetz  * code much cleaner.
4956c0d0381aSMike Kravetz  *
4957c0d0381aSMike Kravetz  * This routine must be called with i_mmap_rwsem held in at least read mode.
4958c0d0381aSMike Kravetz  * For hugetlbfs, this prevents removal of any page table entries associated
4959c0d0381aSMike Kravetz  * with the address space.  This is important as we are setting up sharing
4960c0d0381aSMike Kravetz  * based on existing page table entries (mappings).
49613212b535SSteve Capper  */
49623212b535SSteve Capper pte_t *huge_pmd_share(struct mm_struct *mm, unsigned long addr, pud_t *pud)
49633212b535SSteve Capper {
49643212b535SSteve Capper 	struct vm_area_struct *vma = find_vma(mm, addr);
49653212b535SSteve Capper 	struct address_space *mapping = vma->vm_file->f_mapping;
49663212b535SSteve Capper 	pgoff_t idx = ((addr - vma->vm_start) >> PAGE_SHIFT) +
49673212b535SSteve Capper 			vma->vm_pgoff;
49683212b535SSteve Capper 	struct vm_area_struct *svma;
49693212b535SSteve Capper 	unsigned long saddr;
49703212b535SSteve Capper 	pte_t *spte = NULL;
49713212b535SSteve Capper 	pte_t *pte;
4972cb900f41SKirill A. Shutemov 	spinlock_t *ptl;
49733212b535SSteve Capper 
49743212b535SSteve Capper 	if (!vma_shareable(vma, addr))
49753212b535SSteve Capper 		return (pte_t *)pmd_alloc(mm, pud, addr);
49763212b535SSteve Capper 
49773212b535SSteve Capper 	vma_interval_tree_foreach(svma, &mapping->i_mmap, idx, idx) {
49783212b535SSteve Capper 		if (svma == vma)
49793212b535SSteve Capper 			continue;
49803212b535SSteve Capper 
49813212b535SSteve Capper 		saddr = page_table_shareable(svma, vma, addr, idx);
49823212b535SSteve Capper 		if (saddr) {
49837868a208SPunit Agrawal 			spte = huge_pte_offset(svma->vm_mm, saddr,
49847868a208SPunit Agrawal 					       vma_mmu_pagesize(svma));
49853212b535SSteve Capper 			if (spte) {
49863212b535SSteve Capper 				get_page(virt_to_page(spte));
49873212b535SSteve Capper 				break;
49883212b535SSteve Capper 			}
49893212b535SSteve Capper 		}
49903212b535SSteve Capper 	}
49913212b535SSteve Capper 
49923212b535SSteve Capper 	if (!spte)
49933212b535SSteve Capper 		goto out;
49943212b535SSteve Capper 
49958bea8052SAneesh Kumar K.V 	ptl = huge_pte_lock(hstate_vma(vma), mm, spte);
4996dc6c9a35SKirill A. Shutemov 	if (pud_none(*pud)) {
49973212b535SSteve Capper 		pud_populate(mm, pud,
49983212b535SSteve Capper 				(pmd_t *)((unsigned long)spte & PAGE_MASK));
4999c17b1f42SKirill A. Shutemov 		mm_inc_nr_pmds(mm);
5000dc6c9a35SKirill A. Shutemov 	} else {
50013212b535SSteve Capper 		put_page(virt_to_page(spte));
5002dc6c9a35SKirill A. Shutemov 	}
5003cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
50043212b535SSteve Capper out:
50053212b535SSteve Capper 	pte = (pte_t *)pmd_alloc(mm, pud, addr);
50063212b535SSteve Capper 	return pte;
50073212b535SSteve Capper }
50083212b535SSteve Capper 
50093212b535SSteve Capper /*
50103212b535SSteve Capper  * unmap huge page backed by shared pte.
50113212b535SSteve Capper  *
50123212b535SSteve Capper  * Hugetlb pte page is ref counted at the time of mapping.  If pte is shared
50133212b535SSteve Capper  * indicated by page_count > 1, unmap is achieved by clearing pud and
50143212b535SSteve Capper  * decrementing the ref count. If count == 1, the pte page is not shared.
50153212b535SSteve Capper  *
5016c0d0381aSMike Kravetz  * Called with page table lock held and i_mmap_rwsem held in write mode.
50173212b535SSteve Capper  *
50183212b535SSteve Capper  * returns: 1 successfully unmapped a shared pte page
50193212b535SSteve Capper  *	    0 the underlying pte page is not shared, or it is the last user
50203212b535SSteve Capper  */
50213212b535SSteve Capper int huge_pmd_unshare(struct mm_struct *mm, unsigned long *addr, pte_t *ptep)
50223212b535SSteve Capper {
50233212b535SSteve Capper 	pgd_t *pgd = pgd_offset(mm, *addr);
5024c2febafcSKirill A. Shutemov 	p4d_t *p4d = p4d_offset(pgd, *addr);
5025c2febafcSKirill A. Shutemov 	pud_t *pud = pud_offset(p4d, *addr);
50263212b535SSteve Capper 
50273212b535SSteve Capper 	BUG_ON(page_count(virt_to_page(ptep)) == 0);
50283212b535SSteve Capper 	if (page_count(virt_to_page(ptep)) == 1)
50293212b535SSteve Capper 		return 0;
50303212b535SSteve Capper 
50313212b535SSteve Capper 	pud_clear(pud);
50323212b535SSteve Capper 	put_page(virt_to_page(ptep));
5033dc6c9a35SKirill A. Shutemov 	mm_dec_nr_pmds(mm);
50343212b535SSteve Capper 	*addr = ALIGN(*addr, HPAGE_SIZE * PTRS_PER_PTE) - HPAGE_SIZE;
50353212b535SSteve Capper 	return 1;
50363212b535SSteve Capper }
50379e5fc74cSSteve Capper #define want_pmd_share()	(1)
50389e5fc74cSSteve Capper #else /* !CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
50399e5fc74cSSteve Capper pte_t *huge_pmd_share(struct mm_struct *mm, unsigned long addr, pud_t *pud)
50409e5fc74cSSteve Capper {
50419e5fc74cSSteve Capper 	return NULL;
50429e5fc74cSSteve Capper }
5043e81f2d22SZhang Zhen 
5044e81f2d22SZhang Zhen int huge_pmd_unshare(struct mm_struct *mm, unsigned long *addr, pte_t *ptep)
5045e81f2d22SZhang Zhen {
5046e81f2d22SZhang Zhen 	return 0;
5047e81f2d22SZhang Zhen }
5048017b1660SMike Kravetz 
5049017b1660SMike Kravetz void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
5050017b1660SMike Kravetz 				unsigned long *start, unsigned long *end)
5051017b1660SMike Kravetz {
5052017b1660SMike Kravetz }
50539e5fc74cSSteve Capper #define want_pmd_share()	(0)
50543212b535SSteve Capper #endif /* CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
50553212b535SSteve Capper 
50569e5fc74cSSteve Capper #ifdef CONFIG_ARCH_WANT_GENERAL_HUGETLB
50579e5fc74cSSteve Capper pte_t *huge_pte_alloc(struct mm_struct *mm,
50589e5fc74cSSteve Capper 			unsigned long addr, unsigned long sz)
50599e5fc74cSSteve Capper {
50609e5fc74cSSteve Capper 	pgd_t *pgd;
5061c2febafcSKirill A. Shutemov 	p4d_t *p4d;
50629e5fc74cSSteve Capper 	pud_t *pud;
50639e5fc74cSSteve Capper 	pte_t *pte = NULL;
50649e5fc74cSSteve Capper 
50659e5fc74cSSteve Capper 	pgd = pgd_offset(mm, addr);
5066f4f0a3d8SKirill A. Shutemov 	p4d = p4d_alloc(mm, pgd, addr);
5067f4f0a3d8SKirill A. Shutemov 	if (!p4d)
5068f4f0a3d8SKirill A. Shutemov 		return NULL;
5069c2febafcSKirill A. Shutemov 	pud = pud_alloc(mm, p4d, addr);
50709e5fc74cSSteve Capper 	if (pud) {
50719e5fc74cSSteve Capper 		if (sz == PUD_SIZE) {
50729e5fc74cSSteve Capper 			pte = (pte_t *)pud;
50739e5fc74cSSteve Capper 		} else {
50749e5fc74cSSteve Capper 			BUG_ON(sz != PMD_SIZE);
50759e5fc74cSSteve Capper 			if (want_pmd_share() && pud_none(*pud))
50769e5fc74cSSteve Capper 				pte = huge_pmd_share(mm, addr, pud);
50779e5fc74cSSteve Capper 			else
50789e5fc74cSSteve Capper 				pte = (pte_t *)pmd_alloc(mm, pud, addr);
50799e5fc74cSSteve Capper 		}
50809e5fc74cSSteve Capper 	}
50814e666314SMichal Hocko 	BUG_ON(pte && pte_present(*pte) && !pte_huge(*pte));
50829e5fc74cSSteve Capper 
50839e5fc74cSSteve Capper 	return pte;
50849e5fc74cSSteve Capper }
50859e5fc74cSSteve Capper 
50869b19df29SPunit Agrawal /*
50879b19df29SPunit Agrawal  * huge_pte_offset() - Walk the page table to resolve the hugepage
50889b19df29SPunit Agrawal  * entry at address @addr
50899b19df29SPunit Agrawal  *
50909b19df29SPunit Agrawal  * Return: Pointer to page table or swap entry (PUD or PMD) for
50919b19df29SPunit Agrawal  * address @addr, or NULL if a p*d_none() entry is encountered and the
50929b19df29SPunit Agrawal  * size @sz doesn't match the hugepage size at this level of the page
50939b19df29SPunit Agrawal  * table.
50949b19df29SPunit Agrawal  */
50957868a208SPunit Agrawal pte_t *huge_pte_offset(struct mm_struct *mm,
50967868a208SPunit Agrawal 		       unsigned long addr, unsigned long sz)
50979e5fc74cSSteve Capper {
50989e5fc74cSSteve Capper 	pgd_t *pgd;
5099c2febafcSKirill A. Shutemov 	p4d_t *p4d;
51009e5fc74cSSteve Capper 	pud_t *pud;
5101c2febafcSKirill A. Shutemov 	pmd_t *pmd;
51029e5fc74cSSteve Capper 
51039e5fc74cSSteve Capper 	pgd = pgd_offset(mm, addr);
5104c2febafcSKirill A. Shutemov 	if (!pgd_present(*pgd))
5105c2febafcSKirill A. Shutemov 		return NULL;
5106c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, addr);
5107c2febafcSKirill A. Shutemov 	if (!p4d_present(*p4d))
5108c2febafcSKirill A. Shutemov 		return NULL;
51099b19df29SPunit Agrawal 
5110c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, addr);
51119b19df29SPunit Agrawal 	if (sz != PUD_SIZE && pud_none(*pud))
5112c2febafcSKirill A. Shutemov 		return NULL;
51139b19df29SPunit Agrawal 	/* hugepage or swap? */
51149b19df29SPunit Agrawal 	if (pud_huge(*pud) || !pud_present(*pud))
51159e5fc74cSSteve Capper 		return (pte_t *)pud;
51169b19df29SPunit Agrawal 
51179e5fc74cSSteve Capper 	pmd = pmd_offset(pud, addr);
51189b19df29SPunit Agrawal 	if (sz != PMD_SIZE && pmd_none(*pmd))
51199b19df29SPunit Agrawal 		return NULL;
51209b19df29SPunit Agrawal 	/* hugepage or swap? */
51219b19df29SPunit Agrawal 	if (pmd_huge(*pmd) || !pmd_present(*pmd))
51229e5fc74cSSteve Capper 		return (pte_t *)pmd;
51239b19df29SPunit Agrawal 
51249b19df29SPunit Agrawal 	return NULL;
51259e5fc74cSSteve Capper }
51269e5fc74cSSteve Capper 
512761f77edaSNaoya Horiguchi #endif /* CONFIG_ARCH_WANT_GENERAL_HUGETLB */
512861f77edaSNaoya Horiguchi 
512961f77edaSNaoya Horiguchi /*
513061f77edaSNaoya Horiguchi  * These functions are overwritable if your architecture needs its own
513161f77edaSNaoya Horiguchi  * behavior.
513261f77edaSNaoya Horiguchi  */
513361f77edaSNaoya Horiguchi struct page * __weak
513461f77edaSNaoya Horiguchi follow_huge_addr(struct mm_struct *mm, unsigned long address,
513561f77edaSNaoya Horiguchi 			      int write)
513661f77edaSNaoya Horiguchi {
513761f77edaSNaoya Horiguchi 	return ERR_PTR(-EINVAL);
513861f77edaSNaoya Horiguchi }
513961f77edaSNaoya Horiguchi 
514061f77edaSNaoya Horiguchi struct page * __weak
51414dc71451SAneesh Kumar K.V follow_huge_pd(struct vm_area_struct *vma,
51424dc71451SAneesh Kumar K.V 	       unsigned long address, hugepd_t hpd, int flags, int pdshift)
51434dc71451SAneesh Kumar K.V {
51444dc71451SAneesh Kumar K.V 	WARN(1, "hugepd follow called with no support for hugepage directory format\n");
51454dc71451SAneesh Kumar K.V 	return NULL;
51464dc71451SAneesh Kumar K.V }
51474dc71451SAneesh Kumar K.V 
51484dc71451SAneesh Kumar K.V struct page * __weak
51499e5fc74cSSteve Capper follow_huge_pmd(struct mm_struct *mm, unsigned long address,
5150e66f17ffSNaoya Horiguchi 		pmd_t *pmd, int flags)
51519e5fc74cSSteve Capper {
5152e66f17ffSNaoya Horiguchi 	struct page *page = NULL;
5153e66f17ffSNaoya Horiguchi 	spinlock_t *ptl;
5154c9d398faSNaoya Horiguchi 	pte_t pte;
51553faa52c0SJohn Hubbard 
51563faa52c0SJohn Hubbard 	/* FOLL_GET and FOLL_PIN are mutually exclusive. */
51573faa52c0SJohn Hubbard 	if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
51583faa52c0SJohn Hubbard 			 (FOLL_PIN | FOLL_GET)))
51593faa52c0SJohn Hubbard 		return NULL;
51603faa52c0SJohn Hubbard 
5161e66f17ffSNaoya Horiguchi retry:
5162e66f17ffSNaoya Horiguchi 	ptl = pmd_lockptr(mm, pmd);
5163e66f17ffSNaoya Horiguchi 	spin_lock(ptl);
5164e66f17ffSNaoya Horiguchi 	/*
5165e66f17ffSNaoya Horiguchi 	 * make sure that the address range covered by this pmd is not
5166e66f17ffSNaoya Horiguchi 	 * unmapped from other threads.
5167e66f17ffSNaoya Horiguchi 	 */
5168e66f17ffSNaoya Horiguchi 	if (!pmd_huge(*pmd))
5169e66f17ffSNaoya Horiguchi 		goto out;
5170c9d398faSNaoya Horiguchi 	pte = huge_ptep_get((pte_t *)pmd);
5171c9d398faSNaoya Horiguchi 	if (pte_present(pte)) {
517297534127SGerald Schaefer 		page = pmd_page(*pmd) + ((address & ~PMD_MASK) >> PAGE_SHIFT);
51733faa52c0SJohn Hubbard 		/*
51743faa52c0SJohn Hubbard 		 * try_grab_page() should always succeed here, because: a) we
51753faa52c0SJohn Hubbard 		 * hold the pmd (ptl) lock, and b) we've just checked that the
51763faa52c0SJohn Hubbard 		 * huge pmd (head) page is present in the page tables. The ptl
51773faa52c0SJohn Hubbard 		 * prevents the head page and tail pages from being rearranged
51783faa52c0SJohn Hubbard 		 * in any way. So this page must be available at this point,
51793faa52c0SJohn Hubbard 		 * unless the page refcount overflowed:
51803faa52c0SJohn Hubbard 		 */
51813faa52c0SJohn Hubbard 		if (WARN_ON_ONCE(!try_grab_page(page, flags))) {
51823faa52c0SJohn Hubbard 			page = NULL;
51833faa52c0SJohn Hubbard 			goto out;
51843faa52c0SJohn Hubbard 		}
5185e66f17ffSNaoya Horiguchi 	} else {
5186c9d398faSNaoya Horiguchi 		if (is_hugetlb_entry_migration(pte)) {
5187e66f17ffSNaoya Horiguchi 			spin_unlock(ptl);
5188e66f17ffSNaoya Horiguchi 			__migration_entry_wait(mm, (pte_t *)pmd, ptl);
5189e66f17ffSNaoya Horiguchi 			goto retry;
5190e66f17ffSNaoya Horiguchi 		}
5191e66f17ffSNaoya Horiguchi 		/*
5192e66f17ffSNaoya Horiguchi 		 * hwpoisoned entry is treated as no_page_table in
5193e66f17ffSNaoya Horiguchi 		 * follow_page_mask().
5194e66f17ffSNaoya Horiguchi 		 */
5195e66f17ffSNaoya Horiguchi 	}
5196e66f17ffSNaoya Horiguchi out:
5197e66f17ffSNaoya Horiguchi 	spin_unlock(ptl);
51989e5fc74cSSteve Capper 	return page;
51999e5fc74cSSteve Capper }
52009e5fc74cSSteve Capper 
520161f77edaSNaoya Horiguchi struct page * __weak
52029e5fc74cSSteve Capper follow_huge_pud(struct mm_struct *mm, unsigned long address,
5203e66f17ffSNaoya Horiguchi 		pud_t *pud, int flags)
52049e5fc74cSSteve Capper {
52053faa52c0SJohn Hubbard 	if (flags & (FOLL_GET | FOLL_PIN))
5206e66f17ffSNaoya Horiguchi 		return NULL;
52079e5fc74cSSteve Capper 
5208e66f17ffSNaoya Horiguchi 	return pte_page(*(pte_t *)pud) + ((address & ~PUD_MASK) >> PAGE_SHIFT);
52099e5fc74cSSteve Capper }
52109e5fc74cSSteve Capper 
5211faaa5b62SAnshuman Khandual struct page * __weak
5212faaa5b62SAnshuman Khandual follow_huge_pgd(struct mm_struct *mm, unsigned long address, pgd_t *pgd, int flags)
5213faaa5b62SAnshuman Khandual {
52143faa52c0SJohn Hubbard 	if (flags & (FOLL_GET | FOLL_PIN))
5215faaa5b62SAnshuman Khandual 		return NULL;
5216faaa5b62SAnshuman Khandual 
5217faaa5b62SAnshuman Khandual 	return pte_page(*(pte_t *)pgd) + ((address & ~PGDIR_MASK) >> PAGE_SHIFT);
5218faaa5b62SAnshuman Khandual }
5219faaa5b62SAnshuman Khandual 
522031caf665SNaoya Horiguchi bool isolate_huge_page(struct page *page, struct list_head *list)
522131caf665SNaoya Horiguchi {
5222bcc54222SNaoya Horiguchi 	bool ret = true;
5223bcc54222SNaoya Horiguchi 
5224309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageHead(page), page);
522531caf665SNaoya Horiguchi 	spin_lock(&hugetlb_lock);
5226bcc54222SNaoya Horiguchi 	if (!page_huge_active(page) || !get_page_unless_zero(page)) {
5227bcc54222SNaoya Horiguchi 		ret = false;
5228bcc54222SNaoya Horiguchi 		goto unlock;
5229bcc54222SNaoya Horiguchi 	}
5230bcc54222SNaoya Horiguchi 	clear_page_huge_active(page);
523131caf665SNaoya Horiguchi 	list_move_tail(&page->lru, list);
5232bcc54222SNaoya Horiguchi unlock:
523331caf665SNaoya Horiguchi 	spin_unlock(&hugetlb_lock);
5234bcc54222SNaoya Horiguchi 	return ret;
523531caf665SNaoya Horiguchi }
523631caf665SNaoya Horiguchi 
523731caf665SNaoya Horiguchi void putback_active_hugepage(struct page *page)
523831caf665SNaoya Horiguchi {
5239309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageHead(page), page);
524031caf665SNaoya Horiguchi 	spin_lock(&hugetlb_lock);
5241bcc54222SNaoya Horiguchi 	set_page_huge_active(page);
524231caf665SNaoya Horiguchi 	list_move_tail(&page->lru, &(page_hstate(page))->hugepage_activelist);
524331caf665SNaoya Horiguchi 	spin_unlock(&hugetlb_lock);
524431caf665SNaoya Horiguchi 	put_page(page);
524531caf665SNaoya Horiguchi }
5246ab5ac90aSMichal Hocko 
5247ab5ac90aSMichal Hocko void move_hugetlb_state(struct page *oldpage, struct page *newpage, int reason)
5248ab5ac90aSMichal Hocko {
5249ab5ac90aSMichal Hocko 	struct hstate *h = page_hstate(oldpage);
5250ab5ac90aSMichal Hocko 
5251ab5ac90aSMichal Hocko 	hugetlb_cgroup_migrate(oldpage, newpage);
5252ab5ac90aSMichal Hocko 	set_page_owner_migrate_reason(newpage, reason);
5253ab5ac90aSMichal Hocko 
5254ab5ac90aSMichal Hocko 	/*
5255ab5ac90aSMichal Hocko 	 * transfer temporary state of the new huge page. This is
5256ab5ac90aSMichal Hocko 	 * reverse to other transitions because the newpage is going to
5257ab5ac90aSMichal Hocko 	 * be final while the old one will be freed so it takes over
5258ab5ac90aSMichal Hocko 	 * the temporary status.
5259ab5ac90aSMichal Hocko 	 *
5260ab5ac90aSMichal Hocko 	 * Also note that we have to transfer the per-node surplus state
5261ab5ac90aSMichal Hocko 	 * here as well otherwise the global surplus count will not match
5262ab5ac90aSMichal Hocko 	 * the per-node's.
5263ab5ac90aSMichal Hocko 	 */
5264ab5ac90aSMichal Hocko 	if (PageHugeTemporary(newpage)) {
5265ab5ac90aSMichal Hocko 		int old_nid = page_to_nid(oldpage);
5266ab5ac90aSMichal Hocko 		int new_nid = page_to_nid(newpage);
5267ab5ac90aSMichal Hocko 
5268ab5ac90aSMichal Hocko 		SetPageHugeTemporary(oldpage);
5269ab5ac90aSMichal Hocko 		ClearPageHugeTemporary(newpage);
5270ab5ac90aSMichal Hocko 
5271ab5ac90aSMichal Hocko 		spin_lock(&hugetlb_lock);
5272ab5ac90aSMichal Hocko 		if (h->surplus_huge_pages_node[old_nid]) {
5273ab5ac90aSMichal Hocko 			h->surplus_huge_pages_node[old_nid]--;
5274ab5ac90aSMichal Hocko 			h->surplus_huge_pages_node[new_nid]++;
5275ab5ac90aSMichal Hocko 		}
5276ab5ac90aSMichal Hocko 		spin_unlock(&hugetlb_lock);
5277ab5ac90aSMichal Hocko 	}
5278ab5ac90aSMichal Hocko }
5279