xref: /openbmc/linux/mm/hugetlb.c (revision 9fee021d)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  * Generic hugetlb support.
36d49e352SNadia Yvette Chambers  * (C) Nadia Yvette Chambers, April 2004
41da177e4SLinus Torvalds  */
51da177e4SLinus Torvalds #include <linux/list.h>
61da177e4SLinus Torvalds #include <linux/init.h>
71da177e4SLinus Torvalds #include <linux/mm.h>
8e1759c21SAlexey Dobriyan #include <linux/seq_file.h>
91da177e4SLinus Torvalds #include <linux/sysctl.h>
101da177e4SLinus Torvalds #include <linux/highmem.h>
11cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
121da177e4SLinus Torvalds #include <linux/nodemask.h>
1363551ae0SDavid Gibson #include <linux/pagemap.h>
145da7ca86SChristoph Lameter #include <linux/mempolicy.h>
153b32123dSGideon Israel Dsouza #include <linux/compiler.h>
16aea47ff3SChristoph Lameter #include <linux/cpuset.h>
173935baa9SDavid Gibson #include <linux/mutex.h>
18aa888a74SAndi Kleen #include <linux/bootmem.h>
19a3437870SNishanth Aravamudan #include <linux/sysfs.h>
205a0e3ad6STejun Heo #include <linux/slab.h>
210fe6e20bSNaoya Horiguchi #include <linux/rmap.h>
22fd6a03edSNaoya Horiguchi #include <linux/swap.h>
23fd6a03edSNaoya Horiguchi #include <linux/swapops.h>
24c8721bbbSNaoya Horiguchi #include <linux/page-isolation.h>
258382d914SDavidlohr Bueso #include <linux/jhash.h>
26d6606683SLinus Torvalds 
2763551ae0SDavid Gibson #include <asm/page.h>
2863551ae0SDavid Gibson #include <asm/pgtable.h>
2924669e58SAneesh Kumar K.V #include <asm/tlb.h>
3063551ae0SDavid Gibson 
3124669e58SAneesh Kumar K.V #include <linux/io.h>
3263551ae0SDavid Gibson #include <linux/hugetlb.h>
339dd540e2SAneesh Kumar K.V #include <linux/hugetlb_cgroup.h>
349a305230SLee Schermerhorn #include <linux/node.h>
357835e98bSNick Piggin #include "internal.h"
361da177e4SLinus Torvalds 
37753162cdSAndrey Ryabinin int hugepages_treat_as_movable;
38a5516438SAndi Kleen 
39c3f38a38SAneesh Kumar K.V int hugetlb_max_hstate __read_mostly;
40e5ff2159SAndi Kleen unsigned int default_hstate_idx;
41e5ff2159SAndi Kleen struct hstate hstates[HUGE_MAX_HSTATE];
42641844f5SNaoya Horiguchi /*
43641844f5SNaoya Horiguchi  * Minimum page order among possible hugepage sizes, set to a proper value
44641844f5SNaoya Horiguchi  * at boot time.
45641844f5SNaoya Horiguchi  */
46641844f5SNaoya Horiguchi static unsigned int minimum_order __read_mostly = UINT_MAX;
47e5ff2159SAndi Kleen 
4853ba51d2SJon Tollefson __initdata LIST_HEAD(huge_boot_pages);
4953ba51d2SJon Tollefson 
50e5ff2159SAndi Kleen /* for command line parsing */
51e5ff2159SAndi Kleen static struct hstate * __initdata parsed_hstate;
52e5ff2159SAndi Kleen static unsigned long __initdata default_hstate_max_huge_pages;
53e11bfbfcSNick Piggin static unsigned long __initdata default_hstate_size;
549fee021dSVaishali Thakkar static bool __initdata parsed_valid_hugepagesz = true;
55e5ff2159SAndi Kleen 
563935baa9SDavid Gibson /*
5731caf665SNaoya Horiguchi  * Protects updates to hugepage_freelists, hugepage_activelist, nr_huge_pages,
5831caf665SNaoya Horiguchi  * free_huge_pages, and surplus_huge_pages.
593935baa9SDavid Gibson  */
60c3f38a38SAneesh Kumar K.V DEFINE_SPINLOCK(hugetlb_lock);
610bd0f9fbSEric Paris 
628382d914SDavidlohr Bueso /*
638382d914SDavidlohr Bueso  * Serializes faults on the same logical page.  This is used to
648382d914SDavidlohr Bueso  * prevent spurious OOMs when the hugepage pool is fully utilized.
658382d914SDavidlohr Bueso  */
668382d914SDavidlohr Bueso static int num_fault_mutexes;
67c672c7f2SMike Kravetz struct mutex *hugetlb_fault_mutex_table ____cacheline_aligned_in_smp;
688382d914SDavidlohr Bueso 
697ca02d0aSMike Kravetz /* Forward declaration */
707ca02d0aSMike Kravetz static int hugetlb_acct_memory(struct hstate *h, long delta);
717ca02d0aSMike Kravetz 
7290481622SDavid Gibson static inline void unlock_or_release_subpool(struct hugepage_subpool *spool)
7390481622SDavid Gibson {
7490481622SDavid Gibson 	bool free = (spool->count == 0) && (spool->used_hpages == 0);
7590481622SDavid Gibson 
7690481622SDavid Gibson 	spin_unlock(&spool->lock);
7790481622SDavid Gibson 
7890481622SDavid Gibson 	/* If no pages are used, and no other handles to the subpool
797ca02d0aSMike Kravetz 	 * remain, give up any reservations mased on minimum size and
807ca02d0aSMike Kravetz 	 * free the subpool */
817ca02d0aSMike Kravetz 	if (free) {
827ca02d0aSMike Kravetz 		if (spool->min_hpages != -1)
837ca02d0aSMike Kravetz 			hugetlb_acct_memory(spool->hstate,
847ca02d0aSMike Kravetz 						-spool->min_hpages);
8590481622SDavid Gibson 		kfree(spool);
8690481622SDavid Gibson 	}
877ca02d0aSMike Kravetz }
8890481622SDavid Gibson 
897ca02d0aSMike Kravetz struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages,
907ca02d0aSMike Kravetz 						long min_hpages)
9190481622SDavid Gibson {
9290481622SDavid Gibson 	struct hugepage_subpool *spool;
9390481622SDavid Gibson 
94c6a91820SMike Kravetz 	spool = kzalloc(sizeof(*spool), GFP_KERNEL);
9590481622SDavid Gibson 	if (!spool)
9690481622SDavid Gibson 		return NULL;
9790481622SDavid Gibson 
9890481622SDavid Gibson 	spin_lock_init(&spool->lock);
9990481622SDavid Gibson 	spool->count = 1;
1007ca02d0aSMike Kravetz 	spool->max_hpages = max_hpages;
1017ca02d0aSMike Kravetz 	spool->hstate = h;
1027ca02d0aSMike Kravetz 	spool->min_hpages = min_hpages;
1037ca02d0aSMike Kravetz 
1047ca02d0aSMike Kravetz 	if (min_hpages != -1 && hugetlb_acct_memory(h, min_hpages)) {
1057ca02d0aSMike Kravetz 		kfree(spool);
1067ca02d0aSMike Kravetz 		return NULL;
1077ca02d0aSMike Kravetz 	}
1087ca02d0aSMike Kravetz 	spool->rsv_hpages = min_hpages;
10990481622SDavid Gibson 
11090481622SDavid Gibson 	return spool;
11190481622SDavid Gibson }
11290481622SDavid Gibson 
11390481622SDavid Gibson void hugepage_put_subpool(struct hugepage_subpool *spool)
11490481622SDavid Gibson {
11590481622SDavid Gibson 	spin_lock(&spool->lock);
11690481622SDavid Gibson 	BUG_ON(!spool->count);
11790481622SDavid Gibson 	spool->count--;
11890481622SDavid Gibson 	unlock_or_release_subpool(spool);
11990481622SDavid Gibson }
12090481622SDavid Gibson 
1211c5ecae3SMike Kravetz /*
1221c5ecae3SMike Kravetz  * Subpool accounting for allocating and reserving pages.
1231c5ecae3SMike Kravetz  * Return -ENOMEM if there are not enough resources to satisfy the
1241c5ecae3SMike Kravetz  * the request.  Otherwise, return the number of pages by which the
1251c5ecae3SMike Kravetz  * global pools must be adjusted (upward).  The returned value may
1261c5ecae3SMike Kravetz  * only be different than the passed value (delta) in the case where
1271c5ecae3SMike Kravetz  * a subpool minimum size must be manitained.
1281c5ecae3SMike Kravetz  */
1291c5ecae3SMike Kravetz static long hugepage_subpool_get_pages(struct hugepage_subpool *spool,
13090481622SDavid Gibson 				      long delta)
13190481622SDavid Gibson {
1321c5ecae3SMike Kravetz 	long ret = delta;
13390481622SDavid Gibson 
13490481622SDavid Gibson 	if (!spool)
1351c5ecae3SMike Kravetz 		return ret;
13690481622SDavid Gibson 
13790481622SDavid Gibson 	spin_lock(&spool->lock);
13890481622SDavid Gibson 
1391c5ecae3SMike Kravetz 	if (spool->max_hpages != -1) {		/* maximum size accounting */
1401c5ecae3SMike Kravetz 		if ((spool->used_hpages + delta) <= spool->max_hpages)
1411c5ecae3SMike Kravetz 			spool->used_hpages += delta;
1421c5ecae3SMike Kravetz 		else {
1431c5ecae3SMike Kravetz 			ret = -ENOMEM;
1441c5ecae3SMike Kravetz 			goto unlock_ret;
1451c5ecae3SMike Kravetz 		}
1461c5ecae3SMike Kravetz 	}
1471c5ecae3SMike Kravetz 
14809a95e29SMike Kravetz 	/* minimum size accounting */
14909a95e29SMike Kravetz 	if (spool->min_hpages != -1 && spool->rsv_hpages) {
1501c5ecae3SMike Kravetz 		if (delta > spool->rsv_hpages) {
1511c5ecae3SMike Kravetz 			/*
1521c5ecae3SMike Kravetz 			 * Asking for more reserves than those already taken on
1531c5ecae3SMike Kravetz 			 * behalf of subpool.  Return difference.
1541c5ecae3SMike Kravetz 			 */
1551c5ecae3SMike Kravetz 			ret = delta - spool->rsv_hpages;
1561c5ecae3SMike Kravetz 			spool->rsv_hpages = 0;
1571c5ecae3SMike Kravetz 		} else {
1581c5ecae3SMike Kravetz 			ret = 0;	/* reserves already accounted for */
1591c5ecae3SMike Kravetz 			spool->rsv_hpages -= delta;
1601c5ecae3SMike Kravetz 		}
1611c5ecae3SMike Kravetz 	}
1621c5ecae3SMike Kravetz 
1631c5ecae3SMike Kravetz unlock_ret:
1641c5ecae3SMike Kravetz 	spin_unlock(&spool->lock);
16590481622SDavid Gibson 	return ret;
16690481622SDavid Gibson }
16790481622SDavid Gibson 
1681c5ecae3SMike Kravetz /*
1691c5ecae3SMike Kravetz  * Subpool accounting for freeing and unreserving pages.
1701c5ecae3SMike Kravetz  * Return the number of global page reservations that must be dropped.
1711c5ecae3SMike Kravetz  * The return value may only be different than the passed value (delta)
1721c5ecae3SMike Kravetz  * in the case where a subpool minimum size must be maintained.
1731c5ecae3SMike Kravetz  */
1741c5ecae3SMike Kravetz static long hugepage_subpool_put_pages(struct hugepage_subpool *spool,
17590481622SDavid Gibson 				       long delta)
17690481622SDavid Gibson {
1771c5ecae3SMike Kravetz 	long ret = delta;
1781c5ecae3SMike Kravetz 
17990481622SDavid Gibson 	if (!spool)
1801c5ecae3SMike Kravetz 		return delta;
18190481622SDavid Gibson 
18290481622SDavid Gibson 	spin_lock(&spool->lock);
1831c5ecae3SMike Kravetz 
1841c5ecae3SMike Kravetz 	if (spool->max_hpages != -1)		/* maximum size accounting */
18590481622SDavid Gibson 		spool->used_hpages -= delta;
1861c5ecae3SMike Kravetz 
18709a95e29SMike Kravetz 	 /* minimum size accounting */
18809a95e29SMike Kravetz 	if (spool->min_hpages != -1 && spool->used_hpages < spool->min_hpages) {
1891c5ecae3SMike Kravetz 		if (spool->rsv_hpages + delta <= spool->min_hpages)
1901c5ecae3SMike Kravetz 			ret = 0;
1911c5ecae3SMike Kravetz 		else
1921c5ecae3SMike Kravetz 			ret = spool->rsv_hpages + delta - spool->min_hpages;
1931c5ecae3SMike Kravetz 
1941c5ecae3SMike Kravetz 		spool->rsv_hpages += delta;
1951c5ecae3SMike Kravetz 		if (spool->rsv_hpages > spool->min_hpages)
1961c5ecae3SMike Kravetz 			spool->rsv_hpages = spool->min_hpages;
1971c5ecae3SMike Kravetz 	}
1981c5ecae3SMike Kravetz 
1991c5ecae3SMike Kravetz 	/*
2001c5ecae3SMike Kravetz 	 * If hugetlbfs_put_super couldn't free spool due to an outstanding
2011c5ecae3SMike Kravetz 	 * quota reference, free it now.
2021c5ecae3SMike Kravetz 	 */
20390481622SDavid Gibson 	unlock_or_release_subpool(spool);
2041c5ecae3SMike Kravetz 
2051c5ecae3SMike Kravetz 	return ret;
20690481622SDavid Gibson }
20790481622SDavid Gibson 
20890481622SDavid Gibson static inline struct hugepage_subpool *subpool_inode(struct inode *inode)
20990481622SDavid Gibson {
21090481622SDavid Gibson 	return HUGETLBFS_SB(inode->i_sb)->spool;
21190481622SDavid Gibson }
21290481622SDavid Gibson 
21390481622SDavid Gibson static inline struct hugepage_subpool *subpool_vma(struct vm_area_struct *vma)
21490481622SDavid Gibson {
215496ad9aaSAl Viro 	return subpool_inode(file_inode(vma->vm_file));
21690481622SDavid Gibson }
21790481622SDavid Gibson 
218e7c4b0bfSAndy Whitcroft /*
21996822904SAndy Whitcroft  * Region tracking -- allows tracking of reservations and instantiated pages
22096822904SAndy Whitcroft  *                    across the pages in a mapping.
22184afd99bSAndy Whitcroft  *
2221dd308a7SMike Kravetz  * The region data structures are embedded into a resv_map and protected
2231dd308a7SMike Kravetz  * by a resv_map's lock.  The set of regions within the resv_map represent
2241dd308a7SMike Kravetz  * reservations for huge pages, or huge pages that have already been
2251dd308a7SMike Kravetz  * instantiated within the map.  The from and to elements are huge page
2261dd308a7SMike Kravetz  * indicies into the associated mapping.  from indicates the starting index
2271dd308a7SMike Kravetz  * of the region.  to represents the first index past the end of  the region.
2281dd308a7SMike Kravetz  *
2291dd308a7SMike Kravetz  * For example, a file region structure with from == 0 and to == 4 represents
2301dd308a7SMike Kravetz  * four huge pages in a mapping.  It is important to note that the to element
2311dd308a7SMike Kravetz  * represents the first element past the end of the region. This is used in
2321dd308a7SMike Kravetz  * arithmetic as 4(to) - 0(from) = 4 huge pages in the region.
2331dd308a7SMike Kravetz  *
2341dd308a7SMike Kravetz  * Interval notation of the form [from, to) will be used to indicate that
2351dd308a7SMike Kravetz  * the endpoint from is inclusive and to is exclusive.
23696822904SAndy Whitcroft  */
23796822904SAndy Whitcroft struct file_region {
23896822904SAndy Whitcroft 	struct list_head link;
23996822904SAndy Whitcroft 	long from;
24096822904SAndy Whitcroft 	long to;
24196822904SAndy Whitcroft };
24296822904SAndy Whitcroft 
2431dd308a7SMike Kravetz /*
2441dd308a7SMike Kravetz  * Add the huge page range represented by [f, t) to the reserve
2455e911373SMike Kravetz  * map.  In the normal case, existing regions will be expanded
2465e911373SMike Kravetz  * to accommodate the specified range.  Sufficient regions should
2475e911373SMike Kravetz  * exist for expansion due to the previous call to region_chg
2485e911373SMike Kravetz  * with the same range.  However, it is possible that region_del
2495e911373SMike Kravetz  * could have been called after region_chg and modifed the map
2505e911373SMike Kravetz  * in such a way that no region exists to be expanded.  In this
2515e911373SMike Kravetz  * case, pull a region descriptor from the cache associated with
2525e911373SMike Kravetz  * the map and use that for the new range.
253cf3ad20bSMike Kravetz  *
254cf3ad20bSMike Kravetz  * Return the number of new huge pages added to the map.  This
255cf3ad20bSMike Kravetz  * number is greater than or equal to zero.
2561dd308a7SMike Kravetz  */
2571406ec9bSJoonsoo Kim static long region_add(struct resv_map *resv, long f, long t)
25896822904SAndy Whitcroft {
2591406ec9bSJoonsoo Kim 	struct list_head *head = &resv->regions;
26096822904SAndy Whitcroft 	struct file_region *rg, *nrg, *trg;
261cf3ad20bSMike Kravetz 	long add = 0;
26296822904SAndy Whitcroft 
2637b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
26496822904SAndy Whitcroft 	/* Locate the region we are either in or before. */
26596822904SAndy Whitcroft 	list_for_each_entry(rg, head, link)
26696822904SAndy Whitcroft 		if (f <= rg->to)
26796822904SAndy Whitcroft 			break;
26896822904SAndy Whitcroft 
2695e911373SMike Kravetz 	/*
2705e911373SMike Kravetz 	 * If no region exists which can be expanded to include the
2715e911373SMike Kravetz 	 * specified range, the list must have been modified by an
2725e911373SMike Kravetz 	 * interleving call to region_del().  Pull a region descriptor
2735e911373SMike Kravetz 	 * from the cache and use it for this range.
2745e911373SMike Kravetz 	 */
2755e911373SMike Kravetz 	if (&rg->link == head || t < rg->from) {
2765e911373SMike Kravetz 		VM_BUG_ON(resv->region_cache_count <= 0);
2775e911373SMike Kravetz 
2785e911373SMike Kravetz 		resv->region_cache_count--;
2795e911373SMike Kravetz 		nrg = list_first_entry(&resv->region_cache, struct file_region,
2805e911373SMike Kravetz 					link);
2815e911373SMike Kravetz 		list_del(&nrg->link);
2825e911373SMike Kravetz 
2835e911373SMike Kravetz 		nrg->from = f;
2845e911373SMike Kravetz 		nrg->to = t;
2855e911373SMike Kravetz 		list_add(&nrg->link, rg->link.prev);
2865e911373SMike Kravetz 
2875e911373SMike Kravetz 		add += t - f;
2885e911373SMike Kravetz 		goto out_locked;
2895e911373SMike Kravetz 	}
2905e911373SMike Kravetz 
29196822904SAndy Whitcroft 	/* Round our left edge to the current segment if it encloses us. */
29296822904SAndy Whitcroft 	if (f > rg->from)
29396822904SAndy Whitcroft 		f = rg->from;
29496822904SAndy Whitcroft 
29596822904SAndy Whitcroft 	/* Check for and consume any regions we now overlap with. */
29696822904SAndy Whitcroft 	nrg = rg;
29796822904SAndy Whitcroft 	list_for_each_entry_safe(rg, trg, rg->link.prev, link) {
29896822904SAndy Whitcroft 		if (&rg->link == head)
29996822904SAndy Whitcroft 			break;
30096822904SAndy Whitcroft 		if (rg->from > t)
30196822904SAndy Whitcroft 			break;
30296822904SAndy Whitcroft 
30396822904SAndy Whitcroft 		/* If this area reaches higher then extend our area to
30496822904SAndy Whitcroft 		 * include it completely.  If this is not the first area
30596822904SAndy Whitcroft 		 * which we intend to reuse, free it. */
30696822904SAndy Whitcroft 		if (rg->to > t)
30796822904SAndy Whitcroft 			t = rg->to;
30896822904SAndy Whitcroft 		if (rg != nrg) {
309cf3ad20bSMike Kravetz 			/* Decrement return value by the deleted range.
310cf3ad20bSMike Kravetz 			 * Another range will span this area so that by
311cf3ad20bSMike Kravetz 			 * end of routine add will be >= zero
312cf3ad20bSMike Kravetz 			 */
313cf3ad20bSMike Kravetz 			add -= (rg->to - rg->from);
31496822904SAndy Whitcroft 			list_del(&rg->link);
31596822904SAndy Whitcroft 			kfree(rg);
31696822904SAndy Whitcroft 		}
31796822904SAndy Whitcroft 	}
318cf3ad20bSMike Kravetz 
319cf3ad20bSMike Kravetz 	add += (nrg->from - f);		/* Added to beginning of region */
32096822904SAndy Whitcroft 	nrg->from = f;
321cf3ad20bSMike Kravetz 	add += t - nrg->to;		/* Added to end of region */
32296822904SAndy Whitcroft 	nrg->to = t;
323cf3ad20bSMike Kravetz 
3245e911373SMike Kravetz out_locked:
3255e911373SMike Kravetz 	resv->adds_in_progress--;
3267b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
327cf3ad20bSMike Kravetz 	VM_BUG_ON(add < 0);
328cf3ad20bSMike Kravetz 	return add;
32996822904SAndy Whitcroft }
33096822904SAndy Whitcroft 
3311dd308a7SMike Kravetz /*
3321dd308a7SMike Kravetz  * Examine the existing reserve map and determine how many
3331dd308a7SMike Kravetz  * huge pages in the specified range [f, t) are NOT currently
3341dd308a7SMike Kravetz  * represented.  This routine is called before a subsequent
3351dd308a7SMike Kravetz  * call to region_add that will actually modify the reserve
3361dd308a7SMike Kravetz  * map to add the specified range [f, t).  region_chg does
3371dd308a7SMike Kravetz  * not change the number of huge pages represented by the
3381dd308a7SMike Kravetz  * map.  However, if the existing regions in the map can not
3391dd308a7SMike Kravetz  * be expanded to represent the new range, a new file_region
3401dd308a7SMike Kravetz  * structure is added to the map as a placeholder.  This is
3411dd308a7SMike Kravetz  * so that the subsequent region_add call will have all the
3421dd308a7SMike Kravetz  * regions it needs and will not fail.
3431dd308a7SMike Kravetz  *
3445e911373SMike Kravetz  * Upon entry, region_chg will also examine the cache of region descriptors
3455e911373SMike Kravetz  * associated with the map.  If there are not enough descriptors cached, one
3465e911373SMike Kravetz  * will be allocated for the in progress add operation.
3475e911373SMike Kravetz  *
3485e911373SMike Kravetz  * Returns the number of huge pages that need to be added to the existing
3495e911373SMike Kravetz  * reservation map for the range [f, t).  This number is greater or equal to
3505e911373SMike Kravetz  * zero.  -ENOMEM is returned if a new file_region structure or cache entry
3515e911373SMike Kravetz  * is needed and can not be allocated.
3521dd308a7SMike Kravetz  */
3531406ec9bSJoonsoo Kim static long region_chg(struct resv_map *resv, long f, long t)
35496822904SAndy Whitcroft {
3551406ec9bSJoonsoo Kim 	struct list_head *head = &resv->regions;
3567b24d861SDavidlohr Bueso 	struct file_region *rg, *nrg = NULL;
35796822904SAndy Whitcroft 	long chg = 0;
35896822904SAndy Whitcroft 
3597b24d861SDavidlohr Bueso retry:
3607b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
3615e911373SMike Kravetz retry_locked:
3625e911373SMike Kravetz 	resv->adds_in_progress++;
3635e911373SMike Kravetz 
3645e911373SMike Kravetz 	/*
3655e911373SMike Kravetz 	 * Check for sufficient descriptors in the cache to accommodate
3665e911373SMike Kravetz 	 * the number of in progress add operations.
3675e911373SMike Kravetz 	 */
3685e911373SMike Kravetz 	if (resv->adds_in_progress > resv->region_cache_count) {
3695e911373SMike Kravetz 		struct file_region *trg;
3705e911373SMike Kravetz 
3715e911373SMike Kravetz 		VM_BUG_ON(resv->adds_in_progress - resv->region_cache_count > 1);
3725e911373SMike Kravetz 		/* Must drop lock to allocate a new descriptor. */
3735e911373SMike Kravetz 		resv->adds_in_progress--;
3745e911373SMike Kravetz 		spin_unlock(&resv->lock);
3755e911373SMike Kravetz 
3765e911373SMike Kravetz 		trg = kmalloc(sizeof(*trg), GFP_KERNEL);
377dbe409e4SMike Kravetz 		if (!trg) {
378dbe409e4SMike Kravetz 			kfree(nrg);
3795e911373SMike Kravetz 			return -ENOMEM;
380dbe409e4SMike Kravetz 		}
3815e911373SMike Kravetz 
3825e911373SMike Kravetz 		spin_lock(&resv->lock);
3835e911373SMike Kravetz 		list_add(&trg->link, &resv->region_cache);
3845e911373SMike Kravetz 		resv->region_cache_count++;
3855e911373SMike Kravetz 		goto retry_locked;
3865e911373SMike Kravetz 	}
3875e911373SMike Kravetz 
38896822904SAndy Whitcroft 	/* Locate the region we are before or in. */
38996822904SAndy Whitcroft 	list_for_each_entry(rg, head, link)
39096822904SAndy Whitcroft 		if (f <= rg->to)
39196822904SAndy Whitcroft 			break;
39296822904SAndy Whitcroft 
39396822904SAndy Whitcroft 	/* If we are below the current region then a new region is required.
39496822904SAndy Whitcroft 	 * Subtle, allocate a new region at the position but make it zero
39596822904SAndy Whitcroft 	 * size such that we can guarantee to record the reservation. */
39696822904SAndy Whitcroft 	if (&rg->link == head || t < rg->from) {
3977b24d861SDavidlohr Bueso 		if (!nrg) {
3985e911373SMike Kravetz 			resv->adds_in_progress--;
3997b24d861SDavidlohr Bueso 			spin_unlock(&resv->lock);
40096822904SAndy Whitcroft 			nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
40196822904SAndy Whitcroft 			if (!nrg)
40296822904SAndy Whitcroft 				return -ENOMEM;
4037b24d861SDavidlohr Bueso 
40496822904SAndy Whitcroft 			nrg->from = f;
40596822904SAndy Whitcroft 			nrg->to   = f;
40696822904SAndy Whitcroft 			INIT_LIST_HEAD(&nrg->link);
4077b24d861SDavidlohr Bueso 			goto retry;
4087b24d861SDavidlohr Bueso 		}
40996822904SAndy Whitcroft 
4107b24d861SDavidlohr Bueso 		list_add(&nrg->link, rg->link.prev);
4117b24d861SDavidlohr Bueso 		chg = t - f;
4127b24d861SDavidlohr Bueso 		goto out_nrg;
41396822904SAndy Whitcroft 	}
41496822904SAndy Whitcroft 
41596822904SAndy Whitcroft 	/* Round our left edge to the current segment if it encloses us. */
41696822904SAndy Whitcroft 	if (f > rg->from)
41796822904SAndy Whitcroft 		f = rg->from;
41896822904SAndy Whitcroft 	chg = t - f;
41996822904SAndy Whitcroft 
42096822904SAndy Whitcroft 	/* Check for and consume any regions we now overlap with. */
42196822904SAndy Whitcroft 	list_for_each_entry(rg, rg->link.prev, link) {
42296822904SAndy Whitcroft 		if (&rg->link == head)
42396822904SAndy Whitcroft 			break;
42496822904SAndy Whitcroft 		if (rg->from > t)
4257b24d861SDavidlohr Bueso 			goto out;
42696822904SAndy Whitcroft 
42725985edcSLucas De Marchi 		/* We overlap with this area, if it extends further than
42896822904SAndy Whitcroft 		 * us then we must extend ourselves.  Account for its
42996822904SAndy Whitcroft 		 * existing reservation. */
43096822904SAndy Whitcroft 		if (rg->to > t) {
43196822904SAndy Whitcroft 			chg += rg->to - t;
43296822904SAndy Whitcroft 			t = rg->to;
43396822904SAndy Whitcroft 		}
43496822904SAndy Whitcroft 		chg -= rg->to - rg->from;
43596822904SAndy Whitcroft 	}
4367b24d861SDavidlohr Bueso 
4377b24d861SDavidlohr Bueso out:
4387b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
4397b24d861SDavidlohr Bueso 	/*  We already know we raced and no longer need the new region */
4407b24d861SDavidlohr Bueso 	kfree(nrg);
4417b24d861SDavidlohr Bueso 	return chg;
4427b24d861SDavidlohr Bueso out_nrg:
4437b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
44496822904SAndy Whitcroft 	return chg;
44596822904SAndy Whitcroft }
44696822904SAndy Whitcroft 
4471dd308a7SMike Kravetz /*
4485e911373SMike Kravetz  * Abort the in progress add operation.  The adds_in_progress field
4495e911373SMike Kravetz  * of the resv_map keeps track of the operations in progress between
4505e911373SMike Kravetz  * calls to region_chg and region_add.  Operations are sometimes
4515e911373SMike Kravetz  * aborted after the call to region_chg.  In such cases, region_abort
4525e911373SMike Kravetz  * is called to decrement the adds_in_progress counter.
4535e911373SMike Kravetz  *
4545e911373SMike Kravetz  * NOTE: The range arguments [f, t) are not needed or used in this
4555e911373SMike Kravetz  * routine.  They are kept to make reading the calling code easier as
4565e911373SMike Kravetz  * arguments will match the associated region_chg call.
4575e911373SMike Kravetz  */
4585e911373SMike Kravetz static void region_abort(struct resv_map *resv, long f, long t)
4595e911373SMike Kravetz {
4605e911373SMike Kravetz 	spin_lock(&resv->lock);
4615e911373SMike Kravetz 	VM_BUG_ON(!resv->region_cache_count);
4625e911373SMike Kravetz 	resv->adds_in_progress--;
4635e911373SMike Kravetz 	spin_unlock(&resv->lock);
4645e911373SMike Kravetz }
4655e911373SMike Kravetz 
4665e911373SMike Kravetz /*
467feba16e2SMike Kravetz  * Delete the specified range [f, t) from the reserve map.  If the
468feba16e2SMike Kravetz  * t parameter is LONG_MAX, this indicates that ALL regions after f
469feba16e2SMike Kravetz  * should be deleted.  Locate the regions which intersect [f, t)
470feba16e2SMike Kravetz  * and either trim, delete or split the existing regions.
471feba16e2SMike Kravetz  *
472feba16e2SMike Kravetz  * Returns the number of huge pages deleted from the reserve map.
473feba16e2SMike Kravetz  * In the normal case, the return value is zero or more.  In the
474feba16e2SMike Kravetz  * case where a region must be split, a new region descriptor must
475feba16e2SMike Kravetz  * be allocated.  If the allocation fails, -ENOMEM will be returned.
476feba16e2SMike Kravetz  * NOTE: If the parameter t == LONG_MAX, then we will never split
477feba16e2SMike Kravetz  * a region and possibly return -ENOMEM.  Callers specifying
478feba16e2SMike Kravetz  * t == LONG_MAX do not need to check for -ENOMEM error.
4791dd308a7SMike Kravetz  */
480feba16e2SMike Kravetz static long region_del(struct resv_map *resv, long f, long t)
48196822904SAndy Whitcroft {
4821406ec9bSJoonsoo Kim 	struct list_head *head = &resv->regions;
48396822904SAndy Whitcroft 	struct file_region *rg, *trg;
484feba16e2SMike Kravetz 	struct file_region *nrg = NULL;
485feba16e2SMike Kravetz 	long del = 0;
48696822904SAndy Whitcroft 
487feba16e2SMike Kravetz retry:
4887b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
489feba16e2SMike Kravetz 	list_for_each_entry_safe(rg, trg, head, link) {
490dbe409e4SMike Kravetz 		/*
491dbe409e4SMike Kravetz 		 * Skip regions before the range to be deleted.  file_region
492dbe409e4SMike Kravetz 		 * ranges are normally of the form [from, to).  However, there
493dbe409e4SMike Kravetz 		 * may be a "placeholder" entry in the map which is of the form
494dbe409e4SMike Kravetz 		 * (from, to) with from == to.  Check for placeholder entries
495dbe409e4SMike Kravetz 		 * at the beginning of the range to be deleted.
496dbe409e4SMike Kravetz 		 */
497dbe409e4SMike Kravetz 		if (rg->to <= f && (rg->to != rg->from || rg->to != f))
498feba16e2SMike Kravetz 			continue;
499dbe409e4SMike Kravetz 
500feba16e2SMike Kravetz 		if (rg->from >= t)
50196822904SAndy Whitcroft 			break;
50296822904SAndy Whitcroft 
503feba16e2SMike Kravetz 		if (f > rg->from && t < rg->to) { /* Must split region */
504feba16e2SMike Kravetz 			/*
505feba16e2SMike Kravetz 			 * Check for an entry in the cache before dropping
506feba16e2SMike Kravetz 			 * lock and attempting allocation.
507feba16e2SMike Kravetz 			 */
508feba16e2SMike Kravetz 			if (!nrg &&
509feba16e2SMike Kravetz 			    resv->region_cache_count > resv->adds_in_progress) {
510feba16e2SMike Kravetz 				nrg = list_first_entry(&resv->region_cache,
511feba16e2SMike Kravetz 							struct file_region,
512feba16e2SMike Kravetz 							link);
513feba16e2SMike Kravetz 				list_del(&nrg->link);
514feba16e2SMike Kravetz 				resv->region_cache_count--;
51596822904SAndy Whitcroft 			}
51696822904SAndy Whitcroft 
517feba16e2SMike Kravetz 			if (!nrg) {
518feba16e2SMike Kravetz 				spin_unlock(&resv->lock);
519feba16e2SMike Kravetz 				nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
520feba16e2SMike Kravetz 				if (!nrg)
521feba16e2SMike Kravetz 					return -ENOMEM;
522feba16e2SMike Kravetz 				goto retry;
523feba16e2SMike Kravetz 			}
524feba16e2SMike Kravetz 
525feba16e2SMike Kravetz 			del += t - f;
526feba16e2SMike Kravetz 
527feba16e2SMike Kravetz 			/* New entry for end of split region */
528feba16e2SMike Kravetz 			nrg->from = t;
529feba16e2SMike Kravetz 			nrg->to = rg->to;
530feba16e2SMike Kravetz 			INIT_LIST_HEAD(&nrg->link);
531feba16e2SMike Kravetz 
532feba16e2SMike Kravetz 			/* Original entry is trimmed */
533feba16e2SMike Kravetz 			rg->to = f;
534feba16e2SMike Kravetz 
535feba16e2SMike Kravetz 			list_add(&nrg->link, &rg->link);
536feba16e2SMike Kravetz 			nrg = NULL;
53796822904SAndy Whitcroft 			break;
538feba16e2SMike Kravetz 		}
539feba16e2SMike Kravetz 
540feba16e2SMike Kravetz 		if (f <= rg->from && t >= rg->to) { /* Remove entire region */
541feba16e2SMike Kravetz 			del += rg->to - rg->from;
54296822904SAndy Whitcroft 			list_del(&rg->link);
54396822904SAndy Whitcroft 			kfree(rg);
544feba16e2SMike Kravetz 			continue;
54596822904SAndy Whitcroft 		}
5467b24d861SDavidlohr Bueso 
547feba16e2SMike Kravetz 		if (f <= rg->from) {	/* Trim beginning of region */
548feba16e2SMike Kravetz 			del += t - rg->from;
549feba16e2SMike Kravetz 			rg->from = t;
550feba16e2SMike Kravetz 		} else {		/* Trim end of region */
551feba16e2SMike Kravetz 			del += rg->to - f;
552feba16e2SMike Kravetz 			rg->to = f;
553feba16e2SMike Kravetz 		}
554feba16e2SMike Kravetz 	}
555feba16e2SMike Kravetz 
5567b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
557feba16e2SMike Kravetz 	kfree(nrg);
558feba16e2SMike Kravetz 	return del;
55996822904SAndy Whitcroft }
56096822904SAndy Whitcroft 
5611dd308a7SMike Kravetz /*
562b5cec28dSMike Kravetz  * A rare out of memory error was encountered which prevented removal of
563b5cec28dSMike Kravetz  * the reserve map region for a page.  The huge page itself was free'ed
564b5cec28dSMike Kravetz  * and removed from the page cache.  This routine will adjust the subpool
565b5cec28dSMike Kravetz  * usage count, and the global reserve count if needed.  By incrementing
566b5cec28dSMike Kravetz  * these counts, the reserve map entry which could not be deleted will
567b5cec28dSMike Kravetz  * appear as a "reserved" entry instead of simply dangling with incorrect
568b5cec28dSMike Kravetz  * counts.
569b5cec28dSMike Kravetz  */
570b5cec28dSMike Kravetz void hugetlb_fix_reserve_counts(struct inode *inode, bool restore_reserve)
571b5cec28dSMike Kravetz {
572b5cec28dSMike Kravetz 	struct hugepage_subpool *spool = subpool_inode(inode);
573b5cec28dSMike Kravetz 	long rsv_adjust;
574b5cec28dSMike Kravetz 
575b5cec28dSMike Kravetz 	rsv_adjust = hugepage_subpool_get_pages(spool, 1);
576b5cec28dSMike Kravetz 	if (restore_reserve && rsv_adjust) {
577b5cec28dSMike Kravetz 		struct hstate *h = hstate_inode(inode);
578b5cec28dSMike Kravetz 
579b5cec28dSMike Kravetz 		hugetlb_acct_memory(h, 1);
580b5cec28dSMike Kravetz 	}
581b5cec28dSMike Kravetz }
582b5cec28dSMike Kravetz 
583b5cec28dSMike Kravetz /*
5841dd308a7SMike Kravetz  * Count and return the number of huge pages in the reserve map
5851dd308a7SMike Kravetz  * that intersect with the range [f, t).
5861dd308a7SMike Kravetz  */
5871406ec9bSJoonsoo Kim static long region_count(struct resv_map *resv, long f, long t)
58884afd99bSAndy Whitcroft {
5891406ec9bSJoonsoo Kim 	struct list_head *head = &resv->regions;
59084afd99bSAndy Whitcroft 	struct file_region *rg;
59184afd99bSAndy Whitcroft 	long chg = 0;
59284afd99bSAndy Whitcroft 
5937b24d861SDavidlohr Bueso 	spin_lock(&resv->lock);
59484afd99bSAndy Whitcroft 	/* Locate each segment we overlap with, and count that overlap. */
59584afd99bSAndy Whitcroft 	list_for_each_entry(rg, head, link) {
596f2135a4aSWang Sheng-Hui 		long seg_from;
597f2135a4aSWang Sheng-Hui 		long seg_to;
59884afd99bSAndy Whitcroft 
59984afd99bSAndy Whitcroft 		if (rg->to <= f)
60084afd99bSAndy Whitcroft 			continue;
60184afd99bSAndy Whitcroft 		if (rg->from >= t)
60284afd99bSAndy Whitcroft 			break;
60384afd99bSAndy Whitcroft 
60484afd99bSAndy Whitcroft 		seg_from = max(rg->from, f);
60584afd99bSAndy Whitcroft 		seg_to = min(rg->to, t);
60684afd99bSAndy Whitcroft 
60784afd99bSAndy Whitcroft 		chg += seg_to - seg_from;
60884afd99bSAndy Whitcroft 	}
6097b24d861SDavidlohr Bueso 	spin_unlock(&resv->lock);
61084afd99bSAndy Whitcroft 
61184afd99bSAndy Whitcroft 	return chg;
61284afd99bSAndy Whitcroft }
61384afd99bSAndy Whitcroft 
61496822904SAndy Whitcroft /*
615e7c4b0bfSAndy Whitcroft  * Convert the address within this vma to the page offset within
616e7c4b0bfSAndy Whitcroft  * the mapping, in pagecache page units; huge pages here.
617e7c4b0bfSAndy Whitcroft  */
618a5516438SAndi Kleen static pgoff_t vma_hugecache_offset(struct hstate *h,
619a5516438SAndi Kleen 			struct vm_area_struct *vma, unsigned long address)
620e7c4b0bfSAndy Whitcroft {
621a5516438SAndi Kleen 	return ((address - vma->vm_start) >> huge_page_shift(h)) +
622a5516438SAndi Kleen 			(vma->vm_pgoff >> huge_page_order(h));
623e7c4b0bfSAndy Whitcroft }
624e7c4b0bfSAndy Whitcroft 
6250fe6e20bSNaoya Horiguchi pgoff_t linear_hugepage_index(struct vm_area_struct *vma,
6260fe6e20bSNaoya Horiguchi 				     unsigned long address)
6270fe6e20bSNaoya Horiguchi {
6280fe6e20bSNaoya Horiguchi 	return vma_hugecache_offset(hstate_vma(vma), vma, address);
6290fe6e20bSNaoya Horiguchi }
6300fe6e20bSNaoya Horiguchi 
63184afd99bSAndy Whitcroft /*
63208fba699SMel Gorman  * Return the size of the pages allocated when backing a VMA. In the majority
63308fba699SMel Gorman  * cases this will be same size as used by the page table entries.
63408fba699SMel Gorman  */
63508fba699SMel Gorman unsigned long vma_kernel_pagesize(struct vm_area_struct *vma)
63608fba699SMel Gorman {
63708fba699SMel Gorman 	struct hstate *hstate;
63808fba699SMel Gorman 
63908fba699SMel Gorman 	if (!is_vm_hugetlb_page(vma))
64008fba699SMel Gorman 		return PAGE_SIZE;
64108fba699SMel Gorman 
64208fba699SMel Gorman 	hstate = hstate_vma(vma);
64308fba699SMel Gorman 
6442415cf12SWanpeng Li 	return 1UL << huge_page_shift(hstate);
64508fba699SMel Gorman }
646f340ca0fSJoerg Roedel EXPORT_SYMBOL_GPL(vma_kernel_pagesize);
64708fba699SMel Gorman 
64808fba699SMel Gorman /*
6493340289dSMel Gorman  * Return the page size being used by the MMU to back a VMA. In the majority
6503340289dSMel Gorman  * of cases, the page size used by the kernel matches the MMU size. On
6513340289dSMel Gorman  * architectures where it differs, an architecture-specific version of this
6523340289dSMel Gorman  * function is required.
6533340289dSMel Gorman  */
6543340289dSMel Gorman #ifndef vma_mmu_pagesize
6553340289dSMel Gorman unsigned long vma_mmu_pagesize(struct vm_area_struct *vma)
6563340289dSMel Gorman {
6573340289dSMel Gorman 	return vma_kernel_pagesize(vma);
6583340289dSMel Gorman }
6593340289dSMel Gorman #endif
6603340289dSMel Gorman 
6613340289dSMel Gorman /*
66284afd99bSAndy Whitcroft  * Flags for MAP_PRIVATE reservations.  These are stored in the bottom
66384afd99bSAndy Whitcroft  * bits of the reservation map pointer, which are always clear due to
66484afd99bSAndy Whitcroft  * alignment.
66584afd99bSAndy Whitcroft  */
66684afd99bSAndy Whitcroft #define HPAGE_RESV_OWNER    (1UL << 0)
66784afd99bSAndy Whitcroft #define HPAGE_RESV_UNMAPPED (1UL << 1)
66804f2cbe3SMel Gorman #define HPAGE_RESV_MASK (HPAGE_RESV_OWNER | HPAGE_RESV_UNMAPPED)
66984afd99bSAndy Whitcroft 
670a1e78772SMel Gorman /*
671a1e78772SMel Gorman  * These helpers are used to track how many pages are reserved for
672a1e78772SMel Gorman  * faults in a MAP_PRIVATE mapping. Only the process that called mmap()
673a1e78772SMel Gorman  * is guaranteed to have their future faults succeed.
674a1e78772SMel Gorman  *
675a1e78772SMel Gorman  * With the exception of reset_vma_resv_huge_pages() which is called at fork(),
676a1e78772SMel Gorman  * the reserve counters are updated with the hugetlb_lock held. It is safe
677a1e78772SMel Gorman  * to reset the VMA at fork() time as it is not in use yet and there is no
678a1e78772SMel Gorman  * chance of the global counters getting corrupted as a result of the values.
67984afd99bSAndy Whitcroft  *
68084afd99bSAndy Whitcroft  * The private mapping reservation is represented in a subtly different
68184afd99bSAndy Whitcroft  * manner to a shared mapping.  A shared mapping has a region map associated
68284afd99bSAndy Whitcroft  * with the underlying file, this region map represents the backing file
68384afd99bSAndy Whitcroft  * pages which have ever had a reservation assigned which this persists even
68484afd99bSAndy Whitcroft  * after the page is instantiated.  A private mapping has a region map
68584afd99bSAndy Whitcroft  * associated with the original mmap which is attached to all VMAs which
68684afd99bSAndy Whitcroft  * reference it, this region map represents those offsets which have consumed
68784afd99bSAndy Whitcroft  * reservation ie. where pages have been instantiated.
688a1e78772SMel Gorman  */
689e7c4b0bfSAndy Whitcroft static unsigned long get_vma_private_data(struct vm_area_struct *vma)
690e7c4b0bfSAndy Whitcroft {
691e7c4b0bfSAndy Whitcroft 	return (unsigned long)vma->vm_private_data;
692e7c4b0bfSAndy Whitcroft }
693e7c4b0bfSAndy Whitcroft 
694e7c4b0bfSAndy Whitcroft static void set_vma_private_data(struct vm_area_struct *vma,
695e7c4b0bfSAndy Whitcroft 							unsigned long value)
696e7c4b0bfSAndy Whitcroft {
697e7c4b0bfSAndy Whitcroft 	vma->vm_private_data = (void *)value;
698e7c4b0bfSAndy Whitcroft }
699e7c4b0bfSAndy Whitcroft 
7009119a41eSJoonsoo Kim struct resv_map *resv_map_alloc(void)
70184afd99bSAndy Whitcroft {
70284afd99bSAndy Whitcroft 	struct resv_map *resv_map = kmalloc(sizeof(*resv_map), GFP_KERNEL);
7035e911373SMike Kravetz 	struct file_region *rg = kmalloc(sizeof(*rg), GFP_KERNEL);
7045e911373SMike Kravetz 
7055e911373SMike Kravetz 	if (!resv_map || !rg) {
7065e911373SMike Kravetz 		kfree(resv_map);
7075e911373SMike Kravetz 		kfree(rg);
70884afd99bSAndy Whitcroft 		return NULL;
7095e911373SMike Kravetz 	}
71084afd99bSAndy Whitcroft 
71184afd99bSAndy Whitcroft 	kref_init(&resv_map->refs);
7127b24d861SDavidlohr Bueso 	spin_lock_init(&resv_map->lock);
71384afd99bSAndy Whitcroft 	INIT_LIST_HEAD(&resv_map->regions);
71484afd99bSAndy Whitcroft 
7155e911373SMike Kravetz 	resv_map->adds_in_progress = 0;
7165e911373SMike Kravetz 
7175e911373SMike Kravetz 	INIT_LIST_HEAD(&resv_map->region_cache);
7185e911373SMike Kravetz 	list_add(&rg->link, &resv_map->region_cache);
7195e911373SMike Kravetz 	resv_map->region_cache_count = 1;
7205e911373SMike Kravetz 
72184afd99bSAndy Whitcroft 	return resv_map;
72284afd99bSAndy Whitcroft }
72384afd99bSAndy Whitcroft 
7249119a41eSJoonsoo Kim void resv_map_release(struct kref *ref)
72584afd99bSAndy Whitcroft {
72684afd99bSAndy Whitcroft 	struct resv_map *resv_map = container_of(ref, struct resv_map, refs);
7275e911373SMike Kravetz 	struct list_head *head = &resv_map->region_cache;
7285e911373SMike Kravetz 	struct file_region *rg, *trg;
72984afd99bSAndy Whitcroft 
73084afd99bSAndy Whitcroft 	/* Clear out any active regions before we release the map. */
731feba16e2SMike Kravetz 	region_del(resv_map, 0, LONG_MAX);
7325e911373SMike Kravetz 
7335e911373SMike Kravetz 	/* ... and any entries left in the cache */
7345e911373SMike Kravetz 	list_for_each_entry_safe(rg, trg, head, link) {
7355e911373SMike Kravetz 		list_del(&rg->link);
7365e911373SMike Kravetz 		kfree(rg);
7375e911373SMike Kravetz 	}
7385e911373SMike Kravetz 
7395e911373SMike Kravetz 	VM_BUG_ON(resv_map->adds_in_progress);
7405e911373SMike Kravetz 
74184afd99bSAndy Whitcroft 	kfree(resv_map);
74284afd99bSAndy Whitcroft }
74384afd99bSAndy Whitcroft 
7444e35f483SJoonsoo Kim static inline struct resv_map *inode_resv_map(struct inode *inode)
7454e35f483SJoonsoo Kim {
7464e35f483SJoonsoo Kim 	return inode->i_mapping->private_data;
7474e35f483SJoonsoo Kim }
7484e35f483SJoonsoo Kim 
74984afd99bSAndy Whitcroft static struct resv_map *vma_resv_map(struct vm_area_struct *vma)
750a1e78772SMel Gorman {
75181d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
7524e35f483SJoonsoo Kim 	if (vma->vm_flags & VM_MAYSHARE) {
7534e35f483SJoonsoo Kim 		struct address_space *mapping = vma->vm_file->f_mapping;
7544e35f483SJoonsoo Kim 		struct inode *inode = mapping->host;
7554e35f483SJoonsoo Kim 
7564e35f483SJoonsoo Kim 		return inode_resv_map(inode);
7574e35f483SJoonsoo Kim 
7584e35f483SJoonsoo Kim 	} else {
75984afd99bSAndy Whitcroft 		return (struct resv_map *)(get_vma_private_data(vma) &
76084afd99bSAndy Whitcroft 							~HPAGE_RESV_MASK);
7614e35f483SJoonsoo Kim 	}
762a1e78772SMel Gorman }
763a1e78772SMel Gorman 
76484afd99bSAndy Whitcroft static void set_vma_resv_map(struct vm_area_struct *vma, struct resv_map *map)
765a1e78772SMel Gorman {
76681d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
76781d1b09cSSasha Levin 	VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
768a1e78772SMel Gorman 
76984afd99bSAndy Whitcroft 	set_vma_private_data(vma, (get_vma_private_data(vma) &
77084afd99bSAndy Whitcroft 				HPAGE_RESV_MASK) | (unsigned long)map);
77104f2cbe3SMel Gorman }
77204f2cbe3SMel Gorman 
77304f2cbe3SMel Gorman static void set_vma_resv_flags(struct vm_area_struct *vma, unsigned long flags)
77404f2cbe3SMel Gorman {
77581d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
77681d1b09cSSasha Levin 	VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
777e7c4b0bfSAndy Whitcroft 
778e7c4b0bfSAndy Whitcroft 	set_vma_private_data(vma, get_vma_private_data(vma) | flags);
77904f2cbe3SMel Gorman }
78004f2cbe3SMel Gorman 
78104f2cbe3SMel Gorman static int is_vma_resv_set(struct vm_area_struct *vma, unsigned long flag)
78204f2cbe3SMel Gorman {
78381d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
784e7c4b0bfSAndy Whitcroft 
785e7c4b0bfSAndy Whitcroft 	return (get_vma_private_data(vma) & flag) != 0;
786a1e78772SMel Gorman }
787a1e78772SMel Gorman 
78804f2cbe3SMel Gorman /* Reset counters to 0 and clear all HPAGE_RESV_* flags */
789a1e78772SMel Gorman void reset_vma_resv_huge_pages(struct vm_area_struct *vma)
790a1e78772SMel Gorman {
79181d1b09cSSasha Levin 	VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
792f83a275dSMel Gorman 	if (!(vma->vm_flags & VM_MAYSHARE))
793a1e78772SMel Gorman 		vma->vm_private_data = (void *)0;
794a1e78772SMel Gorman }
795a1e78772SMel Gorman 
796a1e78772SMel Gorman /* Returns true if the VMA has associated reserve pages */
797559ec2f8SNicholas Krause static bool vma_has_reserves(struct vm_area_struct *vma, long chg)
798a1e78772SMel Gorman {
799af0ed73eSJoonsoo Kim 	if (vma->vm_flags & VM_NORESERVE) {
800af0ed73eSJoonsoo Kim 		/*
801af0ed73eSJoonsoo Kim 		 * This address is already reserved by other process(chg == 0),
802af0ed73eSJoonsoo Kim 		 * so, we should decrement reserved count. Without decrementing,
803af0ed73eSJoonsoo Kim 		 * reserve count remains after releasing inode, because this
804af0ed73eSJoonsoo Kim 		 * allocated page will go into page cache and is regarded as
805af0ed73eSJoonsoo Kim 		 * coming from reserved pool in releasing step.  Currently, we
806af0ed73eSJoonsoo Kim 		 * don't have any other solution to deal with this situation
807af0ed73eSJoonsoo Kim 		 * properly, so add work-around here.
808af0ed73eSJoonsoo Kim 		 */
809af0ed73eSJoonsoo Kim 		if (vma->vm_flags & VM_MAYSHARE && chg == 0)
810559ec2f8SNicholas Krause 			return true;
811af0ed73eSJoonsoo Kim 		else
812559ec2f8SNicholas Krause 			return false;
813af0ed73eSJoonsoo Kim 	}
814a63884e9SJoonsoo Kim 
815a63884e9SJoonsoo Kim 	/* Shared mappings always use reserves */
8161fb1b0e9SMike Kravetz 	if (vma->vm_flags & VM_MAYSHARE) {
8171fb1b0e9SMike Kravetz 		/*
8181fb1b0e9SMike Kravetz 		 * We know VM_NORESERVE is not set.  Therefore, there SHOULD
8191fb1b0e9SMike Kravetz 		 * be a region map for all pages.  The only situation where
8201fb1b0e9SMike Kravetz 		 * there is no region map is if a hole was punched via
8211fb1b0e9SMike Kravetz 		 * fallocate.  In this case, there really are no reverves to
8221fb1b0e9SMike Kravetz 		 * use.  This situation is indicated if chg != 0.
8231fb1b0e9SMike Kravetz 		 */
8241fb1b0e9SMike Kravetz 		if (chg)
8251fb1b0e9SMike Kravetz 			return false;
8261fb1b0e9SMike Kravetz 		else
827559ec2f8SNicholas Krause 			return true;
8281fb1b0e9SMike Kravetz 	}
829a63884e9SJoonsoo Kim 
830a63884e9SJoonsoo Kim 	/*
831a63884e9SJoonsoo Kim 	 * Only the process that called mmap() has reserves for
832a63884e9SJoonsoo Kim 	 * private mappings.
833a63884e9SJoonsoo Kim 	 */
8347f09ca51SMel Gorman 	if (is_vma_resv_set(vma, HPAGE_RESV_OWNER))
835559ec2f8SNicholas Krause 		return true;
836a63884e9SJoonsoo Kim 
837559ec2f8SNicholas Krause 	return false;
838a1e78772SMel Gorman }
839a1e78772SMel Gorman 
840a5516438SAndi Kleen static void enqueue_huge_page(struct hstate *h, struct page *page)
8411da177e4SLinus Torvalds {
8421da177e4SLinus Torvalds 	int nid = page_to_nid(page);
8430edaecfaSAneesh Kumar K.V 	list_move(&page->lru, &h->hugepage_freelists[nid]);
844a5516438SAndi Kleen 	h->free_huge_pages++;
845a5516438SAndi Kleen 	h->free_huge_pages_node[nid]++;
8461da177e4SLinus Torvalds }
8471da177e4SLinus Torvalds 
848bf50bab2SNaoya Horiguchi static struct page *dequeue_huge_page_node(struct hstate *h, int nid)
849bf50bab2SNaoya Horiguchi {
850bf50bab2SNaoya Horiguchi 	struct page *page;
851bf50bab2SNaoya Horiguchi 
852c8721bbbSNaoya Horiguchi 	list_for_each_entry(page, &h->hugepage_freelists[nid], lru)
853c8721bbbSNaoya Horiguchi 		if (!is_migrate_isolate_page(page))
854c8721bbbSNaoya Horiguchi 			break;
855c8721bbbSNaoya Horiguchi 	/*
856c8721bbbSNaoya Horiguchi 	 * if 'non-isolated free hugepage' not found on the list,
857c8721bbbSNaoya Horiguchi 	 * the allocation fails.
858c8721bbbSNaoya Horiguchi 	 */
859c8721bbbSNaoya Horiguchi 	if (&h->hugepage_freelists[nid] == &page->lru)
860bf50bab2SNaoya Horiguchi 		return NULL;
8610edaecfaSAneesh Kumar K.V 	list_move(&page->lru, &h->hugepage_activelist);
862a9869b83SNaoya Horiguchi 	set_page_refcounted(page);
863bf50bab2SNaoya Horiguchi 	h->free_huge_pages--;
864bf50bab2SNaoya Horiguchi 	h->free_huge_pages_node[nid]--;
865bf50bab2SNaoya Horiguchi 	return page;
866bf50bab2SNaoya Horiguchi }
867bf50bab2SNaoya Horiguchi 
86886cdb465SNaoya Horiguchi /* Movability of hugepages depends on migration support. */
86986cdb465SNaoya Horiguchi static inline gfp_t htlb_alloc_mask(struct hstate *h)
87086cdb465SNaoya Horiguchi {
871100873d7SNaoya Horiguchi 	if (hugepages_treat_as_movable || hugepage_migration_supported(h))
87286cdb465SNaoya Horiguchi 		return GFP_HIGHUSER_MOVABLE;
87386cdb465SNaoya Horiguchi 	else
87486cdb465SNaoya Horiguchi 		return GFP_HIGHUSER;
87586cdb465SNaoya Horiguchi }
87686cdb465SNaoya Horiguchi 
877a5516438SAndi Kleen static struct page *dequeue_huge_page_vma(struct hstate *h,
878a5516438SAndi Kleen 				struct vm_area_struct *vma,
879af0ed73eSJoonsoo Kim 				unsigned long address, int avoid_reserve,
880af0ed73eSJoonsoo Kim 				long chg)
8811da177e4SLinus Torvalds {
882b1c12cbcSKonstantin Khlebnikov 	struct page *page = NULL;
883480eccf9SLee Schermerhorn 	struct mempolicy *mpol;
88419770b32SMel Gorman 	nodemask_t *nodemask;
885c0ff7453SMiao Xie 	struct zonelist *zonelist;
886dd1a239fSMel Gorman 	struct zone *zone;
887dd1a239fSMel Gorman 	struct zoneref *z;
888cc9a6c87SMel Gorman 	unsigned int cpuset_mems_cookie;
8891da177e4SLinus Torvalds 
890a1e78772SMel Gorman 	/*
891a1e78772SMel Gorman 	 * A child process with MAP_PRIVATE mappings created by their parent
892a1e78772SMel Gorman 	 * have no page reserves. This check ensures that reservations are
893a1e78772SMel Gorman 	 * not "stolen". The child may still get SIGKILLed
894a1e78772SMel Gorman 	 */
895af0ed73eSJoonsoo Kim 	if (!vma_has_reserves(vma, chg) &&
896a5516438SAndi Kleen 			h->free_huge_pages - h->resv_huge_pages == 0)
897c0ff7453SMiao Xie 		goto err;
898a1e78772SMel Gorman 
89904f2cbe3SMel Gorman 	/* If reserves cannot be used, ensure enough pages are in the pool */
900a5516438SAndi Kleen 	if (avoid_reserve && h->free_huge_pages - h->resv_huge_pages == 0)
9016eab04a8SJustin P. Mattock 		goto err;
90204f2cbe3SMel Gorman 
9039966c4bbSJoonsoo Kim retry_cpuset:
904d26914d1SMel Gorman 	cpuset_mems_cookie = read_mems_allowed_begin();
9059966c4bbSJoonsoo Kim 	zonelist = huge_zonelist(vma, address,
90686cdb465SNaoya Horiguchi 					htlb_alloc_mask(h), &mpol, &nodemask);
9079966c4bbSJoonsoo Kim 
90819770b32SMel Gorman 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
90919770b32SMel Gorman 						MAX_NR_ZONES - 1, nodemask) {
910344736f2SVladimir Davydov 		if (cpuset_zone_allowed(zone, htlb_alloc_mask(h))) {
911bf50bab2SNaoya Horiguchi 			page = dequeue_huge_page_node(h, zone_to_nid(zone));
912bf50bab2SNaoya Horiguchi 			if (page) {
913af0ed73eSJoonsoo Kim 				if (avoid_reserve)
914af0ed73eSJoonsoo Kim 					break;
915af0ed73eSJoonsoo Kim 				if (!vma_has_reserves(vma, chg))
916af0ed73eSJoonsoo Kim 					break;
917af0ed73eSJoonsoo Kim 
91807443a85SJoonsoo Kim 				SetPagePrivate(page);
919a63884e9SJoonsoo Kim 				h->resv_huge_pages--;
9205ab3ee7bSKen Chen 				break;
9211da177e4SLinus Torvalds 			}
9223abf7afdSAndrew Morton 		}
923bf50bab2SNaoya Horiguchi 	}
924cc9a6c87SMel Gorman 
925cc9a6c87SMel Gorman 	mpol_cond_put(mpol);
926d26914d1SMel Gorman 	if (unlikely(!page && read_mems_allowed_retry(cpuset_mems_cookie)))
927cc9a6c87SMel Gorman 		goto retry_cpuset;
928cc9a6c87SMel Gorman 	return page;
929cc9a6c87SMel Gorman 
930c0ff7453SMiao Xie err:
931cc9a6c87SMel Gorman 	return NULL;
9321da177e4SLinus Torvalds }
9331da177e4SLinus Torvalds 
9341cac6f2cSLuiz Capitulino /*
9351cac6f2cSLuiz Capitulino  * common helper functions for hstate_next_node_to_{alloc|free}.
9361cac6f2cSLuiz Capitulino  * We may have allocated or freed a huge page based on a different
9371cac6f2cSLuiz Capitulino  * nodes_allowed previously, so h->next_node_to_{alloc|free} might
9381cac6f2cSLuiz Capitulino  * be outside of *nodes_allowed.  Ensure that we use an allowed
9391cac6f2cSLuiz Capitulino  * node for alloc or free.
9401cac6f2cSLuiz Capitulino  */
9411cac6f2cSLuiz Capitulino static int next_node_allowed(int nid, nodemask_t *nodes_allowed)
9421cac6f2cSLuiz Capitulino {
9430edaf86cSAndrew Morton 	nid = next_node_in(nid, *nodes_allowed);
9441cac6f2cSLuiz Capitulino 	VM_BUG_ON(nid >= MAX_NUMNODES);
9451cac6f2cSLuiz Capitulino 
9461cac6f2cSLuiz Capitulino 	return nid;
9471cac6f2cSLuiz Capitulino }
9481cac6f2cSLuiz Capitulino 
9491cac6f2cSLuiz Capitulino static int get_valid_node_allowed(int nid, nodemask_t *nodes_allowed)
9501cac6f2cSLuiz Capitulino {
9511cac6f2cSLuiz Capitulino 	if (!node_isset(nid, *nodes_allowed))
9521cac6f2cSLuiz Capitulino 		nid = next_node_allowed(nid, nodes_allowed);
9531cac6f2cSLuiz Capitulino 	return nid;
9541cac6f2cSLuiz Capitulino }
9551cac6f2cSLuiz Capitulino 
9561cac6f2cSLuiz Capitulino /*
9571cac6f2cSLuiz Capitulino  * returns the previously saved node ["this node"] from which to
9581cac6f2cSLuiz Capitulino  * allocate a persistent huge page for the pool and advance the
9591cac6f2cSLuiz Capitulino  * next node from which to allocate, handling wrap at end of node
9601cac6f2cSLuiz Capitulino  * mask.
9611cac6f2cSLuiz Capitulino  */
9621cac6f2cSLuiz Capitulino static int hstate_next_node_to_alloc(struct hstate *h,
9631cac6f2cSLuiz Capitulino 					nodemask_t *nodes_allowed)
9641cac6f2cSLuiz Capitulino {
9651cac6f2cSLuiz Capitulino 	int nid;
9661cac6f2cSLuiz Capitulino 
9671cac6f2cSLuiz Capitulino 	VM_BUG_ON(!nodes_allowed);
9681cac6f2cSLuiz Capitulino 
9691cac6f2cSLuiz Capitulino 	nid = get_valid_node_allowed(h->next_nid_to_alloc, nodes_allowed);
9701cac6f2cSLuiz Capitulino 	h->next_nid_to_alloc = next_node_allowed(nid, nodes_allowed);
9711cac6f2cSLuiz Capitulino 
9721cac6f2cSLuiz Capitulino 	return nid;
9731cac6f2cSLuiz Capitulino }
9741cac6f2cSLuiz Capitulino 
9751cac6f2cSLuiz Capitulino /*
9761cac6f2cSLuiz Capitulino  * helper for free_pool_huge_page() - return the previously saved
9771cac6f2cSLuiz Capitulino  * node ["this node"] from which to free a huge page.  Advance the
9781cac6f2cSLuiz Capitulino  * next node id whether or not we find a free huge page to free so
9791cac6f2cSLuiz Capitulino  * that the next attempt to free addresses the next node.
9801cac6f2cSLuiz Capitulino  */
9811cac6f2cSLuiz Capitulino static int hstate_next_node_to_free(struct hstate *h, nodemask_t *nodes_allowed)
9821cac6f2cSLuiz Capitulino {
9831cac6f2cSLuiz Capitulino 	int nid;
9841cac6f2cSLuiz Capitulino 
9851cac6f2cSLuiz Capitulino 	VM_BUG_ON(!nodes_allowed);
9861cac6f2cSLuiz Capitulino 
9871cac6f2cSLuiz Capitulino 	nid = get_valid_node_allowed(h->next_nid_to_free, nodes_allowed);
9881cac6f2cSLuiz Capitulino 	h->next_nid_to_free = next_node_allowed(nid, nodes_allowed);
9891cac6f2cSLuiz Capitulino 
9901cac6f2cSLuiz Capitulino 	return nid;
9911cac6f2cSLuiz Capitulino }
9921cac6f2cSLuiz Capitulino 
9931cac6f2cSLuiz Capitulino #define for_each_node_mask_to_alloc(hs, nr_nodes, node, mask)		\
9941cac6f2cSLuiz Capitulino 	for (nr_nodes = nodes_weight(*mask);				\
9951cac6f2cSLuiz Capitulino 		nr_nodes > 0 &&						\
9961cac6f2cSLuiz Capitulino 		((node = hstate_next_node_to_alloc(hs, mask)) || 1);	\
9971cac6f2cSLuiz Capitulino 		nr_nodes--)
9981cac6f2cSLuiz Capitulino 
9991cac6f2cSLuiz Capitulino #define for_each_node_mask_to_free(hs, nr_nodes, node, mask)		\
10001cac6f2cSLuiz Capitulino 	for (nr_nodes = nodes_weight(*mask);				\
10011cac6f2cSLuiz Capitulino 		nr_nodes > 0 &&						\
10021cac6f2cSLuiz Capitulino 		((node = hstate_next_node_to_free(hs, mask)) || 1);	\
10031cac6f2cSLuiz Capitulino 		nr_nodes--)
10041cac6f2cSLuiz Capitulino 
1005080fe206SVlastimil Babka #if defined(CONFIG_X86_64) && ((defined(CONFIG_MEMORY_ISOLATION) && defined(CONFIG_COMPACTION)) || defined(CONFIG_CMA))
1006944d9fecSLuiz Capitulino static void destroy_compound_gigantic_page(struct page *page,
1007d00181b9SKirill A. Shutemov 					unsigned int order)
1008944d9fecSLuiz Capitulino {
1009944d9fecSLuiz Capitulino 	int i;
1010944d9fecSLuiz Capitulino 	int nr_pages = 1 << order;
1011944d9fecSLuiz Capitulino 	struct page *p = page + 1;
1012944d9fecSLuiz Capitulino 
1013944d9fecSLuiz Capitulino 	for (i = 1; i < nr_pages; i++, p = mem_map_next(p, page, i)) {
10141d798ca3SKirill A. Shutemov 		clear_compound_head(p);
1015944d9fecSLuiz Capitulino 		set_page_refcounted(p);
1016944d9fecSLuiz Capitulino 	}
1017944d9fecSLuiz Capitulino 
1018944d9fecSLuiz Capitulino 	set_compound_order(page, 0);
1019944d9fecSLuiz Capitulino 	__ClearPageHead(page);
1020944d9fecSLuiz Capitulino }
1021944d9fecSLuiz Capitulino 
1022d00181b9SKirill A. Shutemov static void free_gigantic_page(struct page *page, unsigned int order)
1023944d9fecSLuiz Capitulino {
1024944d9fecSLuiz Capitulino 	free_contig_range(page_to_pfn(page), 1 << order);
1025944d9fecSLuiz Capitulino }
1026944d9fecSLuiz Capitulino 
1027944d9fecSLuiz Capitulino static int __alloc_gigantic_page(unsigned long start_pfn,
1028944d9fecSLuiz Capitulino 				unsigned long nr_pages)
1029944d9fecSLuiz Capitulino {
1030944d9fecSLuiz Capitulino 	unsigned long end_pfn = start_pfn + nr_pages;
1031944d9fecSLuiz Capitulino 	return alloc_contig_range(start_pfn, end_pfn, MIGRATE_MOVABLE);
1032944d9fecSLuiz Capitulino }
1033944d9fecSLuiz Capitulino 
1034944d9fecSLuiz Capitulino static bool pfn_range_valid_gigantic(unsigned long start_pfn,
1035944d9fecSLuiz Capitulino 				unsigned long nr_pages)
1036944d9fecSLuiz Capitulino {
1037944d9fecSLuiz Capitulino 	unsigned long i, end_pfn = start_pfn + nr_pages;
1038944d9fecSLuiz Capitulino 	struct page *page;
1039944d9fecSLuiz Capitulino 
1040944d9fecSLuiz Capitulino 	for (i = start_pfn; i < end_pfn; i++) {
1041944d9fecSLuiz Capitulino 		if (!pfn_valid(i))
1042944d9fecSLuiz Capitulino 			return false;
1043944d9fecSLuiz Capitulino 
1044944d9fecSLuiz Capitulino 		page = pfn_to_page(i);
1045944d9fecSLuiz Capitulino 
1046944d9fecSLuiz Capitulino 		if (PageReserved(page))
1047944d9fecSLuiz Capitulino 			return false;
1048944d9fecSLuiz Capitulino 
1049944d9fecSLuiz Capitulino 		if (page_count(page) > 0)
1050944d9fecSLuiz Capitulino 			return false;
1051944d9fecSLuiz Capitulino 
1052944d9fecSLuiz Capitulino 		if (PageHuge(page))
1053944d9fecSLuiz Capitulino 			return false;
1054944d9fecSLuiz Capitulino 	}
1055944d9fecSLuiz Capitulino 
1056944d9fecSLuiz Capitulino 	return true;
1057944d9fecSLuiz Capitulino }
1058944d9fecSLuiz Capitulino 
1059944d9fecSLuiz Capitulino static bool zone_spans_last_pfn(const struct zone *zone,
1060944d9fecSLuiz Capitulino 			unsigned long start_pfn, unsigned long nr_pages)
1061944d9fecSLuiz Capitulino {
1062944d9fecSLuiz Capitulino 	unsigned long last_pfn = start_pfn + nr_pages - 1;
1063944d9fecSLuiz Capitulino 	return zone_spans_pfn(zone, last_pfn);
1064944d9fecSLuiz Capitulino }
1065944d9fecSLuiz Capitulino 
1066d00181b9SKirill A. Shutemov static struct page *alloc_gigantic_page(int nid, unsigned int order)
1067944d9fecSLuiz Capitulino {
1068944d9fecSLuiz Capitulino 	unsigned long nr_pages = 1 << order;
1069944d9fecSLuiz Capitulino 	unsigned long ret, pfn, flags;
1070944d9fecSLuiz Capitulino 	struct zone *z;
1071944d9fecSLuiz Capitulino 
1072944d9fecSLuiz Capitulino 	z = NODE_DATA(nid)->node_zones;
1073944d9fecSLuiz Capitulino 	for (; z - NODE_DATA(nid)->node_zones < MAX_NR_ZONES; z++) {
1074944d9fecSLuiz Capitulino 		spin_lock_irqsave(&z->lock, flags);
1075944d9fecSLuiz Capitulino 
1076944d9fecSLuiz Capitulino 		pfn = ALIGN(z->zone_start_pfn, nr_pages);
1077944d9fecSLuiz Capitulino 		while (zone_spans_last_pfn(z, pfn, nr_pages)) {
1078944d9fecSLuiz Capitulino 			if (pfn_range_valid_gigantic(pfn, nr_pages)) {
1079944d9fecSLuiz Capitulino 				/*
1080944d9fecSLuiz Capitulino 				 * We release the zone lock here because
1081944d9fecSLuiz Capitulino 				 * alloc_contig_range() will also lock the zone
1082944d9fecSLuiz Capitulino 				 * at some point. If there's an allocation
1083944d9fecSLuiz Capitulino 				 * spinning on this lock, it may win the race
1084944d9fecSLuiz Capitulino 				 * and cause alloc_contig_range() to fail...
1085944d9fecSLuiz Capitulino 				 */
1086944d9fecSLuiz Capitulino 				spin_unlock_irqrestore(&z->lock, flags);
1087944d9fecSLuiz Capitulino 				ret = __alloc_gigantic_page(pfn, nr_pages);
1088944d9fecSLuiz Capitulino 				if (!ret)
1089944d9fecSLuiz Capitulino 					return pfn_to_page(pfn);
1090944d9fecSLuiz Capitulino 				spin_lock_irqsave(&z->lock, flags);
1091944d9fecSLuiz Capitulino 			}
1092944d9fecSLuiz Capitulino 			pfn += nr_pages;
1093944d9fecSLuiz Capitulino 		}
1094944d9fecSLuiz Capitulino 
1095944d9fecSLuiz Capitulino 		spin_unlock_irqrestore(&z->lock, flags);
1096944d9fecSLuiz Capitulino 	}
1097944d9fecSLuiz Capitulino 
1098944d9fecSLuiz Capitulino 	return NULL;
1099944d9fecSLuiz Capitulino }
1100944d9fecSLuiz Capitulino 
1101944d9fecSLuiz Capitulino static void prep_new_huge_page(struct hstate *h, struct page *page, int nid);
1102d00181b9SKirill A. Shutemov static void prep_compound_gigantic_page(struct page *page, unsigned int order);
1103944d9fecSLuiz Capitulino 
1104944d9fecSLuiz Capitulino static struct page *alloc_fresh_gigantic_page_node(struct hstate *h, int nid)
1105944d9fecSLuiz Capitulino {
1106944d9fecSLuiz Capitulino 	struct page *page;
1107944d9fecSLuiz Capitulino 
1108944d9fecSLuiz Capitulino 	page = alloc_gigantic_page(nid, huge_page_order(h));
1109944d9fecSLuiz Capitulino 	if (page) {
1110944d9fecSLuiz Capitulino 		prep_compound_gigantic_page(page, huge_page_order(h));
1111944d9fecSLuiz Capitulino 		prep_new_huge_page(h, page, nid);
1112944d9fecSLuiz Capitulino 	}
1113944d9fecSLuiz Capitulino 
1114944d9fecSLuiz Capitulino 	return page;
1115944d9fecSLuiz Capitulino }
1116944d9fecSLuiz Capitulino 
1117944d9fecSLuiz Capitulino static int alloc_fresh_gigantic_page(struct hstate *h,
1118944d9fecSLuiz Capitulino 				nodemask_t *nodes_allowed)
1119944d9fecSLuiz Capitulino {
1120944d9fecSLuiz Capitulino 	struct page *page = NULL;
1121944d9fecSLuiz Capitulino 	int nr_nodes, node;
1122944d9fecSLuiz Capitulino 
1123944d9fecSLuiz Capitulino 	for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
1124944d9fecSLuiz Capitulino 		page = alloc_fresh_gigantic_page_node(h, node);
1125944d9fecSLuiz Capitulino 		if (page)
1126944d9fecSLuiz Capitulino 			return 1;
1127944d9fecSLuiz Capitulino 	}
1128944d9fecSLuiz Capitulino 
1129944d9fecSLuiz Capitulino 	return 0;
1130944d9fecSLuiz Capitulino }
1131944d9fecSLuiz Capitulino 
1132944d9fecSLuiz Capitulino static inline bool gigantic_page_supported(void) { return true; }
1133944d9fecSLuiz Capitulino #else
1134944d9fecSLuiz Capitulino static inline bool gigantic_page_supported(void) { return false; }
1135d00181b9SKirill A. Shutemov static inline void free_gigantic_page(struct page *page, unsigned int order) { }
1136944d9fecSLuiz Capitulino static inline void destroy_compound_gigantic_page(struct page *page,
1137d00181b9SKirill A. Shutemov 						unsigned int order) { }
1138944d9fecSLuiz Capitulino static inline int alloc_fresh_gigantic_page(struct hstate *h,
1139944d9fecSLuiz Capitulino 					nodemask_t *nodes_allowed) { return 0; }
1140944d9fecSLuiz Capitulino #endif
1141944d9fecSLuiz Capitulino 
1142a5516438SAndi Kleen static void update_and_free_page(struct hstate *h, struct page *page)
11436af2acb6SAdam Litke {
11446af2acb6SAdam Litke 	int i;
1145a5516438SAndi Kleen 
1146944d9fecSLuiz Capitulino 	if (hstate_is_gigantic(h) && !gigantic_page_supported())
1147944d9fecSLuiz Capitulino 		return;
114818229df5SAndy Whitcroft 
1149a5516438SAndi Kleen 	h->nr_huge_pages--;
1150a5516438SAndi Kleen 	h->nr_huge_pages_node[page_to_nid(page)]--;
1151a5516438SAndi Kleen 	for (i = 0; i < pages_per_huge_page(h); i++) {
115232f84528SChris Forbes 		page[i].flags &= ~(1 << PG_locked | 1 << PG_error |
115332f84528SChris Forbes 				1 << PG_referenced | 1 << PG_dirty |
1154a7407a27SLuiz Capitulino 				1 << PG_active | 1 << PG_private |
1155a7407a27SLuiz Capitulino 				1 << PG_writeback);
11566af2acb6SAdam Litke 	}
1157309381feSSasha Levin 	VM_BUG_ON_PAGE(hugetlb_cgroup_from_page(page), page);
1158f1e61557SKirill A. Shutemov 	set_compound_page_dtor(page, NULL_COMPOUND_DTOR);
11596af2acb6SAdam Litke 	set_page_refcounted(page);
1160944d9fecSLuiz Capitulino 	if (hstate_is_gigantic(h)) {
1161944d9fecSLuiz Capitulino 		destroy_compound_gigantic_page(page, huge_page_order(h));
1162944d9fecSLuiz Capitulino 		free_gigantic_page(page, huge_page_order(h));
1163944d9fecSLuiz Capitulino 	} else {
1164a5516438SAndi Kleen 		__free_pages(page, huge_page_order(h));
11656af2acb6SAdam Litke 	}
1166944d9fecSLuiz Capitulino }
11676af2acb6SAdam Litke 
1168e5ff2159SAndi Kleen struct hstate *size_to_hstate(unsigned long size)
1169e5ff2159SAndi Kleen {
1170e5ff2159SAndi Kleen 	struct hstate *h;
1171e5ff2159SAndi Kleen 
1172e5ff2159SAndi Kleen 	for_each_hstate(h) {
1173e5ff2159SAndi Kleen 		if (huge_page_size(h) == size)
1174e5ff2159SAndi Kleen 			return h;
1175e5ff2159SAndi Kleen 	}
1176e5ff2159SAndi Kleen 	return NULL;
1177e5ff2159SAndi Kleen }
1178e5ff2159SAndi Kleen 
1179bcc54222SNaoya Horiguchi /*
1180bcc54222SNaoya Horiguchi  * Test to determine whether the hugepage is "active/in-use" (i.e. being linked
1181bcc54222SNaoya Horiguchi  * to hstate->hugepage_activelist.)
1182bcc54222SNaoya Horiguchi  *
1183bcc54222SNaoya Horiguchi  * This function can be called for tail pages, but never returns true for them.
1184bcc54222SNaoya Horiguchi  */
1185bcc54222SNaoya Horiguchi bool page_huge_active(struct page *page)
1186bcc54222SNaoya Horiguchi {
1187bcc54222SNaoya Horiguchi 	VM_BUG_ON_PAGE(!PageHuge(page), page);
1188bcc54222SNaoya Horiguchi 	return PageHead(page) && PagePrivate(&page[1]);
1189bcc54222SNaoya Horiguchi }
1190bcc54222SNaoya Horiguchi 
1191bcc54222SNaoya Horiguchi /* never called for tail page */
1192bcc54222SNaoya Horiguchi static void set_page_huge_active(struct page *page)
1193bcc54222SNaoya Horiguchi {
1194bcc54222SNaoya Horiguchi 	VM_BUG_ON_PAGE(!PageHeadHuge(page), page);
1195bcc54222SNaoya Horiguchi 	SetPagePrivate(&page[1]);
1196bcc54222SNaoya Horiguchi }
1197bcc54222SNaoya Horiguchi 
1198bcc54222SNaoya Horiguchi static void clear_page_huge_active(struct page *page)
1199bcc54222SNaoya Horiguchi {
1200bcc54222SNaoya Horiguchi 	VM_BUG_ON_PAGE(!PageHeadHuge(page), page);
1201bcc54222SNaoya Horiguchi 	ClearPagePrivate(&page[1]);
1202bcc54222SNaoya Horiguchi }
1203bcc54222SNaoya Horiguchi 
12048f1d26d0SAtsushi Kumagai void free_huge_page(struct page *page)
120527a85ef1SDavid Gibson {
1206a5516438SAndi Kleen 	/*
1207a5516438SAndi Kleen 	 * Can't pass hstate in here because it is called from the
1208a5516438SAndi Kleen 	 * compound page destructor.
1209a5516438SAndi Kleen 	 */
1210e5ff2159SAndi Kleen 	struct hstate *h = page_hstate(page);
12117893d1d5SAdam Litke 	int nid = page_to_nid(page);
121290481622SDavid Gibson 	struct hugepage_subpool *spool =
121390481622SDavid Gibson 		(struct hugepage_subpool *)page_private(page);
121407443a85SJoonsoo Kim 	bool restore_reserve;
121527a85ef1SDavid Gibson 
1216e5df70abSAndy Whitcroft 	set_page_private(page, 0);
121723be7468SMel Gorman 	page->mapping = NULL;
1218b4330afbSMike Kravetz 	VM_BUG_ON_PAGE(page_count(page), page);
1219b4330afbSMike Kravetz 	VM_BUG_ON_PAGE(page_mapcount(page), page);
122007443a85SJoonsoo Kim 	restore_reserve = PagePrivate(page);
122116c794b4SJoonsoo Kim 	ClearPagePrivate(page);
122227a85ef1SDavid Gibson 
12231c5ecae3SMike Kravetz 	/*
12241c5ecae3SMike Kravetz 	 * A return code of zero implies that the subpool will be under its
12251c5ecae3SMike Kravetz 	 * minimum size if the reservation is not restored after page is free.
12261c5ecae3SMike Kravetz 	 * Therefore, force restore_reserve operation.
12271c5ecae3SMike Kravetz 	 */
12281c5ecae3SMike Kravetz 	if (hugepage_subpool_put_pages(spool, 1) == 0)
12291c5ecae3SMike Kravetz 		restore_reserve = true;
12301c5ecae3SMike Kravetz 
123127a85ef1SDavid Gibson 	spin_lock(&hugetlb_lock);
1232bcc54222SNaoya Horiguchi 	clear_page_huge_active(page);
12336d76dcf4SAneesh Kumar K.V 	hugetlb_cgroup_uncharge_page(hstate_index(h),
12346d76dcf4SAneesh Kumar K.V 				     pages_per_huge_page(h), page);
123507443a85SJoonsoo Kim 	if (restore_reserve)
123607443a85SJoonsoo Kim 		h->resv_huge_pages++;
123707443a85SJoonsoo Kim 
1238944d9fecSLuiz Capitulino 	if (h->surplus_huge_pages_node[nid]) {
12390edaecfaSAneesh Kumar K.V 		/* remove the page from active list */
12400edaecfaSAneesh Kumar K.V 		list_del(&page->lru);
1241a5516438SAndi Kleen 		update_and_free_page(h, page);
1242a5516438SAndi Kleen 		h->surplus_huge_pages--;
1243a5516438SAndi Kleen 		h->surplus_huge_pages_node[nid]--;
12447893d1d5SAdam Litke 	} else {
12455d3a551cSWill Deacon 		arch_clear_hugepage_flags(page);
1246a5516438SAndi Kleen 		enqueue_huge_page(h, page);
12477893d1d5SAdam Litke 	}
124827a85ef1SDavid Gibson 	spin_unlock(&hugetlb_lock);
124927a85ef1SDavid Gibson }
125027a85ef1SDavid Gibson 
1251a5516438SAndi Kleen static void prep_new_huge_page(struct hstate *h, struct page *page, int nid)
1252b7ba30c6SAndi Kleen {
12530edaecfaSAneesh Kumar K.V 	INIT_LIST_HEAD(&page->lru);
1254f1e61557SKirill A. Shutemov 	set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
1255b7ba30c6SAndi Kleen 	spin_lock(&hugetlb_lock);
12569dd540e2SAneesh Kumar K.V 	set_hugetlb_cgroup(page, NULL);
1257a5516438SAndi Kleen 	h->nr_huge_pages++;
1258a5516438SAndi Kleen 	h->nr_huge_pages_node[nid]++;
1259b7ba30c6SAndi Kleen 	spin_unlock(&hugetlb_lock);
1260b7ba30c6SAndi Kleen 	put_page(page); /* free it into the hugepage allocator */
1261b7ba30c6SAndi Kleen }
1262b7ba30c6SAndi Kleen 
1263d00181b9SKirill A. Shutemov static void prep_compound_gigantic_page(struct page *page, unsigned int order)
126420a0307cSWu Fengguang {
126520a0307cSWu Fengguang 	int i;
126620a0307cSWu Fengguang 	int nr_pages = 1 << order;
126720a0307cSWu Fengguang 	struct page *p = page + 1;
126820a0307cSWu Fengguang 
126920a0307cSWu Fengguang 	/* we rely on prep_new_huge_page to set the destructor */
127020a0307cSWu Fengguang 	set_compound_order(page, order);
1271ef5a22beSAndrea Arcangeli 	__ClearPageReserved(page);
1272de09d31dSKirill A. Shutemov 	__SetPageHead(page);
127320a0307cSWu Fengguang 	for (i = 1; i < nr_pages; i++, p = mem_map_next(p, page, i)) {
1274ef5a22beSAndrea Arcangeli 		/*
1275ef5a22beSAndrea Arcangeli 		 * For gigantic hugepages allocated through bootmem at
1276ef5a22beSAndrea Arcangeli 		 * boot, it's safer to be consistent with the not-gigantic
1277ef5a22beSAndrea Arcangeli 		 * hugepages and clear the PG_reserved bit from all tail pages
1278ef5a22beSAndrea Arcangeli 		 * too.  Otherwse drivers using get_user_pages() to access tail
1279ef5a22beSAndrea Arcangeli 		 * pages may get the reference counting wrong if they see
1280ef5a22beSAndrea Arcangeli 		 * PG_reserved set on a tail page (despite the head page not
1281ef5a22beSAndrea Arcangeli 		 * having PG_reserved set).  Enforcing this consistency between
1282ef5a22beSAndrea Arcangeli 		 * head and tail pages allows drivers to optimize away a check
1283ef5a22beSAndrea Arcangeli 		 * on the head page when they need know if put_page() is needed
1284ef5a22beSAndrea Arcangeli 		 * after get_user_pages().
1285ef5a22beSAndrea Arcangeli 		 */
1286ef5a22beSAndrea Arcangeli 		__ClearPageReserved(p);
128758a84aa9SYouquan Song 		set_page_count(p, 0);
12881d798ca3SKirill A. Shutemov 		set_compound_head(p, page);
128920a0307cSWu Fengguang 	}
1290b4330afbSMike Kravetz 	atomic_set(compound_mapcount_ptr(page), -1);
129120a0307cSWu Fengguang }
129220a0307cSWu Fengguang 
12937795912cSAndrew Morton /*
12947795912cSAndrew Morton  * PageHuge() only returns true for hugetlbfs pages, but not for normal or
12957795912cSAndrew Morton  * transparent huge pages.  See the PageTransHuge() documentation for more
12967795912cSAndrew Morton  * details.
12977795912cSAndrew Morton  */
129820a0307cSWu Fengguang int PageHuge(struct page *page)
129920a0307cSWu Fengguang {
130020a0307cSWu Fengguang 	if (!PageCompound(page))
130120a0307cSWu Fengguang 		return 0;
130220a0307cSWu Fengguang 
130320a0307cSWu Fengguang 	page = compound_head(page);
1304f1e61557SKirill A. Shutemov 	return page[1].compound_dtor == HUGETLB_PAGE_DTOR;
130520a0307cSWu Fengguang }
130643131e14SNaoya Horiguchi EXPORT_SYMBOL_GPL(PageHuge);
130743131e14SNaoya Horiguchi 
130827c73ae7SAndrea Arcangeli /*
130927c73ae7SAndrea Arcangeli  * PageHeadHuge() only returns true for hugetlbfs head page, but not for
131027c73ae7SAndrea Arcangeli  * normal or transparent huge pages.
131127c73ae7SAndrea Arcangeli  */
131227c73ae7SAndrea Arcangeli int PageHeadHuge(struct page *page_head)
131327c73ae7SAndrea Arcangeli {
131427c73ae7SAndrea Arcangeli 	if (!PageHead(page_head))
131527c73ae7SAndrea Arcangeli 		return 0;
131627c73ae7SAndrea Arcangeli 
1317758f66a2SAndrew Morton 	return get_compound_page_dtor(page_head) == free_huge_page;
131827c73ae7SAndrea Arcangeli }
131927c73ae7SAndrea Arcangeli 
132013d60f4bSZhang Yi pgoff_t __basepage_index(struct page *page)
132113d60f4bSZhang Yi {
132213d60f4bSZhang Yi 	struct page *page_head = compound_head(page);
132313d60f4bSZhang Yi 	pgoff_t index = page_index(page_head);
132413d60f4bSZhang Yi 	unsigned long compound_idx;
132513d60f4bSZhang Yi 
132613d60f4bSZhang Yi 	if (!PageHuge(page_head))
132713d60f4bSZhang Yi 		return page_index(page);
132813d60f4bSZhang Yi 
132913d60f4bSZhang Yi 	if (compound_order(page_head) >= MAX_ORDER)
133013d60f4bSZhang Yi 		compound_idx = page_to_pfn(page) - page_to_pfn(page_head);
133113d60f4bSZhang Yi 	else
133213d60f4bSZhang Yi 		compound_idx = page - page_head;
133313d60f4bSZhang Yi 
133413d60f4bSZhang Yi 	return (index << compound_order(page_head)) + compound_idx;
133513d60f4bSZhang Yi }
133613d60f4bSZhang Yi 
1337a5516438SAndi Kleen static struct page *alloc_fresh_huge_page_node(struct hstate *h, int nid)
13381da177e4SLinus Torvalds {
13391da177e4SLinus Torvalds 	struct page *page;
1340f96efd58SJoe Jin 
134196db800fSVlastimil Babka 	page = __alloc_pages_node(nid,
134286cdb465SNaoya Horiguchi 		htlb_alloc_mask(h)|__GFP_COMP|__GFP_THISNODE|
1343551883aeSNishanth Aravamudan 						__GFP_REPEAT|__GFP_NOWARN,
1344a5516438SAndi Kleen 		huge_page_order(h));
13451da177e4SLinus Torvalds 	if (page) {
1346a5516438SAndi Kleen 		prep_new_huge_page(h, page, nid);
13471da177e4SLinus Torvalds 	}
134863b4613cSNishanth Aravamudan 
134963b4613cSNishanth Aravamudan 	return page;
135063b4613cSNishanth Aravamudan }
135163b4613cSNishanth Aravamudan 
1352b2261026SJoonsoo Kim static int alloc_fresh_huge_page(struct hstate *h, nodemask_t *nodes_allowed)
1353b2261026SJoonsoo Kim {
1354b2261026SJoonsoo Kim 	struct page *page;
1355b2261026SJoonsoo Kim 	int nr_nodes, node;
1356b2261026SJoonsoo Kim 	int ret = 0;
1357b2261026SJoonsoo Kim 
1358b2261026SJoonsoo Kim 	for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
1359b2261026SJoonsoo Kim 		page = alloc_fresh_huge_page_node(h, node);
1360b2261026SJoonsoo Kim 		if (page) {
1361b2261026SJoonsoo Kim 			ret = 1;
1362b2261026SJoonsoo Kim 			break;
1363b2261026SJoonsoo Kim 		}
1364b2261026SJoonsoo Kim 	}
1365b2261026SJoonsoo Kim 
1366b2261026SJoonsoo Kim 	if (ret)
1367b2261026SJoonsoo Kim 		count_vm_event(HTLB_BUDDY_PGALLOC);
1368b2261026SJoonsoo Kim 	else
1369b2261026SJoonsoo Kim 		count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
1370b2261026SJoonsoo Kim 
1371b2261026SJoonsoo Kim 	return ret;
1372b2261026SJoonsoo Kim }
1373b2261026SJoonsoo Kim 
1374e8c5c824SLee Schermerhorn /*
1375e8c5c824SLee Schermerhorn  * Free huge page from pool from next node to free.
1376e8c5c824SLee Schermerhorn  * Attempt to keep persistent huge pages more or less
1377e8c5c824SLee Schermerhorn  * balanced over allowed nodes.
1378e8c5c824SLee Schermerhorn  * Called with hugetlb_lock locked.
1379e8c5c824SLee Schermerhorn  */
13806ae11b27SLee Schermerhorn static int free_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed,
13816ae11b27SLee Schermerhorn 							 bool acct_surplus)
1382e8c5c824SLee Schermerhorn {
1383b2261026SJoonsoo Kim 	int nr_nodes, node;
1384e8c5c824SLee Schermerhorn 	int ret = 0;
1385e8c5c824SLee Schermerhorn 
1386b2261026SJoonsoo Kim 	for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
1387685f3457SLee Schermerhorn 		/*
1388685f3457SLee Schermerhorn 		 * If we're returning unused surplus pages, only examine
1389685f3457SLee Schermerhorn 		 * nodes with surplus pages.
1390685f3457SLee Schermerhorn 		 */
1391b2261026SJoonsoo Kim 		if ((!acct_surplus || h->surplus_huge_pages_node[node]) &&
1392b2261026SJoonsoo Kim 		    !list_empty(&h->hugepage_freelists[node])) {
1393e8c5c824SLee Schermerhorn 			struct page *page =
1394b2261026SJoonsoo Kim 				list_entry(h->hugepage_freelists[node].next,
1395e8c5c824SLee Schermerhorn 					  struct page, lru);
1396e8c5c824SLee Schermerhorn 			list_del(&page->lru);
1397e8c5c824SLee Schermerhorn 			h->free_huge_pages--;
1398b2261026SJoonsoo Kim 			h->free_huge_pages_node[node]--;
1399685f3457SLee Schermerhorn 			if (acct_surplus) {
1400685f3457SLee Schermerhorn 				h->surplus_huge_pages--;
1401b2261026SJoonsoo Kim 				h->surplus_huge_pages_node[node]--;
1402685f3457SLee Schermerhorn 			}
1403e8c5c824SLee Schermerhorn 			update_and_free_page(h, page);
1404e8c5c824SLee Schermerhorn 			ret = 1;
14059a76db09SLee Schermerhorn 			break;
1406e8c5c824SLee Schermerhorn 		}
1407b2261026SJoonsoo Kim 	}
1408e8c5c824SLee Schermerhorn 
1409e8c5c824SLee Schermerhorn 	return ret;
1410e8c5c824SLee Schermerhorn }
1411e8c5c824SLee Schermerhorn 
1412c8721bbbSNaoya Horiguchi /*
1413c8721bbbSNaoya Horiguchi  * Dissolve a given free hugepage into free buddy pages. This function does
1414c8721bbbSNaoya Horiguchi  * nothing for in-use (including surplus) hugepages.
1415c8721bbbSNaoya Horiguchi  */
1416c8721bbbSNaoya Horiguchi static void dissolve_free_huge_page(struct page *page)
1417c8721bbbSNaoya Horiguchi {
1418c8721bbbSNaoya Horiguchi 	spin_lock(&hugetlb_lock);
1419c8721bbbSNaoya Horiguchi 	if (PageHuge(page) && !page_count(page)) {
1420c8721bbbSNaoya Horiguchi 		struct hstate *h = page_hstate(page);
1421c8721bbbSNaoya Horiguchi 		int nid = page_to_nid(page);
1422c8721bbbSNaoya Horiguchi 		list_del(&page->lru);
1423c8721bbbSNaoya Horiguchi 		h->free_huge_pages--;
1424c8721bbbSNaoya Horiguchi 		h->free_huge_pages_node[nid]--;
1425c8721bbbSNaoya Horiguchi 		update_and_free_page(h, page);
1426c8721bbbSNaoya Horiguchi 	}
1427c8721bbbSNaoya Horiguchi 	spin_unlock(&hugetlb_lock);
1428c8721bbbSNaoya Horiguchi }
1429c8721bbbSNaoya Horiguchi 
1430c8721bbbSNaoya Horiguchi /*
1431c8721bbbSNaoya Horiguchi  * Dissolve free hugepages in a given pfn range. Used by memory hotplug to
1432c8721bbbSNaoya Horiguchi  * make specified memory blocks removable from the system.
1433c8721bbbSNaoya Horiguchi  * Note that start_pfn should aligned with (minimum) hugepage size.
1434c8721bbbSNaoya Horiguchi  */
1435c8721bbbSNaoya Horiguchi void dissolve_free_huge_pages(unsigned long start_pfn, unsigned long end_pfn)
1436c8721bbbSNaoya Horiguchi {
1437c8721bbbSNaoya Horiguchi 	unsigned long pfn;
1438c8721bbbSNaoya Horiguchi 
1439d0177639SLi Zhong 	if (!hugepages_supported())
1440d0177639SLi Zhong 		return;
1441d0177639SLi Zhong 
1442641844f5SNaoya Horiguchi 	VM_BUG_ON(!IS_ALIGNED(start_pfn, 1 << minimum_order));
1443641844f5SNaoya Horiguchi 	for (pfn = start_pfn; pfn < end_pfn; pfn += 1 << minimum_order)
1444c8721bbbSNaoya Horiguchi 		dissolve_free_huge_page(pfn_to_page(pfn));
1445c8721bbbSNaoya Horiguchi }
1446c8721bbbSNaoya Horiguchi 
1447099730d6SDave Hansen /*
1448099730d6SDave Hansen  * There are 3 ways this can get called:
1449099730d6SDave Hansen  * 1. With vma+addr: we use the VMA's memory policy
1450099730d6SDave Hansen  * 2. With !vma, but nid=NUMA_NO_NODE:  We try to allocate a huge
1451099730d6SDave Hansen  *    page from any node, and let the buddy allocator itself figure
1452099730d6SDave Hansen  *    it out.
1453099730d6SDave Hansen  * 3. With !vma, but nid!=NUMA_NO_NODE.  We allocate a huge page
1454099730d6SDave Hansen  *    strictly from 'nid'
1455099730d6SDave Hansen  */
1456099730d6SDave Hansen static struct page *__hugetlb_alloc_buddy_huge_page(struct hstate *h,
1457099730d6SDave Hansen 		struct vm_area_struct *vma, unsigned long addr, int nid)
1458099730d6SDave Hansen {
1459099730d6SDave Hansen 	int order = huge_page_order(h);
1460099730d6SDave Hansen 	gfp_t gfp = htlb_alloc_mask(h)|__GFP_COMP|__GFP_REPEAT|__GFP_NOWARN;
1461099730d6SDave Hansen 	unsigned int cpuset_mems_cookie;
1462099730d6SDave Hansen 
1463099730d6SDave Hansen 	/*
1464099730d6SDave Hansen 	 * We need a VMA to get a memory policy.  If we do not
1465e0ec90eeSDave Hansen 	 * have one, we use the 'nid' argument.
1466e0ec90eeSDave Hansen 	 *
1467e0ec90eeSDave Hansen 	 * The mempolicy stuff below has some non-inlined bits
1468e0ec90eeSDave Hansen 	 * and calls ->vm_ops.  That makes it hard to optimize at
1469e0ec90eeSDave Hansen 	 * compile-time, even when NUMA is off and it does
1470e0ec90eeSDave Hansen 	 * nothing.  This helps the compiler optimize it out.
1471099730d6SDave Hansen 	 */
1472e0ec90eeSDave Hansen 	if (!IS_ENABLED(CONFIG_NUMA) || !vma) {
1473099730d6SDave Hansen 		/*
1474099730d6SDave Hansen 		 * If a specific node is requested, make sure to
1475099730d6SDave Hansen 		 * get memory from there, but only when a node
1476099730d6SDave Hansen 		 * is explicitly specified.
1477099730d6SDave Hansen 		 */
1478099730d6SDave Hansen 		if (nid != NUMA_NO_NODE)
1479099730d6SDave Hansen 			gfp |= __GFP_THISNODE;
1480099730d6SDave Hansen 		/*
1481099730d6SDave Hansen 		 * Make sure to call something that can handle
1482099730d6SDave Hansen 		 * nid=NUMA_NO_NODE
1483099730d6SDave Hansen 		 */
1484099730d6SDave Hansen 		return alloc_pages_node(nid, gfp, order);
1485099730d6SDave Hansen 	}
1486099730d6SDave Hansen 
1487099730d6SDave Hansen 	/*
1488099730d6SDave Hansen 	 * OK, so we have a VMA.  Fetch the mempolicy and try to
1489e0ec90eeSDave Hansen 	 * allocate a huge page with it.  We will only reach this
1490e0ec90eeSDave Hansen 	 * when CONFIG_NUMA=y.
1491099730d6SDave Hansen 	 */
1492099730d6SDave Hansen 	do {
1493099730d6SDave Hansen 		struct page *page;
1494099730d6SDave Hansen 		struct mempolicy *mpol;
1495099730d6SDave Hansen 		struct zonelist *zl;
1496099730d6SDave Hansen 		nodemask_t *nodemask;
1497099730d6SDave Hansen 
1498099730d6SDave Hansen 		cpuset_mems_cookie = read_mems_allowed_begin();
1499099730d6SDave Hansen 		zl = huge_zonelist(vma, addr, gfp, &mpol, &nodemask);
1500099730d6SDave Hansen 		mpol_cond_put(mpol);
1501099730d6SDave Hansen 		page = __alloc_pages_nodemask(gfp, order, zl, nodemask);
1502099730d6SDave Hansen 		if (page)
1503099730d6SDave Hansen 			return page;
1504099730d6SDave Hansen 	} while (read_mems_allowed_retry(cpuset_mems_cookie));
1505099730d6SDave Hansen 
1506099730d6SDave Hansen 	return NULL;
1507099730d6SDave Hansen }
1508099730d6SDave Hansen 
1509099730d6SDave Hansen /*
1510099730d6SDave Hansen  * There are two ways to allocate a huge page:
1511099730d6SDave Hansen  * 1. When you have a VMA and an address (like a fault)
1512099730d6SDave Hansen  * 2. When you have no VMA (like when setting /proc/.../nr_hugepages)
1513099730d6SDave Hansen  *
1514099730d6SDave Hansen  * 'vma' and 'addr' are only for (1).  'nid' is always NUMA_NO_NODE in
1515099730d6SDave Hansen  * this case which signifies that the allocation should be done with
1516099730d6SDave Hansen  * respect for the VMA's memory policy.
1517099730d6SDave Hansen  *
1518099730d6SDave Hansen  * For (2), we ignore 'vma' and 'addr' and use 'nid' exclusively. This
1519099730d6SDave Hansen  * implies that memory policies will not be taken in to account.
1520099730d6SDave Hansen  */
1521099730d6SDave Hansen static struct page *__alloc_buddy_huge_page(struct hstate *h,
1522099730d6SDave Hansen 		struct vm_area_struct *vma, unsigned long addr, int nid)
15237893d1d5SAdam Litke {
15247893d1d5SAdam Litke 	struct page *page;
1525bf50bab2SNaoya Horiguchi 	unsigned int r_nid;
15267893d1d5SAdam Litke 
1527bae7f4aeSLuiz Capitulino 	if (hstate_is_gigantic(h))
1528aa888a74SAndi Kleen 		return NULL;
1529aa888a74SAndi Kleen 
1530d1c3fb1fSNishanth Aravamudan 	/*
1531099730d6SDave Hansen 	 * Make sure that anyone specifying 'nid' is not also specifying a VMA.
1532099730d6SDave Hansen 	 * This makes sure the caller is picking _one_ of the modes with which
1533099730d6SDave Hansen 	 * we can call this function, not both.
1534099730d6SDave Hansen 	 */
1535099730d6SDave Hansen 	if (vma || (addr != -1)) {
1536e0ec90eeSDave Hansen 		VM_WARN_ON_ONCE(addr == -1);
1537e0ec90eeSDave Hansen 		VM_WARN_ON_ONCE(nid != NUMA_NO_NODE);
1538099730d6SDave Hansen 	}
1539099730d6SDave Hansen 	/*
1540d1c3fb1fSNishanth Aravamudan 	 * Assume we will successfully allocate the surplus page to
1541d1c3fb1fSNishanth Aravamudan 	 * prevent racing processes from causing the surplus to exceed
1542d1c3fb1fSNishanth Aravamudan 	 * overcommit
1543d1c3fb1fSNishanth Aravamudan 	 *
1544d1c3fb1fSNishanth Aravamudan 	 * This however introduces a different race, where a process B
1545d1c3fb1fSNishanth Aravamudan 	 * tries to grow the static hugepage pool while alloc_pages() is
1546d1c3fb1fSNishanth Aravamudan 	 * called by process A. B will only examine the per-node
1547d1c3fb1fSNishanth Aravamudan 	 * counters in determining if surplus huge pages can be
1548d1c3fb1fSNishanth Aravamudan 	 * converted to normal huge pages in adjust_pool_surplus(). A
1549d1c3fb1fSNishanth Aravamudan 	 * won't be able to increment the per-node counter, until the
1550d1c3fb1fSNishanth Aravamudan 	 * lock is dropped by B, but B doesn't drop hugetlb_lock until
1551d1c3fb1fSNishanth Aravamudan 	 * no more huge pages can be converted from surplus to normal
1552d1c3fb1fSNishanth Aravamudan 	 * state (and doesn't try to convert again). Thus, we have a
1553d1c3fb1fSNishanth Aravamudan 	 * case where a surplus huge page exists, the pool is grown, and
1554d1c3fb1fSNishanth Aravamudan 	 * the surplus huge page still exists after, even though it
1555d1c3fb1fSNishanth Aravamudan 	 * should just have been converted to a normal huge page. This
1556d1c3fb1fSNishanth Aravamudan 	 * does not leak memory, though, as the hugepage will be freed
1557d1c3fb1fSNishanth Aravamudan 	 * once it is out of use. It also does not allow the counters to
1558d1c3fb1fSNishanth Aravamudan 	 * go out of whack in adjust_pool_surplus() as we don't modify
1559d1c3fb1fSNishanth Aravamudan 	 * the node values until we've gotten the hugepage and only the
1560d1c3fb1fSNishanth Aravamudan 	 * per-node value is checked there.
1561d1c3fb1fSNishanth Aravamudan 	 */
1562d1c3fb1fSNishanth Aravamudan 	spin_lock(&hugetlb_lock);
1563a5516438SAndi Kleen 	if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) {
1564d1c3fb1fSNishanth Aravamudan 		spin_unlock(&hugetlb_lock);
1565d1c3fb1fSNishanth Aravamudan 		return NULL;
1566d1c3fb1fSNishanth Aravamudan 	} else {
1567a5516438SAndi Kleen 		h->nr_huge_pages++;
1568a5516438SAndi Kleen 		h->surplus_huge_pages++;
1569d1c3fb1fSNishanth Aravamudan 	}
1570d1c3fb1fSNishanth Aravamudan 	spin_unlock(&hugetlb_lock);
1571d1c3fb1fSNishanth Aravamudan 
1572099730d6SDave Hansen 	page = __hugetlb_alloc_buddy_huge_page(h, vma, addr, nid);
1573d1c3fb1fSNishanth Aravamudan 
15747893d1d5SAdam Litke 	spin_lock(&hugetlb_lock);
1575d1c3fb1fSNishanth Aravamudan 	if (page) {
15760edaecfaSAneesh Kumar K.V 		INIT_LIST_HEAD(&page->lru);
1577bf50bab2SNaoya Horiguchi 		r_nid = page_to_nid(page);
1578f1e61557SKirill A. Shutemov 		set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
15799dd540e2SAneesh Kumar K.V 		set_hugetlb_cgroup(page, NULL);
1580d1c3fb1fSNishanth Aravamudan 		/*
1581d1c3fb1fSNishanth Aravamudan 		 * We incremented the global counters already
1582d1c3fb1fSNishanth Aravamudan 		 */
1583bf50bab2SNaoya Horiguchi 		h->nr_huge_pages_node[r_nid]++;
1584bf50bab2SNaoya Horiguchi 		h->surplus_huge_pages_node[r_nid]++;
15853b116300SAdam Litke 		__count_vm_event(HTLB_BUDDY_PGALLOC);
1586d1c3fb1fSNishanth Aravamudan 	} else {
1587a5516438SAndi Kleen 		h->nr_huge_pages--;
1588a5516438SAndi Kleen 		h->surplus_huge_pages--;
15893b116300SAdam Litke 		__count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
15907893d1d5SAdam Litke 	}
1591d1c3fb1fSNishanth Aravamudan 	spin_unlock(&hugetlb_lock);
15927893d1d5SAdam Litke 
15937893d1d5SAdam Litke 	return page;
15947893d1d5SAdam Litke }
15957893d1d5SAdam Litke 
1596e4e574b7SAdam Litke /*
1597099730d6SDave Hansen  * Allocate a huge page from 'nid'.  Note, 'nid' may be
1598099730d6SDave Hansen  * NUMA_NO_NODE, which means that it may be allocated
1599099730d6SDave Hansen  * anywhere.
1600099730d6SDave Hansen  */
1601e0ec90eeSDave Hansen static
1602099730d6SDave Hansen struct page *__alloc_buddy_huge_page_no_mpol(struct hstate *h, int nid)
1603099730d6SDave Hansen {
1604099730d6SDave Hansen 	unsigned long addr = -1;
1605099730d6SDave Hansen 
1606099730d6SDave Hansen 	return __alloc_buddy_huge_page(h, NULL, addr, nid);
1607099730d6SDave Hansen }
1608099730d6SDave Hansen 
1609099730d6SDave Hansen /*
1610099730d6SDave Hansen  * Use the VMA's mpolicy to allocate a huge page from the buddy.
1611099730d6SDave Hansen  */
1612e0ec90eeSDave Hansen static
1613099730d6SDave Hansen struct page *__alloc_buddy_huge_page_with_mpol(struct hstate *h,
1614099730d6SDave Hansen 		struct vm_area_struct *vma, unsigned long addr)
1615099730d6SDave Hansen {
1616099730d6SDave Hansen 	return __alloc_buddy_huge_page(h, vma, addr, NUMA_NO_NODE);
1617099730d6SDave Hansen }
1618099730d6SDave Hansen 
1619099730d6SDave Hansen /*
1620bf50bab2SNaoya Horiguchi  * This allocation function is useful in the context where vma is irrelevant.
1621bf50bab2SNaoya Horiguchi  * E.g. soft-offlining uses this function because it only cares physical
1622bf50bab2SNaoya Horiguchi  * address of error page.
1623bf50bab2SNaoya Horiguchi  */
1624bf50bab2SNaoya Horiguchi struct page *alloc_huge_page_node(struct hstate *h, int nid)
1625bf50bab2SNaoya Horiguchi {
16264ef91848SJoonsoo Kim 	struct page *page = NULL;
1627bf50bab2SNaoya Horiguchi 
1628bf50bab2SNaoya Horiguchi 	spin_lock(&hugetlb_lock);
16294ef91848SJoonsoo Kim 	if (h->free_huge_pages - h->resv_huge_pages > 0)
1630bf50bab2SNaoya Horiguchi 		page = dequeue_huge_page_node(h, nid);
1631bf50bab2SNaoya Horiguchi 	spin_unlock(&hugetlb_lock);
1632bf50bab2SNaoya Horiguchi 
163394ae8ba7SAneesh Kumar K.V 	if (!page)
1634099730d6SDave Hansen 		page = __alloc_buddy_huge_page_no_mpol(h, nid);
1635bf50bab2SNaoya Horiguchi 
1636bf50bab2SNaoya Horiguchi 	return page;
1637bf50bab2SNaoya Horiguchi }
1638bf50bab2SNaoya Horiguchi 
1639bf50bab2SNaoya Horiguchi /*
164025985edcSLucas De Marchi  * Increase the hugetlb pool such that it can accommodate a reservation
1641e4e574b7SAdam Litke  * of size 'delta'.
1642e4e574b7SAdam Litke  */
1643a5516438SAndi Kleen static int gather_surplus_pages(struct hstate *h, int delta)
1644e4e574b7SAdam Litke {
1645e4e574b7SAdam Litke 	struct list_head surplus_list;
1646e4e574b7SAdam Litke 	struct page *page, *tmp;
1647e4e574b7SAdam Litke 	int ret, i;
1648e4e574b7SAdam Litke 	int needed, allocated;
164928073b02SHillf Danton 	bool alloc_ok = true;
1650e4e574b7SAdam Litke 
1651a5516438SAndi Kleen 	needed = (h->resv_huge_pages + delta) - h->free_huge_pages;
1652ac09b3a1SAdam Litke 	if (needed <= 0) {
1653a5516438SAndi Kleen 		h->resv_huge_pages += delta;
1654e4e574b7SAdam Litke 		return 0;
1655ac09b3a1SAdam Litke 	}
1656e4e574b7SAdam Litke 
1657e4e574b7SAdam Litke 	allocated = 0;
1658e4e574b7SAdam Litke 	INIT_LIST_HEAD(&surplus_list);
1659e4e574b7SAdam Litke 
1660e4e574b7SAdam Litke 	ret = -ENOMEM;
1661e4e574b7SAdam Litke retry:
1662e4e574b7SAdam Litke 	spin_unlock(&hugetlb_lock);
1663e4e574b7SAdam Litke 	for (i = 0; i < needed; i++) {
1664099730d6SDave Hansen 		page = __alloc_buddy_huge_page_no_mpol(h, NUMA_NO_NODE);
166528073b02SHillf Danton 		if (!page) {
166628073b02SHillf Danton 			alloc_ok = false;
166728073b02SHillf Danton 			break;
166828073b02SHillf Danton 		}
1669e4e574b7SAdam Litke 		list_add(&page->lru, &surplus_list);
1670e4e574b7SAdam Litke 	}
167128073b02SHillf Danton 	allocated += i;
1672e4e574b7SAdam Litke 
1673e4e574b7SAdam Litke 	/*
1674e4e574b7SAdam Litke 	 * After retaking hugetlb_lock, we need to recalculate 'needed'
1675e4e574b7SAdam Litke 	 * because either resv_huge_pages or free_huge_pages may have changed.
1676e4e574b7SAdam Litke 	 */
1677e4e574b7SAdam Litke 	spin_lock(&hugetlb_lock);
1678a5516438SAndi Kleen 	needed = (h->resv_huge_pages + delta) -
1679a5516438SAndi Kleen 			(h->free_huge_pages + allocated);
168028073b02SHillf Danton 	if (needed > 0) {
168128073b02SHillf Danton 		if (alloc_ok)
1682e4e574b7SAdam Litke 			goto retry;
168328073b02SHillf Danton 		/*
168428073b02SHillf Danton 		 * We were not able to allocate enough pages to
168528073b02SHillf Danton 		 * satisfy the entire reservation so we free what
168628073b02SHillf Danton 		 * we've allocated so far.
168728073b02SHillf Danton 		 */
168828073b02SHillf Danton 		goto free;
168928073b02SHillf Danton 	}
1690e4e574b7SAdam Litke 	/*
1691e4e574b7SAdam Litke 	 * The surplus_list now contains _at_least_ the number of extra pages
169225985edcSLucas De Marchi 	 * needed to accommodate the reservation.  Add the appropriate number
1693e4e574b7SAdam Litke 	 * of pages to the hugetlb pool and free the extras back to the buddy
1694ac09b3a1SAdam Litke 	 * allocator.  Commit the entire reservation here to prevent another
1695ac09b3a1SAdam Litke 	 * process from stealing the pages as they are added to the pool but
1696ac09b3a1SAdam Litke 	 * before they are reserved.
1697e4e574b7SAdam Litke 	 */
1698e4e574b7SAdam Litke 	needed += allocated;
1699a5516438SAndi Kleen 	h->resv_huge_pages += delta;
1700e4e574b7SAdam Litke 	ret = 0;
1701a9869b83SNaoya Horiguchi 
170219fc3f0aSAdam Litke 	/* Free the needed pages to the hugetlb pool */
170319fc3f0aSAdam Litke 	list_for_each_entry_safe(page, tmp, &surplus_list, lru) {
170419fc3f0aSAdam Litke 		if ((--needed) < 0)
170519fc3f0aSAdam Litke 			break;
1706a9869b83SNaoya Horiguchi 		/*
1707a9869b83SNaoya Horiguchi 		 * This page is now managed by the hugetlb allocator and has
1708a9869b83SNaoya Horiguchi 		 * no users -- drop the buddy allocator's reference.
1709a9869b83SNaoya Horiguchi 		 */
1710a9869b83SNaoya Horiguchi 		put_page_testzero(page);
1711309381feSSasha Levin 		VM_BUG_ON_PAGE(page_count(page), page);
1712a5516438SAndi Kleen 		enqueue_huge_page(h, page);
171319fc3f0aSAdam Litke 	}
171428073b02SHillf Danton free:
1715b0365c8dSHillf Danton 	spin_unlock(&hugetlb_lock);
171619fc3f0aSAdam Litke 
171719fc3f0aSAdam Litke 	/* Free unnecessary surplus pages to the buddy allocator */
1718c0d934baSJoonsoo Kim 	list_for_each_entry_safe(page, tmp, &surplus_list, lru)
1719a9869b83SNaoya Horiguchi 		put_page(page);
172019fc3f0aSAdam Litke 	spin_lock(&hugetlb_lock);
1721e4e574b7SAdam Litke 
1722e4e574b7SAdam Litke 	return ret;
1723e4e574b7SAdam Litke }
1724e4e574b7SAdam Litke 
1725e4e574b7SAdam Litke /*
1726e4e574b7SAdam Litke  * When releasing a hugetlb pool reservation, any surplus pages that were
1727e4e574b7SAdam Litke  * allocated to satisfy the reservation must be explicitly freed if they were
1728e4e574b7SAdam Litke  * never used.
1729685f3457SLee Schermerhorn  * Called with hugetlb_lock held.
1730e4e574b7SAdam Litke  */
1731a5516438SAndi Kleen static void return_unused_surplus_pages(struct hstate *h,
1732a5516438SAndi Kleen 					unsigned long unused_resv_pages)
1733e4e574b7SAdam Litke {
1734e4e574b7SAdam Litke 	unsigned long nr_pages;
1735e4e574b7SAdam Litke 
1736ac09b3a1SAdam Litke 	/* Uncommit the reservation */
1737a5516438SAndi Kleen 	h->resv_huge_pages -= unused_resv_pages;
1738ac09b3a1SAdam Litke 
1739aa888a74SAndi Kleen 	/* Cannot return gigantic pages currently */
1740bae7f4aeSLuiz Capitulino 	if (hstate_is_gigantic(h))
1741aa888a74SAndi Kleen 		return;
1742aa888a74SAndi Kleen 
1743a5516438SAndi Kleen 	nr_pages = min(unused_resv_pages, h->surplus_huge_pages);
1744e4e574b7SAdam Litke 
1745685f3457SLee Schermerhorn 	/*
1746685f3457SLee Schermerhorn 	 * We want to release as many surplus pages as possible, spread
17479b5e5d0fSLee Schermerhorn 	 * evenly across all nodes with memory. Iterate across these nodes
17489b5e5d0fSLee Schermerhorn 	 * until we can no longer free unreserved surplus pages. This occurs
17499b5e5d0fSLee Schermerhorn 	 * when the nodes with surplus pages have no free pages.
17509b5e5d0fSLee Schermerhorn 	 * free_pool_huge_page() will balance the the freed pages across the
17519b5e5d0fSLee Schermerhorn 	 * on-line nodes with memory and will handle the hstate accounting.
1752685f3457SLee Schermerhorn 	 */
1753685f3457SLee Schermerhorn 	while (nr_pages--) {
17548cebfcd0SLai Jiangshan 		if (!free_pool_huge_page(h, &node_states[N_MEMORY], 1))
1755685f3457SLee Schermerhorn 			break;
17567848a4bfSMizuma, Masayoshi 		cond_resched_lock(&hugetlb_lock);
1757e4e574b7SAdam Litke 	}
1758e4e574b7SAdam Litke }
1759e4e574b7SAdam Litke 
17605e911373SMike Kravetz 
1761c37f9fb1SAndy Whitcroft /*
1762feba16e2SMike Kravetz  * vma_needs_reservation, vma_commit_reservation and vma_end_reservation
17635e911373SMike Kravetz  * are used by the huge page allocation routines to manage reservations.
1764cf3ad20bSMike Kravetz  *
1765cf3ad20bSMike Kravetz  * vma_needs_reservation is called to determine if the huge page at addr
1766cf3ad20bSMike Kravetz  * within the vma has an associated reservation.  If a reservation is
1767cf3ad20bSMike Kravetz  * needed, the value 1 is returned.  The caller is then responsible for
1768cf3ad20bSMike Kravetz  * managing the global reservation and subpool usage counts.  After
1769cf3ad20bSMike Kravetz  * the huge page has been allocated, vma_commit_reservation is called
1770feba16e2SMike Kravetz  * to add the page to the reservation map.  If the page allocation fails,
1771feba16e2SMike Kravetz  * the reservation must be ended instead of committed.  vma_end_reservation
1772feba16e2SMike Kravetz  * is called in such cases.
1773cf3ad20bSMike Kravetz  *
1774cf3ad20bSMike Kravetz  * In the normal case, vma_commit_reservation returns the same value
1775cf3ad20bSMike Kravetz  * as the preceding vma_needs_reservation call.  The only time this
1776cf3ad20bSMike Kravetz  * is not the case is if a reserve map was changed between calls.  It
1777cf3ad20bSMike Kravetz  * is the responsibility of the caller to notice the difference and
1778cf3ad20bSMike Kravetz  * take appropriate action.
1779c37f9fb1SAndy Whitcroft  */
17805e911373SMike Kravetz enum vma_resv_mode {
17815e911373SMike Kravetz 	VMA_NEEDS_RESV,
17825e911373SMike Kravetz 	VMA_COMMIT_RESV,
1783feba16e2SMike Kravetz 	VMA_END_RESV,
17845e911373SMike Kravetz };
1785cf3ad20bSMike Kravetz static long __vma_reservation_common(struct hstate *h,
1786cf3ad20bSMike Kravetz 				struct vm_area_struct *vma, unsigned long addr,
17875e911373SMike Kravetz 				enum vma_resv_mode mode)
1788c37f9fb1SAndy Whitcroft {
17894e35f483SJoonsoo Kim 	struct resv_map *resv;
17904e35f483SJoonsoo Kim 	pgoff_t idx;
1791cf3ad20bSMike Kravetz 	long ret;
1792c37f9fb1SAndy Whitcroft 
17934e35f483SJoonsoo Kim 	resv = vma_resv_map(vma);
17944e35f483SJoonsoo Kim 	if (!resv)
1795c37f9fb1SAndy Whitcroft 		return 1;
1796c37f9fb1SAndy Whitcroft 
17974e35f483SJoonsoo Kim 	idx = vma_hugecache_offset(h, vma, addr);
17985e911373SMike Kravetz 	switch (mode) {
17995e911373SMike Kravetz 	case VMA_NEEDS_RESV:
1800cf3ad20bSMike Kravetz 		ret = region_chg(resv, idx, idx + 1);
18015e911373SMike Kravetz 		break;
18025e911373SMike Kravetz 	case VMA_COMMIT_RESV:
18035e911373SMike Kravetz 		ret = region_add(resv, idx, idx + 1);
18045e911373SMike Kravetz 		break;
1805feba16e2SMike Kravetz 	case VMA_END_RESV:
18065e911373SMike Kravetz 		region_abort(resv, idx, idx + 1);
18075e911373SMike Kravetz 		ret = 0;
18085e911373SMike Kravetz 		break;
18095e911373SMike Kravetz 	default:
18105e911373SMike Kravetz 		BUG();
18115e911373SMike Kravetz 	}
181284afd99bSAndy Whitcroft 
18134e35f483SJoonsoo Kim 	if (vma->vm_flags & VM_MAYSHARE)
1814cf3ad20bSMike Kravetz 		return ret;
18154e35f483SJoonsoo Kim 	else
1816cf3ad20bSMike Kravetz 		return ret < 0 ? ret : 0;
181784afd99bSAndy Whitcroft }
1818cf3ad20bSMike Kravetz 
1819cf3ad20bSMike Kravetz static long vma_needs_reservation(struct hstate *h,
1820a5516438SAndi Kleen 			struct vm_area_struct *vma, unsigned long addr)
1821c37f9fb1SAndy Whitcroft {
18225e911373SMike Kravetz 	return __vma_reservation_common(h, vma, addr, VMA_NEEDS_RESV);
1823cf3ad20bSMike Kravetz }
1824c37f9fb1SAndy Whitcroft 
1825cf3ad20bSMike Kravetz static long vma_commit_reservation(struct hstate *h,
1826cf3ad20bSMike Kravetz 			struct vm_area_struct *vma, unsigned long addr)
1827cf3ad20bSMike Kravetz {
18285e911373SMike Kravetz 	return __vma_reservation_common(h, vma, addr, VMA_COMMIT_RESV);
18295e911373SMike Kravetz }
18305e911373SMike Kravetz 
1831feba16e2SMike Kravetz static void vma_end_reservation(struct hstate *h,
18325e911373SMike Kravetz 			struct vm_area_struct *vma, unsigned long addr)
18335e911373SMike Kravetz {
1834feba16e2SMike Kravetz 	(void)__vma_reservation_common(h, vma, addr, VMA_END_RESV);
1835c37f9fb1SAndy Whitcroft }
1836c37f9fb1SAndy Whitcroft 
183770c3547eSMike Kravetz struct page *alloc_huge_page(struct vm_area_struct *vma,
183804f2cbe3SMel Gorman 				    unsigned long addr, int avoid_reserve)
1839348ea204SAdam Litke {
184090481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_vma(vma);
1841a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
1842348ea204SAdam Litke 	struct page *page;
1843d85f69b0SMike Kravetz 	long map_chg, map_commit;
1844d85f69b0SMike Kravetz 	long gbl_chg;
18456d76dcf4SAneesh Kumar K.V 	int ret, idx;
18466d76dcf4SAneesh Kumar K.V 	struct hugetlb_cgroup *h_cg;
18472fc39cecSAdam Litke 
18486d76dcf4SAneesh Kumar K.V 	idx = hstate_index(h);
1849a1e78772SMel Gorman 	/*
1850d85f69b0SMike Kravetz 	 * Examine the region/reserve map to determine if the process
1851d85f69b0SMike Kravetz 	 * has a reservation for the page to be allocated.  A return
1852d85f69b0SMike Kravetz 	 * code of zero indicates a reservation exists (no change).
1853a1e78772SMel Gorman 	 */
1854d85f69b0SMike Kravetz 	map_chg = gbl_chg = vma_needs_reservation(h, vma, addr);
1855d85f69b0SMike Kravetz 	if (map_chg < 0)
185676dcee75SAneesh Kumar K.V 		return ERR_PTR(-ENOMEM);
1857d85f69b0SMike Kravetz 
1858d85f69b0SMike Kravetz 	/*
1859d85f69b0SMike Kravetz 	 * Processes that did not create the mapping will have no
1860d85f69b0SMike Kravetz 	 * reserves as indicated by the region/reserve map. Check
1861d85f69b0SMike Kravetz 	 * that the allocation will not exceed the subpool limit.
1862d85f69b0SMike Kravetz 	 * Allocations for MAP_NORESERVE mappings also need to be
1863d85f69b0SMike Kravetz 	 * checked against any subpool limit.
1864d85f69b0SMike Kravetz 	 */
1865d85f69b0SMike Kravetz 	if (map_chg || avoid_reserve) {
1866d85f69b0SMike Kravetz 		gbl_chg = hugepage_subpool_get_pages(spool, 1);
1867d85f69b0SMike Kravetz 		if (gbl_chg < 0) {
1868feba16e2SMike Kravetz 			vma_end_reservation(h, vma, addr);
186976dcee75SAneesh Kumar K.V 			return ERR_PTR(-ENOSPC);
18705e911373SMike Kravetz 		}
187190d8b7e6SAdam Litke 
1872d85f69b0SMike Kravetz 		/*
1873d85f69b0SMike Kravetz 		 * Even though there was no reservation in the region/reserve
1874d85f69b0SMike Kravetz 		 * map, there could be reservations associated with the
1875d85f69b0SMike Kravetz 		 * subpool that can be used.  This would be indicated if the
1876d85f69b0SMike Kravetz 		 * return value of hugepage_subpool_get_pages() is zero.
1877d85f69b0SMike Kravetz 		 * However, if avoid_reserve is specified we still avoid even
1878d85f69b0SMike Kravetz 		 * the subpool reservations.
1879d85f69b0SMike Kravetz 		 */
1880d85f69b0SMike Kravetz 		if (avoid_reserve)
1881d85f69b0SMike Kravetz 			gbl_chg = 1;
1882d85f69b0SMike Kravetz 	}
1883d85f69b0SMike Kravetz 
18846d76dcf4SAneesh Kumar K.V 	ret = hugetlb_cgroup_charge_cgroup(idx, pages_per_huge_page(h), &h_cg);
18858f34af6fSJianyu Zhan 	if (ret)
18868f34af6fSJianyu Zhan 		goto out_subpool_put;
18878f34af6fSJianyu Zhan 
1888a1e78772SMel Gorman 	spin_lock(&hugetlb_lock);
1889d85f69b0SMike Kravetz 	/*
1890d85f69b0SMike Kravetz 	 * glb_chg is passed to indicate whether or not a page must be taken
1891d85f69b0SMike Kravetz 	 * from the global free pool (global change).  gbl_chg == 0 indicates
1892d85f69b0SMike Kravetz 	 * a reservation exists for the allocation.
1893d85f69b0SMike Kravetz 	 */
1894d85f69b0SMike Kravetz 	page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve, gbl_chg);
189581a6fcaeSJoonsoo Kim 	if (!page) {
189694ae8ba7SAneesh Kumar K.V 		spin_unlock(&hugetlb_lock);
1897099730d6SDave Hansen 		page = __alloc_buddy_huge_page_with_mpol(h, vma, addr);
18988f34af6fSJianyu Zhan 		if (!page)
18998f34af6fSJianyu Zhan 			goto out_uncharge_cgroup;
1900a88c7695SNaoya Horiguchi 		if (!avoid_reserve && vma_has_reserves(vma, gbl_chg)) {
1901a88c7695SNaoya Horiguchi 			SetPagePrivate(page);
1902a88c7695SNaoya Horiguchi 			h->resv_huge_pages--;
1903a88c7695SNaoya Horiguchi 		}
190479dbb236SAneesh Kumar K.V 		spin_lock(&hugetlb_lock);
190579dbb236SAneesh Kumar K.V 		list_move(&page->lru, &h->hugepage_activelist);
190681a6fcaeSJoonsoo Kim 		/* Fall through */
1907a1e78772SMel Gorman 	}
190881a6fcaeSJoonsoo Kim 	hugetlb_cgroup_commit_charge(idx, pages_per_huge_page(h), h_cg, page);
190981a6fcaeSJoonsoo Kim 	spin_unlock(&hugetlb_lock);
1910a1e78772SMel Gorman 
191190481622SDavid Gibson 	set_page_private(page, (unsigned long)spool);
1912a1e78772SMel Gorman 
1913d85f69b0SMike Kravetz 	map_commit = vma_commit_reservation(h, vma, addr);
1914d85f69b0SMike Kravetz 	if (unlikely(map_chg > map_commit)) {
191533039678SMike Kravetz 		/*
191633039678SMike Kravetz 		 * The page was added to the reservation map between
191733039678SMike Kravetz 		 * vma_needs_reservation and vma_commit_reservation.
191833039678SMike Kravetz 		 * This indicates a race with hugetlb_reserve_pages.
191933039678SMike Kravetz 		 * Adjust for the subpool count incremented above AND
192033039678SMike Kravetz 		 * in hugetlb_reserve_pages for the same page.  Also,
192133039678SMike Kravetz 		 * the reservation count added in hugetlb_reserve_pages
192233039678SMike Kravetz 		 * no longer applies.
192333039678SMike Kravetz 		 */
192433039678SMike Kravetz 		long rsv_adjust;
192533039678SMike Kravetz 
192633039678SMike Kravetz 		rsv_adjust = hugepage_subpool_put_pages(spool, 1);
192733039678SMike Kravetz 		hugetlb_acct_memory(h, -rsv_adjust);
192833039678SMike Kravetz 	}
19297893d1d5SAdam Litke 	return page;
19308f34af6fSJianyu Zhan 
19318f34af6fSJianyu Zhan out_uncharge_cgroup:
19328f34af6fSJianyu Zhan 	hugetlb_cgroup_uncharge_cgroup(idx, pages_per_huge_page(h), h_cg);
19338f34af6fSJianyu Zhan out_subpool_put:
1934d85f69b0SMike Kravetz 	if (map_chg || avoid_reserve)
19358f34af6fSJianyu Zhan 		hugepage_subpool_put_pages(spool, 1);
1936feba16e2SMike Kravetz 	vma_end_reservation(h, vma, addr);
19378f34af6fSJianyu Zhan 	return ERR_PTR(-ENOSPC);
1938b45b5bd6SDavid Gibson }
1939b45b5bd6SDavid Gibson 
194074060e4dSNaoya Horiguchi /*
194174060e4dSNaoya Horiguchi  * alloc_huge_page()'s wrapper which simply returns the page if allocation
194274060e4dSNaoya Horiguchi  * succeeds, otherwise NULL. This function is called from new_vma_page(),
194374060e4dSNaoya Horiguchi  * where no ERR_VALUE is expected to be returned.
194474060e4dSNaoya Horiguchi  */
194574060e4dSNaoya Horiguchi struct page *alloc_huge_page_noerr(struct vm_area_struct *vma,
194674060e4dSNaoya Horiguchi 				unsigned long addr, int avoid_reserve)
194774060e4dSNaoya Horiguchi {
194874060e4dSNaoya Horiguchi 	struct page *page = alloc_huge_page(vma, addr, avoid_reserve);
194974060e4dSNaoya Horiguchi 	if (IS_ERR(page))
195074060e4dSNaoya Horiguchi 		page = NULL;
195174060e4dSNaoya Horiguchi 	return page;
195274060e4dSNaoya Horiguchi }
195374060e4dSNaoya Horiguchi 
195491f47662SCyrill Gorcunov int __weak alloc_bootmem_huge_page(struct hstate *h)
1955aa888a74SAndi Kleen {
1956aa888a74SAndi Kleen 	struct huge_bootmem_page *m;
1957b2261026SJoonsoo Kim 	int nr_nodes, node;
1958aa888a74SAndi Kleen 
1959b2261026SJoonsoo Kim 	for_each_node_mask_to_alloc(h, nr_nodes, node, &node_states[N_MEMORY]) {
1960aa888a74SAndi Kleen 		void *addr;
1961aa888a74SAndi Kleen 
19628b89a116SGrygorii Strashko 		addr = memblock_virt_alloc_try_nid_nopanic(
19638b89a116SGrygorii Strashko 				huge_page_size(h), huge_page_size(h),
19648b89a116SGrygorii Strashko 				0, BOOTMEM_ALLOC_ACCESSIBLE, node);
1965aa888a74SAndi Kleen 		if (addr) {
1966aa888a74SAndi Kleen 			/*
1967aa888a74SAndi Kleen 			 * Use the beginning of the huge page to store the
1968aa888a74SAndi Kleen 			 * huge_bootmem_page struct (until gather_bootmem
1969aa888a74SAndi Kleen 			 * puts them into the mem_map).
1970aa888a74SAndi Kleen 			 */
1971aa888a74SAndi Kleen 			m = addr;
1972aa888a74SAndi Kleen 			goto found;
1973aa888a74SAndi Kleen 		}
1974aa888a74SAndi Kleen 	}
1975aa888a74SAndi Kleen 	return 0;
1976aa888a74SAndi Kleen 
1977aa888a74SAndi Kleen found:
1978df994eadSLuiz Capitulino 	BUG_ON(!IS_ALIGNED(virt_to_phys(m), huge_page_size(h)));
1979aa888a74SAndi Kleen 	/* Put them into a private list first because mem_map is not up yet */
1980aa888a74SAndi Kleen 	list_add(&m->list, &huge_boot_pages);
1981aa888a74SAndi Kleen 	m->hstate = h;
1982aa888a74SAndi Kleen 	return 1;
1983aa888a74SAndi Kleen }
1984aa888a74SAndi Kleen 
1985d00181b9SKirill A. Shutemov static void __init prep_compound_huge_page(struct page *page,
1986d00181b9SKirill A. Shutemov 		unsigned int order)
198718229df5SAndy Whitcroft {
198818229df5SAndy Whitcroft 	if (unlikely(order > (MAX_ORDER - 1)))
198918229df5SAndy Whitcroft 		prep_compound_gigantic_page(page, order);
199018229df5SAndy Whitcroft 	else
199118229df5SAndy Whitcroft 		prep_compound_page(page, order);
199218229df5SAndy Whitcroft }
199318229df5SAndy Whitcroft 
1994aa888a74SAndi Kleen /* Put bootmem huge pages into the standard lists after mem_map is up */
1995aa888a74SAndi Kleen static void __init gather_bootmem_prealloc(void)
1996aa888a74SAndi Kleen {
1997aa888a74SAndi Kleen 	struct huge_bootmem_page *m;
1998aa888a74SAndi Kleen 
1999aa888a74SAndi Kleen 	list_for_each_entry(m, &huge_boot_pages, list) {
2000aa888a74SAndi Kleen 		struct hstate *h = m->hstate;
2001ee8f248dSBecky Bruce 		struct page *page;
2002ee8f248dSBecky Bruce 
2003ee8f248dSBecky Bruce #ifdef CONFIG_HIGHMEM
2004ee8f248dSBecky Bruce 		page = pfn_to_page(m->phys >> PAGE_SHIFT);
20058b89a116SGrygorii Strashko 		memblock_free_late(__pa(m),
2006ee8f248dSBecky Bruce 				   sizeof(struct huge_bootmem_page));
2007ee8f248dSBecky Bruce #else
2008ee8f248dSBecky Bruce 		page = virt_to_page(m);
2009ee8f248dSBecky Bruce #endif
2010aa888a74SAndi Kleen 		WARN_ON(page_count(page) != 1);
201118229df5SAndy Whitcroft 		prep_compound_huge_page(page, h->order);
2012ef5a22beSAndrea Arcangeli 		WARN_ON(PageReserved(page));
2013aa888a74SAndi Kleen 		prep_new_huge_page(h, page, page_to_nid(page));
2014b0320c7bSRafael Aquini 		/*
2015b0320c7bSRafael Aquini 		 * If we had gigantic hugepages allocated at boot time, we need
2016b0320c7bSRafael Aquini 		 * to restore the 'stolen' pages to totalram_pages in order to
2017b0320c7bSRafael Aquini 		 * fix confusing memory reports from free(1) and another
2018b0320c7bSRafael Aquini 		 * side-effects, like CommitLimit going negative.
2019b0320c7bSRafael Aquini 		 */
2020bae7f4aeSLuiz Capitulino 		if (hstate_is_gigantic(h))
20213dcc0571SJiang Liu 			adjust_managed_page_count(page, 1 << h->order);
2022aa888a74SAndi Kleen 	}
2023aa888a74SAndi Kleen }
2024aa888a74SAndi Kleen 
20258faa8b07SAndi Kleen static void __init hugetlb_hstate_alloc_pages(struct hstate *h)
20261da177e4SLinus Torvalds {
20271da177e4SLinus Torvalds 	unsigned long i;
20281da177e4SLinus Torvalds 
2029e5ff2159SAndi Kleen 	for (i = 0; i < h->max_huge_pages; ++i) {
2030bae7f4aeSLuiz Capitulino 		if (hstate_is_gigantic(h)) {
2031aa888a74SAndi Kleen 			if (!alloc_bootmem_huge_page(h))
2032aa888a74SAndi Kleen 				break;
20339b5e5d0fSLee Schermerhorn 		} else if (!alloc_fresh_huge_page(h,
20348cebfcd0SLai Jiangshan 					 &node_states[N_MEMORY]))
20351da177e4SLinus Torvalds 			break;
20361da177e4SLinus Torvalds 	}
20378faa8b07SAndi Kleen 	h->max_huge_pages = i;
2038e5ff2159SAndi Kleen }
2039e5ff2159SAndi Kleen 
2040e5ff2159SAndi Kleen static void __init hugetlb_init_hstates(void)
2041e5ff2159SAndi Kleen {
2042e5ff2159SAndi Kleen 	struct hstate *h;
2043e5ff2159SAndi Kleen 
2044e5ff2159SAndi Kleen 	for_each_hstate(h) {
2045641844f5SNaoya Horiguchi 		if (minimum_order > huge_page_order(h))
2046641844f5SNaoya Horiguchi 			minimum_order = huge_page_order(h);
2047641844f5SNaoya Horiguchi 
20488faa8b07SAndi Kleen 		/* oversize hugepages were init'ed in early boot */
2049bae7f4aeSLuiz Capitulino 		if (!hstate_is_gigantic(h))
20508faa8b07SAndi Kleen 			hugetlb_hstate_alloc_pages(h);
2051e5ff2159SAndi Kleen 	}
2052641844f5SNaoya Horiguchi 	VM_BUG_ON(minimum_order == UINT_MAX);
2053e5ff2159SAndi Kleen }
2054e5ff2159SAndi Kleen 
20554abd32dbSAndi Kleen static char * __init memfmt(char *buf, unsigned long n)
20564abd32dbSAndi Kleen {
20574abd32dbSAndi Kleen 	if (n >= (1UL << 30))
20584abd32dbSAndi Kleen 		sprintf(buf, "%lu GB", n >> 30);
20594abd32dbSAndi Kleen 	else if (n >= (1UL << 20))
20604abd32dbSAndi Kleen 		sprintf(buf, "%lu MB", n >> 20);
20614abd32dbSAndi Kleen 	else
20624abd32dbSAndi Kleen 		sprintf(buf, "%lu KB", n >> 10);
20634abd32dbSAndi Kleen 	return buf;
20644abd32dbSAndi Kleen }
20654abd32dbSAndi Kleen 
2066e5ff2159SAndi Kleen static void __init report_hugepages(void)
2067e5ff2159SAndi Kleen {
2068e5ff2159SAndi Kleen 	struct hstate *h;
2069e5ff2159SAndi Kleen 
2070e5ff2159SAndi Kleen 	for_each_hstate(h) {
20714abd32dbSAndi Kleen 		char buf[32];
2072ffb22af5SAndrew Morton 		pr_info("HugeTLB registered %s page size, pre-allocated %ld pages\n",
20734abd32dbSAndi Kleen 			memfmt(buf, huge_page_size(h)),
20744abd32dbSAndi Kleen 			h->free_huge_pages);
2075e5ff2159SAndi Kleen 	}
2076e5ff2159SAndi Kleen }
2077e5ff2159SAndi Kleen 
20781da177e4SLinus Torvalds #ifdef CONFIG_HIGHMEM
20796ae11b27SLee Schermerhorn static void try_to_free_low(struct hstate *h, unsigned long count,
20806ae11b27SLee Schermerhorn 						nodemask_t *nodes_allowed)
20811da177e4SLinus Torvalds {
20824415cc8dSChristoph Lameter 	int i;
20834415cc8dSChristoph Lameter 
2084bae7f4aeSLuiz Capitulino 	if (hstate_is_gigantic(h))
2085aa888a74SAndi Kleen 		return;
2086aa888a74SAndi Kleen 
20876ae11b27SLee Schermerhorn 	for_each_node_mask(i, *nodes_allowed) {
20881da177e4SLinus Torvalds 		struct page *page, *next;
2089a5516438SAndi Kleen 		struct list_head *freel = &h->hugepage_freelists[i];
2090a5516438SAndi Kleen 		list_for_each_entry_safe(page, next, freel, lru) {
2091a5516438SAndi Kleen 			if (count >= h->nr_huge_pages)
20926b0c880dSAdam Litke 				return;
20931da177e4SLinus Torvalds 			if (PageHighMem(page))
20941da177e4SLinus Torvalds 				continue;
20951da177e4SLinus Torvalds 			list_del(&page->lru);
2096e5ff2159SAndi Kleen 			update_and_free_page(h, page);
2097a5516438SAndi Kleen 			h->free_huge_pages--;
2098a5516438SAndi Kleen 			h->free_huge_pages_node[page_to_nid(page)]--;
20991da177e4SLinus Torvalds 		}
21001da177e4SLinus Torvalds 	}
21011da177e4SLinus Torvalds }
21021da177e4SLinus Torvalds #else
21036ae11b27SLee Schermerhorn static inline void try_to_free_low(struct hstate *h, unsigned long count,
21046ae11b27SLee Schermerhorn 						nodemask_t *nodes_allowed)
21051da177e4SLinus Torvalds {
21061da177e4SLinus Torvalds }
21071da177e4SLinus Torvalds #endif
21081da177e4SLinus Torvalds 
210920a0307cSWu Fengguang /*
211020a0307cSWu Fengguang  * Increment or decrement surplus_huge_pages.  Keep node-specific counters
211120a0307cSWu Fengguang  * balanced by operating on them in a round-robin fashion.
211220a0307cSWu Fengguang  * Returns 1 if an adjustment was made.
211320a0307cSWu Fengguang  */
21146ae11b27SLee Schermerhorn static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed,
21156ae11b27SLee Schermerhorn 				int delta)
211620a0307cSWu Fengguang {
2117b2261026SJoonsoo Kim 	int nr_nodes, node;
211820a0307cSWu Fengguang 
211920a0307cSWu Fengguang 	VM_BUG_ON(delta != -1 && delta != 1);
212020a0307cSWu Fengguang 
2121e8c5c824SLee Schermerhorn 	if (delta < 0) {
2122b2261026SJoonsoo Kim 		for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
2123b2261026SJoonsoo Kim 			if (h->surplus_huge_pages_node[node])
2124b2261026SJoonsoo Kim 				goto found;
2125b2261026SJoonsoo Kim 		}
2126b2261026SJoonsoo Kim 	} else {
2127b2261026SJoonsoo Kim 		for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
2128b2261026SJoonsoo Kim 			if (h->surplus_huge_pages_node[node] <
2129b2261026SJoonsoo Kim 					h->nr_huge_pages_node[node])
2130b2261026SJoonsoo Kim 				goto found;
2131e8c5c824SLee Schermerhorn 		}
21329a76db09SLee Schermerhorn 	}
2133b2261026SJoonsoo Kim 	return 0;
213420a0307cSWu Fengguang 
2135b2261026SJoonsoo Kim found:
213620a0307cSWu Fengguang 	h->surplus_huge_pages += delta;
2137b2261026SJoonsoo Kim 	h->surplus_huge_pages_node[node] += delta;
2138b2261026SJoonsoo Kim 	return 1;
213920a0307cSWu Fengguang }
214020a0307cSWu Fengguang 
2141a5516438SAndi Kleen #define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages)
21426ae11b27SLee Schermerhorn static unsigned long set_max_huge_pages(struct hstate *h, unsigned long count,
21436ae11b27SLee Schermerhorn 						nodemask_t *nodes_allowed)
21441da177e4SLinus Torvalds {
21457893d1d5SAdam Litke 	unsigned long min_count, ret;
21461da177e4SLinus Torvalds 
2147944d9fecSLuiz Capitulino 	if (hstate_is_gigantic(h) && !gigantic_page_supported())
2148aa888a74SAndi Kleen 		return h->max_huge_pages;
2149aa888a74SAndi Kleen 
21507893d1d5SAdam Litke 	/*
21517893d1d5SAdam Litke 	 * Increase the pool size
21527893d1d5SAdam Litke 	 * First take pages out of surplus state.  Then make up the
21537893d1d5SAdam Litke 	 * remaining difference by allocating fresh huge pages.
2154d1c3fb1fSNishanth Aravamudan 	 *
2155d15c7c09SNaoya Horiguchi 	 * We might race with __alloc_buddy_huge_page() here and be unable
2156d1c3fb1fSNishanth Aravamudan 	 * to convert a surplus huge page to a normal huge page. That is
2157d1c3fb1fSNishanth Aravamudan 	 * not critical, though, it just means the overall size of the
2158d1c3fb1fSNishanth Aravamudan 	 * pool might be one hugepage larger than it needs to be, but
2159d1c3fb1fSNishanth Aravamudan 	 * within all the constraints specified by the sysctls.
21607893d1d5SAdam Litke 	 */
21611da177e4SLinus Torvalds 	spin_lock(&hugetlb_lock);
2162a5516438SAndi Kleen 	while (h->surplus_huge_pages && count > persistent_huge_pages(h)) {
21636ae11b27SLee Schermerhorn 		if (!adjust_pool_surplus(h, nodes_allowed, -1))
21647893d1d5SAdam Litke 			break;
21657893d1d5SAdam Litke 	}
21667893d1d5SAdam Litke 
2167a5516438SAndi Kleen 	while (count > persistent_huge_pages(h)) {
21687893d1d5SAdam Litke 		/*
21697893d1d5SAdam Litke 		 * If this allocation races such that we no longer need the
21707893d1d5SAdam Litke 		 * page, free_huge_page will handle it by freeing the page
21717893d1d5SAdam Litke 		 * and reducing the surplus.
21727893d1d5SAdam Litke 		 */
21737893d1d5SAdam Litke 		spin_unlock(&hugetlb_lock);
2174944d9fecSLuiz Capitulino 		if (hstate_is_gigantic(h))
2175944d9fecSLuiz Capitulino 			ret = alloc_fresh_gigantic_page(h, nodes_allowed);
2176944d9fecSLuiz Capitulino 		else
21776ae11b27SLee Schermerhorn 			ret = alloc_fresh_huge_page(h, nodes_allowed);
21787893d1d5SAdam Litke 		spin_lock(&hugetlb_lock);
21797893d1d5SAdam Litke 		if (!ret)
21807893d1d5SAdam Litke 			goto out;
21817893d1d5SAdam Litke 
2182536240f2SMel Gorman 		/* Bail for signals. Probably ctrl-c from user */
2183536240f2SMel Gorman 		if (signal_pending(current))
2184536240f2SMel Gorman 			goto out;
21857893d1d5SAdam Litke 	}
21867893d1d5SAdam Litke 
21877893d1d5SAdam Litke 	/*
21887893d1d5SAdam Litke 	 * Decrease the pool size
21897893d1d5SAdam Litke 	 * First return free pages to the buddy allocator (being careful
21907893d1d5SAdam Litke 	 * to keep enough around to satisfy reservations).  Then place
21917893d1d5SAdam Litke 	 * pages into surplus state as needed so the pool will shrink
21927893d1d5SAdam Litke 	 * to the desired size as pages become free.
2193d1c3fb1fSNishanth Aravamudan 	 *
2194d1c3fb1fSNishanth Aravamudan 	 * By placing pages into the surplus state independent of the
2195d1c3fb1fSNishanth Aravamudan 	 * overcommit value, we are allowing the surplus pool size to
2196d1c3fb1fSNishanth Aravamudan 	 * exceed overcommit. There are few sane options here. Since
2197d15c7c09SNaoya Horiguchi 	 * __alloc_buddy_huge_page() is checking the global counter,
2198d1c3fb1fSNishanth Aravamudan 	 * though, we'll note that we're not allowed to exceed surplus
2199d1c3fb1fSNishanth Aravamudan 	 * and won't grow the pool anywhere else. Not until one of the
2200d1c3fb1fSNishanth Aravamudan 	 * sysctls are changed, or the surplus pages go out of use.
22017893d1d5SAdam Litke 	 */
2202a5516438SAndi Kleen 	min_count = h->resv_huge_pages + h->nr_huge_pages - h->free_huge_pages;
22036b0c880dSAdam Litke 	min_count = max(count, min_count);
22046ae11b27SLee Schermerhorn 	try_to_free_low(h, min_count, nodes_allowed);
2205a5516438SAndi Kleen 	while (min_count < persistent_huge_pages(h)) {
22066ae11b27SLee Schermerhorn 		if (!free_pool_huge_page(h, nodes_allowed, 0))
22071da177e4SLinus Torvalds 			break;
220855f67141SMizuma, Masayoshi 		cond_resched_lock(&hugetlb_lock);
22091da177e4SLinus Torvalds 	}
2210a5516438SAndi Kleen 	while (count < persistent_huge_pages(h)) {
22116ae11b27SLee Schermerhorn 		if (!adjust_pool_surplus(h, nodes_allowed, 1))
22127893d1d5SAdam Litke 			break;
22137893d1d5SAdam Litke 	}
22147893d1d5SAdam Litke out:
2215a5516438SAndi Kleen 	ret = persistent_huge_pages(h);
22161da177e4SLinus Torvalds 	spin_unlock(&hugetlb_lock);
22177893d1d5SAdam Litke 	return ret;
22181da177e4SLinus Torvalds }
22191da177e4SLinus Torvalds 
2220a3437870SNishanth Aravamudan #define HSTATE_ATTR_RO(_name) \
2221a3437870SNishanth Aravamudan 	static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
2222a3437870SNishanth Aravamudan 
2223a3437870SNishanth Aravamudan #define HSTATE_ATTR(_name) \
2224a3437870SNishanth Aravamudan 	static struct kobj_attribute _name##_attr = \
2225a3437870SNishanth Aravamudan 		__ATTR(_name, 0644, _name##_show, _name##_store)
2226a3437870SNishanth Aravamudan 
2227a3437870SNishanth Aravamudan static struct kobject *hugepages_kobj;
2228a3437870SNishanth Aravamudan static struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
2229a3437870SNishanth Aravamudan 
22309a305230SLee Schermerhorn static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp);
22319a305230SLee Schermerhorn 
22329a305230SLee Schermerhorn static struct hstate *kobj_to_hstate(struct kobject *kobj, int *nidp)
2233a3437870SNishanth Aravamudan {
2234a3437870SNishanth Aravamudan 	int i;
22359a305230SLee Schermerhorn 
2236a3437870SNishanth Aravamudan 	for (i = 0; i < HUGE_MAX_HSTATE; i++)
22379a305230SLee Schermerhorn 		if (hstate_kobjs[i] == kobj) {
22389a305230SLee Schermerhorn 			if (nidp)
22399a305230SLee Schermerhorn 				*nidp = NUMA_NO_NODE;
2240a3437870SNishanth Aravamudan 			return &hstates[i];
22419a305230SLee Schermerhorn 		}
22429a305230SLee Schermerhorn 
22439a305230SLee Schermerhorn 	return kobj_to_node_hstate(kobj, nidp);
2244a3437870SNishanth Aravamudan }
2245a3437870SNishanth Aravamudan 
224606808b08SLee Schermerhorn static ssize_t nr_hugepages_show_common(struct kobject *kobj,
2247a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
2248a3437870SNishanth Aravamudan {
22499a305230SLee Schermerhorn 	struct hstate *h;
22509a305230SLee Schermerhorn 	unsigned long nr_huge_pages;
22519a305230SLee Schermerhorn 	int nid;
22529a305230SLee Schermerhorn 
22539a305230SLee Schermerhorn 	h = kobj_to_hstate(kobj, &nid);
22549a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE)
22559a305230SLee Schermerhorn 		nr_huge_pages = h->nr_huge_pages;
22569a305230SLee Schermerhorn 	else
22579a305230SLee Schermerhorn 		nr_huge_pages = h->nr_huge_pages_node[nid];
22589a305230SLee Schermerhorn 
22599a305230SLee Schermerhorn 	return sprintf(buf, "%lu\n", nr_huge_pages);
2260a3437870SNishanth Aravamudan }
2261adbe8726SEric B Munson 
2262238d3c13SDavid Rientjes static ssize_t __nr_hugepages_store_common(bool obey_mempolicy,
2263238d3c13SDavid Rientjes 					   struct hstate *h, int nid,
2264238d3c13SDavid Rientjes 					   unsigned long count, size_t len)
2265a3437870SNishanth Aravamudan {
2266a3437870SNishanth Aravamudan 	int err;
2267bad44b5bSDavid Rientjes 	NODEMASK_ALLOC(nodemask_t, nodes_allowed, GFP_KERNEL | __GFP_NORETRY);
2268a3437870SNishanth Aravamudan 
2269944d9fecSLuiz Capitulino 	if (hstate_is_gigantic(h) && !gigantic_page_supported()) {
2270adbe8726SEric B Munson 		err = -EINVAL;
2271adbe8726SEric B Munson 		goto out;
2272adbe8726SEric B Munson 	}
2273adbe8726SEric B Munson 
22749a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE) {
22759a305230SLee Schermerhorn 		/*
22769a305230SLee Schermerhorn 		 * global hstate attribute
22779a305230SLee Schermerhorn 		 */
22789a305230SLee Schermerhorn 		if (!(obey_mempolicy &&
22799a305230SLee Schermerhorn 				init_nodemask_of_mempolicy(nodes_allowed))) {
228006808b08SLee Schermerhorn 			NODEMASK_FREE(nodes_allowed);
22818cebfcd0SLai Jiangshan 			nodes_allowed = &node_states[N_MEMORY];
228206808b08SLee Schermerhorn 		}
22839a305230SLee Schermerhorn 	} else if (nodes_allowed) {
22849a305230SLee Schermerhorn 		/*
22859a305230SLee Schermerhorn 		 * per node hstate attribute: adjust count to global,
22869a305230SLee Schermerhorn 		 * but restrict alloc/free to the specified node.
22879a305230SLee Schermerhorn 		 */
22889a305230SLee Schermerhorn 		count += h->nr_huge_pages - h->nr_huge_pages_node[nid];
22899a305230SLee Schermerhorn 		init_nodemask_of_node(nodes_allowed, nid);
22909a305230SLee Schermerhorn 	} else
22918cebfcd0SLai Jiangshan 		nodes_allowed = &node_states[N_MEMORY];
22929a305230SLee Schermerhorn 
229306808b08SLee Schermerhorn 	h->max_huge_pages = set_max_huge_pages(h, count, nodes_allowed);
2294a3437870SNishanth Aravamudan 
22958cebfcd0SLai Jiangshan 	if (nodes_allowed != &node_states[N_MEMORY])
229606808b08SLee Schermerhorn 		NODEMASK_FREE(nodes_allowed);
229706808b08SLee Schermerhorn 
229806808b08SLee Schermerhorn 	return len;
2299adbe8726SEric B Munson out:
2300adbe8726SEric B Munson 	NODEMASK_FREE(nodes_allowed);
2301adbe8726SEric B Munson 	return err;
230206808b08SLee Schermerhorn }
230306808b08SLee Schermerhorn 
2304238d3c13SDavid Rientjes static ssize_t nr_hugepages_store_common(bool obey_mempolicy,
2305238d3c13SDavid Rientjes 					 struct kobject *kobj, const char *buf,
2306238d3c13SDavid Rientjes 					 size_t len)
2307238d3c13SDavid Rientjes {
2308238d3c13SDavid Rientjes 	struct hstate *h;
2309238d3c13SDavid Rientjes 	unsigned long count;
2310238d3c13SDavid Rientjes 	int nid;
2311238d3c13SDavid Rientjes 	int err;
2312238d3c13SDavid Rientjes 
2313238d3c13SDavid Rientjes 	err = kstrtoul(buf, 10, &count);
2314238d3c13SDavid Rientjes 	if (err)
2315238d3c13SDavid Rientjes 		return err;
2316238d3c13SDavid Rientjes 
2317238d3c13SDavid Rientjes 	h = kobj_to_hstate(kobj, &nid);
2318238d3c13SDavid Rientjes 	return __nr_hugepages_store_common(obey_mempolicy, h, nid, count, len);
2319238d3c13SDavid Rientjes }
2320238d3c13SDavid Rientjes 
232106808b08SLee Schermerhorn static ssize_t nr_hugepages_show(struct kobject *kobj,
232206808b08SLee Schermerhorn 				       struct kobj_attribute *attr, char *buf)
232306808b08SLee Schermerhorn {
232406808b08SLee Schermerhorn 	return nr_hugepages_show_common(kobj, attr, buf);
232506808b08SLee Schermerhorn }
232606808b08SLee Schermerhorn 
232706808b08SLee Schermerhorn static ssize_t nr_hugepages_store(struct kobject *kobj,
232806808b08SLee Schermerhorn 	       struct kobj_attribute *attr, const char *buf, size_t len)
232906808b08SLee Schermerhorn {
2330238d3c13SDavid Rientjes 	return nr_hugepages_store_common(false, kobj, buf, len);
2331a3437870SNishanth Aravamudan }
2332a3437870SNishanth Aravamudan HSTATE_ATTR(nr_hugepages);
2333a3437870SNishanth Aravamudan 
233406808b08SLee Schermerhorn #ifdef CONFIG_NUMA
233506808b08SLee Schermerhorn 
233606808b08SLee Schermerhorn /*
233706808b08SLee Schermerhorn  * hstate attribute for optionally mempolicy-based constraint on persistent
233806808b08SLee Schermerhorn  * huge page alloc/free.
233906808b08SLee Schermerhorn  */
234006808b08SLee Schermerhorn static ssize_t nr_hugepages_mempolicy_show(struct kobject *kobj,
234106808b08SLee Schermerhorn 				       struct kobj_attribute *attr, char *buf)
234206808b08SLee Schermerhorn {
234306808b08SLee Schermerhorn 	return nr_hugepages_show_common(kobj, attr, buf);
234406808b08SLee Schermerhorn }
234506808b08SLee Schermerhorn 
234606808b08SLee Schermerhorn static ssize_t nr_hugepages_mempolicy_store(struct kobject *kobj,
234706808b08SLee Schermerhorn 	       struct kobj_attribute *attr, const char *buf, size_t len)
234806808b08SLee Schermerhorn {
2349238d3c13SDavid Rientjes 	return nr_hugepages_store_common(true, kobj, buf, len);
235006808b08SLee Schermerhorn }
235106808b08SLee Schermerhorn HSTATE_ATTR(nr_hugepages_mempolicy);
235206808b08SLee Schermerhorn #endif
235306808b08SLee Schermerhorn 
235406808b08SLee Schermerhorn 
2355a3437870SNishanth Aravamudan static ssize_t nr_overcommit_hugepages_show(struct kobject *kobj,
2356a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
2357a3437870SNishanth Aravamudan {
23589a305230SLee Schermerhorn 	struct hstate *h = kobj_to_hstate(kobj, NULL);
2359a3437870SNishanth Aravamudan 	return sprintf(buf, "%lu\n", h->nr_overcommit_huge_pages);
2360a3437870SNishanth Aravamudan }
2361adbe8726SEric B Munson 
2362a3437870SNishanth Aravamudan static ssize_t nr_overcommit_hugepages_store(struct kobject *kobj,
2363a3437870SNishanth Aravamudan 		struct kobj_attribute *attr, const char *buf, size_t count)
2364a3437870SNishanth Aravamudan {
2365a3437870SNishanth Aravamudan 	int err;
2366a3437870SNishanth Aravamudan 	unsigned long input;
23679a305230SLee Schermerhorn 	struct hstate *h = kobj_to_hstate(kobj, NULL);
2368a3437870SNishanth Aravamudan 
2369bae7f4aeSLuiz Capitulino 	if (hstate_is_gigantic(h))
2370adbe8726SEric B Munson 		return -EINVAL;
2371adbe8726SEric B Munson 
23723dbb95f7SJingoo Han 	err = kstrtoul(buf, 10, &input);
2373a3437870SNishanth Aravamudan 	if (err)
237473ae31e5SEric B Munson 		return err;
2375a3437870SNishanth Aravamudan 
2376a3437870SNishanth Aravamudan 	spin_lock(&hugetlb_lock);
2377a3437870SNishanth Aravamudan 	h->nr_overcommit_huge_pages = input;
2378a3437870SNishanth Aravamudan 	spin_unlock(&hugetlb_lock);
2379a3437870SNishanth Aravamudan 
2380a3437870SNishanth Aravamudan 	return count;
2381a3437870SNishanth Aravamudan }
2382a3437870SNishanth Aravamudan HSTATE_ATTR(nr_overcommit_hugepages);
2383a3437870SNishanth Aravamudan 
2384a3437870SNishanth Aravamudan static ssize_t free_hugepages_show(struct kobject *kobj,
2385a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
2386a3437870SNishanth Aravamudan {
23879a305230SLee Schermerhorn 	struct hstate *h;
23889a305230SLee Schermerhorn 	unsigned long free_huge_pages;
23899a305230SLee Schermerhorn 	int nid;
23909a305230SLee Schermerhorn 
23919a305230SLee Schermerhorn 	h = kobj_to_hstate(kobj, &nid);
23929a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE)
23939a305230SLee Schermerhorn 		free_huge_pages = h->free_huge_pages;
23949a305230SLee Schermerhorn 	else
23959a305230SLee Schermerhorn 		free_huge_pages = h->free_huge_pages_node[nid];
23969a305230SLee Schermerhorn 
23979a305230SLee Schermerhorn 	return sprintf(buf, "%lu\n", free_huge_pages);
2398a3437870SNishanth Aravamudan }
2399a3437870SNishanth Aravamudan HSTATE_ATTR_RO(free_hugepages);
2400a3437870SNishanth Aravamudan 
2401a3437870SNishanth Aravamudan static ssize_t resv_hugepages_show(struct kobject *kobj,
2402a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
2403a3437870SNishanth Aravamudan {
24049a305230SLee Schermerhorn 	struct hstate *h = kobj_to_hstate(kobj, NULL);
2405a3437870SNishanth Aravamudan 	return sprintf(buf, "%lu\n", h->resv_huge_pages);
2406a3437870SNishanth Aravamudan }
2407a3437870SNishanth Aravamudan HSTATE_ATTR_RO(resv_hugepages);
2408a3437870SNishanth Aravamudan 
2409a3437870SNishanth Aravamudan static ssize_t surplus_hugepages_show(struct kobject *kobj,
2410a3437870SNishanth Aravamudan 					struct kobj_attribute *attr, char *buf)
2411a3437870SNishanth Aravamudan {
24129a305230SLee Schermerhorn 	struct hstate *h;
24139a305230SLee Schermerhorn 	unsigned long surplus_huge_pages;
24149a305230SLee Schermerhorn 	int nid;
24159a305230SLee Schermerhorn 
24169a305230SLee Schermerhorn 	h = kobj_to_hstate(kobj, &nid);
24179a305230SLee Schermerhorn 	if (nid == NUMA_NO_NODE)
24189a305230SLee Schermerhorn 		surplus_huge_pages = h->surplus_huge_pages;
24199a305230SLee Schermerhorn 	else
24209a305230SLee Schermerhorn 		surplus_huge_pages = h->surplus_huge_pages_node[nid];
24219a305230SLee Schermerhorn 
24229a305230SLee Schermerhorn 	return sprintf(buf, "%lu\n", surplus_huge_pages);
2423a3437870SNishanth Aravamudan }
2424a3437870SNishanth Aravamudan HSTATE_ATTR_RO(surplus_hugepages);
2425a3437870SNishanth Aravamudan 
2426a3437870SNishanth Aravamudan static struct attribute *hstate_attrs[] = {
2427a3437870SNishanth Aravamudan 	&nr_hugepages_attr.attr,
2428a3437870SNishanth Aravamudan 	&nr_overcommit_hugepages_attr.attr,
2429a3437870SNishanth Aravamudan 	&free_hugepages_attr.attr,
2430a3437870SNishanth Aravamudan 	&resv_hugepages_attr.attr,
2431a3437870SNishanth Aravamudan 	&surplus_hugepages_attr.attr,
243206808b08SLee Schermerhorn #ifdef CONFIG_NUMA
243306808b08SLee Schermerhorn 	&nr_hugepages_mempolicy_attr.attr,
243406808b08SLee Schermerhorn #endif
2435a3437870SNishanth Aravamudan 	NULL,
2436a3437870SNishanth Aravamudan };
2437a3437870SNishanth Aravamudan 
2438a3437870SNishanth Aravamudan static struct attribute_group hstate_attr_group = {
2439a3437870SNishanth Aravamudan 	.attrs = hstate_attrs,
2440a3437870SNishanth Aravamudan };
2441a3437870SNishanth Aravamudan 
2442094e9539SJeff Mahoney static int hugetlb_sysfs_add_hstate(struct hstate *h, struct kobject *parent,
24439a305230SLee Schermerhorn 				    struct kobject **hstate_kobjs,
24449a305230SLee Schermerhorn 				    struct attribute_group *hstate_attr_group)
2445a3437870SNishanth Aravamudan {
2446a3437870SNishanth Aravamudan 	int retval;
2447972dc4deSAneesh Kumar K.V 	int hi = hstate_index(h);
2448a3437870SNishanth Aravamudan 
24499a305230SLee Schermerhorn 	hstate_kobjs[hi] = kobject_create_and_add(h->name, parent);
24509a305230SLee Schermerhorn 	if (!hstate_kobjs[hi])
2451a3437870SNishanth Aravamudan 		return -ENOMEM;
2452a3437870SNishanth Aravamudan 
24539a305230SLee Schermerhorn 	retval = sysfs_create_group(hstate_kobjs[hi], hstate_attr_group);
2454a3437870SNishanth Aravamudan 	if (retval)
24559a305230SLee Schermerhorn 		kobject_put(hstate_kobjs[hi]);
2456a3437870SNishanth Aravamudan 
2457a3437870SNishanth Aravamudan 	return retval;
2458a3437870SNishanth Aravamudan }
2459a3437870SNishanth Aravamudan 
2460a3437870SNishanth Aravamudan static void __init hugetlb_sysfs_init(void)
2461a3437870SNishanth Aravamudan {
2462a3437870SNishanth Aravamudan 	struct hstate *h;
2463a3437870SNishanth Aravamudan 	int err;
2464a3437870SNishanth Aravamudan 
2465a3437870SNishanth Aravamudan 	hugepages_kobj = kobject_create_and_add("hugepages", mm_kobj);
2466a3437870SNishanth Aravamudan 	if (!hugepages_kobj)
2467a3437870SNishanth Aravamudan 		return;
2468a3437870SNishanth Aravamudan 
2469a3437870SNishanth Aravamudan 	for_each_hstate(h) {
24709a305230SLee Schermerhorn 		err = hugetlb_sysfs_add_hstate(h, hugepages_kobj,
24719a305230SLee Schermerhorn 					 hstate_kobjs, &hstate_attr_group);
2472a3437870SNishanth Aravamudan 		if (err)
2473ffb22af5SAndrew Morton 			pr_err("Hugetlb: Unable to add hstate %s", h->name);
2474a3437870SNishanth Aravamudan 	}
2475a3437870SNishanth Aravamudan }
2476a3437870SNishanth Aravamudan 
24779a305230SLee Schermerhorn #ifdef CONFIG_NUMA
24789a305230SLee Schermerhorn 
24799a305230SLee Schermerhorn /*
24809a305230SLee Schermerhorn  * node_hstate/s - associate per node hstate attributes, via their kobjects,
248110fbcf4cSKay Sievers  * with node devices in node_devices[] using a parallel array.  The array
248210fbcf4cSKay Sievers  * index of a node device or _hstate == node id.
248310fbcf4cSKay Sievers  * This is here to avoid any static dependency of the node device driver, in
24849a305230SLee Schermerhorn  * the base kernel, on the hugetlb module.
24859a305230SLee Schermerhorn  */
24869a305230SLee Schermerhorn struct node_hstate {
24879a305230SLee Schermerhorn 	struct kobject		*hugepages_kobj;
24889a305230SLee Schermerhorn 	struct kobject		*hstate_kobjs[HUGE_MAX_HSTATE];
24899a305230SLee Schermerhorn };
2490b4e289a6SAlexander Kuleshov static struct node_hstate node_hstates[MAX_NUMNODES];
24919a305230SLee Schermerhorn 
24929a305230SLee Schermerhorn /*
249310fbcf4cSKay Sievers  * A subset of global hstate attributes for node devices
24949a305230SLee Schermerhorn  */
24959a305230SLee Schermerhorn static struct attribute *per_node_hstate_attrs[] = {
24969a305230SLee Schermerhorn 	&nr_hugepages_attr.attr,
24979a305230SLee Schermerhorn 	&free_hugepages_attr.attr,
24989a305230SLee Schermerhorn 	&surplus_hugepages_attr.attr,
24999a305230SLee Schermerhorn 	NULL,
25009a305230SLee Schermerhorn };
25019a305230SLee Schermerhorn 
25029a305230SLee Schermerhorn static struct attribute_group per_node_hstate_attr_group = {
25039a305230SLee Schermerhorn 	.attrs = per_node_hstate_attrs,
25049a305230SLee Schermerhorn };
25059a305230SLee Schermerhorn 
25069a305230SLee Schermerhorn /*
250710fbcf4cSKay Sievers  * kobj_to_node_hstate - lookup global hstate for node device hstate attr kobj.
25089a305230SLee Schermerhorn  * Returns node id via non-NULL nidp.
25099a305230SLee Schermerhorn  */
25109a305230SLee Schermerhorn static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
25119a305230SLee Schermerhorn {
25129a305230SLee Schermerhorn 	int nid;
25139a305230SLee Schermerhorn 
25149a305230SLee Schermerhorn 	for (nid = 0; nid < nr_node_ids; nid++) {
25159a305230SLee Schermerhorn 		struct node_hstate *nhs = &node_hstates[nid];
25169a305230SLee Schermerhorn 		int i;
25179a305230SLee Schermerhorn 		for (i = 0; i < HUGE_MAX_HSTATE; i++)
25189a305230SLee Schermerhorn 			if (nhs->hstate_kobjs[i] == kobj) {
25199a305230SLee Schermerhorn 				if (nidp)
25209a305230SLee Schermerhorn 					*nidp = nid;
25219a305230SLee Schermerhorn 				return &hstates[i];
25229a305230SLee Schermerhorn 			}
25239a305230SLee Schermerhorn 	}
25249a305230SLee Schermerhorn 
25259a305230SLee Schermerhorn 	BUG();
25269a305230SLee Schermerhorn 	return NULL;
25279a305230SLee Schermerhorn }
25289a305230SLee Schermerhorn 
25299a305230SLee Schermerhorn /*
253010fbcf4cSKay Sievers  * Unregister hstate attributes from a single node device.
25319a305230SLee Schermerhorn  * No-op if no hstate attributes attached.
25329a305230SLee Schermerhorn  */
25333cd8b44fSClaudiu Ghioc static void hugetlb_unregister_node(struct node *node)
25349a305230SLee Schermerhorn {
25359a305230SLee Schermerhorn 	struct hstate *h;
253610fbcf4cSKay Sievers 	struct node_hstate *nhs = &node_hstates[node->dev.id];
25379a305230SLee Schermerhorn 
25389a305230SLee Schermerhorn 	if (!nhs->hugepages_kobj)
25399b5e5d0fSLee Schermerhorn 		return;		/* no hstate attributes */
25409a305230SLee Schermerhorn 
2541972dc4deSAneesh Kumar K.V 	for_each_hstate(h) {
2542972dc4deSAneesh Kumar K.V 		int idx = hstate_index(h);
2543972dc4deSAneesh Kumar K.V 		if (nhs->hstate_kobjs[idx]) {
2544972dc4deSAneesh Kumar K.V 			kobject_put(nhs->hstate_kobjs[idx]);
2545972dc4deSAneesh Kumar K.V 			nhs->hstate_kobjs[idx] = NULL;
2546972dc4deSAneesh Kumar K.V 		}
25479a305230SLee Schermerhorn 	}
25489a305230SLee Schermerhorn 
25499a305230SLee Schermerhorn 	kobject_put(nhs->hugepages_kobj);
25509a305230SLee Schermerhorn 	nhs->hugepages_kobj = NULL;
25519a305230SLee Schermerhorn }
25529a305230SLee Schermerhorn 
25539a305230SLee Schermerhorn 
25549a305230SLee Schermerhorn /*
255510fbcf4cSKay Sievers  * Register hstate attributes for a single node device.
25569a305230SLee Schermerhorn  * No-op if attributes already registered.
25579a305230SLee Schermerhorn  */
25583cd8b44fSClaudiu Ghioc static void hugetlb_register_node(struct node *node)
25599a305230SLee Schermerhorn {
25609a305230SLee Schermerhorn 	struct hstate *h;
256110fbcf4cSKay Sievers 	struct node_hstate *nhs = &node_hstates[node->dev.id];
25629a305230SLee Schermerhorn 	int err;
25639a305230SLee Schermerhorn 
25649a305230SLee Schermerhorn 	if (nhs->hugepages_kobj)
25659a305230SLee Schermerhorn 		return;		/* already allocated */
25669a305230SLee Schermerhorn 
25679a305230SLee Schermerhorn 	nhs->hugepages_kobj = kobject_create_and_add("hugepages",
256810fbcf4cSKay Sievers 							&node->dev.kobj);
25699a305230SLee Schermerhorn 	if (!nhs->hugepages_kobj)
25709a305230SLee Schermerhorn 		return;
25719a305230SLee Schermerhorn 
25729a305230SLee Schermerhorn 	for_each_hstate(h) {
25739a305230SLee Schermerhorn 		err = hugetlb_sysfs_add_hstate(h, nhs->hugepages_kobj,
25749a305230SLee Schermerhorn 						nhs->hstate_kobjs,
25759a305230SLee Schermerhorn 						&per_node_hstate_attr_group);
25769a305230SLee Schermerhorn 		if (err) {
2577ffb22af5SAndrew Morton 			pr_err("Hugetlb: Unable to add hstate %s for node %d\n",
257810fbcf4cSKay Sievers 				h->name, node->dev.id);
25799a305230SLee Schermerhorn 			hugetlb_unregister_node(node);
25809a305230SLee Schermerhorn 			break;
25819a305230SLee Schermerhorn 		}
25829a305230SLee Schermerhorn 	}
25839a305230SLee Schermerhorn }
25849a305230SLee Schermerhorn 
25859a305230SLee Schermerhorn /*
25869b5e5d0fSLee Schermerhorn  * hugetlb init time:  register hstate attributes for all registered node
258710fbcf4cSKay Sievers  * devices of nodes that have memory.  All on-line nodes should have
258810fbcf4cSKay Sievers  * registered their associated device by this time.
25899a305230SLee Schermerhorn  */
25907d9ca000SLuiz Capitulino static void __init hugetlb_register_all_nodes(void)
25919a305230SLee Schermerhorn {
25929a305230SLee Schermerhorn 	int nid;
25939a305230SLee Schermerhorn 
25948cebfcd0SLai Jiangshan 	for_each_node_state(nid, N_MEMORY) {
25958732794bSWen Congyang 		struct node *node = node_devices[nid];
259610fbcf4cSKay Sievers 		if (node->dev.id == nid)
25979a305230SLee Schermerhorn 			hugetlb_register_node(node);
25989a305230SLee Schermerhorn 	}
25999a305230SLee Schermerhorn 
26009a305230SLee Schermerhorn 	/*
260110fbcf4cSKay Sievers 	 * Let the node device driver know we're here so it can
26029a305230SLee Schermerhorn 	 * [un]register hstate attributes on node hotplug.
26039a305230SLee Schermerhorn 	 */
26049a305230SLee Schermerhorn 	register_hugetlbfs_with_node(hugetlb_register_node,
26059a305230SLee Schermerhorn 				     hugetlb_unregister_node);
26069a305230SLee Schermerhorn }
26079a305230SLee Schermerhorn #else	/* !CONFIG_NUMA */
26089a305230SLee Schermerhorn 
26099a305230SLee Schermerhorn static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
26109a305230SLee Schermerhorn {
26119a305230SLee Schermerhorn 	BUG();
26129a305230SLee Schermerhorn 	if (nidp)
26139a305230SLee Schermerhorn 		*nidp = -1;
26149a305230SLee Schermerhorn 	return NULL;
26159a305230SLee Schermerhorn }
26169a305230SLee Schermerhorn 
26179a305230SLee Schermerhorn static void hugetlb_register_all_nodes(void) { }
26189a305230SLee Schermerhorn 
26199a305230SLee Schermerhorn #endif
26209a305230SLee Schermerhorn 
2621a3437870SNishanth Aravamudan static int __init hugetlb_init(void)
2622a3437870SNishanth Aravamudan {
26238382d914SDavidlohr Bueso 	int i;
26248382d914SDavidlohr Bueso 
2625457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
26260ef89d25SBenjamin Herrenschmidt 		return 0;
2627a3437870SNishanth Aravamudan 
2628e11bfbfcSNick Piggin 	if (!size_to_hstate(default_hstate_size)) {
2629e11bfbfcSNick Piggin 		default_hstate_size = HPAGE_SIZE;
2630e11bfbfcSNick Piggin 		if (!size_to_hstate(default_hstate_size))
2631a3437870SNishanth Aravamudan 			hugetlb_add_hstate(HUGETLB_PAGE_ORDER);
2632a3437870SNishanth Aravamudan 	}
2633972dc4deSAneesh Kumar K.V 	default_hstate_idx = hstate_index(size_to_hstate(default_hstate_size));
2634f8b74815SVaishali Thakkar 	if (default_hstate_max_huge_pages) {
2635f8b74815SVaishali Thakkar 		if (!default_hstate.max_huge_pages)
2636e11bfbfcSNick Piggin 			default_hstate.max_huge_pages = default_hstate_max_huge_pages;
2637f8b74815SVaishali Thakkar 	}
2638a3437870SNishanth Aravamudan 
2639a3437870SNishanth Aravamudan 	hugetlb_init_hstates();
2640aa888a74SAndi Kleen 	gather_bootmem_prealloc();
2641a3437870SNishanth Aravamudan 	report_hugepages();
2642a3437870SNishanth Aravamudan 
2643a3437870SNishanth Aravamudan 	hugetlb_sysfs_init();
26449a305230SLee Schermerhorn 	hugetlb_register_all_nodes();
26457179e7bfSJianguo Wu 	hugetlb_cgroup_file_init();
26469a305230SLee Schermerhorn 
26478382d914SDavidlohr Bueso #ifdef CONFIG_SMP
26488382d914SDavidlohr Bueso 	num_fault_mutexes = roundup_pow_of_two(8 * num_possible_cpus());
26498382d914SDavidlohr Bueso #else
26508382d914SDavidlohr Bueso 	num_fault_mutexes = 1;
26518382d914SDavidlohr Bueso #endif
2652c672c7f2SMike Kravetz 	hugetlb_fault_mutex_table =
26538382d914SDavidlohr Bueso 		kmalloc(sizeof(struct mutex) * num_fault_mutexes, GFP_KERNEL);
2654c672c7f2SMike Kravetz 	BUG_ON(!hugetlb_fault_mutex_table);
26558382d914SDavidlohr Bueso 
26568382d914SDavidlohr Bueso 	for (i = 0; i < num_fault_mutexes; i++)
2657c672c7f2SMike Kravetz 		mutex_init(&hugetlb_fault_mutex_table[i]);
2658a3437870SNishanth Aravamudan 	return 0;
2659a3437870SNishanth Aravamudan }
26603e89e1c5SPaul Gortmaker subsys_initcall(hugetlb_init);
2661a3437870SNishanth Aravamudan 
2662a3437870SNishanth Aravamudan /* Should be called on processing a hugepagesz=... option */
26639fee021dSVaishali Thakkar void __init hugetlb_bad_size(void)
26649fee021dSVaishali Thakkar {
26659fee021dSVaishali Thakkar 	parsed_valid_hugepagesz = false;
26669fee021dSVaishali Thakkar }
26679fee021dSVaishali Thakkar 
2668d00181b9SKirill A. Shutemov void __init hugetlb_add_hstate(unsigned int order)
2669a3437870SNishanth Aravamudan {
2670a3437870SNishanth Aravamudan 	struct hstate *h;
26718faa8b07SAndi Kleen 	unsigned long i;
26728faa8b07SAndi Kleen 
2673a3437870SNishanth Aravamudan 	if (size_to_hstate(PAGE_SIZE << order)) {
2674598d8091SJoe Perches 		pr_warn("hugepagesz= specified twice, ignoring\n");
2675a3437870SNishanth Aravamudan 		return;
2676a3437870SNishanth Aravamudan 	}
267747d38344SAneesh Kumar K.V 	BUG_ON(hugetlb_max_hstate >= HUGE_MAX_HSTATE);
2678a3437870SNishanth Aravamudan 	BUG_ON(order == 0);
267947d38344SAneesh Kumar K.V 	h = &hstates[hugetlb_max_hstate++];
2680a3437870SNishanth Aravamudan 	h->order = order;
2681a3437870SNishanth Aravamudan 	h->mask = ~((1ULL << (order + PAGE_SHIFT)) - 1);
26828faa8b07SAndi Kleen 	h->nr_huge_pages = 0;
26838faa8b07SAndi Kleen 	h->free_huge_pages = 0;
26848faa8b07SAndi Kleen 	for (i = 0; i < MAX_NUMNODES; ++i)
26858faa8b07SAndi Kleen 		INIT_LIST_HEAD(&h->hugepage_freelists[i]);
26860edaecfaSAneesh Kumar K.V 	INIT_LIST_HEAD(&h->hugepage_activelist);
26878cebfcd0SLai Jiangshan 	h->next_nid_to_alloc = first_node(node_states[N_MEMORY]);
26888cebfcd0SLai Jiangshan 	h->next_nid_to_free = first_node(node_states[N_MEMORY]);
2689a3437870SNishanth Aravamudan 	snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB",
2690a3437870SNishanth Aravamudan 					huge_page_size(h)/1024);
26918faa8b07SAndi Kleen 
2692a3437870SNishanth Aravamudan 	parsed_hstate = h;
2693a3437870SNishanth Aravamudan }
2694a3437870SNishanth Aravamudan 
2695e11bfbfcSNick Piggin static int __init hugetlb_nrpages_setup(char *s)
2696a3437870SNishanth Aravamudan {
2697a3437870SNishanth Aravamudan 	unsigned long *mhp;
26988faa8b07SAndi Kleen 	static unsigned long *last_mhp;
2699a3437870SNishanth Aravamudan 
27009fee021dSVaishali Thakkar 	if (!parsed_valid_hugepagesz) {
27019fee021dSVaishali Thakkar 		pr_warn("hugepages = %s preceded by "
27029fee021dSVaishali Thakkar 			"an unsupported hugepagesz, ignoring\n", s);
27039fee021dSVaishali Thakkar 		parsed_valid_hugepagesz = true;
27049fee021dSVaishali Thakkar 		return 1;
27059fee021dSVaishali Thakkar 	}
2706a3437870SNishanth Aravamudan 	/*
270747d38344SAneesh Kumar K.V 	 * !hugetlb_max_hstate means we haven't parsed a hugepagesz= parameter yet,
2708a3437870SNishanth Aravamudan 	 * so this hugepages= parameter goes to the "default hstate".
2709a3437870SNishanth Aravamudan 	 */
27109fee021dSVaishali Thakkar 	else if (!hugetlb_max_hstate)
2711a3437870SNishanth Aravamudan 		mhp = &default_hstate_max_huge_pages;
2712a3437870SNishanth Aravamudan 	else
2713a3437870SNishanth Aravamudan 		mhp = &parsed_hstate->max_huge_pages;
2714a3437870SNishanth Aravamudan 
27158faa8b07SAndi Kleen 	if (mhp == last_mhp) {
2716598d8091SJoe Perches 		pr_warn("hugepages= specified twice without interleaving hugepagesz=, ignoring\n");
27178faa8b07SAndi Kleen 		return 1;
27188faa8b07SAndi Kleen 	}
27198faa8b07SAndi Kleen 
2720a3437870SNishanth Aravamudan 	if (sscanf(s, "%lu", mhp) <= 0)
2721a3437870SNishanth Aravamudan 		*mhp = 0;
2722a3437870SNishanth Aravamudan 
27238faa8b07SAndi Kleen 	/*
27248faa8b07SAndi Kleen 	 * Global state is always initialized later in hugetlb_init.
27258faa8b07SAndi Kleen 	 * But we need to allocate >= MAX_ORDER hstates here early to still
27268faa8b07SAndi Kleen 	 * use the bootmem allocator.
27278faa8b07SAndi Kleen 	 */
272847d38344SAneesh Kumar K.V 	if (hugetlb_max_hstate && parsed_hstate->order >= MAX_ORDER)
27298faa8b07SAndi Kleen 		hugetlb_hstate_alloc_pages(parsed_hstate);
27308faa8b07SAndi Kleen 
27318faa8b07SAndi Kleen 	last_mhp = mhp;
27328faa8b07SAndi Kleen 
2733a3437870SNishanth Aravamudan 	return 1;
2734a3437870SNishanth Aravamudan }
2735e11bfbfcSNick Piggin __setup("hugepages=", hugetlb_nrpages_setup);
2736e11bfbfcSNick Piggin 
2737e11bfbfcSNick Piggin static int __init hugetlb_default_setup(char *s)
2738e11bfbfcSNick Piggin {
2739e11bfbfcSNick Piggin 	default_hstate_size = memparse(s, &s);
2740e11bfbfcSNick Piggin 	return 1;
2741e11bfbfcSNick Piggin }
2742e11bfbfcSNick Piggin __setup("default_hugepagesz=", hugetlb_default_setup);
2743a3437870SNishanth Aravamudan 
27448a213460SNishanth Aravamudan static unsigned int cpuset_mems_nr(unsigned int *array)
27458a213460SNishanth Aravamudan {
27468a213460SNishanth Aravamudan 	int node;
27478a213460SNishanth Aravamudan 	unsigned int nr = 0;
27488a213460SNishanth Aravamudan 
27498a213460SNishanth Aravamudan 	for_each_node_mask(node, cpuset_current_mems_allowed)
27508a213460SNishanth Aravamudan 		nr += array[node];
27518a213460SNishanth Aravamudan 
27528a213460SNishanth Aravamudan 	return nr;
27538a213460SNishanth Aravamudan }
27548a213460SNishanth Aravamudan 
27558a213460SNishanth Aravamudan #ifdef CONFIG_SYSCTL
275606808b08SLee Schermerhorn static int hugetlb_sysctl_handler_common(bool obey_mempolicy,
275706808b08SLee Schermerhorn 			 struct ctl_table *table, int write,
275806808b08SLee Schermerhorn 			 void __user *buffer, size_t *length, loff_t *ppos)
27591da177e4SLinus Torvalds {
2760e5ff2159SAndi Kleen 	struct hstate *h = &default_hstate;
2761238d3c13SDavid Rientjes 	unsigned long tmp = h->max_huge_pages;
276208d4a246SMichal Hocko 	int ret;
2763e5ff2159SAndi Kleen 
2764457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
276586613628SJan Stancek 		return -EOPNOTSUPP;
2766457c1b27SNishanth Aravamudan 
2767e5ff2159SAndi Kleen 	table->data = &tmp;
2768e5ff2159SAndi Kleen 	table->maxlen = sizeof(unsigned long);
276908d4a246SMichal Hocko 	ret = proc_doulongvec_minmax(table, write, buffer, length, ppos);
277008d4a246SMichal Hocko 	if (ret)
277108d4a246SMichal Hocko 		goto out;
2772e5ff2159SAndi Kleen 
2773238d3c13SDavid Rientjes 	if (write)
2774238d3c13SDavid Rientjes 		ret = __nr_hugepages_store_common(obey_mempolicy, h,
2775238d3c13SDavid Rientjes 						  NUMA_NO_NODE, tmp, *length);
277608d4a246SMichal Hocko out:
277708d4a246SMichal Hocko 	return ret;
27781da177e4SLinus Torvalds }
2779396faf03SMel Gorman 
278006808b08SLee Schermerhorn int hugetlb_sysctl_handler(struct ctl_table *table, int write,
278106808b08SLee Schermerhorn 			  void __user *buffer, size_t *length, loff_t *ppos)
278206808b08SLee Schermerhorn {
278306808b08SLee Schermerhorn 
278406808b08SLee Schermerhorn 	return hugetlb_sysctl_handler_common(false, table, write,
278506808b08SLee Schermerhorn 							buffer, length, ppos);
278606808b08SLee Schermerhorn }
278706808b08SLee Schermerhorn 
278806808b08SLee Schermerhorn #ifdef CONFIG_NUMA
278906808b08SLee Schermerhorn int hugetlb_mempolicy_sysctl_handler(struct ctl_table *table, int write,
279006808b08SLee Schermerhorn 			  void __user *buffer, size_t *length, loff_t *ppos)
279106808b08SLee Schermerhorn {
279206808b08SLee Schermerhorn 	return hugetlb_sysctl_handler_common(true, table, write,
279306808b08SLee Schermerhorn 							buffer, length, ppos);
279406808b08SLee Schermerhorn }
279506808b08SLee Schermerhorn #endif /* CONFIG_NUMA */
279606808b08SLee Schermerhorn 
2797a3d0c6aaSNishanth Aravamudan int hugetlb_overcommit_handler(struct ctl_table *table, int write,
27988d65af78SAlexey Dobriyan 			void __user *buffer,
2799a3d0c6aaSNishanth Aravamudan 			size_t *length, loff_t *ppos)
2800a3d0c6aaSNishanth Aravamudan {
2801a5516438SAndi Kleen 	struct hstate *h = &default_hstate;
2802e5ff2159SAndi Kleen 	unsigned long tmp;
280308d4a246SMichal Hocko 	int ret;
2804e5ff2159SAndi Kleen 
2805457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
280686613628SJan Stancek 		return -EOPNOTSUPP;
2807457c1b27SNishanth Aravamudan 
2808e5ff2159SAndi Kleen 	tmp = h->nr_overcommit_huge_pages;
2809e5ff2159SAndi Kleen 
2810bae7f4aeSLuiz Capitulino 	if (write && hstate_is_gigantic(h))
2811adbe8726SEric B Munson 		return -EINVAL;
2812adbe8726SEric B Munson 
2813e5ff2159SAndi Kleen 	table->data = &tmp;
2814e5ff2159SAndi Kleen 	table->maxlen = sizeof(unsigned long);
281508d4a246SMichal Hocko 	ret = proc_doulongvec_minmax(table, write, buffer, length, ppos);
281608d4a246SMichal Hocko 	if (ret)
281708d4a246SMichal Hocko 		goto out;
2818e5ff2159SAndi Kleen 
2819e5ff2159SAndi Kleen 	if (write) {
2820064d9efeSNishanth Aravamudan 		spin_lock(&hugetlb_lock);
2821e5ff2159SAndi Kleen 		h->nr_overcommit_huge_pages = tmp;
2822a3d0c6aaSNishanth Aravamudan 		spin_unlock(&hugetlb_lock);
2823e5ff2159SAndi Kleen 	}
282408d4a246SMichal Hocko out:
282508d4a246SMichal Hocko 	return ret;
2826a3d0c6aaSNishanth Aravamudan }
2827a3d0c6aaSNishanth Aravamudan 
28281da177e4SLinus Torvalds #endif /* CONFIG_SYSCTL */
28291da177e4SLinus Torvalds 
2830e1759c21SAlexey Dobriyan void hugetlb_report_meminfo(struct seq_file *m)
28311da177e4SLinus Torvalds {
2832a5516438SAndi Kleen 	struct hstate *h = &default_hstate;
2833457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
2834457c1b27SNishanth Aravamudan 		return;
2835e1759c21SAlexey Dobriyan 	seq_printf(m,
28361da177e4SLinus Torvalds 			"HugePages_Total:   %5lu\n"
28371da177e4SLinus Torvalds 			"HugePages_Free:    %5lu\n"
2838b45b5bd6SDavid Gibson 			"HugePages_Rsvd:    %5lu\n"
28397893d1d5SAdam Litke 			"HugePages_Surp:    %5lu\n"
28404f98a2feSRik van Riel 			"Hugepagesize:   %8lu kB\n",
2841a5516438SAndi Kleen 			h->nr_huge_pages,
2842a5516438SAndi Kleen 			h->free_huge_pages,
2843a5516438SAndi Kleen 			h->resv_huge_pages,
2844a5516438SAndi Kleen 			h->surplus_huge_pages,
2845a5516438SAndi Kleen 			1UL << (huge_page_order(h) + PAGE_SHIFT - 10));
28461da177e4SLinus Torvalds }
28471da177e4SLinus Torvalds 
28481da177e4SLinus Torvalds int hugetlb_report_node_meminfo(int nid, char *buf)
28491da177e4SLinus Torvalds {
2850a5516438SAndi Kleen 	struct hstate *h = &default_hstate;
2851457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
2852457c1b27SNishanth Aravamudan 		return 0;
28531da177e4SLinus Torvalds 	return sprintf(buf,
28541da177e4SLinus Torvalds 		"Node %d HugePages_Total: %5u\n"
2855a1de0919SNishanth Aravamudan 		"Node %d HugePages_Free:  %5u\n"
2856a1de0919SNishanth Aravamudan 		"Node %d HugePages_Surp:  %5u\n",
2857a5516438SAndi Kleen 		nid, h->nr_huge_pages_node[nid],
2858a5516438SAndi Kleen 		nid, h->free_huge_pages_node[nid],
2859a5516438SAndi Kleen 		nid, h->surplus_huge_pages_node[nid]);
28601da177e4SLinus Torvalds }
28611da177e4SLinus Torvalds 
2862949f7ec5SDavid Rientjes void hugetlb_show_meminfo(void)
2863949f7ec5SDavid Rientjes {
2864949f7ec5SDavid Rientjes 	struct hstate *h;
2865949f7ec5SDavid Rientjes 	int nid;
2866949f7ec5SDavid Rientjes 
2867457c1b27SNishanth Aravamudan 	if (!hugepages_supported())
2868457c1b27SNishanth Aravamudan 		return;
2869457c1b27SNishanth Aravamudan 
2870949f7ec5SDavid Rientjes 	for_each_node_state(nid, N_MEMORY)
2871949f7ec5SDavid Rientjes 		for_each_hstate(h)
2872949f7ec5SDavid Rientjes 			pr_info("Node %d hugepages_total=%u hugepages_free=%u hugepages_surp=%u hugepages_size=%lukB\n",
2873949f7ec5SDavid Rientjes 				nid,
2874949f7ec5SDavid Rientjes 				h->nr_huge_pages_node[nid],
2875949f7ec5SDavid Rientjes 				h->free_huge_pages_node[nid],
2876949f7ec5SDavid Rientjes 				h->surplus_huge_pages_node[nid],
2877949f7ec5SDavid Rientjes 				1UL << (huge_page_order(h) + PAGE_SHIFT - 10));
2878949f7ec5SDavid Rientjes }
2879949f7ec5SDavid Rientjes 
28805d317b2bSNaoya Horiguchi void hugetlb_report_usage(struct seq_file *m, struct mm_struct *mm)
28815d317b2bSNaoya Horiguchi {
28825d317b2bSNaoya Horiguchi 	seq_printf(m, "HugetlbPages:\t%8lu kB\n",
28835d317b2bSNaoya Horiguchi 		   atomic_long_read(&mm->hugetlb_usage) << (PAGE_SHIFT - 10));
28845d317b2bSNaoya Horiguchi }
28855d317b2bSNaoya Horiguchi 
28861da177e4SLinus Torvalds /* Return the number pages of memory we physically have, in PAGE_SIZE units. */
28871da177e4SLinus Torvalds unsigned long hugetlb_total_pages(void)
28881da177e4SLinus Torvalds {
2889d0028588SWanpeng Li 	struct hstate *h;
2890d0028588SWanpeng Li 	unsigned long nr_total_pages = 0;
2891d0028588SWanpeng Li 
2892d0028588SWanpeng Li 	for_each_hstate(h)
2893d0028588SWanpeng Li 		nr_total_pages += h->nr_huge_pages * pages_per_huge_page(h);
2894d0028588SWanpeng Li 	return nr_total_pages;
28951da177e4SLinus Torvalds }
28961da177e4SLinus Torvalds 
2897a5516438SAndi Kleen static int hugetlb_acct_memory(struct hstate *h, long delta)
2898fc1b8a73SMel Gorman {
2899fc1b8a73SMel Gorman 	int ret = -ENOMEM;
2900fc1b8a73SMel Gorman 
2901fc1b8a73SMel Gorman 	spin_lock(&hugetlb_lock);
2902fc1b8a73SMel Gorman 	/*
2903fc1b8a73SMel Gorman 	 * When cpuset is configured, it breaks the strict hugetlb page
2904fc1b8a73SMel Gorman 	 * reservation as the accounting is done on a global variable. Such
2905fc1b8a73SMel Gorman 	 * reservation is completely rubbish in the presence of cpuset because
2906fc1b8a73SMel Gorman 	 * the reservation is not checked against page availability for the
2907fc1b8a73SMel Gorman 	 * current cpuset. Application can still potentially OOM'ed by kernel
2908fc1b8a73SMel Gorman 	 * with lack of free htlb page in cpuset that the task is in.
2909fc1b8a73SMel Gorman 	 * Attempt to enforce strict accounting with cpuset is almost
2910fc1b8a73SMel Gorman 	 * impossible (or too ugly) because cpuset is too fluid that
2911fc1b8a73SMel Gorman 	 * task or memory node can be dynamically moved between cpusets.
2912fc1b8a73SMel Gorman 	 *
2913fc1b8a73SMel Gorman 	 * The change of semantics for shared hugetlb mapping with cpuset is
2914fc1b8a73SMel Gorman 	 * undesirable. However, in order to preserve some of the semantics,
2915fc1b8a73SMel Gorman 	 * we fall back to check against current free page availability as
2916fc1b8a73SMel Gorman 	 * a best attempt and hopefully to minimize the impact of changing
2917fc1b8a73SMel Gorman 	 * semantics that cpuset has.
2918fc1b8a73SMel Gorman 	 */
2919fc1b8a73SMel Gorman 	if (delta > 0) {
2920a5516438SAndi Kleen 		if (gather_surplus_pages(h, delta) < 0)
2921fc1b8a73SMel Gorman 			goto out;
2922fc1b8a73SMel Gorman 
2923a5516438SAndi Kleen 		if (delta > cpuset_mems_nr(h->free_huge_pages_node)) {
2924a5516438SAndi Kleen 			return_unused_surplus_pages(h, delta);
2925fc1b8a73SMel Gorman 			goto out;
2926fc1b8a73SMel Gorman 		}
2927fc1b8a73SMel Gorman 	}
2928fc1b8a73SMel Gorman 
2929fc1b8a73SMel Gorman 	ret = 0;
2930fc1b8a73SMel Gorman 	if (delta < 0)
2931a5516438SAndi Kleen 		return_unused_surplus_pages(h, (unsigned long) -delta);
2932fc1b8a73SMel Gorman 
2933fc1b8a73SMel Gorman out:
2934fc1b8a73SMel Gorman 	spin_unlock(&hugetlb_lock);
2935fc1b8a73SMel Gorman 	return ret;
2936fc1b8a73SMel Gorman }
2937fc1b8a73SMel Gorman 
293884afd99bSAndy Whitcroft static void hugetlb_vm_op_open(struct vm_area_struct *vma)
293984afd99bSAndy Whitcroft {
2940f522c3acSJoonsoo Kim 	struct resv_map *resv = vma_resv_map(vma);
294184afd99bSAndy Whitcroft 
294284afd99bSAndy Whitcroft 	/*
294384afd99bSAndy Whitcroft 	 * This new VMA should share its siblings reservation map if present.
294484afd99bSAndy Whitcroft 	 * The VMA will only ever have a valid reservation map pointer where
294584afd99bSAndy Whitcroft 	 * it is being copied for another still existing VMA.  As that VMA
294625985edcSLucas De Marchi 	 * has a reference to the reservation map it cannot disappear until
294784afd99bSAndy Whitcroft 	 * after this open call completes.  It is therefore safe to take a
294884afd99bSAndy Whitcroft 	 * new reference here without additional locking.
294984afd99bSAndy Whitcroft 	 */
29504e35f483SJoonsoo Kim 	if (resv && is_vma_resv_set(vma, HPAGE_RESV_OWNER))
2951f522c3acSJoonsoo Kim 		kref_get(&resv->refs);
295284afd99bSAndy Whitcroft }
295384afd99bSAndy Whitcroft 
2954a1e78772SMel Gorman static void hugetlb_vm_op_close(struct vm_area_struct *vma)
2955a1e78772SMel Gorman {
2956a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
2957f522c3acSJoonsoo Kim 	struct resv_map *resv = vma_resv_map(vma);
295890481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_vma(vma);
29594e35f483SJoonsoo Kim 	unsigned long reserve, start, end;
29601c5ecae3SMike Kravetz 	long gbl_reserve;
296184afd99bSAndy Whitcroft 
29624e35f483SJoonsoo Kim 	if (!resv || !is_vma_resv_set(vma, HPAGE_RESV_OWNER))
29634e35f483SJoonsoo Kim 		return;
29644e35f483SJoonsoo Kim 
2965a5516438SAndi Kleen 	start = vma_hugecache_offset(h, vma, vma->vm_start);
2966a5516438SAndi Kleen 	end = vma_hugecache_offset(h, vma, vma->vm_end);
296784afd99bSAndy Whitcroft 
29684e35f483SJoonsoo Kim 	reserve = (end - start) - region_count(resv, start, end);
296984afd99bSAndy Whitcroft 
2970f031dd27SJoonsoo Kim 	kref_put(&resv->refs, resv_map_release);
297184afd99bSAndy Whitcroft 
29727251ff78SAdam Litke 	if (reserve) {
29731c5ecae3SMike Kravetz 		/*
29741c5ecae3SMike Kravetz 		 * Decrement reserve counts.  The global reserve count may be
29751c5ecae3SMike Kravetz 		 * adjusted if the subpool has a minimum size.
29761c5ecae3SMike Kravetz 		 */
29771c5ecae3SMike Kravetz 		gbl_reserve = hugepage_subpool_put_pages(spool, reserve);
29781c5ecae3SMike Kravetz 		hugetlb_acct_memory(h, -gbl_reserve);
29797251ff78SAdam Litke 	}
2980a1e78772SMel Gorman }
2981a1e78772SMel Gorman 
29821da177e4SLinus Torvalds /*
29831da177e4SLinus Torvalds  * We cannot handle pagefaults against hugetlb pages at all.  They cause
29841da177e4SLinus Torvalds  * handle_mm_fault() to try to instantiate regular-sized pages in the
29851da177e4SLinus Torvalds  * hugegpage VMA.  do_page_fault() is supposed to trap this, so BUG is we get
29861da177e4SLinus Torvalds  * this far.
29871da177e4SLinus Torvalds  */
2988d0217ac0SNick Piggin static int hugetlb_vm_op_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
29891da177e4SLinus Torvalds {
29901da177e4SLinus Torvalds 	BUG();
2991d0217ac0SNick Piggin 	return 0;
29921da177e4SLinus Torvalds }
29931da177e4SLinus Torvalds 
2994f0f37e2fSAlexey Dobriyan const struct vm_operations_struct hugetlb_vm_ops = {
2995d0217ac0SNick Piggin 	.fault = hugetlb_vm_op_fault,
299684afd99bSAndy Whitcroft 	.open = hugetlb_vm_op_open,
2997a1e78772SMel Gorman 	.close = hugetlb_vm_op_close,
29981da177e4SLinus Torvalds };
29991da177e4SLinus Torvalds 
30001e8f889bSDavid Gibson static pte_t make_huge_pte(struct vm_area_struct *vma, struct page *page,
30011e8f889bSDavid Gibson 				int writable)
300263551ae0SDavid Gibson {
300363551ae0SDavid Gibson 	pte_t entry;
300463551ae0SDavid Gibson 
30051e8f889bSDavid Gibson 	if (writable) {
3006106c992aSGerald Schaefer 		entry = huge_pte_mkwrite(huge_pte_mkdirty(mk_huge_pte(page,
3007106c992aSGerald Schaefer 					 vma->vm_page_prot)));
300863551ae0SDavid Gibson 	} else {
3009106c992aSGerald Schaefer 		entry = huge_pte_wrprotect(mk_huge_pte(page,
3010106c992aSGerald Schaefer 					   vma->vm_page_prot));
301163551ae0SDavid Gibson 	}
301263551ae0SDavid Gibson 	entry = pte_mkyoung(entry);
301363551ae0SDavid Gibson 	entry = pte_mkhuge(entry);
3014d9ed9faaSChris Metcalf 	entry = arch_make_huge_pte(entry, vma, page, writable);
301563551ae0SDavid Gibson 
301663551ae0SDavid Gibson 	return entry;
301763551ae0SDavid Gibson }
301863551ae0SDavid Gibson 
30191e8f889bSDavid Gibson static void set_huge_ptep_writable(struct vm_area_struct *vma,
30201e8f889bSDavid Gibson 				   unsigned long address, pte_t *ptep)
30211e8f889bSDavid Gibson {
30221e8f889bSDavid Gibson 	pte_t entry;
30231e8f889bSDavid Gibson 
3024106c992aSGerald Schaefer 	entry = huge_pte_mkwrite(huge_pte_mkdirty(huge_ptep_get(ptep)));
302532f84528SChris Forbes 	if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1))
30264b3073e1SRussell King 		update_mmu_cache(vma, address, ptep);
30271e8f889bSDavid Gibson }
30281e8f889bSDavid Gibson 
30294a705fefSNaoya Horiguchi static int is_hugetlb_entry_migration(pte_t pte)
30304a705fefSNaoya Horiguchi {
30314a705fefSNaoya Horiguchi 	swp_entry_t swp;
30324a705fefSNaoya Horiguchi 
30334a705fefSNaoya Horiguchi 	if (huge_pte_none(pte) || pte_present(pte))
30344a705fefSNaoya Horiguchi 		return 0;
30354a705fefSNaoya Horiguchi 	swp = pte_to_swp_entry(pte);
30364a705fefSNaoya Horiguchi 	if (non_swap_entry(swp) && is_migration_entry(swp))
30374a705fefSNaoya Horiguchi 		return 1;
30384a705fefSNaoya Horiguchi 	else
30394a705fefSNaoya Horiguchi 		return 0;
30404a705fefSNaoya Horiguchi }
30414a705fefSNaoya Horiguchi 
30424a705fefSNaoya Horiguchi static int is_hugetlb_entry_hwpoisoned(pte_t pte)
30434a705fefSNaoya Horiguchi {
30444a705fefSNaoya Horiguchi 	swp_entry_t swp;
30454a705fefSNaoya Horiguchi 
30464a705fefSNaoya Horiguchi 	if (huge_pte_none(pte) || pte_present(pte))
30474a705fefSNaoya Horiguchi 		return 0;
30484a705fefSNaoya Horiguchi 	swp = pte_to_swp_entry(pte);
30494a705fefSNaoya Horiguchi 	if (non_swap_entry(swp) && is_hwpoison_entry(swp))
30504a705fefSNaoya Horiguchi 		return 1;
30514a705fefSNaoya Horiguchi 	else
30524a705fefSNaoya Horiguchi 		return 0;
30534a705fefSNaoya Horiguchi }
30541e8f889bSDavid Gibson 
305563551ae0SDavid Gibson int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src,
305663551ae0SDavid Gibson 			    struct vm_area_struct *vma)
305763551ae0SDavid Gibson {
305863551ae0SDavid Gibson 	pte_t *src_pte, *dst_pte, entry;
305963551ae0SDavid Gibson 	struct page *ptepage;
30601c59827dSHugh Dickins 	unsigned long addr;
30611e8f889bSDavid Gibson 	int cow;
3062a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
3063a5516438SAndi Kleen 	unsigned long sz = huge_page_size(h);
3064e8569dd2SAndreas Sandberg 	unsigned long mmun_start;	/* For mmu_notifiers */
3065e8569dd2SAndreas Sandberg 	unsigned long mmun_end;		/* For mmu_notifiers */
3066e8569dd2SAndreas Sandberg 	int ret = 0;
30671e8f889bSDavid Gibson 
30681e8f889bSDavid Gibson 	cow = (vma->vm_flags & (VM_SHARED | VM_MAYWRITE)) == VM_MAYWRITE;
306963551ae0SDavid Gibson 
3070e8569dd2SAndreas Sandberg 	mmun_start = vma->vm_start;
3071e8569dd2SAndreas Sandberg 	mmun_end = vma->vm_end;
3072e8569dd2SAndreas Sandberg 	if (cow)
3073e8569dd2SAndreas Sandberg 		mmu_notifier_invalidate_range_start(src, mmun_start, mmun_end);
3074e8569dd2SAndreas Sandberg 
3075a5516438SAndi Kleen 	for (addr = vma->vm_start; addr < vma->vm_end; addr += sz) {
3076cb900f41SKirill A. Shutemov 		spinlock_t *src_ptl, *dst_ptl;
3077c74df32cSHugh Dickins 		src_pte = huge_pte_offset(src, addr);
3078c74df32cSHugh Dickins 		if (!src_pte)
3079c74df32cSHugh Dickins 			continue;
3080a5516438SAndi Kleen 		dst_pte = huge_pte_alloc(dst, addr, sz);
3081e8569dd2SAndreas Sandberg 		if (!dst_pte) {
3082e8569dd2SAndreas Sandberg 			ret = -ENOMEM;
3083e8569dd2SAndreas Sandberg 			break;
3084e8569dd2SAndreas Sandberg 		}
3085c5c99429SLarry Woodman 
3086c5c99429SLarry Woodman 		/* If the pagetables are shared don't copy or take references */
3087c5c99429SLarry Woodman 		if (dst_pte == src_pte)
3088c5c99429SLarry Woodman 			continue;
3089c5c99429SLarry Woodman 
3090cb900f41SKirill A. Shutemov 		dst_ptl = huge_pte_lock(h, dst, dst_pte);
3091cb900f41SKirill A. Shutemov 		src_ptl = huge_pte_lockptr(h, src, src_pte);
3092cb900f41SKirill A. Shutemov 		spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
30934a705fefSNaoya Horiguchi 		entry = huge_ptep_get(src_pte);
30944a705fefSNaoya Horiguchi 		if (huge_pte_none(entry)) { /* skip none entry */
30954a705fefSNaoya Horiguchi 			;
30964a705fefSNaoya Horiguchi 		} else if (unlikely(is_hugetlb_entry_migration(entry) ||
30974a705fefSNaoya Horiguchi 				    is_hugetlb_entry_hwpoisoned(entry))) {
30984a705fefSNaoya Horiguchi 			swp_entry_t swp_entry = pte_to_swp_entry(entry);
30994a705fefSNaoya Horiguchi 
31004a705fefSNaoya Horiguchi 			if (is_write_migration_entry(swp_entry) && cow) {
31014a705fefSNaoya Horiguchi 				/*
31024a705fefSNaoya Horiguchi 				 * COW mappings require pages in both
31034a705fefSNaoya Horiguchi 				 * parent and child to be set to read.
31044a705fefSNaoya Horiguchi 				 */
31054a705fefSNaoya Horiguchi 				make_migration_entry_read(&swp_entry);
31064a705fefSNaoya Horiguchi 				entry = swp_entry_to_pte(swp_entry);
31074a705fefSNaoya Horiguchi 				set_huge_pte_at(src, addr, src_pte, entry);
31084a705fefSNaoya Horiguchi 			}
31094a705fefSNaoya Horiguchi 			set_huge_pte_at(dst, addr, dst_pte, entry);
31104a705fefSNaoya Horiguchi 		} else {
311134ee645eSJoerg Roedel 			if (cow) {
31127f2e9525SGerald Schaefer 				huge_ptep_set_wrprotect(src, addr, src_pte);
311334ee645eSJoerg Roedel 				mmu_notifier_invalidate_range(src, mmun_start,
311434ee645eSJoerg Roedel 								   mmun_end);
311534ee645eSJoerg Roedel 			}
31160253d634SNaoya Horiguchi 			entry = huge_ptep_get(src_pte);
311763551ae0SDavid Gibson 			ptepage = pte_page(entry);
311863551ae0SDavid Gibson 			get_page(ptepage);
311953f9263bSKirill A. Shutemov 			page_dup_rmap(ptepage, true);
312063551ae0SDavid Gibson 			set_huge_pte_at(dst, addr, dst_pte, entry);
31215d317b2bSNaoya Horiguchi 			hugetlb_count_add(pages_per_huge_page(h), dst);
31221c59827dSHugh Dickins 		}
3123cb900f41SKirill A. Shutemov 		spin_unlock(src_ptl);
3124cb900f41SKirill A. Shutemov 		spin_unlock(dst_ptl);
312563551ae0SDavid Gibson 	}
312663551ae0SDavid Gibson 
3127e8569dd2SAndreas Sandberg 	if (cow)
3128e8569dd2SAndreas Sandberg 		mmu_notifier_invalidate_range_end(src, mmun_start, mmun_end);
3129e8569dd2SAndreas Sandberg 
3130e8569dd2SAndreas Sandberg 	return ret;
313163551ae0SDavid Gibson }
313263551ae0SDavid Gibson 
313324669e58SAneesh Kumar K.V void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
313424669e58SAneesh Kumar K.V 			    unsigned long start, unsigned long end,
313524669e58SAneesh Kumar K.V 			    struct page *ref_page)
313663551ae0SDavid Gibson {
313724669e58SAneesh Kumar K.V 	int force_flush = 0;
313863551ae0SDavid Gibson 	struct mm_struct *mm = vma->vm_mm;
313963551ae0SDavid Gibson 	unsigned long address;
3140c7546f8fSDavid Gibson 	pte_t *ptep;
314163551ae0SDavid Gibson 	pte_t pte;
3142cb900f41SKirill A. Shutemov 	spinlock_t *ptl;
314363551ae0SDavid Gibson 	struct page *page;
3144a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
3145a5516438SAndi Kleen 	unsigned long sz = huge_page_size(h);
31462ec74c3eSSagi Grimberg 	const unsigned long mmun_start = start;	/* For mmu_notifiers */
31472ec74c3eSSagi Grimberg 	const unsigned long mmun_end   = end;	/* For mmu_notifiers */
3148a5516438SAndi Kleen 
314963551ae0SDavid Gibson 	WARN_ON(!is_vm_hugetlb_page(vma));
3150a5516438SAndi Kleen 	BUG_ON(start & ~huge_page_mask(h));
3151a5516438SAndi Kleen 	BUG_ON(end & ~huge_page_mask(h));
315263551ae0SDavid Gibson 
315324669e58SAneesh Kumar K.V 	tlb_start_vma(tlb, vma);
31542ec74c3eSSagi Grimberg 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
3155569f48b8SHillf Danton 	address = start;
315624669e58SAneesh Kumar K.V again:
3157569f48b8SHillf Danton 	for (; address < end; address += sz) {
3158c7546f8fSDavid Gibson 		ptep = huge_pte_offset(mm, address);
3159c7546f8fSDavid Gibson 		if (!ptep)
3160c7546f8fSDavid Gibson 			continue;
3161c7546f8fSDavid Gibson 
3162cb900f41SKirill A. Shutemov 		ptl = huge_pte_lock(h, mm, ptep);
316339dde65cSChen, Kenneth W 		if (huge_pmd_unshare(mm, &address, ptep))
3164cb900f41SKirill A. Shutemov 			goto unlock;
316539dde65cSChen, Kenneth W 
31666629326bSHillf Danton 		pte = huge_ptep_get(ptep);
31676629326bSHillf Danton 		if (huge_pte_none(pte))
3168cb900f41SKirill A. Shutemov 			goto unlock;
31696629326bSHillf Danton 
31706629326bSHillf Danton 		/*
31719fbc1f63SNaoya Horiguchi 		 * Migrating hugepage or HWPoisoned hugepage is already
31729fbc1f63SNaoya Horiguchi 		 * unmapped and its refcount is dropped, so just clear pte here.
31736629326bSHillf Danton 		 */
31749fbc1f63SNaoya Horiguchi 		if (unlikely(!pte_present(pte))) {
3175106c992aSGerald Schaefer 			huge_pte_clear(mm, address, ptep);
3176cb900f41SKirill A. Shutemov 			goto unlock;
31778c4894c6SNaoya Horiguchi 		}
31786629326bSHillf Danton 
31796629326bSHillf Danton 		page = pte_page(pte);
318004f2cbe3SMel Gorman 		/*
318104f2cbe3SMel Gorman 		 * If a reference page is supplied, it is because a specific
318204f2cbe3SMel Gorman 		 * page is being unmapped, not a range. Ensure the page we
318304f2cbe3SMel Gorman 		 * are about to unmap is the actual page of interest.
318404f2cbe3SMel Gorman 		 */
318504f2cbe3SMel Gorman 		if (ref_page) {
318604f2cbe3SMel Gorman 			if (page != ref_page)
3187cb900f41SKirill A. Shutemov 				goto unlock;
318804f2cbe3SMel Gorman 
318904f2cbe3SMel Gorman 			/*
319004f2cbe3SMel Gorman 			 * Mark the VMA as having unmapped its page so that
319104f2cbe3SMel Gorman 			 * future faults in this VMA will fail rather than
319204f2cbe3SMel Gorman 			 * looking like data was lost
319304f2cbe3SMel Gorman 			 */
319404f2cbe3SMel Gorman 			set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED);
319504f2cbe3SMel Gorman 		}
319604f2cbe3SMel Gorman 
3197c7546f8fSDavid Gibson 		pte = huge_ptep_get_and_clear(mm, address, ptep);
319824669e58SAneesh Kumar K.V 		tlb_remove_tlb_entry(tlb, ptep, address);
3199106c992aSGerald Schaefer 		if (huge_pte_dirty(pte))
32006649a386SKen Chen 			set_page_dirty(page);
32019e81130bSHillf Danton 
32025d317b2bSNaoya Horiguchi 		hugetlb_count_sub(pages_per_huge_page(h), mm);
3203d281ee61SKirill A. Shutemov 		page_remove_rmap(page, true);
320424669e58SAneesh Kumar K.V 		force_flush = !__tlb_remove_page(tlb, page);
3205cb900f41SKirill A. Shutemov 		if (force_flush) {
3206569f48b8SHillf Danton 			address += sz;
3207cb900f41SKirill A. Shutemov 			spin_unlock(ptl);
32089e81130bSHillf Danton 			break;
320963551ae0SDavid Gibson 		}
3210cb900f41SKirill A. Shutemov 		/* Bail out after unmapping reference page if supplied */
3211cb900f41SKirill A. Shutemov 		if (ref_page) {
3212cb900f41SKirill A. Shutemov 			spin_unlock(ptl);
3213cb900f41SKirill A. Shutemov 			break;
3214cb900f41SKirill A. Shutemov 		}
3215cb900f41SKirill A. Shutemov unlock:
3216cb900f41SKirill A. Shutemov 		spin_unlock(ptl);
3217cb900f41SKirill A. Shutemov 	}
321824669e58SAneesh Kumar K.V 	/*
321924669e58SAneesh Kumar K.V 	 * mmu_gather ran out of room to batch pages, we break out of
322024669e58SAneesh Kumar K.V 	 * the PTE lock to avoid doing the potential expensive TLB invalidate
322124669e58SAneesh Kumar K.V 	 * and page-free while holding it.
322224669e58SAneesh Kumar K.V 	 */
322324669e58SAneesh Kumar K.V 	if (force_flush) {
322424669e58SAneesh Kumar K.V 		force_flush = 0;
322524669e58SAneesh Kumar K.V 		tlb_flush_mmu(tlb);
322624669e58SAneesh Kumar K.V 		if (address < end && !ref_page)
322724669e58SAneesh Kumar K.V 			goto again;
3228fe1668aeSChen, Kenneth W 	}
32292ec74c3eSSagi Grimberg 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
323024669e58SAneesh Kumar K.V 	tlb_end_vma(tlb, vma);
32311da177e4SLinus Torvalds }
323263551ae0SDavid Gibson 
3233d833352aSMel Gorman void __unmap_hugepage_range_final(struct mmu_gather *tlb,
3234d833352aSMel Gorman 			  struct vm_area_struct *vma, unsigned long start,
3235d833352aSMel Gorman 			  unsigned long end, struct page *ref_page)
3236d833352aSMel Gorman {
3237d833352aSMel Gorman 	__unmap_hugepage_range(tlb, vma, start, end, ref_page);
3238d833352aSMel Gorman 
3239d833352aSMel Gorman 	/*
3240d833352aSMel Gorman 	 * Clear this flag so that x86's huge_pmd_share page_table_shareable
3241d833352aSMel Gorman 	 * test will fail on a vma being torn down, and not grab a page table
3242d833352aSMel Gorman 	 * on its way out.  We're lucky that the flag has such an appropriate
3243d833352aSMel Gorman 	 * name, and can in fact be safely cleared here. We could clear it
3244d833352aSMel Gorman 	 * before the __unmap_hugepage_range above, but all that's necessary
3245c8c06efaSDavidlohr Bueso 	 * is to clear it before releasing the i_mmap_rwsem. This works
3246d833352aSMel Gorman 	 * because in the context this is called, the VMA is about to be
3247c8c06efaSDavidlohr Bueso 	 * destroyed and the i_mmap_rwsem is held.
3248d833352aSMel Gorman 	 */
3249d833352aSMel Gorman 	vma->vm_flags &= ~VM_MAYSHARE;
3250d833352aSMel Gorman }
3251d833352aSMel Gorman 
3252502717f4SChen, Kenneth W void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
325304f2cbe3SMel Gorman 			  unsigned long end, struct page *ref_page)
3254502717f4SChen, Kenneth W {
325524669e58SAneesh Kumar K.V 	struct mm_struct *mm;
325624669e58SAneesh Kumar K.V 	struct mmu_gather tlb;
325724669e58SAneesh Kumar K.V 
325824669e58SAneesh Kumar K.V 	mm = vma->vm_mm;
325924669e58SAneesh Kumar K.V 
32602b047252SLinus Torvalds 	tlb_gather_mmu(&tlb, mm, start, end);
326124669e58SAneesh Kumar K.V 	__unmap_hugepage_range(&tlb, vma, start, end, ref_page);
326224669e58SAneesh Kumar K.V 	tlb_finish_mmu(&tlb, start, end);
3263502717f4SChen, Kenneth W }
3264502717f4SChen, Kenneth W 
326504f2cbe3SMel Gorman /*
326604f2cbe3SMel Gorman  * This is called when the original mapper is failing to COW a MAP_PRIVATE
326704f2cbe3SMel Gorman  * mappping it owns the reserve page for. The intention is to unmap the page
326804f2cbe3SMel Gorman  * from other VMAs and let the children be SIGKILLed if they are faulting the
326904f2cbe3SMel Gorman  * same region.
327004f2cbe3SMel Gorman  */
32712f4612afSDavidlohr Bueso static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,
32722a4b3dedSHarvey Harrison 			      struct page *page, unsigned long address)
327304f2cbe3SMel Gorman {
32747526674dSAdam Litke 	struct hstate *h = hstate_vma(vma);
327504f2cbe3SMel Gorman 	struct vm_area_struct *iter_vma;
327604f2cbe3SMel Gorman 	struct address_space *mapping;
327704f2cbe3SMel Gorman 	pgoff_t pgoff;
327804f2cbe3SMel Gorman 
327904f2cbe3SMel Gorman 	/*
328004f2cbe3SMel Gorman 	 * vm_pgoff is in PAGE_SIZE units, hence the different calculation
328104f2cbe3SMel Gorman 	 * from page cache lookup which is in HPAGE_SIZE units.
328204f2cbe3SMel Gorman 	 */
32837526674dSAdam Litke 	address = address & huge_page_mask(h);
328436e4f20aSMichal Hocko 	pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) +
328536e4f20aSMichal Hocko 			vma->vm_pgoff;
3286496ad9aaSAl Viro 	mapping = file_inode(vma->vm_file)->i_mapping;
328704f2cbe3SMel Gorman 
32884eb2b1dcSMel Gorman 	/*
32894eb2b1dcSMel Gorman 	 * Take the mapping lock for the duration of the table walk. As
32904eb2b1dcSMel Gorman 	 * this mapping should be shared between all the VMAs,
32914eb2b1dcSMel Gorman 	 * __unmap_hugepage_range() is called as the lock is already held
32924eb2b1dcSMel Gorman 	 */
329383cde9e8SDavidlohr Bueso 	i_mmap_lock_write(mapping);
32946b2dbba8SMichel Lespinasse 	vma_interval_tree_foreach(iter_vma, &mapping->i_mmap, pgoff, pgoff) {
329504f2cbe3SMel Gorman 		/* Do not unmap the current VMA */
329604f2cbe3SMel Gorman 		if (iter_vma == vma)
329704f2cbe3SMel Gorman 			continue;
329804f2cbe3SMel Gorman 
329904f2cbe3SMel Gorman 		/*
33002f84a899SMel Gorman 		 * Shared VMAs have their own reserves and do not affect
33012f84a899SMel Gorman 		 * MAP_PRIVATE accounting but it is possible that a shared
33022f84a899SMel Gorman 		 * VMA is using the same page so check and skip such VMAs.
33032f84a899SMel Gorman 		 */
33042f84a899SMel Gorman 		if (iter_vma->vm_flags & VM_MAYSHARE)
33052f84a899SMel Gorman 			continue;
33062f84a899SMel Gorman 
33072f84a899SMel Gorman 		/*
330804f2cbe3SMel Gorman 		 * Unmap the page from other VMAs without their own reserves.
330904f2cbe3SMel Gorman 		 * They get marked to be SIGKILLed if they fault in these
331004f2cbe3SMel Gorman 		 * areas. This is because a future no-page fault on this VMA
331104f2cbe3SMel Gorman 		 * could insert a zeroed page instead of the data existing
331204f2cbe3SMel Gorman 		 * from the time of fork. This would look like data corruption
331304f2cbe3SMel Gorman 		 */
331404f2cbe3SMel Gorman 		if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER))
331524669e58SAneesh Kumar K.V 			unmap_hugepage_range(iter_vma, address,
331624669e58SAneesh Kumar K.V 					     address + huge_page_size(h), page);
331704f2cbe3SMel Gorman 	}
331883cde9e8SDavidlohr Bueso 	i_mmap_unlock_write(mapping);
331904f2cbe3SMel Gorman }
332004f2cbe3SMel Gorman 
33210fe6e20bSNaoya Horiguchi /*
33220fe6e20bSNaoya Horiguchi  * Hugetlb_cow() should be called with page lock of the original hugepage held.
3323ef009b25SMichal Hocko  * Called with hugetlb_instantiation_mutex held and pte_page locked so we
3324ef009b25SMichal Hocko  * cannot race with other handlers or page migration.
3325ef009b25SMichal Hocko  * Keep the pte_same checks anyway to make transition from the mutex easier.
33260fe6e20bSNaoya Horiguchi  */
33271e8f889bSDavid Gibson static int hugetlb_cow(struct mm_struct *mm, struct vm_area_struct *vma,
332804f2cbe3SMel Gorman 			unsigned long address, pte_t *ptep, pte_t pte,
3329cb900f41SKirill A. Shutemov 			struct page *pagecache_page, spinlock_t *ptl)
33301e8f889bSDavid Gibson {
3331a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
33321e8f889bSDavid Gibson 	struct page *old_page, *new_page;
3333ad4404a2SDavidlohr Bueso 	int ret = 0, outside_reserve = 0;
33342ec74c3eSSagi Grimberg 	unsigned long mmun_start;	/* For mmu_notifiers */
33352ec74c3eSSagi Grimberg 	unsigned long mmun_end;		/* For mmu_notifiers */
33361e8f889bSDavid Gibson 
33371e8f889bSDavid Gibson 	old_page = pte_page(pte);
33381e8f889bSDavid Gibson 
333904f2cbe3SMel Gorman retry_avoidcopy:
33401e8f889bSDavid Gibson 	/* If no-one else is actually using this page, avoid the copy
33411e8f889bSDavid Gibson 	 * and just make the page writable */
334237a2140dSJoonsoo Kim 	if (page_mapcount(old_page) == 1 && PageAnon(old_page)) {
33430fe6e20bSNaoya Horiguchi 		page_move_anon_rmap(old_page, vma, address);
33441e8f889bSDavid Gibson 		set_huge_ptep_writable(vma, address, ptep);
334583c54070SNick Piggin 		return 0;
33461e8f889bSDavid Gibson 	}
33471e8f889bSDavid Gibson 
334804f2cbe3SMel Gorman 	/*
334904f2cbe3SMel Gorman 	 * If the process that created a MAP_PRIVATE mapping is about to
335004f2cbe3SMel Gorman 	 * perform a COW due to a shared page count, attempt to satisfy
335104f2cbe3SMel Gorman 	 * the allocation without using the existing reserves. The pagecache
335204f2cbe3SMel Gorman 	 * page is used to determine if the reserve at this address was
335304f2cbe3SMel Gorman 	 * consumed or not. If reserves were used, a partial faulted mapping
335404f2cbe3SMel Gorman 	 * at the time of fork() could consume its reserves on COW instead
335504f2cbe3SMel Gorman 	 * of the full address range.
335604f2cbe3SMel Gorman 	 */
33575944d011SJoonsoo Kim 	if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) &&
335804f2cbe3SMel Gorman 			old_page != pagecache_page)
335904f2cbe3SMel Gorman 		outside_reserve = 1;
336004f2cbe3SMel Gorman 
336109cbfeafSKirill A. Shutemov 	get_page(old_page);
3362b76c8cfbSLarry Woodman 
3363ad4404a2SDavidlohr Bueso 	/*
3364ad4404a2SDavidlohr Bueso 	 * Drop page table lock as buddy allocator may be called. It will
3365ad4404a2SDavidlohr Bueso 	 * be acquired again before returning to the caller, as expected.
3366ad4404a2SDavidlohr Bueso 	 */
3367cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
336804f2cbe3SMel Gorman 	new_page = alloc_huge_page(vma, address, outside_reserve);
33691e8f889bSDavid Gibson 
33702fc39cecSAdam Litke 	if (IS_ERR(new_page)) {
337104f2cbe3SMel Gorman 		/*
337204f2cbe3SMel Gorman 		 * If a process owning a MAP_PRIVATE mapping fails to COW,
337304f2cbe3SMel Gorman 		 * it is due to references held by a child and an insufficient
337404f2cbe3SMel Gorman 		 * huge page pool. To guarantee the original mappers
337504f2cbe3SMel Gorman 		 * reliability, unmap the page from child processes. The child
337604f2cbe3SMel Gorman 		 * may get SIGKILLed if it later faults.
337704f2cbe3SMel Gorman 		 */
337804f2cbe3SMel Gorman 		if (outside_reserve) {
337909cbfeafSKirill A. Shutemov 			put_page(old_page);
338004f2cbe3SMel Gorman 			BUG_ON(huge_pte_none(pte));
33812f4612afSDavidlohr Bueso 			unmap_ref_private(mm, vma, old_page, address);
338204f2cbe3SMel Gorman 			BUG_ON(huge_pte_none(pte));
3383cb900f41SKirill A. Shutemov 			spin_lock(ptl);
3384a734bcc8SHillf Danton 			ptep = huge_pte_offset(mm, address & huge_page_mask(h));
3385a9af0c5dSNaoya Horiguchi 			if (likely(ptep &&
3386a9af0c5dSNaoya Horiguchi 				   pte_same(huge_ptep_get(ptep), pte)))
338704f2cbe3SMel Gorman 				goto retry_avoidcopy;
3388a734bcc8SHillf Danton 			/*
3389cb900f41SKirill A. Shutemov 			 * race occurs while re-acquiring page table
3390cb900f41SKirill A. Shutemov 			 * lock, and our job is done.
3391a734bcc8SHillf Danton 			 */
3392a734bcc8SHillf Danton 			return 0;
339304f2cbe3SMel Gorman 		}
339404f2cbe3SMel Gorman 
3395ad4404a2SDavidlohr Bueso 		ret = (PTR_ERR(new_page) == -ENOMEM) ?
3396ad4404a2SDavidlohr Bueso 			VM_FAULT_OOM : VM_FAULT_SIGBUS;
3397ad4404a2SDavidlohr Bueso 		goto out_release_old;
33981e8f889bSDavid Gibson 	}
33991e8f889bSDavid Gibson 
34000fe6e20bSNaoya Horiguchi 	/*
34010fe6e20bSNaoya Horiguchi 	 * When the original hugepage is shared one, it does not have
34020fe6e20bSNaoya Horiguchi 	 * anon_vma prepared.
34030fe6e20bSNaoya Horiguchi 	 */
340444e2aa93SDean Nelson 	if (unlikely(anon_vma_prepare(vma))) {
3405ad4404a2SDavidlohr Bueso 		ret = VM_FAULT_OOM;
3406ad4404a2SDavidlohr Bueso 		goto out_release_all;
340744e2aa93SDean Nelson 	}
34080fe6e20bSNaoya Horiguchi 
340947ad8475SAndrea Arcangeli 	copy_user_huge_page(new_page, old_page, address, vma,
341047ad8475SAndrea Arcangeli 			    pages_per_huge_page(h));
34110ed361deSNick Piggin 	__SetPageUptodate(new_page);
3412bcc54222SNaoya Horiguchi 	set_page_huge_active(new_page);
34131e8f889bSDavid Gibson 
34142ec74c3eSSagi Grimberg 	mmun_start = address & huge_page_mask(h);
34152ec74c3eSSagi Grimberg 	mmun_end = mmun_start + huge_page_size(h);
34162ec74c3eSSagi Grimberg 	mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
3417ad4404a2SDavidlohr Bueso 
3418b76c8cfbSLarry Woodman 	/*
3419cb900f41SKirill A. Shutemov 	 * Retake the page table lock to check for racing updates
3420b76c8cfbSLarry Woodman 	 * before the page tables are altered
3421b76c8cfbSLarry Woodman 	 */
3422cb900f41SKirill A. Shutemov 	spin_lock(ptl);
3423a5516438SAndi Kleen 	ptep = huge_pte_offset(mm, address & huge_page_mask(h));
3424a9af0c5dSNaoya Horiguchi 	if (likely(ptep && pte_same(huge_ptep_get(ptep), pte))) {
342507443a85SJoonsoo Kim 		ClearPagePrivate(new_page);
342607443a85SJoonsoo Kim 
34271e8f889bSDavid Gibson 		/* Break COW */
34288fe627ecSGerald Schaefer 		huge_ptep_clear_flush(vma, address, ptep);
342934ee645eSJoerg Roedel 		mmu_notifier_invalidate_range(mm, mmun_start, mmun_end);
34301e8f889bSDavid Gibson 		set_huge_pte_at(mm, address, ptep,
34311e8f889bSDavid Gibson 				make_huge_pte(vma, new_page, 1));
3432d281ee61SKirill A. Shutemov 		page_remove_rmap(old_page, true);
3433cd67f0d2SNaoya Horiguchi 		hugepage_add_new_anon_rmap(new_page, vma, address);
34341e8f889bSDavid Gibson 		/* Make the old page be freed below */
34351e8f889bSDavid Gibson 		new_page = old_page;
34361e8f889bSDavid Gibson 	}
3437cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
34382ec74c3eSSagi Grimberg 	mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
3439ad4404a2SDavidlohr Bueso out_release_all:
344009cbfeafSKirill A. Shutemov 	put_page(new_page);
3441ad4404a2SDavidlohr Bueso out_release_old:
344209cbfeafSKirill A. Shutemov 	put_page(old_page);
34438312034fSJoonsoo Kim 
3444ad4404a2SDavidlohr Bueso 	spin_lock(ptl); /* Caller expects lock to be held */
3445ad4404a2SDavidlohr Bueso 	return ret;
34461e8f889bSDavid Gibson }
34471e8f889bSDavid Gibson 
344804f2cbe3SMel Gorman /* Return the pagecache page at a given address within a VMA */
3449a5516438SAndi Kleen static struct page *hugetlbfs_pagecache_page(struct hstate *h,
3450a5516438SAndi Kleen 			struct vm_area_struct *vma, unsigned long address)
345104f2cbe3SMel Gorman {
345204f2cbe3SMel Gorman 	struct address_space *mapping;
3453e7c4b0bfSAndy Whitcroft 	pgoff_t idx;
345404f2cbe3SMel Gorman 
345504f2cbe3SMel Gorman 	mapping = vma->vm_file->f_mapping;
3456a5516438SAndi Kleen 	idx = vma_hugecache_offset(h, vma, address);
345704f2cbe3SMel Gorman 
345804f2cbe3SMel Gorman 	return find_lock_page(mapping, idx);
345904f2cbe3SMel Gorman }
346004f2cbe3SMel Gorman 
34613ae77f43SHugh Dickins /*
34623ae77f43SHugh Dickins  * Return whether there is a pagecache page to back given address within VMA.
34633ae77f43SHugh Dickins  * Caller follow_hugetlb_page() holds page_table_lock so we cannot lock_page.
34643ae77f43SHugh Dickins  */
34653ae77f43SHugh Dickins static bool hugetlbfs_pagecache_present(struct hstate *h,
34662a15efc9SHugh Dickins 			struct vm_area_struct *vma, unsigned long address)
34672a15efc9SHugh Dickins {
34682a15efc9SHugh Dickins 	struct address_space *mapping;
34692a15efc9SHugh Dickins 	pgoff_t idx;
34702a15efc9SHugh Dickins 	struct page *page;
34712a15efc9SHugh Dickins 
34722a15efc9SHugh Dickins 	mapping = vma->vm_file->f_mapping;
34732a15efc9SHugh Dickins 	idx = vma_hugecache_offset(h, vma, address);
34742a15efc9SHugh Dickins 
34752a15efc9SHugh Dickins 	page = find_get_page(mapping, idx);
34762a15efc9SHugh Dickins 	if (page)
34772a15efc9SHugh Dickins 		put_page(page);
34782a15efc9SHugh Dickins 	return page != NULL;
34792a15efc9SHugh Dickins }
34802a15efc9SHugh Dickins 
3481ab76ad54SMike Kravetz int huge_add_to_page_cache(struct page *page, struct address_space *mapping,
3482ab76ad54SMike Kravetz 			   pgoff_t idx)
3483ab76ad54SMike Kravetz {
3484ab76ad54SMike Kravetz 	struct inode *inode = mapping->host;
3485ab76ad54SMike Kravetz 	struct hstate *h = hstate_inode(inode);
3486ab76ad54SMike Kravetz 	int err = add_to_page_cache(page, mapping, idx, GFP_KERNEL);
3487ab76ad54SMike Kravetz 
3488ab76ad54SMike Kravetz 	if (err)
3489ab76ad54SMike Kravetz 		return err;
3490ab76ad54SMike Kravetz 	ClearPagePrivate(page);
3491ab76ad54SMike Kravetz 
3492ab76ad54SMike Kravetz 	spin_lock(&inode->i_lock);
3493ab76ad54SMike Kravetz 	inode->i_blocks += blocks_per_huge_page(h);
3494ab76ad54SMike Kravetz 	spin_unlock(&inode->i_lock);
3495ab76ad54SMike Kravetz 	return 0;
3496ab76ad54SMike Kravetz }
3497ab76ad54SMike Kravetz 
3498a1ed3ddaSRobert P. J. Day static int hugetlb_no_page(struct mm_struct *mm, struct vm_area_struct *vma,
34998382d914SDavidlohr Bueso 			   struct address_space *mapping, pgoff_t idx,
3500788c7df4SHugh Dickins 			   unsigned long address, pte_t *ptep, unsigned int flags)
3501ac9b9c66SHugh Dickins {
3502a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
3503ac9b9c66SHugh Dickins 	int ret = VM_FAULT_SIGBUS;
3504409eb8c2SHillf Danton 	int anon_rmap = 0;
35054c887265SAdam Litke 	unsigned long size;
35064c887265SAdam Litke 	struct page *page;
35071e8f889bSDavid Gibson 	pte_t new_pte;
3508cb900f41SKirill A. Shutemov 	spinlock_t *ptl;
35094c887265SAdam Litke 
351004f2cbe3SMel Gorman 	/*
351104f2cbe3SMel Gorman 	 * Currently, we are forced to kill the process in the event the
351204f2cbe3SMel Gorman 	 * original mapper has unmapped pages from the child due to a failed
351325985edcSLucas De Marchi 	 * COW. Warn that such a situation has occurred as it may not be obvious
351404f2cbe3SMel Gorman 	 */
351504f2cbe3SMel Gorman 	if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) {
3516910154d5SGeoffrey Thomas 		pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n",
351704f2cbe3SMel Gorman 			   current->pid);
351804f2cbe3SMel Gorman 		return ret;
351904f2cbe3SMel Gorman 	}
352004f2cbe3SMel Gorman 
35214c887265SAdam Litke 	/*
35224c887265SAdam Litke 	 * Use page lock to guard against racing truncation
35234c887265SAdam Litke 	 * before we get page_table_lock.
35244c887265SAdam Litke 	 */
35256bda666aSChristoph Lameter retry:
35266bda666aSChristoph Lameter 	page = find_lock_page(mapping, idx);
35276bda666aSChristoph Lameter 	if (!page) {
3528a5516438SAndi Kleen 		size = i_size_read(mapping->host) >> huge_page_shift(h);
3529ebed4bfcSHugh Dickins 		if (idx >= size)
3530ebed4bfcSHugh Dickins 			goto out;
353104f2cbe3SMel Gorman 		page = alloc_huge_page(vma, address, 0);
35322fc39cecSAdam Litke 		if (IS_ERR(page)) {
353376dcee75SAneesh Kumar K.V 			ret = PTR_ERR(page);
353476dcee75SAneesh Kumar K.V 			if (ret == -ENOMEM)
353576dcee75SAneesh Kumar K.V 				ret = VM_FAULT_OOM;
353676dcee75SAneesh Kumar K.V 			else
353776dcee75SAneesh Kumar K.V 				ret = VM_FAULT_SIGBUS;
35386bda666aSChristoph Lameter 			goto out;
35396bda666aSChristoph Lameter 		}
354047ad8475SAndrea Arcangeli 		clear_huge_page(page, address, pages_per_huge_page(h));
35410ed361deSNick Piggin 		__SetPageUptodate(page);
3542bcc54222SNaoya Horiguchi 		set_page_huge_active(page);
3543ac9b9c66SHugh Dickins 
3544f83a275dSMel Gorman 		if (vma->vm_flags & VM_MAYSHARE) {
3545ab76ad54SMike Kravetz 			int err = huge_add_to_page_cache(page, mapping, idx);
35466bda666aSChristoph Lameter 			if (err) {
35476bda666aSChristoph Lameter 				put_page(page);
35486bda666aSChristoph Lameter 				if (err == -EEXIST)
35496bda666aSChristoph Lameter 					goto retry;
35506bda666aSChristoph Lameter 				goto out;
35516bda666aSChristoph Lameter 			}
355223be7468SMel Gorman 		} else {
35536bda666aSChristoph Lameter 			lock_page(page);
35540fe6e20bSNaoya Horiguchi 			if (unlikely(anon_vma_prepare(vma))) {
35550fe6e20bSNaoya Horiguchi 				ret = VM_FAULT_OOM;
35560fe6e20bSNaoya Horiguchi 				goto backout_unlocked;
355723be7468SMel Gorman 			}
3558409eb8c2SHillf Danton 			anon_rmap = 1;
35590fe6e20bSNaoya Horiguchi 		}
35600fe6e20bSNaoya Horiguchi 	} else {
356157303d80SAndy Whitcroft 		/*
3562998b4382SNaoya Horiguchi 		 * If memory error occurs between mmap() and fault, some process
3563998b4382SNaoya Horiguchi 		 * don't have hwpoisoned swap entry for errored virtual address.
3564998b4382SNaoya Horiguchi 		 * So we need to block hugepage fault by PG_hwpoison bit check.
3565fd6a03edSNaoya Horiguchi 		 */
3566fd6a03edSNaoya Horiguchi 		if (unlikely(PageHWPoison(page))) {
3567aa50d3a7SAndi Kleen 			ret = VM_FAULT_HWPOISON |
3568972dc4deSAneesh Kumar K.V 				VM_FAULT_SET_HINDEX(hstate_index(h));
3569fd6a03edSNaoya Horiguchi 			goto backout_unlocked;
35706bda666aSChristoph Lameter 		}
3571998b4382SNaoya Horiguchi 	}
35721e8f889bSDavid Gibson 
357357303d80SAndy Whitcroft 	/*
357457303d80SAndy Whitcroft 	 * If we are going to COW a private mapping later, we examine the
357557303d80SAndy Whitcroft 	 * pending reservations for this page now. This will ensure that
357657303d80SAndy Whitcroft 	 * any allocations necessary to record that reservation occur outside
357757303d80SAndy Whitcroft 	 * the spinlock.
357857303d80SAndy Whitcroft 	 */
35795e911373SMike Kravetz 	if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
35802b26736cSAndy Whitcroft 		if (vma_needs_reservation(h, vma, address) < 0) {
35812b26736cSAndy Whitcroft 			ret = VM_FAULT_OOM;
35822b26736cSAndy Whitcroft 			goto backout_unlocked;
35832b26736cSAndy Whitcroft 		}
35845e911373SMike Kravetz 		/* Just decrements count, does not deallocate */
3585feba16e2SMike Kravetz 		vma_end_reservation(h, vma, address);
35865e911373SMike Kravetz 	}
358757303d80SAndy Whitcroft 
3588cb900f41SKirill A. Shutemov 	ptl = huge_pte_lockptr(h, mm, ptep);
3589cb900f41SKirill A. Shutemov 	spin_lock(ptl);
3590a5516438SAndi Kleen 	size = i_size_read(mapping->host) >> huge_page_shift(h);
35914c887265SAdam Litke 	if (idx >= size)
35924c887265SAdam Litke 		goto backout;
35934c887265SAdam Litke 
359483c54070SNick Piggin 	ret = 0;
35957f2e9525SGerald Schaefer 	if (!huge_pte_none(huge_ptep_get(ptep)))
35964c887265SAdam Litke 		goto backout;
35974c887265SAdam Litke 
359807443a85SJoonsoo Kim 	if (anon_rmap) {
359907443a85SJoonsoo Kim 		ClearPagePrivate(page);
3600409eb8c2SHillf Danton 		hugepage_add_new_anon_rmap(page, vma, address);
3601ac714904SChoi Gi-yong 	} else
360253f9263bSKirill A. Shutemov 		page_dup_rmap(page, true);
36031e8f889bSDavid Gibson 	new_pte = make_huge_pte(vma, page, ((vma->vm_flags & VM_WRITE)
36041e8f889bSDavid Gibson 				&& (vma->vm_flags & VM_SHARED)));
36051e8f889bSDavid Gibson 	set_huge_pte_at(mm, address, ptep, new_pte);
36061e8f889bSDavid Gibson 
36075d317b2bSNaoya Horiguchi 	hugetlb_count_add(pages_per_huge_page(h), mm);
3608788c7df4SHugh Dickins 	if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
36091e8f889bSDavid Gibson 		/* Optimization, do the COW without a second fault */
3610cb900f41SKirill A. Shutemov 		ret = hugetlb_cow(mm, vma, address, ptep, new_pte, page, ptl);
36111e8f889bSDavid Gibson 	}
36121e8f889bSDavid Gibson 
3613cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
36144c887265SAdam Litke 	unlock_page(page);
36154c887265SAdam Litke out:
3616ac9b9c66SHugh Dickins 	return ret;
36174c887265SAdam Litke 
36184c887265SAdam Litke backout:
3619cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
36202b26736cSAndy Whitcroft backout_unlocked:
36214c887265SAdam Litke 	unlock_page(page);
36224c887265SAdam Litke 	put_page(page);
36234c887265SAdam Litke 	goto out;
3624ac9b9c66SHugh Dickins }
3625ac9b9c66SHugh Dickins 
36268382d914SDavidlohr Bueso #ifdef CONFIG_SMP
3627c672c7f2SMike Kravetz u32 hugetlb_fault_mutex_hash(struct hstate *h, struct mm_struct *mm,
36288382d914SDavidlohr Bueso 			    struct vm_area_struct *vma,
36298382d914SDavidlohr Bueso 			    struct address_space *mapping,
36308382d914SDavidlohr Bueso 			    pgoff_t idx, unsigned long address)
36318382d914SDavidlohr Bueso {
36328382d914SDavidlohr Bueso 	unsigned long key[2];
36338382d914SDavidlohr Bueso 	u32 hash;
36348382d914SDavidlohr Bueso 
36358382d914SDavidlohr Bueso 	if (vma->vm_flags & VM_SHARED) {
36368382d914SDavidlohr Bueso 		key[0] = (unsigned long) mapping;
36378382d914SDavidlohr Bueso 		key[1] = idx;
36388382d914SDavidlohr Bueso 	} else {
36398382d914SDavidlohr Bueso 		key[0] = (unsigned long) mm;
36408382d914SDavidlohr Bueso 		key[1] = address >> huge_page_shift(h);
36418382d914SDavidlohr Bueso 	}
36428382d914SDavidlohr Bueso 
36438382d914SDavidlohr Bueso 	hash = jhash2((u32 *)&key, sizeof(key)/sizeof(u32), 0);
36448382d914SDavidlohr Bueso 
36458382d914SDavidlohr Bueso 	return hash & (num_fault_mutexes - 1);
36468382d914SDavidlohr Bueso }
36478382d914SDavidlohr Bueso #else
36488382d914SDavidlohr Bueso /*
36498382d914SDavidlohr Bueso  * For uniprocesor systems we always use a single mutex, so just
36508382d914SDavidlohr Bueso  * return 0 and avoid the hashing overhead.
36518382d914SDavidlohr Bueso  */
3652c672c7f2SMike Kravetz u32 hugetlb_fault_mutex_hash(struct hstate *h, struct mm_struct *mm,
36538382d914SDavidlohr Bueso 			    struct vm_area_struct *vma,
36548382d914SDavidlohr Bueso 			    struct address_space *mapping,
36558382d914SDavidlohr Bueso 			    pgoff_t idx, unsigned long address)
36568382d914SDavidlohr Bueso {
36578382d914SDavidlohr Bueso 	return 0;
36588382d914SDavidlohr Bueso }
36598382d914SDavidlohr Bueso #endif
36608382d914SDavidlohr Bueso 
366186e5216fSAdam Litke int hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3662788c7df4SHugh Dickins 			unsigned long address, unsigned int flags)
366386e5216fSAdam Litke {
36648382d914SDavidlohr Bueso 	pte_t *ptep, entry;
3665cb900f41SKirill A. Shutemov 	spinlock_t *ptl;
36661e8f889bSDavid Gibson 	int ret;
36678382d914SDavidlohr Bueso 	u32 hash;
36688382d914SDavidlohr Bueso 	pgoff_t idx;
36690fe6e20bSNaoya Horiguchi 	struct page *page = NULL;
367057303d80SAndy Whitcroft 	struct page *pagecache_page = NULL;
3671a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
36728382d914SDavidlohr Bueso 	struct address_space *mapping;
36730f792cf9SNaoya Horiguchi 	int need_wait_lock = 0;
367486e5216fSAdam Litke 
36751e16a539SKAMEZAWA Hiroyuki 	address &= huge_page_mask(h);
36761e16a539SKAMEZAWA Hiroyuki 
3677fd6a03edSNaoya Horiguchi 	ptep = huge_pte_offset(mm, address);
3678fd6a03edSNaoya Horiguchi 	if (ptep) {
3679fd6a03edSNaoya Horiguchi 		entry = huge_ptep_get(ptep);
3680290408d4SNaoya Horiguchi 		if (unlikely(is_hugetlb_entry_migration(entry))) {
3681cb900f41SKirill A. Shutemov 			migration_entry_wait_huge(vma, mm, ptep);
3682290408d4SNaoya Horiguchi 			return 0;
3683290408d4SNaoya Horiguchi 		} else if (unlikely(is_hugetlb_entry_hwpoisoned(entry)))
3684aa50d3a7SAndi Kleen 			return VM_FAULT_HWPOISON_LARGE |
3685972dc4deSAneesh Kumar K.V 				VM_FAULT_SET_HINDEX(hstate_index(h));
36860d777df5SNaoya Horiguchi 	} else {
3687a5516438SAndi Kleen 		ptep = huge_pte_alloc(mm, address, huge_page_size(h));
368886e5216fSAdam Litke 		if (!ptep)
368986e5216fSAdam Litke 			return VM_FAULT_OOM;
36900d777df5SNaoya Horiguchi 	}
369186e5216fSAdam Litke 
36928382d914SDavidlohr Bueso 	mapping = vma->vm_file->f_mapping;
36938382d914SDavidlohr Bueso 	idx = vma_hugecache_offset(h, vma, address);
36948382d914SDavidlohr Bueso 
36953935baa9SDavid Gibson 	/*
36963935baa9SDavid Gibson 	 * Serialize hugepage allocation and instantiation, so that we don't
36973935baa9SDavid Gibson 	 * get spurious allocation failures if two CPUs race to instantiate
36983935baa9SDavid Gibson 	 * the same page in the page cache.
36993935baa9SDavid Gibson 	 */
3700c672c7f2SMike Kravetz 	hash = hugetlb_fault_mutex_hash(h, mm, vma, mapping, idx, address);
3701c672c7f2SMike Kravetz 	mutex_lock(&hugetlb_fault_mutex_table[hash]);
37028382d914SDavidlohr Bueso 
37037f2e9525SGerald Schaefer 	entry = huge_ptep_get(ptep);
37047f2e9525SGerald Schaefer 	if (huge_pte_none(entry)) {
37058382d914SDavidlohr Bueso 		ret = hugetlb_no_page(mm, vma, mapping, idx, address, ptep, flags);
3706b4d1d99fSDavid Gibson 		goto out_mutex;
37073935baa9SDavid Gibson 	}
370886e5216fSAdam Litke 
370983c54070SNick Piggin 	ret = 0;
37101e8f889bSDavid Gibson 
371157303d80SAndy Whitcroft 	/*
37120f792cf9SNaoya Horiguchi 	 * entry could be a migration/hwpoison entry at this point, so this
37130f792cf9SNaoya Horiguchi 	 * check prevents the kernel from going below assuming that we have
37140f792cf9SNaoya Horiguchi 	 * a active hugepage in pagecache. This goto expects the 2nd page fault,
37150f792cf9SNaoya Horiguchi 	 * and is_hugetlb_entry_(migration|hwpoisoned) check will properly
37160f792cf9SNaoya Horiguchi 	 * handle it.
37170f792cf9SNaoya Horiguchi 	 */
37180f792cf9SNaoya Horiguchi 	if (!pte_present(entry))
37190f792cf9SNaoya Horiguchi 		goto out_mutex;
37200f792cf9SNaoya Horiguchi 
37210f792cf9SNaoya Horiguchi 	/*
372257303d80SAndy Whitcroft 	 * If we are going to COW the mapping later, we examine the pending
372357303d80SAndy Whitcroft 	 * reservations for this page now. This will ensure that any
372457303d80SAndy Whitcroft 	 * allocations necessary to record that reservation occur outside the
372557303d80SAndy Whitcroft 	 * spinlock. For private mappings, we also lookup the pagecache
372657303d80SAndy Whitcroft 	 * page now as it is used to determine if a reservation has been
372757303d80SAndy Whitcroft 	 * consumed.
372857303d80SAndy Whitcroft 	 */
3729106c992aSGerald Schaefer 	if ((flags & FAULT_FLAG_WRITE) && !huge_pte_write(entry)) {
37302b26736cSAndy Whitcroft 		if (vma_needs_reservation(h, vma, address) < 0) {
37312b26736cSAndy Whitcroft 			ret = VM_FAULT_OOM;
3732b4d1d99fSDavid Gibson 			goto out_mutex;
37332b26736cSAndy Whitcroft 		}
37345e911373SMike Kravetz 		/* Just decrements count, does not deallocate */
3735feba16e2SMike Kravetz 		vma_end_reservation(h, vma, address);
373657303d80SAndy Whitcroft 
3737f83a275dSMel Gorman 		if (!(vma->vm_flags & VM_MAYSHARE))
373857303d80SAndy Whitcroft 			pagecache_page = hugetlbfs_pagecache_page(h,
373957303d80SAndy Whitcroft 								vma, address);
374057303d80SAndy Whitcroft 	}
374157303d80SAndy Whitcroft 
37420f792cf9SNaoya Horiguchi 	ptl = huge_pte_lock(h, mm, ptep);
37430fe6e20bSNaoya Horiguchi 
37441e8f889bSDavid Gibson 	/* Check for a racing update before calling hugetlb_cow */
3745b4d1d99fSDavid Gibson 	if (unlikely(!pte_same(entry, huge_ptep_get(ptep))))
3746cb900f41SKirill A. Shutemov 		goto out_ptl;
3747b4d1d99fSDavid Gibson 
37480f792cf9SNaoya Horiguchi 	/*
37490f792cf9SNaoya Horiguchi 	 * hugetlb_cow() requires page locks of pte_page(entry) and
37500f792cf9SNaoya Horiguchi 	 * pagecache_page, so here we need take the former one
37510f792cf9SNaoya Horiguchi 	 * when page != pagecache_page or !pagecache_page.
37520f792cf9SNaoya Horiguchi 	 */
37530f792cf9SNaoya Horiguchi 	page = pte_page(entry);
37540f792cf9SNaoya Horiguchi 	if (page != pagecache_page)
37550f792cf9SNaoya Horiguchi 		if (!trylock_page(page)) {
37560f792cf9SNaoya Horiguchi 			need_wait_lock = 1;
37570f792cf9SNaoya Horiguchi 			goto out_ptl;
37580f792cf9SNaoya Horiguchi 		}
37590f792cf9SNaoya Horiguchi 
37600f792cf9SNaoya Horiguchi 	get_page(page);
3761b4d1d99fSDavid Gibson 
3762788c7df4SHugh Dickins 	if (flags & FAULT_FLAG_WRITE) {
3763106c992aSGerald Schaefer 		if (!huge_pte_write(entry)) {
376457303d80SAndy Whitcroft 			ret = hugetlb_cow(mm, vma, address, ptep, entry,
3765cb900f41SKirill A. Shutemov 					pagecache_page, ptl);
37660f792cf9SNaoya Horiguchi 			goto out_put_page;
3767b4d1d99fSDavid Gibson 		}
3768106c992aSGerald Schaefer 		entry = huge_pte_mkdirty(entry);
3769b4d1d99fSDavid Gibson 	}
3770b4d1d99fSDavid Gibson 	entry = pte_mkyoung(entry);
3771788c7df4SHugh Dickins 	if (huge_ptep_set_access_flags(vma, address, ptep, entry,
3772788c7df4SHugh Dickins 						flags & FAULT_FLAG_WRITE))
37734b3073e1SRussell King 		update_mmu_cache(vma, address, ptep);
37740f792cf9SNaoya Horiguchi out_put_page:
37750f792cf9SNaoya Horiguchi 	if (page != pagecache_page)
37760f792cf9SNaoya Horiguchi 		unlock_page(page);
37770f792cf9SNaoya Horiguchi 	put_page(page);
3778cb900f41SKirill A. Shutemov out_ptl:
3779cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
378057303d80SAndy Whitcroft 
378157303d80SAndy Whitcroft 	if (pagecache_page) {
378257303d80SAndy Whitcroft 		unlock_page(pagecache_page);
378357303d80SAndy Whitcroft 		put_page(pagecache_page);
378457303d80SAndy Whitcroft 	}
3785b4d1d99fSDavid Gibson out_mutex:
3786c672c7f2SMike Kravetz 	mutex_unlock(&hugetlb_fault_mutex_table[hash]);
37870f792cf9SNaoya Horiguchi 	/*
37880f792cf9SNaoya Horiguchi 	 * Generally it's safe to hold refcount during waiting page lock. But
37890f792cf9SNaoya Horiguchi 	 * here we just wait to defer the next page fault to avoid busy loop and
37900f792cf9SNaoya Horiguchi 	 * the page is not used after unlocked before returning from the current
37910f792cf9SNaoya Horiguchi 	 * page fault. So we are safe from accessing freed page, even if we wait
37920f792cf9SNaoya Horiguchi 	 * here without taking refcount.
37930f792cf9SNaoya Horiguchi 	 */
37940f792cf9SNaoya Horiguchi 	if (need_wait_lock)
37950f792cf9SNaoya Horiguchi 		wait_on_page_locked(page);
37961e8f889bSDavid Gibson 	return ret;
379786e5216fSAdam Litke }
379886e5216fSAdam Litke 
379928a35716SMichel Lespinasse long follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma,
380063551ae0SDavid Gibson 			 struct page **pages, struct vm_area_struct **vmas,
380128a35716SMichel Lespinasse 			 unsigned long *position, unsigned long *nr_pages,
380228a35716SMichel Lespinasse 			 long i, unsigned int flags)
380363551ae0SDavid Gibson {
3804d5d4b0aaSChen, Kenneth W 	unsigned long pfn_offset;
3805d5d4b0aaSChen, Kenneth W 	unsigned long vaddr = *position;
380628a35716SMichel Lespinasse 	unsigned long remainder = *nr_pages;
3807a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
380863551ae0SDavid Gibson 
380963551ae0SDavid Gibson 	while (vaddr < vma->vm_end && remainder) {
381063551ae0SDavid Gibson 		pte_t *pte;
3811cb900f41SKirill A. Shutemov 		spinlock_t *ptl = NULL;
38122a15efc9SHugh Dickins 		int absent;
381363551ae0SDavid Gibson 		struct page *page;
381463551ae0SDavid Gibson 
38154c887265SAdam Litke 		/*
381602057967SDavid Rientjes 		 * If we have a pending SIGKILL, don't keep faulting pages and
381702057967SDavid Rientjes 		 * potentially allocating memory.
381802057967SDavid Rientjes 		 */
381902057967SDavid Rientjes 		if (unlikely(fatal_signal_pending(current))) {
382002057967SDavid Rientjes 			remainder = 0;
382102057967SDavid Rientjes 			break;
382202057967SDavid Rientjes 		}
382302057967SDavid Rientjes 
382402057967SDavid Rientjes 		/*
38254c887265SAdam Litke 		 * Some archs (sparc64, sh*) have multiple pte_ts to
38262a15efc9SHugh Dickins 		 * each hugepage.  We have to make sure we get the
38274c887265SAdam Litke 		 * first, for the page indexing below to work.
3828cb900f41SKirill A. Shutemov 		 *
3829cb900f41SKirill A. Shutemov 		 * Note that page table lock is not held when pte is null.
38304c887265SAdam Litke 		 */
3831a5516438SAndi Kleen 		pte = huge_pte_offset(mm, vaddr & huge_page_mask(h));
3832cb900f41SKirill A. Shutemov 		if (pte)
3833cb900f41SKirill A. Shutemov 			ptl = huge_pte_lock(h, mm, pte);
38342a15efc9SHugh Dickins 		absent = !pte || huge_pte_none(huge_ptep_get(pte));
383563551ae0SDavid Gibson 
38362a15efc9SHugh Dickins 		/*
38372a15efc9SHugh Dickins 		 * When coredumping, it suits get_dump_page if we just return
38383ae77f43SHugh Dickins 		 * an error where there's an empty slot with no huge pagecache
38393ae77f43SHugh Dickins 		 * to back it.  This way, we avoid allocating a hugepage, and
38403ae77f43SHugh Dickins 		 * the sparse dumpfile avoids allocating disk blocks, but its
38413ae77f43SHugh Dickins 		 * huge holes still show up with zeroes where they need to be.
38422a15efc9SHugh Dickins 		 */
38433ae77f43SHugh Dickins 		if (absent && (flags & FOLL_DUMP) &&
38443ae77f43SHugh Dickins 		    !hugetlbfs_pagecache_present(h, vma, vaddr)) {
3845cb900f41SKirill A. Shutemov 			if (pte)
3846cb900f41SKirill A. Shutemov 				spin_unlock(ptl);
38472a15efc9SHugh Dickins 			remainder = 0;
38482a15efc9SHugh Dickins 			break;
38492a15efc9SHugh Dickins 		}
38502a15efc9SHugh Dickins 
38519cc3a5bdSNaoya Horiguchi 		/*
38529cc3a5bdSNaoya Horiguchi 		 * We need call hugetlb_fault for both hugepages under migration
38539cc3a5bdSNaoya Horiguchi 		 * (in which case hugetlb_fault waits for the migration,) and
38549cc3a5bdSNaoya Horiguchi 		 * hwpoisoned hugepages (in which case we need to prevent the
38559cc3a5bdSNaoya Horiguchi 		 * caller from accessing to them.) In order to do this, we use
38569cc3a5bdSNaoya Horiguchi 		 * here is_swap_pte instead of is_hugetlb_entry_migration and
38579cc3a5bdSNaoya Horiguchi 		 * is_hugetlb_entry_hwpoisoned. This is because it simply covers
38589cc3a5bdSNaoya Horiguchi 		 * both cases, and because we can't follow correct pages
38599cc3a5bdSNaoya Horiguchi 		 * directly from any kind of swap entries.
38609cc3a5bdSNaoya Horiguchi 		 */
38619cc3a5bdSNaoya Horiguchi 		if (absent || is_swap_pte(huge_ptep_get(pte)) ||
3862106c992aSGerald Schaefer 		    ((flags & FOLL_WRITE) &&
3863106c992aSGerald Schaefer 		      !huge_pte_write(huge_ptep_get(pte)))) {
38644c887265SAdam Litke 			int ret;
38654c887265SAdam Litke 
3866cb900f41SKirill A. Shutemov 			if (pte)
3867cb900f41SKirill A. Shutemov 				spin_unlock(ptl);
38682a15efc9SHugh Dickins 			ret = hugetlb_fault(mm, vma, vaddr,
38692a15efc9SHugh Dickins 				(flags & FOLL_WRITE) ? FAULT_FLAG_WRITE : 0);
3870a89182c7SAdam Litke 			if (!(ret & VM_FAULT_ERROR))
38714c887265SAdam Litke 				continue;
38724c887265SAdam Litke 
38731c59827dSHugh Dickins 			remainder = 0;
38741c59827dSHugh Dickins 			break;
38751c59827dSHugh Dickins 		}
387663551ae0SDavid Gibson 
3877a5516438SAndi Kleen 		pfn_offset = (vaddr & ~huge_page_mask(h)) >> PAGE_SHIFT;
38787f2e9525SGerald Schaefer 		page = pte_page(huge_ptep_get(pte));
3879d5d4b0aaSChen, Kenneth W same_page:
3880d6692183SChen, Kenneth W 		if (pages) {
388169d177c2SAndy Whitcroft 			pages[i] = mem_map_offset(page, pfn_offset);
3882ddc58f27SKirill A. Shutemov 			get_page(pages[i]);
3883d6692183SChen, Kenneth W 		}
388463551ae0SDavid Gibson 
388563551ae0SDavid Gibson 		if (vmas)
388663551ae0SDavid Gibson 			vmas[i] = vma;
388763551ae0SDavid Gibson 
388863551ae0SDavid Gibson 		vaddr += PAGE_SIZE;
3889d5d4b0aaSChen, Kenneth W 		++pfn_offset;
389063551ae0SDavid Gibson 		--remainder;
389163551ae0SDavid Gibson 		++i;
3892d5d4b0aaSChen, Kenneth W 		if (vaddr < vma->vm_end && remainder &&
3893a5516438SAndi Kleen 				pfn_offset < pages_per_huge_page(h)) {
3894d5d4b0aaSChen, Kenneth W 			/*
3895d5d4b0aaSChen, Kenneth W 			 * We use pfn_offset to avoid touching the pageframes
3896d5d4b0aaSChen, Kenneth W 			 * of this compound page.
3897d5d4b0aaSChen, Kenneth W 			 */
3898d5d4b0aaSChen, Kenneth W 			goto same_page;
3899d5d4b0aaSChen, Kenneth W 		}
3900cb900f41SKirill A. Shutemov 		spin_unlock(ptl);
390163551ae0SDavid Gibson 	}
390228a35716SMichel Lespinasse 	*nr_pages = remainder;
390363551ae0SDavid Gibson 	*position = vaddr;
390463551ae0SDavid Gibson 
39052a15efc9SHugh Dickins 	return i ? i : -EFAULT;
390663551ae0SDavid Gibson }
39078f860591SZhang, Yanmin 
39087da4d641SPeter Zijlstra unsigned long hugetlb_change_protection(struct vm_area_struct *vma,
39098f860591SZhang, Yanmin 		unsigned long address, unsigned long end, pgprot_t newprot)
39108f860591SZhang, Yanmin {
39118f860591SZhang, Yanmin 	struct mm_struct *mm = vma->vm_mm;
39128f860591SZhang, Yanmin 	unsigned long start = address;
39138f860591SZhang, Yanmin 	pte_t *ptep;
39148f860591SZhang, Yanmin 	pte_t pte;
3915a5516438SAndi Kleen 	struct hstate *h = hstate_vma(vma);
39167da4d641SPeter Zijlstra 	unsigned long pages = 0;
39178f860591SZhang, Yanmin 
39188f860591SZhang, Yanmin 	BUG_ON(address >= end);
39198f860591SZhang, Yanmin 	flush_cache_range(vma, address, end);
39208f860591SZhang, Yanmin 
3921a5338093SRik van Riel 	mmu_notifier_invalidate_range_start(mm, start, end);
392283cde9e8SDavidlohr Bueso 	i_mmap_lock_write(vma->vm_file->f_mapping);
3923a5516438SAndi Kleen 	for (; address < end; address += huge_page_size(h)) {
3924cb900f41SKirill A. Shutemov 		spinlock_t *ptl;
39258f860591SZhang, Yanmin 		ptep = huge_pte_offset(mm, address);
39268f860591SZhang, Yanmin 		if (!ptep)
39278f860591SZhang, Yanmin 			continue;
3928cb900f41SKirill A. Shutemov 		ptl = huge_pte_lock(h, mm, ptep);
39297da4d641SPeter Zijlstra 		if (huge_pmd_unshare(mm, &address, ptep)) {
39307da4d641SPeter Zijlstra 			pages++;
3931cb900f41SKirill A. Shutemov 			spin_unlock(ptl);
393239dde65cSChen, Kenneth W 			continue;
39337da4d641SPeter Zijlstra 		}
3934a8bda28dSNaoya Horiguchi 		pte = huge_ptep_get(ptep);
3935a8bda28dSNaoya Horiguchi 		if (unlikely(is_hugetlb_entry_hwpoisoned(pte))) {
3936a8bda28dSNaoya Horiguchi 			spin_unlock(ptl);
3937a8bda28dSNaoya Horiguchi 			continue;
3938a8bda28dSNaoya Horiguchi 		}
3939a8bda28dSNaoya Horiguchi 		if (unlikely(is_hugetlb_entry_migration(pte))) {
3940a8bda28dSNaoya Horiguchi 			swp_entry_t entry = pte_to_swp_entry(pte);
3941a8bda28dSNaoya Horiguchi 
3942a8bda28dSNaoya Horiguchi 			if (is_write_migration_entry(entry)) {
3943a8bda28dSNaoya Horiguchi 				pte_t newpte;
3944a8bda28dSNaoya Horiguchi 
3945a8bda28dSNaoya Horiguchi 				make_migration_entry_read(&entry);
3946a8bda28dSNaoya Horiguchi 				newpte = swp_entry_to_pte(entry);
3947a8bda28dSNaoya Horiguchi 				set_huge_pte_at(mm, address, ptep, newpte);
3948a8bda28dSNaoya Horiguchi 				pages++;
3949a8bda28dSNaoya Horiguchi 			}
3950a8bda28dSNaoya Horiguchi 			spin_unlock(ptl);
3951a8bda28dSNaoya Horiguchi 			continue;
3952a8bda28dSNaoya Horiguchi 		}
3953a8bda28dSNaoya Horiguchi 		if (!huge_pte_none(pte)) {
39548f860591SZhang, Yanmin 			pte = huge_ptep_get_and_clear(mm, address, ptep);
3955106c992aSGerald Schaefer 			pte = pte_mkhuge(huge_pte_modify(pte, newprot));
3956be7517d6STony Lu 			pte = arch_make_huge_pte(pte, vma, NULL, 0);
39578f860591SZhang, Yanmin 			set_huge_pte_at(mm, address, ptep, pte);
39587da4d641SPeter Zijlstra 			pages++;
39598f860591SZhang, Yanmin 		}
3960cb900f41SKirill A. Shutemov 		spin_unlock(ptl);
39618f860591SZhang, Yanmin 	}
3962d833352aSMel Gorman 	/*
3963c8c06efaSDavidlohr Bueso 	 * Must flush TLB before releasing i_mmap_rwsem: x86's huge_pmd_unshare
3964d833352aSMel Gorman 	 * may have cleared our pud entry and done put_page on the page table:
3965c8c06efaSDavidlohr Bueso 	 * once we release i_mmap_rwsem, another task can do the final put_page
3966d833352aSMel Gorman 	 * and that page table be reused and filled with junk.
3967d833352aSMel Gorman 	 */
39688f860591SZhang, Yanmin 	flush_tlb_range(vma, start, end);
396934ee645eSJoerg Roedel 	mmu_notifier_invalidate_range(mm, start, end);
397083cde9e8SDavidlohr Bueso 	i_mmap_unlock_write(vma->vm_file->f_mapping);
3971a5338093SRik van Riel 	mmu_notifier_invalidate_range_end(mm, start, end);
39727da4d641SPeter Zijlstra 
39737da4d641SPeter Zijlstra 	return pages << h->order;
39748f860591SZhang, Yanmin }
39758f860591SZhang, Yanmin 
3976a1e78772SMel Gorman int hugetlb_reserve_pages(struct inode *inode,
3977a1e78772SMel Gorman 					long from, long to,
39785a6fe125SMel Gorman 					struct vm_area_struct *vma,
3979ca16d140SKOSAKI Motohiro 					vm_flags_t vm_flags)
3980e4e574b7SAdam Litke {
398117c9d12eSMel Gorman 	long ret, chg;
3982a5516438SAndi Kleen 	struct hstate *h = hstate_inode(inode);
398390481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_inode(inode);
39849119a41eSJoonsoo Kim 	struct resv_map *resv_map;
39851c5ecae3SMike Kravetz 	long gbl_reserve;
3986e4e574b7SAdam Litke 
3987a1e78772SMel Gorman 	/*
398817c9d12eSMel Gorman 	 * Only apply hugepage reservation if asked. At fault time, an
398917c9d12eSMel Gorman 	 * attempt will be made for VM_NORESERVE to allocate a page
399090481622SDavid Gibson 	 * without using reserves
399117c9d12eSMel Gorman 	 */
3992ca16d140SKOSAKI Motohiro 	if (vm_flags & VM_NORESERVE)
399317c9d12eSMel Gorman 		return 0;
399417c9d12eSMel Gorman 
399517c9d12eSMel Gorman 	/*
3996a1e78772SMel Gorman 	 * Shared mappings base their reservation on the number of pages that
3997a1e78772SMel Gorman 	 * are already allocated on behalf of the file. Private mappings need
3998a1e78772SMel Gorman 	 * to reserve the full area even if read-only as mprotect() may be
3999a1e78772SMel Gorman 	 * called to make the mapping read-write. Assume !vma is a shm mapping
4000a1e78772SMel Gorman 	 */
40019119a41eSJoonsoo Kim 	if (!vma || vma->vm_flags & VM_MAYSHARE) {
40024e35f483SJoonsoo Kim 		resv_map = inode_resv_map(inode);
40039119a41eSJoonsoo Kim 
40041406ec9bSJoonsoo Kim 		chg = region_chg(resv_map, from, to);
40059119a41eSJoonsoo Kim 
40069119a41eSJoonsoo Kim 	} else {
40079119a41eSJoonsoo Kim 		resv_map = resv_map_alloc();
40085a6fe125SMel Gorman 		if (!resv_map)
40095a6fe125SMel Gorman 			return -ENOMEM;
40105a6fe125SMel Gorman 
401117c9d12eSMel Gorman 		chg = to - from;
401217c9d12eSMel Gorman 
40135a6fe125SMel Gorman 		set_vma_resv_map(vma, resv_map);
40145a6fe125SMel Gorman 		set_vma_resv_flags(vma, HPAGE_RESV_OWNER);
40155a6fe125SMel Gorman 	}
40165a6fe125SMel Gorman 
4017c50ac050SDave Hansen 	if (chg < 0) {
4018c50ac050SDave Hansen 		ret = chg;
4019c50ac050SDave Hansen 		goto out_err;
4020c50ac050SDave Hansen 	}
402117c9d12eSMel Gorman 
40221c5ecae3SMike Kravetz 	/*
40231c5ecae3SMike Kravetz 	 * There must be enough pages in the subpool for the mapping. If
40241c5ecae3SMike Kravetz 	 * the subpool has a minimum size, there may be some global
40251c5ecae3SMike Kravetz 	 * reservations already in place (gbl_reserve).
40261c5ecae3SMike Kravetz 	 */
40271c5ecae3SMike Kravetz 	gbl_reserve = hugepage_subpool_get_pages(spool, chg);
40281c5ecae3SMike Kravetz 	if (gbl_reserve < 0) {
4029c50ac050SDave Hansen 		ret = -ENOSPC;
4030c50ac050SDave Hansen 		goto out_err;
4031c50ac050SDave Hansen 	}
403217c9d12eSMel Gorman 
403317c9d12eSMel Gorman 	/*
403417c9d12eSMel Gorman 	 * Check enough hugepages are available for the reservation.
403590481622SDavid Gibson 	 * Hand the pages back to the subpool if there are not
403617c9d12eSMel Gorman 	 */
40371c5ecae3SMike Kravetz 	ret = hugetlb_acct_memory(h, gbl_reserve);
403817c9d12eSMel Gorman 	if (ret < 0) {
40391c5ecae3SMike Kravetz 		/* put back original number of pages, chg */
40401c5ecae3SMike Kravetz 		(void)hugepage_subpool_put_pages(spool, chg);
4041c50ac050SDave Hansen 		goto out_err;
404217c9d12eSMel Gorman 	}
404317c9d12eSMel Gorman 
404417c9d12eSMel Gorman 	/*
404517c9d12eSMel Gorman 	 * Account for the reservations made. Shared mappings record regions
404617c9d12eSMel Gorman 	 * that have reservations as they are shared by multiple VMAs.
404717c9d12eSMel Gorman 	 * When the last VMA disappears, the region map says how much
404817c9d12eSMel Gorman 	 * the reservation was and the page cache tells how much of
404917c9d12eSMel Gorman 	 * the reservation was consumed. Private mappings are per-VMA and
405017c9d12eSMel Gorman 	 * only the consumed reservations are tracked. When the VMA
405117c9d12eSMel Gorman 	 * disappears, the original reservation is the VMA size and the
405217c9d12eSMel Gorman 	 * consumed reservations are stored in the map. Hence, nothing
405317c9d12eSMel Gorman 	 * else has to be done for private mappings here
405417c9d12eSMel Gorman 	 */
405533039678SMike Kravetz 	if (!vma || vma->vm_flags & VM_MAYSHARE) {
405633039678SMike Kravetz 		long add = region_add(resv_map, from, to);
405733039678SMike Kravetz 
405833039678SMike Kravetz 		if (unlikely(chg > add)) {
405933039678SMike Kravetz 			/*
406033039678SMike Kravetz 			 * pages in this range were added to the reserve
406133039678SMike Kravetz 			 * map between region_chg and region_add.  This
406233039678SMike Kravetz 			 * indicates a race with alloc_huge_page.  Adjust
406333039678SMike Kravetz 			 * the subpool and reserve counts modified above
406433039678SMike Kravetz 			 * based on the difference.
406533039678SMike Kravetz 			 */
406633039678SMike Kravetz 			long rsv_adjust;
406733039678SMike Kravetz 
406833039678SMike Kravetz 			rsv_adjust = hugepage_subpool_put_pages(spool,
406933039678SMike Kravetz 								chg - add);
407033039678SMike Kravetz 			hugetlb_acct_memory(h, -rsv_adjust);
407133039678SMike Kravetz 		}
407233039678SMike Kravetz 	}
4073a43a8c39SChen, Kenneth W 	return 0;
4074c50ac050SDave Hansen out_err:
40755e911373SMike Kravetz 	if (!vma || vma->vm_flags & VM_MAYSHARE)
40765e911373SMike Kravetz 		region_abort(resv_map, from, to);
4077f031dd27SJoonsoo Kim 	if (vma && is_vma_resv_set(vma, HPAGE_RESV_OWNER))
4078f031dd27SJoonsoo Kim 		kref_put(&resv_map->refs, resv_map_release);
4079c50ac050SDave Hansen 	return ret;
4080a43a8c39SChen, Kenneth W }
4081a43a8c39SChen, Kenneth W 
4082b5cec28dSMike Kravetz long hugetlb_unreserve_pages(struct inode *inode, long start, long end,
4083b5cec28dSMike Kravetz 								long freed)
4084a43a8c39SChen, Kenneth W {
4085a5516438SAndi Kleen 	struct hstate *h = hstate_inode(inode);
40864e35f483SJoonsoo Kim 	struct resv_map *resv_map = inode_resv_map(inode);
40879119a41eSJoonsoo Kim 	long chg = 0;
408890481622SDavid Gibson 	struct hugepage_subpool *spool = subpool_inode(inode);
40891c5ecae3SMike Kravetz 	long gbl_reserve;
409045c682a6SKen Chen 
4091b5cec28dSMike Kravetz 	if (resv_map) {
4092b5cec28dSMike Kravetz 		chg = region_del(resv_map, start, end);
4093b5cec28dSMike Kravetz 		/*
4094b5cec28dSMike Kravetz 		 * region_del() can fail in the rare case where a region
4095b5cec28dSMike Kravetz 		 * must be split and another region descriptor can not be
4096b5cec28dSMike Kravetz 		 * allocated.  If end == LONG_MAX, it will not fail.
4097b5cec28dSMike Kravetz 		 */
4098b5cec28dSMike Kravetz 		if (chg < 0)
4099b5cec28dSMike Kravetz 			return chg;
4100b5cec28dSMike Kravetz 	}
4101b5cec28dSMike Kravetz 
410245c682a6SKen Chen 	spin_lock(&inode->i_lock);
4103e4c6f8beSEric Sandeen 	inode->i_blocks -= (blocks_per_huge_page(h) * freed);
410445c682a6SKen Chen 	spin_unlock(&inode->i_lock);
410545c682a6SKen Chen 
41061c5ecae3SMike Kravetz 	/*
41071c5ecae3SMike Kravetz 	 * If the subpool has a minimum size, the number of global
41081c5ecae3SMike Kravetz 	 * reservations to be released may be adjusted.
41091c5ecae3SMike Kravetz 	 */
41101c5ecae3SMike Kravetz 	gbl_reserve = hugepage_subpool_put_pages(spool, (chg - freed));
41111c5ecae3SMike Kravetz 	hugetlb_acct_memory(h, -gbl_reserve);
4112b5cec28dSMike Kravetz 
4113b5cec28dSMike Kravetz 	return 0;
4114a43a8c39SChen, Kenneth W }
411593f70f90SNaoya Horiguchi 
41163212b535SSteve Capper #ifdef CONFIG_ARCH_WANT_HUGE_PMD_SHARE
41173212b535SSteve Capper static unsigned long page_table_shareable(struct vm_area_struct *svma,
41183212b535SSteve Capper 				struct vm_area_struct *vma,
41193212b535SSteve Capper 				unsigned long addr, pgoff_t idx)
41203212b535SSteve Capper {
41213212b535SSteve Capper 	unsigned long saddr = ((idx - svma->vm_pgoff) << PAGE_SHIFT) +
41223212b535SSteve Capper 				svma->vm_start;
41233212b535SSteve Capper 	unsigned long sbase = saddr & PUD_MASK;
41243212b535SSteve Capper 	unsigned long s_end = sbase + PUD_SIZE;
41253212b535SSteve Capper 
41263212b535SSteve Capper 	/* Allow segments to share if only one is marked locked */
4127de60f5f1SEric B Munson 	unsigned long vm_flags = vma->vm_flags & VM_LOCKED_CLEAR_MASK;
4128de60f5f1SEric B Munson 	unsigned long svm_flags = svma->vm_flags & VM_LOCKED_CLEAR_MASK;
41293212b535SSteve Capper 
41303212b535SSteve Capper 	/*
41313212b535SSteve Capper 	 * match the virtual addresses, permission and the alignment of the
41323212b535SSteve Capper 	 * page table page.
41333212b535SSteve Capper 	 */
41343212b535SSteve Capper 	if (pmd_index(addr) != pmd_index(saddr) ||
41353212b535SSteve Capper 	    vm_flags != svm_flags ||
41363212b535SSteve Capper 	    sbase < svma->vm_start || svma->vm_end < s_end)
41373212b535SSteve Capper 		return 0;
41383212b535SSteve Capper 
41393212b535SSteve Capper 	return saddr;
41403212b535SSteve Capper }
41413212b535SSteve Capper 
414231aafb45SNicholas Krause static bool vma_shareable(struct vm_area_struct *vma, unsigned long addr)
41433212b535SSteve Capper {
41443212b535SSteve Capper 	unsigned long base = addr & PUD_MASK;
41453212b535SSteve Capper 	unsigned long end = base + PUD_SIZE;
41463212b535SSteve Capper 
41473212b535SSteve Capper 	/*
41483212b535SSteve Capper 	 * check on proper vm_flags and page table alignment
41493212b535SSteve Capper 	 */
41503212b535SSteve Capper 	if (vma->vm_flags & VM_MAYSHARE &&
41513212b535SSteve Capper 	    vma->vm_start <= base && end <= vma->vm_end)
415231aafb45SNicholas Krause 		return true;
415331aafb45SNicholas Krause 	return false;
41543212b535SSteve Capper }
41553212b535SSteve Capper 
41563212b535SSteve Capper /*
41573212b535SSteve Capper  * Search for a shareable pmd page for hugetlb. In any case calls pmd_alloc()
41583212b535SSteve Capper  * and returns the corresponding pte. While this is not necessary for the
41593212b535SSteve Capper  * !shared pmd case because we can allocate the pmd later as well, it makes the
41603212b535SSteve Capper  * code much cleaner. pmd allocation is essential for the shared case because
4161c8c06efaSDavidlohr Bueso  * pud has to be populated inside the same i_mmap_rwsem section - otherwise
41623212b535SSteve Capper  * racing tasks could either miss the sharing (see huge_pte_offset) or select a
41633212b535SSteve Capper  * bad pmd for sharing.
41643212b535SSteve Capper  */
41653212b535SSteve Capper pte_t *huge_pmd_share(struct mm_struct *mm, unsigned long addr, pud_t *pud)
41663212b535SSteve Capper {
41673212b535SSteve Capper 	struct vm_area_struct *vma = find_vma(mm, addr);
41683212b535SSteve Capper 	struct address_space *mapping = vma->vm_file->f_mapping;
41693212b535SSteve Capper 	pgoff_t idx = ((addr - vma->vm_start) >> PAGE_SHIFT) +
41703212b535SSteve Capper 			vma->vm_pgoff;
41713212b535SSteve Capper 	struct vm_area_struct *svma;
41723212b535SSteve Capper 	unsigned long saddr;
41733212b535SSteve Capper 	pte_t *spte = NULL;
41743212b535SSteve Capper 	pte_t *pte;
4175cb900f41SKirill A. Shutemov 	spinlock_t *ptl;
41763212b535SSteve Capper 
41773212b535SSteve Capper 	if (!vma_shareable(vma, addr))
41783212b535SSteve Capper 		return (pte_t *)pmd_alloc(mm, pud, addr);
41793212b535SSteve Capper 
418083cde9e8SDavidlohr Bueso 	i_mmap_lock_write(mapping);
41813212b535SSteve Capper 	vma_interval_tree_foreach(svma, &mapping->i_mmap, idx, idx) {
41823212b535SSteve Capper 		if (svma == vma)
41833212b535SSteve Capper 			continue;
41843212b535SSteve Capper 
41853212b535SSteve Capper 		saddr = page_table_shareable(svma, vma, addr, idx);
41863212b535SSteve Capper 		if (saddr) {
41873212b535SSteve Capper 			spte = huge_pte_offset(svma->vm_mm, saddr);
41883212b535SSteve Capper 			if (spte) {
4189dc6c9a35SKirill A. Shutemov 				mm_inc_nr_pmds(mm);
41903212b535SSteve Capper 				get_page(virt_to_page(spte));
41913212b535SSteve Capper 				break;
41923212b535SSteve Capper 			}
41933212b535SSteve Capper 		}
41943212b535SSteve Capper 	}
41953212b535SSteve Capper 
41963212b535SSteve Capper 	if (!spte)
41973212b535SSteve Capper 		goto out;
41983212b535SSteve Capper 
4199cb900f41SKirill A. Shutemov 	ptl = huge_pte_lockptr(hstate_vma(vma), mm, spte);
4200cb900f41SKirill A. Shutemov 	spin_lock(ptl);
4201dc6c9a35SKirill A. Shutemov 	if (pud_none(*pud)) {
42023212b535SSteve Capper 		pud_populate(mm, pud,
42033212b535SSteve Capper 				(pmd_t *)((unsigned long)spte & PAGE_MASK));
4204dc6c9a35SKirill A. Shutemov 	} else {
42053212b535SSteve Capper 		put_page(virt_to_page(spte));
4206dc6c9a35SKirill A. Shutemov 		mm_inc_nr_pmds(mm);
4207dc6c9a35SKirill A. Shutemov 	}
4208cb900f41SKirill A. Shutemov 	spin_unlock(ptl);
42093212b535SSteve Capper out:
42103212b535SSteve Capper 	pte = (pte_t *)pmd_alloc(mm, pud, addr);
421183cde9e8SDavidlohr Bueso 	i_mmap_unlock_write(mapping);
42123212b535SSteve Capper 	return pte;
42133212b535SSteve Capper }
42143212b535SSteve Capper 
42153212b535SSteve Capper /*
42163212b535SSteve Capper  * unmap huge page backed by shared pte.
42173212b535SSteve Capper  *
42183212b535SSteve Capper  * Hugetlb pte page is ref counted at the time of mapping.  If pte is shared
42193212b535SSteve Capper  * indicated by page_count > 1, unmap is achieved by clearing pud and
42203212b535SSteve Capper  * decrementing the ref count. If count == 1, the pte page is not shared.
42213212b535SSteve Capper  *
4222cb900f41SKirill A. Shutemov  * called with page table lock held.
42233212b535SSteve Capper  *
42243212b535SSteve Capper  * returns: 1 successfully unmapped a shared pte page
42253212b535SSteve Capper  *	    0 the underlying pte page is not shared, or it is the last user
42263212b535SSteve Capper  */
42273212b535SSteve Capper int huge_pmd_unshare(struct mm_struct *mm, unsigned long *addr, pte_t *ptep)
42283212b535SSteve Capper {
42293212b535SSteve Capper 	pgd_t *pgd = pgd_offset(mm, *addr);
42303212b535SSteve Capper 	pud_t *pud = pud_offset(pgd, *addr);
42313212b535SSteve Capper 
42323212b535SSteve Capper 	BUG_ON(page_count(virt_to_page(ptep)) == 0);
42333212b535SSteve Capper 	if (page_count(virt_to_page(ptep)) == 1)
42343212b535SSteve Capper 		return 0;
42353212b535SSteve Capper 
42363212b535SSteve Capper 	pud_clear(pud);
42373212b535SSteve Capper 	put_page(virt_to_page(ptep));
4238dc6c9a35SKirill A. Shutemov 	mm_dec_nr_pmds(mm);
42393212b535SSteve Capper 	*addr = ALIGN(*addr, HPAGE_SIZE * PTRS_PER_PTE) - HPAGE_SIZE;
42403212b535SSteve Capper 	return 1;
42413212b535SSteve Capper }
42429e5fc74cSSteve Capper #define want_pmd_share()	(1)
42439e5fc74cSSteve Capper #else /* !CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
42449e5fc74cSSteve Capper pte_t *huge_pmd_share(struct mm_struct *mm, unsigned long addr, pud_t *pud)
42459e5fc74cSSteve Capper {
42469e5fc74cSSteve Capper 	return NULL;
42479e5fc74cSSteve Capper }
4248e81f2d22SZhang Zhen 
4249e81f2d22SZhang Zhen int huge_pmd_unshare(struct mm_struct *mm, unsigned long *addr, pte_t *ptep)
4250e81f2d22SZhang Zhen {
4251e81f2d22SZhang Zhen 	return 0;
4252e81f2d22SZhang Zhen }
42539e5fc74cSSteve Capper #define want_pmd_share()	(0)
42543212b535SSteve Capper #endif /* CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
42553212b535SSteve Capper 
42569e5fc74cSSteve Capper #ifdef CONFIG_ARCH_WANT_GENERAL_HUGETLB
42579e5fc74cSSteve Capper pte_t *huge_pte_alloc(struct mm_struct *mm,
42589e5fc74cSSteve Capper 			unsigned long addr, unsigned long sz)
42599e5fc74cSSteve Capper {
42609e5fc74cSSteve Capper 	pgd_t *pgd;
42619e5fc74cSSteve Capper 	pud_t *pud;
42629e5fc74cSSteve Capper 	pte_t *pte = NULL;
42639e5fc74cSSteve Capper 
42649e5fc74cSSteve Capper 	pgd = pgd_offset(mm, addr);
42659e5fc74cSSteve Capper 	pud = pud_alloc(mm, pgd, addr);
42669e5fc74cSSteve Capper 	if (pud) {
42679e5fc74cSSteve Capper 		if (sz == PUD_SIZE) {
42689e5fc74cSSteve Capper 			pte = (pte_t *)pud;
42699e5fc74cSSteve Capper 		} else {
42709e5fc74cSSteve Capper 			BUG_ON(sz != PMD_SIZE);
42719e5fc74cSSteve Capper 			if (want_pmd_share() && pud_none(*pud))
42729e5fc74cSSteve Capper 				pte = huge_pmd_share(mm, addr, pud);
42739e5fc74cSSteve Capper 			else
42749e5fc74cSSteve Capper 				pte = (pte_t *)pmd_alloc(mm, pud, addr);
42759e5fc74cSSteve Capper 		}
42769e5fc74cSSteve Capper 	}
42779e5fc74cSSteve Capper 	BUG_ON(pte && !pte_none(*pte) && !pte_huge(*pte));
42789e5fc74cSSteve Capper 
42799e5fc74cSSteve Capper 	return pte;
42809e5fc74cSSteve Capper }
42819e5fc74cSSteve Capper 
42829e5fc74cSSteve Capper pte_t *huge_pte_offset(struct mm_struct *mm, unsigned long addr)
42839e5fc74cSSteve Capper {
42849e5fc74cSSteve Capper 	pgd_t *pgd;
42859e5fc74cSSteve Capper 	pud_t *pud;
42869e5fc74cSSteve Capper 	pmd_t *pmd = NULL;
42879e5fc74cSSteve Capper 
42889e5fc74cSSteve Capper 	pgd = pgd_offset(mm, addr);
42899e5fc74cSSteve Capper 	if (pgd_present(*pgd)) {
42909e5fc74cSSteve Capper 		pud = pud_offset(pgd, addr);
42919e5fc74cSSteve Capper 		if (pud_present(*pud)) {
42929e5fc74cSSteve Capper 			if (pud_huge(*pud))
42939e5fc74cSSteve Capper 				return (pte_t *)pud;
42949e5fc74cSSteve Capper 			pmd = pmd_offset(pud, addr);
42959e5fc74cSSteve Capper 		}
42969e5fc74cSSteve Capper 	}
42979e5fc74cSSteve Capper 	return (pte_t *) pmd;
42989e5fc74cSSteve Capper }
42999e5fc74cSSteve Capper 
430061f77edaSNaoya Horiguchi #endif /* CONFIG_ARCH_WANT_GENERAL_HUGETLB */
430161f77edaSNaoya Horiguchi 
430261f77edaSNaoya Horiguchi /*
430361f77edaSNaoya Horiguchi  * These functions are overwritable if your architecture needs its own
430461f77edaSNaoya Horiguchi  * behavior.
430561f77edaSNaoya Horiguchi  */
430661f77edaSNaoya Horiguchi struct page * __weak
430761f77edaSNaoya Horiguchi follow_huge_addr(struct mm_struct *mm, unsigned long address,
430861f77edaSNaoya Horiguchi 			      int write)
430961f77edaSNaoya Horiguchi {
431061f77edaSNaoya Horiguchi 	return ERR_PTR(-EINVAL);
431161f77edaSNaoya Horiguchi }
431261f77edaSNaoya Horiguchi 
431361f77edaSNaoya Horiguchi struct page * __weak
43149e5fc74cSSteve Capper follow_huge_pmd(struct mm_struct *mm, unsigned long address,
4315e66f17ffSNaoya Horiguchi 		pmd_t *pmd, int flags)
43169e5fc74cSSteve Capper {
4317e66f17ffSNaoya Horiguchi 	struct page *page = NULL;
4318e66f17ffSNaoya Horiguchi 	spinlock_t *ptl;
4319e66f17ffSNaoya Horiguchi retry:
4320e66f17ffSNaoya Horiguchi 	ptl = pmd_lockptr(mm, pmd);
4321e66f17ffSNaoya Horiguchi 	spin_lock(ptl);
4322e66f17ffSNaoya Horiguchi 	/*
4323e66f17ffSNaoya Horiguchi 	 * make sure that the address range covered by this pmd is not
4324e66f17ffSNaoya Horiguchi 	 * unmapped from other threads.
4325e66f17ffSNaoya Horiguchi 	 */
4326e66f17ffSNaoya Horiguchi 	if (!pmd_huge(*pmd))
4327e66f17ffSNaoya Horiguchi 		goto out;
4328e66f17ffSNaoya Horiguchi 	if (pmd_present(*pmd)) {
432997534127SGerald Schaefer 		page = pmd_page(*pmd) + ((address & ~PMD_MASK) >> PAGE_SHIFT);
4330e66f17ffSNaoya Horiguchi 		if (flags & FOLL_GET)
4331e66f17ffSNaoya Horiguchi 			get_page(page);
4332e66f17ffSNaoya Horiguchi 	} else {
4333e66f17ffSNaoya Horiguchi 		if (is_hugetlb_entry_migration(huge_ptep_get((pte_t *)pmd))) {
4334e66f17ffSNaoya Horiguchi 			spin_unlock(ptl);
4335e66f17ffSNaoya Horiguchi 			__migration_entry_wait(mm, (pte_t *)pmd, ptl);
4336e66f17ffSNaoya Horiguchi 			goto retry;
4337e66f17ffSNaoya Horiguchi 		}
4338e66f17ffSNaoya Horiguchi 		/*
4339e66f17ffSNaoya Horiguchi 		 * hwpoisoned entry is treated as no_page_table in
4340e66f17ffSNaoya Horiguchi 		 * follow_page_mask().
4341e66f17ffSNaoya Horiguchi 		 */
4342e66f17ffSNaoya Horiguchi 	}
4343e66f17ffSNaoya Horiguchi out:
4344e66f17ffSNaoya Horiguchi 	spin_unlock(ptl);
43459e5fc74cSSteve Capper 	return page;
43469e5fc74cSSteve Capper }
43479e5fc74cSSteve Capper 
434861f77edaSNaoya Horiguchi struct page * __weak
43499e5fc74cSSteve Capper follow_huge_pud(struct mm_struct *mm, unsigned long address,
4350e66f17ffSNaoya Horiguchi 		pud_t *pud, int flags)
43519e5fc74cSSteve Capper {
4352e66f17ffSNaoya Horiguchi 	if (flags & FOLL_GET)
4353e66f17ffSNaoya Horiguchi 		return NULL;
43549e5fc74cSSteve Capper 
4355e66f17ffSNaoya Horiguchi 	return pte_page(*(pte_t *)pud) + ((address & ~PUD_MASK) >> PAGE_SHIFT);
43569e5fc74cSSteve Capper }
43579e5fc74cSSteve Capper 
4358d5bd9106SAndi Kleen #ifdef CONFIG_MEMORY_FAILURE
4359d5bd9106SAndi Kleen 
436093f70f90SNaoya Horiguchi /*
436193f70f90SNaoya Horiguchi  * This function is called from memory failure code.
436293f70f90SNaoya Horiguchi  * Assume the caller holds page lock of the head page.
436393f70f90SNaoya Horiguchi  */
43646de2b1aaSNaoya Horiguchi int dequeue_hwpoisoned_huge_page(struct page *hpage)
436593f70f90SNaoya Horiguchi {
436693f70f90SNaoya Horiguchi 	struct hstate *h = page_hstate(hpage);
436793f70f90SNaoya Horiguchi 	int nid = page_to_nid(hpage);
43686de2b1aaSNaoya Horiguchi 	int ret = -EBUSY;
436993f70f90SNaoya Horiguchi 
437093f70f90SNaoya Horiguchi 	spin_lock(&hugetlb_lock);
43717e1f049eSNaoya Horiguchi 	/*
43727e1f049eSNaoya Horiguchi 	 * Just checking !page_huge_active is not enough, because that could be
43737e1f049eSNaoya Horiguchi 	 * an isolated/hwpoisoned hugepage (which have >0 refcount).
43747e1f049eSNaoya Horiguchi 	 */
43757e1f049eSNaoya Horiguchi 	if (!page_huge_active(hpage) && !page_count(hpage)) {
437656f2fb14SNaoya Horiguchi 		/*
437756f2fb14SNaoya Horiguchi 		 * Hwpoisoned hugepage isn't linked to activelist or freelist,
437856f2fb14SNaoya Horiguchi 		 * but dangling hpage->lru can trigger list-debug warnings
437956f2fb14SNaoya Horiguchi 		 * (this happens when we call unpoison_memory() on it),
438056f2fb14SNaoya Horiguchi 		 * so let it point to itself with list_del_init().
438156f2fb14SNaoya Horiguchi 		 */
438256f2fb14SNaoya Horiguchi 		list_del_init(&hpage->lru);
43838c6c2ecbSNaoya Horiguchi 		set_page_refcounted(hpage);
438493f70f90SNaoya Horiguchi 		h->free_huge_pages--;
438593f70f90SNaoya Horiguchi 		h->free_huge_pages_node[nid]--;
43866de2b1aaSNaoya Horiguchi 		ret = 0;
438793f70f90SNaoya Horiguchi 	}
43886de2b1aaSNaoya Horiguchi 	spin_unlock(&hugetlb_lock);
43896de2b1aaSNaoya Horiguchi 	return ret;
43906de2b1aaSNaoya Horiguchi }
43916de2b1aaSNaoya Horiguchi #endif
439231caf665SNaoya Horiguchi 
439331caf665SNaoya Horiguchi bool isolate_huge_page(struct page *page, struct list_head *list)
439431caf665SNaoya Horiguchi {
4395bcc54222SNaoya Horiguchi 	bool ret = true;
4396bcc54222SNaoya Horiguchi 
4397309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageHead(page), page);
439831caf665SNaoya Horiguchi 	spin_lock(&hugetlb_lock);
4399bcc54222SNaoya Horiguchi 	if (!page_huge_active(page) || !get_page_unless_zero(page)) {
4400bcc54222SNaoya Horiguchi 		ret = false;
4401bcc54222SNaoya Horiguchi 		goto unlock;
4402bcc54222SNaoya Horiguchi 	}
4403bcc54222SNaoya Horiguchi 	clear_page_huge_active(page);
440431caf665SNaoya Horiguchi 	list_move_tail(&page->lru, list);
4405bcc54222SNaoya Horiguchi unlock:
440631caf665SNaoya Horiguchi 	spin_unlock(&hugetlb_lock);
4407bcc54222SNaoya Horiguchi 	return ret;
440831caf665SNaoya Horiguchi }
440931caf665SNaoya Horiguchi 
441031caf665SNaoya Horiguchi void putback_active_hugepage(struct page *page)
441131caf665SNaoya Horiguchi {
4412309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageHead(page), page);
441331caf665SNaoya Horiguchi 	spin_lock(&hugetlb_lock);
4414bcc54222SNaoya Horiguchi 	set_page_huge_active(page);
441531caf665SNaoya Horiguchi 	list_move_tail(&page->lru, &(page_hstate(page))->hugepage_activelist);
441631caf665SNaoya Horiguchi 	spin_unlock(&hugetlb_lock);
441731caf665SNaoya Horiguchi 	put_page(page);
441831caf665SNaoya Horiguchi }
4419