mglru: mm/vmscan.c: fix imprecise comments
[linux-block.git] / mm / hugetlb.c
CommitLineData
457c8996 1// SPDX-License-Identifier: GPL-2.0-only
1da177e4
LT
2/*
3 * Generic hugetlb support.
6d49e352 4 * (C) Nadia Yvette Chambers, April 2004
1da177e4 5 */
1da177e4
LT
6#include <linux/list.h>
7#include <linux/init.h>
1da177e4 8#include <linux/mm.h>
e1759c21 9#include <linux/seq_file.h>
1da177e4
LT
10#include <linux/sysctl.h>
11#include <linux/highmem.h>
cddb8a5c 12#include <linux/mmu_notifier.h>
1da177e4 13#include <linux/nodemask.h>
63551ae0 14#include <linux/pagemap.h>
5da7ca86 15#include <linux/mempolicy.h>
3b32123d 16#include <linux/compiler.h>
aea47ff3 17#include <linux/cpuset.h>
3935baa9 18#include <linux/mutex.h>
97ad1087 19#include <linux/memblock.h>
a3437870 20#include <linux/sysfs.h>
5a0e3ad6 21#include <linux/slab.h>
bbe88753 22#include <linux/sched/mm.h>
63489f8e 23#include <linux/mmdebug.h>
174cd4b1 24#include <linux/sched/signal.h>
0fe6e20b 25#include <linux/rmap.h>
c6247f72 26#include <linux/string_helpers.h>
fd6a03ed
NH
27#include <linux/swap.h>
28#include <linux/swapops.h>
8382d914 29#include <linux/jhash.h>
98fa15f3 30#include <linux/numa.h>
c77c0a8a 31#include <linux/llist.h>
cf11e85f 32#include <linux/cma.h>
8cc5fcbb 33#include <linux/migrate.h>
f9317f77 34#include <linux/nospec.h>
662ce1dc 35#include <linux/delayacct.h>
b958d4d0 36#include <linux/memory.h>
d6606683 37
63551ae0 38#include <asm/page.h>
ca15ca40 39#include <asm/pgalloc.h>
24669e58 40#include <asm/tlb.h>
63551ae0 41
24669e58 42#include <linux/io.h>
63551ae0 43#include <linux/hugetlb.h>
9dd540e2 44#include <linux/hugetlb_cgroup.h>
9a305230 45#include <linux/node.h>
ab5ac90a 46#include <linux/page_owner.h>
7835e98b 47#include "internal.h"
f41f2ed4 48#include "hugetlb_vmemmap.h"
1da177e4 49
c3f38a38 50int hugetlb_max_hstate __read_mostly;
e5ff2159
AK
51unsigned int default_hstate_idx;
52struct hstate hstates[HUGE_MAX_HSTATE];
cf11e85f 53
dbda8fea 54#ifdef CONFIG_CMA
cf11e85f 55static struct cma *hugetlb_cma[MAX_NUMNODES];
38e719ab 56static unsigned long hugetlb_cma_size_in_node[MAX_NUMNODES] __initdata;
a01f4390
MK
57static bool hugetlb_cma_page(struct page *page, unsigned int order)
58{
59 return cma_pages_valid(hugetlb_cma[page_to_nid(page)], page,
60 1 << order);
61}
62#else
63static bool hugetlb_cma_page(struct page *page, unsigned int order)
64{
65 return false;
66}
dbda8fea
BS
67#endif
68static unsigned long hugetlb_cma_size __initdata;
cf11e85f 69
53ba51d2
JT
70__initdata LIST_HEAD(huge_boot_pages);
71
e5ff2159
AK
72/* for command line parsing */
73static struct hstate * __initdata parsed_hstate;
74static unsigned long __initdata default_hstate_max_huge_pages;
9fee021d 75static bool __initdata parsed_valid_hugepagesz = true;
282f4214 76static bool __initdata parsed_default_hugepagesz;
b5389086 77static unsigned int default_hugepages_in_node[MAX_NUMNODES] __initdata;
e5ff2159 78
3935baa9 79/*
31caf665
NH
80 * Protects updates to hugepage_freelists, hugepage_activelist, nr_huge_pages,
81 * free_huge_pages, and surplus_huge_pages.
3935baa9 82 */
c3f38a38 83DEFINE_SPINLOCK(hugetlb_lock);
0bd0f9fb 84
8382d914
DB
85/*
86 * Serializes faults on the same logical page. This is used to
87 * prevent spurious OOMs when the hugepage pool is fully utilized.
88 */
89static int num_fault_mutexes;
c672c7f2 90struct mutex *hugetlb_fault_mutex_table ____cacheline_aligned_in_smp;
8382d914 91
7ca02d0a
MK
92/* Forward declaration */
93static int hugetlb_acct_memory(struct hstate *h, long delta);
8d9bfb26
MK
94static void hugetlb_vma_lock_free(struct vm_area_struct *vma);
95static void hugetlb_vma_lock_alloc(struct vm_area_struct *vma);
7ca02d0a 96
1d88433b 97static inline bool subpool_is_free(struct hugepage_subpool *spool)
90481622 98{
1d88433b
ML
99 if (spool->count)
100 return false;
101 if (spool->max_hpages != -1)
102 return spool->used_hpages == 0;
103 if (spool->min_hpages != -1)
104 return spool->rsv_hpages == spool->min_hpages;
105
106 return true;
107}
90481622 108
db71ef79
MK
109static inline void unlock_or_release_subpool(struct hugepage_subpool *spool,
110 unsigned long irq_flags)
1d88433b 111{
db71ef79 112 spin_unlock_irqrestore(&spool->lock, irq_flags);
90481622
DG
113
114 /* If no pages are used, and no other handles to the subpool
7c8de358 115 * remain, give up any reservations based on minimum size and
7ca02d0a 116 * free the subpool */
1d88433b 117 if (subpool_is_free(spool)) {
7ca02d0a
MK
118 if (spool->min_hpages != -1)
119 hugetlb_acct_memory(spool->hstate,
120 -spool->min_hpages);
90481622 121 kfree(spool);
7ca02d0a 122 }
90481622
DG
123}
124
7ca02d0a
MK
125struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages,
126 long min_hpages)
90481622
DG
127{
128 struct hugepage_subpool *spool;
129
c6a91820 130 spool = kzalloc(sizeof(*spool), GFP_KERNEL);
90481622
DG
131 if (!spool)
132 return NULL;
133
134 spin_lock_init(&spool->lock);
135 spool->count = 1;
7ca02d0a
MK
136 spool->max_hpages = max_hpages;
137 spool->hstate = h;
138 spool->min_hpages = min_hpages;
139
140 if (min_hpages != -1 && hugetlb_acct_memory(h, min_hpages)) {
141 kfree(spool);
142 return NULL;
143 }
144 spool->rsv_hpages = min_hpages;
90481622
DG
145
146 return spool;
147}
148
149void hugepage_put_subpool(struct hugepage_subpool *spool)
150{
db71ef79
MK
151 unsigned long flags;
152
153 spin_lock_irqsave(&spool->lock, flags);
90481622
DG
154 BUG_ON(!spool->count);
155 spool->count--;
db71ef79 156 unlock_or_release_subpool(spool, flags);
90481622
DG
157}
158
1c5ecae3
MK
159/*
160 * Subpool accounting for allocating and reserving pages.
161 * Return -ENOMEM if there are not enough resources to satisfy the
9e7ee400 162 * request. Otherwise, return the number of pages by which the
1c5ecae3
MK
163 * global pools must be adjusted (upward). The returned value may
164 * only be different than the passed value (delta) in the case where
7c8de358 165 * a subpool minimum size must be maintained.
1c5ecae3
MK
166 */
167static long hugepage_subpool_get_pages(struct hugepage_subpool *spool,
90481622
DG
168 long delta)
169{
1c5ecae3 170 long ret = delta;
90481622
DG
171
172 if (!spool)
1c5ecae3 173 return ret;
90481622 174
db71ef79 175 spin_lock_irq(&spool->lock);
1c5ecae3
MK
176
177 if (spool->max_hpages != -1) { /* maximum size accounting */
178 if ((spool->used_hpages + delta) <= spool->max_hpages)
179 spool->used_hpages += delta;
180 else {
181 ret = -ENOMEM;
182 goto unlock_ret;
183 }
90481622 184 }
90481622 185
09a95e29
MK
186 /* minimum size accounting */
187 if (spool->min_hpages != -1 && spool->rsv_hpages) {
1c5ecae3
MK
188 if (delta > spool->rsv_hpages) {
189 /*
190 * Asking for more reserves than those already taken on
191 * behalf of subpool. Return difference.
192 */
193 ret = delta - spool->rsv_hpages;
194 spool->rsv_hpages = 0;
195 } else {
196 ret = 0; /* reserves already accounted for */
197 spool->rsv_hpages -= delta;
198 }
199 }
200
201unlock_ret:
db71ef79 202 spin_unlock_irq(&spool->lock);
90481622
DG
203 return ret;
204}
205
1c5ecae3
MK
206/*
207 * Subpool accounting for freeing and unreserving pages.
208 * Return the number of global page reservations that must be dropped.
209 * The return value may only be different than the passed value (delta)
210 * in the case where a subpool minimum size must be maintained.
211 */
212static long hugepage_subpool_put_pages(struct hugepage_subpool *spool,
90481622
DG
213 long delta)
214{
1c5ecae3 215 long ret = delta;
db71ef79 216 unsigned long flags;
1c5ecae3 217
90481622 218 if (!spool)
1c5ecae3 219 return delta;
90481622 220
db71ef79 221 spin_lock_irqsave(&spool->lock, flags);
1c5ecae3
MK
222
223 if (spool->max_hpages != -1) /* maximum size accounting */
224 spool->used_hpages -= delta;
225
09a95e29
MK
226 /* minimum size accounting */
227 if (spool->min_hpages != -1 && spool->used_hpages < spool->min_hpages) {
1c5ecae3
MK
228 if (spool->rsv_hpages + delta <= spool->min_hpages)
229 ret = 0;
230 else
231 ret = spool->rsv_hpages + delta - spool->min_hpages;
232
233 spool->rsv_hpages += delta;
234 if (spool->rsv_hpages > spool->min_hpages)
235 spool->rsv_hpages = spool->min_hpages;
236 }
237
238 /*
239 * If hugetlbfs_put_super couldn't free spool due to an outstanding
240 * quota reference, free it now.
241 */
db71ef79 242 unlock_or_release_subpool(spool, flags);
1c5ecae3
MK
243
244 return ret;
90481622
DG
245}
246
247static inline struct hugepage_subpool *subpool_inode(struct inode *inode)
248{
249 return HUGETLBFS_SB(inode->i_sb)->spool;
250}
251
252static inline struct hugepage_subpool *subpool_vma(struct vm_area_struct *vma)
253{
496ad9aa 254 return subpool_inode(file_inode(vma->vm_file));
90481622
DG
255}
256
0db9d74e
MA
257/* Helper that removes a struct file_region from the resv_map cache and returns
258 * it for use.
259 */
260static struct file_region *
261get_file_region_entry_from_cache(struct resv_map *resv, long from, long to)
262{
3259914f 263 struct file_region *nrg;
0db9d74e
MA
264
265 VM_BUG_ON(resv->region_cache_count <= 0);
266
267 resv->region_cache_count--;
268 nrg = list_first_entry(&resv->region_cache, struct file_region, link);
0db9d74e
MA
269 list_del(&nrg->link);
270
271 nrg->from = from;
272 nrg->to = to;
273
274 return nrg;
275}
276
075a61d0
MA
277static void copy_hugetlb_cgroup_uncharge_info(struct file_region *nrg,
278 struct file_region *rg)
279{
280#ifdef CONFIG_CGROUP_HUGETLB
281 nrg->reservation_counter = rg->reservation_counter;
282 nrg->css = rg->css;
283 if (rg->css)
284 css_get(rg->css);
285#endif
286}
287
288/* Helper that records hugetlb_cgroup uncharge info. */
289static void record_hugetlb_cgroup_uncharge_info(struct hugetlb_cgroup *h_cg,
290 struct hstate *h,
291 struct resv_map *resv,
292 struct file_region *nrg)
293{
294#ifdef CONFIG_CGROUP_HUGETLB
295 if (h_cg) {
296 nrg->reservation_counter =
297 &h_cg->rsvd_hugepage[hstate_index(h)];
298 nrg->css = &h_cg->css;
d85aecf2
ML
299 /*
300 * The caller will hold exactly one h_cg->css reference for the
301 * whole contiguous reservation region. But this area might be
302 * scattered when there are already some file_regions reside in
303 * it. As a result, many file_regions may share only one css
304 * reference. In order to ensure that one file_region must hold
305 * exactly one h_cg->css reference, we should do css_get for
306 * each file_region and leave the reference held by caller
307 * untouched.
308 */
309 css_get(&h_cg->css);
075a61d0
MA
310 if (!resv->pages_per_hpage)
311 resv->pages_per_hpage = pages_per_huge_page(h);
312 /* pages_per_hpage should be the same for all entries in
313 * a resv_map.
314 */
315 VM_BUG_ON(resv->pages_per_hpage != pages_per_huge_page(h));
316 } else {
317 nrg->reservation_counter = NULL;
318 nrg->css = NULL;
319 }
320#endif
321}
322
d85aecf2
ML
323static void put_uncharge_info(struct file_region *rg)
324{
325#ifdef CONFIG_CGROUP_HUGETLB
326 if (rg->css)
327 css_put(rg->css);
328#endif
329}
330
a9b3f867
MA
331static bool has_same_uncharge_info(struct file_region *rg,
332 struct file_region *org)
333{
334#ifdef CONFIG_CGROUP_HUGETLB
0739eb43 335 return rg->reservation_counter == org->reservation_counter &&
a9b3f867
MA
336 rg->css == org->css;
337
338#else
339 return true;
340#endif
341}
342
343static void coalesce_file_region(struct resv_map *resv, struct file_region *rg)
344{
3259914f 345 struct file_region *nrg, *prg;
a9b3f867
MA
346
347 prg = list_prev_entry(rg, link);
348 if (&prg->link != &resv->regions && prg->to == rg->from &&
349 has_same_uncharge_info(prg, rg)) {
350 prg->to = rg->to;
351
352 list_del(&rg->link);
d85aecf2 353 put_uncharge_info(rg);
a9b3f867
MA
354 kfree(rg);
355
7db5e7b6 356 rg = prg;
a9b3f867
MA
357 }
358
359 nrg = list_next_entry(rg, link);
360 if (&nrg->link != &resv->regions && nrg->from == rg->to &&
361 has_same_uncharge_info(nrg, rg)) {
362 nrg->from = rg->from;
363
364 list_del(&rg->link);
d85aecf2 365 put_uncharge_info(rg);
a9b3f867 366 kfree(rg);
a9b3f867
MA
367 }
368}
369
2103cf9c 370static inline long
84448c8e 371hugetlb_resv_map_add(struct resv_map *map, struct list_head *rg, long from,
2103cf9c
PX
372 long to, struct hstate *h, struct hugetlb_cgroup *cg,
373 long *regions_needed)
374{
375 struct file_region *nrg;
376
377 if (!regions_needed) {
378 nrg = get_file_region_entry_from_cache(map, from, to);
379 record_hugetlb_cgroup_uncharge_info(cg, h, map, nrg);
84448c8e 380 list_add(&nrg->link, rg);
2103cf9c
PX
381 coalesce_file_region(map, nrg);
382 } else
383 *regions_needed += 1;
384
385 return to - from;
386}
387
972a3da3
WY
388/*
389 * Must be called with resv->lock held.
390 *
391 * Calling this with regions_needed != NULL will count the number of pages
392 * to be added but will not modify the linked list. And regions_needed will
393 * indicate the number of file_regions needed in the cache to carry out to add
394 * the regions for this range.
d75c6af9
MA
395 */
396static long add_reservation_in_range(struct resv_map *resv, long f, long t,
075a61d0 397 struct hugetlb_cgroup *h_cg,
972a3da3 398 struct hstate *h, long *regions_needed)
d75c6af9 399{
0db9d74e 400 long add = 0;
d75c6af9 401 struct list_head *head = &resv->regions;
0db9d74e 402 long last_accounted_offset = f;
84448c8e
JK
403 struct file_region *iter, *trg = NULL;
404 struct list_head *rg = NULL;
d75c6af9 405
0db9d74e
MA
406 if (regions_needed)
407 *regions_needed = 0;
d75c6af9 408
0db9d74e 409 /* In this loop, we essentially handle an entry for the range
84448c8e 410 * [last_accounted_offset, iter->from), at every iteration, with some
0db9d74e
MA
411 * bounds checking.
412 */
84448c8e 413 list_for_each_entry_safe(iter, trg, head, link) {
0db9d74e 414 /* Skip irrelevant regions that start before our range. */
84448c8e 415 if (iter->from < f) {
0db9d74e
MA
416 /* If this region ends after the last accounted offset,
417 * then we need to update last_accounted_offset.
418 */
84448c8e
JK
419 if (iter->to > last_accounted_offset)
420 last_accounted_offset = iter->to;
0db9d74e
MA
421 continue;
422 }
d75c6af9 423
0db9d74e
MA
424 /* When we find a region that starts beyond our range, we've
425 * finished.
426 */
84448c8e
JK
427 if (iter->from >= t) {
428 rg = iter->link.prev;
d75c6af9 429 break;
84448c8e 430 }
d75c6af9 431
84448c8e 432 /* Add an entry for last_accounted_offset -> iter->from, and
0db9d74e
MA
433 * update last_accounted_offset.
434 */
84448c8e
JK
435 if (iter->from > last_accounted_offset)
436 add += hugetlb_resv_map_add(resv, iter->link.prev,
2103cf9c 437 last_accounted_offset,
84448c8e 438 iter->from, h, h_cg,
2103cf9c 439 regions_needed);
0db9d74e 440
84448c8e 441 last_accounted_offset = iter->to;
0db9d74e
MA
442 }
443
444 /* Handle the case where our range extends beyond
445 * last_accounted_offset.
446 */
84448c8e
JK
447 if (!rg)
448 rg = head->prev;
2103cf9c
PX
449 if (last_accounted_offset < t)
450 add += hugetlb_resv_map_add(resv, rg, last_accounted_offset,
451 t, h, h_cg, regions_needed);
0db9d74e 452
0db9d74e
MA
453 return add;
454}
455
456/* Must be called with resv->lock acquired. Will drop lock to allocate entries.
457 */
458static int allocate_file_region_entries(struct resv_map *resv,
459 int regions_needed)
460 __must_hold(&resv->lock)
461{
34665341 462 LIST_HEAD(allocated_regions);
0db9d74e
MA
463 int to_allocate = 0, i = 0;
464 struct file_region *trg = NULL, *rg = NULL;
465
466 VM_BUG_ON(regions_needed < 0);
467
0db9d74e
MA
468 /*
469 * Check for sufficient descriptors in the cache to accommodate
470 * the number of in progress add operations plus regions_needed.
471 *
472 * This is a while loop because when we drop the lock, some other call
473 * to region_add or region_del may have consumed some region_entries,
474 * so we keep looping here until we finally have enough entries for
475 * (adds_in_progress + regions_needed).
476 */
477 while (resv->region_cache_count <
478 (resv->adds_in_progress + regions_needed)) {
479 to_allocate = resv->adds_in_progress + regions_needed -
480 resv->region_cache_count;
481
482 /* At this point, we should have enough entries in the cache
f0953a1b 483 * for all the existing adds_in_progress. We should only be
0db9d74e 484 * needing to allocate for regions_needed.
d75c6af9 485 */
0db9d74e
MA
486 VM_BUG_ON(resv->region_cache_count < resv->adds_in_progress);
487
488 spin_unlock(&resv->lock);
489 for (i = 0; i < to_allocate; i++) {
490 trg = kmalloc(sizeof(*trg), GFP_KERNEL);
491 if (!trg)
492 goto out_of_memory;
493 list_add(&trg->link, &allocated_regions);
d75c6af9 494 }
d75c6af9 495
0db9d74e
MA
496 spin_lock(&resv->lock);
497
d3ec7b6e
WY
498 list_splice(&allocated_regions, &resv->region_cache);
499 resv->region_cache_count += to_allocate;
d75c6af9
MA
500 }
501
0db9d74e 502 return 0;
d75c6af9 503
0db9d74e
MA
504out_of_memory:
505 list_for_each_entry_safe(rg, trg, &allocated_regions, link) {
506 list_del(&rg->link);
507 kfree(rg);
508 }
509 return -ENOMEM;
d75c6af9
MA
510}
511
1dd308a7
MK
512/*
513 * Add the huge page range represented by [f, t) to the reserve
0db9d74e
MA
514 * map. Regions will be taken from the cache to fill in this range.
515 * Sufficient regions should exist in the cache due to the previous
516 * call to region_chg with the same range, but in some cases the cache will not
517 * have sufficient entries due to races with other code doing region_add or
518 * region_del. The extra needed entries will be allocated.
cf3ad20b 519 *
0db9d74e
MA
520 * regions_needed is the out value provided by a previous call to region_chg.
521 *
522 * Return the number of new huge pages added to the map. This number is greater
523 * than or equal to zero. If file_region entries needed to be allocated for
7c8de358 524 * this operation and we were not able to allocate, it returns -ENOMEM.
0db9d74e
MA
525 * region_add of regions of length 1 never allocate file_regions and cannot
526 * fail; region_chg will always allocate at least 1 entry and a region_add for
527 * 1 page will only require at most 1 entry.
1dd308a7 528 */
0db9d74e 529static long region_add(struct resv_map *resv, long f, long t,
075a61d0
MA
530 long in_regions_needed, struct hstate *h,
531 struct hugetlb_cgroup *h_cg)
96822904 532{
0db9d74e 533 long add = 0, actual_regions_needed = 0;
96822904 534
7b24d861 535 spin_lock(&resv->lock);
0db9d74e
MA
536retry:
537
538 /* Count how many regions are actually needed to execute this add. */
972a3da3
WY
539 add_reservation_in_range(resv, f, t, NULL, NULL,
540 &actual_regions_needed);
96822904 541
5e911373 542 /*
0db9d74e
MA
543 * Check for sufficient descriptors in the cache to accommodate
544 * this add operation. Note that actual_regions_needed may be greater
545 * than in_regions_needed, as the resv_map may have been modified since
546 * the region_chg call. In this case, we need to make sure that we
547 * allocate extra entries, such that we have enough for all the
548 * existing adds_in_progress, plus the excess needed for this
549 * operation.
5e911373 550 */
0db9d74e
MA
551 if (actual_regions_needed > in_regions_needed &&
552 resv->region_cache_count <
553 resv->adds_in_progress +
554 (actual_regions_needed - in_regions_needed)) {
555 /* region_add operation of range 1 should never need to
556 * allocate file_region entries.
557 */
558 VM_BUG_ON(t - f <= 1);
5e911373 559
0db9d74e
MA
560 if (allocate_file_region_entries(
561 resv, actual_regions_needed - in_regions_needed)) {
562 return -ENOMEM;
563 }
5e911373 564
0db9d74e 565 goto retry;
5e911373
MK
566 }
567
972a3da3 568 add = add_reservation_in_range(resv, f, t, h_cg, h, NULL);
0db9d74e
MA
569
570 resv->adds_in_progress -= in_regions_needed;
cf3ad20b 571
7b24d861 572 spin_unlock(&resv->lock);
cf3ad20b 573 return add;
96822904
AW
574}
575
1dd308a7
MK
576/*
577 * Examine the existing reserve map and determine how many
578 * huge pages in the specified range [f, t) are NOT currently
579 * represented. This routine is called before a subsequent
580 * call to region_add that will actually modify the reserve
581 * map to add the specified range [f, t). region_chg does
582 * not change the number of huge pages represented by the
0db9d74e
MA
583 * map. A number of new file_region structures is added to the cache as a
584 * placeholder, for the subsequent region_add call to use. At least 1
585 * file_region structure is added.
586 *
587 * out_regions_needed is the number of regions added to the
588 * resv->adds_in_progress. This value needs to be provided to a follow up call
589 * to region_add or region_abort for proper accounting.
5e911373
MK
590 *
591 * Returns the number of huge pages that need to be added to the existing
592 * reservation map for the range [f, t). This number is greater or equal to
593 * zero. -ENOMEM is returned if a new file_region structure or cache entry
594 * is needed and can not be allocated.
1dd308a7 595 */
0db9d74e
MA
596static long region_chg(struct resv_map *resv, long f, long t,
597 long *out_regions_needed)
96822904 598{
96822904
AW
599 long chg = 0;
600
7b24d861 601 spin_lock(&resv->lock);
5e911373 602
972a3da3 603 /* Count how many hugepages in this range are NOT represented. */
075a61d0 604 chg = add_reservation_in_range(resv, f, t, NULL, NULL,
972a3da3 605 out_regions_needed);
5e911373 606
0db9d74e
MA
607 if (*out_regions_needed == 0)
608 *out_regions_needed = 1;
5e911373 609
0db9d74e
MA
610 if (allocate_file_region_entries(resv, *out_regions_needed))
611 return -ENOMEM;
5e911373 612
0db9d74e 613 resv->adds_in_progress += *out_regions_needed;
7b24d861 614
7b24d861 615 spin_unlock(&resv->lock);
96822904
AW
616 return chg;
617}
618
5e911373
MK
619/*
620 * Abort the in progress add operation. The adds_in_progress field
621 * of the resv_map keeps track of the operations in progress between
622 * calls to region_chg and region_add. Operations are sometimes
623 * aborted after the call to region_chg. In such cases, region_abort
0db9d74e
MA
624 * is called to decrement the adds_in_progress counter. regions_needed
625 * is the value returned by the region_chg call, it is used to decrement
626 * the adds_in_progress counter.
5e911373
MK
627 *
628 * NOTE: The range arguments [f, t) are not needed or used in this
629 * routine. They are kept to make reading the calling code easier as
630 * arguments will match the associated region_chg call.
631 */
0db9d74e
MA
632static void region_abort(struct resv_map *resv, long f, long t,
633 long regions_needed)
5e911373
MK
634{
635 spin_lock(&resv->lock);
636 VM_BUG_ON(!resv->region_cache_count);
0db9d74e 637 resv->adds_in_progress -= regions_needed;
5e911373
MK
638 spin_unlock(&resv->lock);
639}
640
1dd308a7 641/*
feba16e2
MK
642 * Delete the specified range [f, t) from the reserve map. If the
643 * t parameter is LONG_MAX, this indicates that ALL regions after f
644 * should be deleted. Locate the regions which intersect [f, t)
645 * and either trim, delete or split the existing regions.
646 *
647 * Returns the number of huge pages deleted from the reserve map.
648 * In the normal case, the return value is zero or more. In the
649 * case where a region must be split, a new region descriptor must
650 * be allocated. If the allocation fails, -ENOMEM will be returned.
651 * NOTE: If the parameter t == LONG_MAX, then we will never split
652 * a region and possibly return -ENOMEM. Callers specifying
653 * t == LONG_MAX do not need to check for -ENOMEM error.
1dd308a7 654 */
feba16e2 655static long region_del(struct resv_map *resv, long f, long t)
96822904 656{
1406ec9b 657 struct list_head *head = &resv->regions;
96822904 658 struct file_region *rg, *trg;
feba16e2
MK
659 struct file_region *nrg = NULL;
660 long del = 0;
96822904 661
feba16e2 662retry:
7b24d861 663 spin_lock(&resv->lock);
feba16e2 664 list_for_each_entry_safe(rg, trg, head, link) {
dbe409e4
MK
665 /*
666 * Skip regions before the range to be deleted. file_region
667 * ranges are normally of the form [from, to). However, there
668 * may be a "placeholder" entry in the map which is of the form
669 * (from, to) with from == to. Check for placeholder entries
670 * at the beginning of the range to be deleted.
671 */
672 if (rg->to <= f && (rg->to != rg->from || rg->to != f))
feba16e2 673 continue;
dbe409e4 674
feba16e2 675 if (rg->from >= t)
96822904 676 break;
96822904 677
feba16e2
MK
678 if (f > rg->from && t < rg->to) { /* Must split region */
679 /*
680 * Check for an entry in the cache before dropping
681 * lock and attempting allocation.
682 */
683 if (!nrg &&
684 resv->region_cache_count > resv->adds_in_progress) {
685 nrg = list_first_entry(&resv->region_cache,
686 struct file_region,
687 link);
688 list_del(&nrg->link);
689 resv->region_cache_count--;
690 }
96822904 691
feba16e2
MK
692 if (!nrg) {
693 spin_unlock(&resv->lock);
694 nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
695 if (!nrg)
696 return -ENOMEM;
697 goto retry;
698 }
699
700 del += t - f;
79aa925b 701 hugetlb_cgroup_uncharge_file_region(
d85aecf2 702 resv, rg, t - f, false);
feba16e2
MK
703
704 /* New entry for end of split region */
705 nrg->from = t;
706 nrg->to = rg->to;
075a61d0
MA
707
708 copy_hugetlb_cgroup_uncharge_info(nrg, rg);
709
feba16e2
MK
710 INIT_LIST_HEAD(&nrg->link);
711
712 /* Original entry is trimmed */
713 rg->to = f;
714
715 list_add(&nrg->link, &rg->link);
716 nrg = NULL;
96822904 717 break;
feba16e2
MK
718 }
719
720 if (f <= rg->from && t >= rg->to) { /* Remove entire region */
721 del += rg->to - rg->from;
075a61d0 722 hugetlb_cgroup_uncharge_file_region(resv, rg,
d85aecf2 723 rg->to - rg->from, true);
feba16e2
MK
724 list_del(&rg->link);
725 kfree(rg);
726 continue;
727 }
728
729 if (f <= rg->from) { /* Trim beginning of region */
075a61d0 730 hugetlb_cgroup_uncharge_file_region(resv, rg,
d85aecf2 731 t - rg->from, false);
075a61d0 732
79aa925b
MK
733 del += t - rg->from;
734 rg->from = t;
735 } else { /* Trim end of region */
075a61d0 736 hugetlb_cgroup_uncharge_file_region(resv, rg,
d85aecf2 737 rg->to - f, false);
79aa925b
MK
738
739 del += rg->to - f;
740 rg->to = f;
feba16e2 741 }
96822904 742 }
7b24d861 743
7b24d861 744 spin_unlock(&resv->lock);
feba16e2
MK
745 kfree(nrg);
746 return del;
96822904
AW
747}
748
b5cec28d
MK
749/*
750 * A rare out of memory error was encountered which prevented removal of
751 * the reserve map region for a page. The huge page itself was free'ed
752 * and removed from the page cache. This routine will adjust the subpool
753 * usage count, and the global reserve count if needed. By incrementing
754 * these counts, the reserve map entry which could not be deleted will
755 * appear as a "reserved" entry instead of simply dangling with incorrect
756 * counts.
757 */
72e2936c 758void hugetlb_fix_reserve_counts(struct inode *inode)
b5cec28d
MK
759{
760 struct hugepage_subpool *spool = subpool_inode(inode);
761 long rsv_adjust;
da56388c 762 bool reserved = false;
b5cec28d
MK
763
764 rsv_adjust = hugepage_subpool_get_pages(spool, 1);
da56388c 765 if (rsv_adjust > 0) {
b5cec28d
MK
766 struct hstate *h = hstate_inode(inode);
767
da56388c
ML
768 if (!hugetlb_acct_memory(h, 1))
769 reserved = true;
770 } else if (!rsv_adjust) {
771 reserved = true;
b5cec28d 772 }
da56388c
ML
773
774 if (!reserved)
775 pr_warn("hugetlb: Huge Page Reserved count may go negative.\n");
b5cec28d
MK
776}
777
1dd308a7
MK
778/*
779 * Count and return the number of huge pages in the reserve map
780 * that intersect with the range [f, t).
781 */
1406ec9b 782static long region_count(struct resv_map *resv, long f, long t)
84afd99b 783{
1406ec9b 784 struct list_head *head = &resv->regions;
84afd99b
AW
785 struct file_region *rg;
786 long chg = 0;
787
7b24d861 788 spin_lock(&resv->lock);
84afd99b
AW
789 /* Locate each segment we overlap with, and count that overlap. */
790 list_for_each_entry(rg, head, link) {
f2135a4a
WSH
791 long seg_from;
792 long seg_to;
84afd99b
AW
793
794 if (rg->to <= f)
795 continue;
796 if (rg->from >= t)
797 break;
798
799 seg_from = max(rg->from, f);
800 seg_to = min(rg->to, t);
801
802 chg += seg_to - seg_from;
803 }
7b24d861 804 spin_unlock(&resv->lock);
84afd99b
AW
805
806 return chg;
807}
808
e7c4b0bf
AW
809/*
810 * Convert the address within this vma to the page offset within
811 * the mapping, in pagecache page units; huge pages here.
812 */
a5516438
AK
813static pgoff_t vma_hugecache_offset(struct hstate *h,
814 struct vm_area_struct *vma, unsigned long address)
e7c4b0bf 815{
a5516438
AK
816 return ((address - vma->vm_start) >> huge_page_shift(h)) +
817 (vma->vm_pgoff >> huge_page_order(h));
e7c4b0bf
AW
818}
819
0fe6e20b
NH
820pgoff_t linear_hugepage_index(struct vm_area_struct *vma,
821 unsigned long address)
822{
823 return vma_hugecache_offset(hstate_vma(vma), vma, address);
824}
dee41079 825EXPORT_SYMBOL_GPL(linear_hugepage_index);
0fe6e20b 826
08fba699
MG
827/*
828 * Return the size of the pages allocated when backing a VMA. In the majority
829 * cases this will be same size as used by the page table entries.
830 */
831unsigned long vma_kernel_pagesize(struct vm_area_struct *vma)
832{
05ea8860
DW
833 if (vma->vm_ops && vma->vm_ops->pagesize)
834 return vma->vm_ops->pagesize(vma);
835 return PAGE_SIZE;
08fba699 836}
f340ca0f 837EXPORT_SYMBOL_GPL(vma_kernel_pagesize);
08fba699 838
3340289d
MG
839/*
840 * Return the page size being used by the MMU to back a VMA. In the majority
841 * of cases, the page size used by the kernel matches the MMU size. On
09135cc5
DW
842 * architectures where it differs, an architecture-specific 'strong'
843 * version of this symbol is required.
3340289d 844 */
09135cc5 845__weak unsigned long vma_mmu_pagesize(struct vm_area_struct *vma)
3340289d
MG
846{
847 return vma_kernel_pagesize(vma);
848}
3340289d 849
84afd99b
AW
850/*
851 * Flags for MAP_PRIVATE reservations. These are stored in the bottom
852 * bits of the reservation map pointer, which are always clear due to
853 * alignment.
854 */
855#define HPAGE_RESV_OWNER (1UL << 0)
856#define HPAGE_RESV_UNMAPPED (1UL << 1)
04f2cbe3 857#define HPAGE_RESV_MASK (HPAGE_RESV_OWNER | HPAGE_RESV_UNMAPPED)
84afd99b 858
a1e78772
MG
859/*
860 * These helpers are used to track how many pages are reserved for
861 * faults in a MAP_PRIVATE mapping. Only the process that called mmap()
862 * is guaranteed to have their future faults succeed.
863 *
8d9bfb26 864 * With the exception of hugetlb_dup_vma_private() which is called at fork(),
a1e78772
MG
865 * the reserve counters are updated with the hugetlb_lock held. It is safe
866 * to reset the VMA at fork() time as it is not in use yet and there is no
867 * chance of the global counters getting corrupted as a result of the values.
84afd99b
AW
868 *
869 * The private mapping reservation is represented in a subtly different
870 * manner to a shared mapping. A shared mapping has a region map associated
871 * with the underlying file, this region map represents the backing file
872 * pages which have ever had a reservation assigned which this persists even
873 * after the page is instantiated. A private mapping has a region map
874 * associated with the original mmap which is attached to all VMAs which
875 * reference it, this region map represents those offsets which have consumed
876 * reservation ie. where pages have been instantiated.
a1e78772 877 */
e7c4b0bf
AW
878static unsigned long get_vma_private_data(struct vm_area_struct *vma)
879{
880 return (unsigned long)vma->vm_private_data;
881}
882
883static void set_vma_private_data(struct vm_area_struct *vma,
884 unsigned long value)
885{
886 vma->vm_private_data = (void *)value;
887}
888
e9fe92ae
MA
889static void
890resv_map_set_hugetlb_cgroup_uncharge_info(struct resv_map *resv_map,
891 struct hugetlb_cgroup *h_cg,
892 struct hstate *h)
893{
894#ifdef CONFIG_CGROUP_HUGETLB
895 if (!h_cg || !h) {
896 resv_map->reservation_counter = NULL;
897 resv_map->pages_per_hpage = 0;
898 resv_map->css = NULL;
899 } else {
900 resv_map->reservation_counter =
901 &h_cg->rsvd_hugepage[hstate_index(h)];
902 resv_map->pages_per_hpage = pages_per_huge_page(h);
903 resv_map->css = &h_cg->css;
904 }
905#endif
906}
907
9119a41e 908struct resv_map *resv_map_alloc(void)
84afd99b
AW
909{
910 struct resv_map *resv_map = kmalloc(sizeof(*resv_map), GFP_KERNEL);
5e911373
MK
911 struct file_region *rg = kmalloc(sizeof(*rg), GFP_KERNEL);
912
913 if (!resv_map || !rg) {
914 kfree(resv_map);
915 kfree(rg);
84afd99b 916 return NULL;
5e911373 917 }
84afd99b
AW
918
919 kref_init(&resv_map->refs);
7b24d861 920 spin_lock_init(&resv_map->lock);
84afd99b
AW
921 INIT_LIST_HEAD(&resv_map->regions);
922
5e911373 923 resv_map->adds_in_progress = 0;
e9fe92ae
MA
924 /*
925 * Initialize these to 0. On shared mappings, 0's here indicate these
926 * fields don't do cgroup accounting. On private mappings, these will be
927 * re-initialized to the proper values, to indicate that hugetlb cgroup
928 * reservations are to be un-charged from here.
929 */
930 resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, NULL, NULL);
5e911373
MK
931
932 INIT_LIST_HEAD(&resv_map->region_cache);
933 list_add(&rg->link, &resv_map->region_cache);
934 resv_map->region_cache_count = 1;
935
84afd99b
AW
936 return resv_map;
937}
938
9119a41e 939void resv_map_release(struct kref *ref)
84afd99b
AW
940{
941 struct resv_map *resv_map = container_of(ref, struct resv_map, refs);
5e911373
MK
942 struct list_head *head = &resv_map->region_cache;
943 struct file_region *rg, *trg;
84afd99b
AW
944
945 /* Clear out any active regions before we release the map. */
feba16e2 946 region_del(resv_map, 0, LONG_MAX);
5e911373
MK
947
948 /* ... and any entries left in the cache */
949 list_for_each_entry_safe(rg, trg, head, link) {
950 list_del(&rg->link);
951 kfree(rg);
952 }
953
954 VM_BUG_ON(resv_map->adds_in_progress);
955
84afd99b
AW
956 kfree(resv_map);
957}
958
4e35f483
JK
959static inline struct resv_map *inode_resv_map(struct inode *inode)
960{
f27a5136
MK
961 /*
962 * At inode evict time, i_mapping may not point to the original
963 * address space within the inode. This original address space
964 * contains the pointer to the resv_map. So, always use the
965 * address space embedded within the inode.
966 * The VERY common case is inode->mapping == &inode->i_data but,
967 * this may not be true for device special inodes.
968 */
969 return (struct resv_map *)(&inode->i_data)->private_data;
4e35f483
JK
970}
971
84afd99b 972static struct resv_map *vma_resv_map(struct vm_area_struct *vma)
a1e78772 973{
81d1b09c 974 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
4e35f483
JK
975 if (vma->vm_flags & VM_MAYSHARE) {
976 struct address_space *mapping = vma->vm_file->f_mapping;
977 struct inode *inode = mapping->host;
978
979 return inode_resv_map(inode);
980
981 } else {
84afd99b
AW
982 return (struct resv_map *)(get_vma_private_data(vma) &
983 ~HPAGE_RESV_MASK);
4e35f483 984 }
a1e78772
MG
985}
986
84afd99b 987static void set_vma_resv_map(struct vm_area_struct *vma, struct resv_map *map)
a1e78772 988{
81d1b09c
SL
989 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
990 VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
a1e78772 991
84afd99b
AW
992 set_vma_private_data(vma, (get_vma_private_data(vma) &
993 HPAGE_RESV_MASK) | (unsigned long)map);
04f2cbe3
MG
994}
995
996static void set_vma_resv_flags(struct vm_area_struct *vma, unsigned long flags)
997{
81d1b09c
SL
998 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
999 VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
e7c4b0bf
AW
1000
1001 set_vma_private_data(vma, get_vma_private_data(vma) | flags);
04f2cbe3
MG
1002}
1003
1004static int is_vma_resv_set(struct vm_area_struct *vma, unsigned long flag)
1005{
81d1b09c 1006 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
e7c4b0bf
AW
1007
1008 return (get_vma_private_data(vma) & flag) != 0;
a1e78772
MG
1009}
1010
8d9bfb26 1011void hugetlb_dup_vma_private(struct vm_area_struct *vma)
a1e78772 1012{
81d1b09c 1013 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
8d9bfb26
MK
1014 /*
1015 * Clear vm_private_data
1016 * - For MAP_PRIVATE mappings, this is the reserve map which does
1017 * not apply to children. Faults generated by the children are
1018 * not guaranteed to succeed, even if read-only.
1019 * - For shared mappings this is a per-vma semaphore that may be
1020 * allocated in a subsequent call to hugetlb_vm_op_open.
1021 */
1022 vma->vm_private_data = (void *)0;
f83a275d 1023 if (!(vma->vm_flags & VM_MAYSHARE))
8d9bfb26 1024 return;
a1e78772
MG
1025}
1026
550a7d60
MA
1027/*
1028 * Reset and decrement one ref on hugepage private reservation.
1029 * Called with mm->mmap_sem writer semaphore held.
1030 * This function should be only used by move_vma() and operate on
1031 * same sized vma. It should never come here with last ref on the
1032 * reservation.
1033 */
1034void clear_vma_resv_huge_pages(struct vm_area_struct *vma)
1035{
1036 /*
1037 * Clear the old hugetlb private page reservation.
1038 * It has already been transferred to new_vma.
1039 *
1040 * During a mremap() operation of a hugetlb vma we call move_vma()
1041 * which copies vma into new_vma and unmaps vma. After the copy
1042 * operation both new_vma and vma share a reference to the resv_map
1043 * struct, and at that point vma is about to be unmapped. We don't
1044 * want to return the reservation to the pool at unmap of vma because
1045 * the reservation still lives on in new_vma, so simply decrement the
1046 * ref here and remove the resv_map reference from this vma.
1047 */
1048 struct resv_map *reservations = vma_resv_map(vma);
1049
afe041c2
BQM
1050 if (reservations && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
1051 resv_map_put_hugetlb_cgroup_uncharge_info(reservations);
550a7d60 1052 kref_put(&reservations->refs, resv_map_release);
afe041c2 1053 }
550a7d60 1054
8d9bfb26 1055 hugetlb_dup_vma_private(vma);
550a7d60
MA
1056}
1057
a1e78772 1058/* Returns true if the VMA has associated reserve pages */
559ec2f8 1059static bool vma_has_reserves(struct vm_area_struct *vma, long chg)
a1e78772 1060{
af0ed73e
JK
1061 if (vma->vm_flags & VM_NORESERVE) {
1062 /*
1063 * This address is already reserved by other process(chg == 0),
1064 * so, we should decrement reserved count. Without decrementing,
1065 * reserve count remains after releasing inode, because this
1066 * allocated page will go into page cache and is regarded as
1067 * coming from reserved pool in releasing step. Currently, we
1068 * don't have any other solution to deal with this situation
1069 * properly, so add work-around here.
1070 */
1071 if (vma->vm_flags & VM_MAYSHARE && chg == 0)
559ec2f8 1072 return true;
af0ed73e 1073 else
559ec2f8 1074 return false;
af0ed73e 1075 }
a63884e9
JK
1076
1077 /* Shared mappings always use reserves */
1fb1b0e9
MK
1078 if (vma->vm_flags & VM_MAYSHARE) {
1079 /*
1080 * We know VM_NORESERVE is not set. Therefore, there SHOULD
1081 * be a region map for all pages. The only situation where
1082 * there is no region map is if a hole was punched via
7c8de358 1083 * fallocate. In this case, there really are no reserves to
1fb1b0e9
MK
1084 * use. This situation is indicated if chg != 0.
1085 */
1086 if (chg)
1087 return false;
1088 else
1089 return true;
1090 }
a63884e9
JK
1091
1092 /*
1093 * Only the process that called mmap() has reserves for
1094 * private mappings.
1095 */
67961f9d
MK
1096 if (is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
1097 /*
1098 * Like the shared case above, a hole punch or truncate
1099 * could have been performed on the private mapping.
1100 * Examine the value of chg to determine if reserves
1101 * actually exist or were previously consumed.
1102 * Very Subtle - The value of chg comes from a previous
1103 * call to vma_needs_reserves(). The reserve map for
1104 * private mappings has different (opposite) semantics
1105 * than that of shared mappings. vma_needs_reserves()
1106 * has already taken this difference in semantics into
1107 * account. Therefore, the meaning of chg is the same
1108 * as in the shared case above. Code could easily be
1109 * combined, but keeping it separate draws attention to
1110 * subtle differences.
1111 */
1112 if (chg)
1113 return false;
1114 else
1115 return true;
1116 }
a63884e9 1117
559ec2f8 1118 return false;
a1e78772
MG
1119}
1120
a5516438 1121static void enqueue_huge_page(struct hstate *h, struct page *page)
1da177e4
LT
1122{
1123 int nid = page_to_nid(page);
9487ca60
MK
1124
1125 lockdep_assert_held(&hugetlb_lock);
b65a4eda
MK
1126 VM_BUG_ON_PAGE(page_count(page), page);
1127
0edaecfa 1128 list_move(&page->lru, &h->hugepage_freelists[nid]);
a5516438
AK
1129 h->free_huge_pages++;
1130 h->free_huge_pages_node[nid]++;
6c037149 1131 SetHPageFreed(page);
1da177e4
LT
1132}
1133
94310cbc 1134static struct page *dequeue_huge_page_node_exact(struct hstate *h, int nid)
bf50bab2
NH
1135{
1136 struct page *page;
1a08ae36 1137 bool pin = !!(current->flags & PF_MEMALLOC_PIN);
bbe88753 1138
9487ca60 1139 lockdep_assert_held(&hugetlb_lock);
bbe88753 1140 list_for_each_entry(page, &h->hugepage_freelists[nid], lru) {
6077c943 1141 if (pin && !is_longterm_pinnable_page(page))
bbe88753 1142 continue;
bf50bab2 1143
6664bfc8
WY
1144 if (PageHWPoison(page))
1145 continue;
1146
1147 list_move(&page->lru, &h->hugepage_activelist);
1148 set_page_refcounted(page);
6c037149 1149 ClearHPageFreed(page);
6664bfc8
WY
1150 h->free_huge_pages--;
1151 h->free_huge_pages_node[nid]--;
1152 return page;
bbe88753
JK
1153 }
1154
6664bfc8 1155 return NULL;
bf50bab2
NH
1156}
1157
3e59fcb0
MH
1158static struct page *dequeue_huge_page_nodemask(struct hstate *h, gfp_t gfp_mask, int nid,
1159 nodemask_t *nmask)
94310cbc 1160{
3e59fcb0
MH
1161 unsigned int cpuset_mems_cookie;
1162 struct zonelist *zonelist;
1163 struct zone *zone;
1164 struct zoneref *z;
98fa15f3 1165 int node = NUMA_NO_NODE;
94310cbc 1166
3e59fcb0
MH
1167 zonelist = node_zonelist(nid, gfp_mask);
1168
1169retry_cpuset:
1170 cpuset_mems_cookie = read_mems_allowed_begin();
1171 for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nmask) {
1172 struct page *page;
1173
1174 if (!cpuset_zone_allowed(zone, gfp_mask))
1175 continue;
1176 /*
1177 * no need to ask again on the same node. Pool is node rather than
1178 * zone aware
1179 */
1180 if (zone_to_nid(zone) == node)
1181 continue;
1182 node = zone_to_nid(zone);
94310cbc 1183
94310cbc
AK
1184 page = dequeue_huge_page_node_exact(h, node);
1185 if (page)
1186 return page;
1187 }
3e59fcb0
MH
1188 if (unlikely(read_mems_allowed_retry(cpuset_mems_cookie)))
1189 goto retry_cpuset;
1190
94310cbc
AK
1191 return NULL;
1192}
1193
8346d69d
XH
1194static unsigned long available_huge_pages(struct hstate *h)
1195{
1196 return h->free_huge_pages - h->resv_huge_pages;
1197}
1198
a5516438
AK
1199static struct page *dequeue_huge_page_vma(struct hstate *h,
1200 struct vm_area_struct *vma,
af0ed73e
JK
1201 unsigned long address, int avoid_reserve,
1202 long chg)
1da177e4 1203{
cfcaa66f 1204 struct page *page = NULL;
480eccf9 1205 struct mempolicy *mpol;
04ec6264 1206 gfp_t gfp_mask;
3e59fcb0 1207 nodemask_t *nodemask;
04ec6264 1208 int nid;
1da177e4 1209
a1e78772
MG
1210 /*
1211 * A child process with MAP_PRIVATE mappings created by their parent
1212 * have no page reserves. This check ensures that reservations are
1213 * not "stolen". The child may still get SIGKILLed
1214 */
8346d69d 1215 if (!vma_has_reserves(vma, chg) && !available_huge_pages(h))
c0ff7453 1216 goto err;
a1e78772 1217
04f2cbe3 1218 /* If reserves cannot be used, ensure enough pages are in the pool */
8346d69d 1219 if (avoid_reserve && !available_huge_pages(h))
6eab04a8 1220 goto err;
04f2cbe3 1221
04ec6264
VB
1222 gfp_mask = htlb_alloc_mask(h);
1223 nid = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
cfcaa66f
BW
1224
1225 if (mpol_is_preferred_many(mpol)) {
1226 page = dequeue_huge_page_nodemask(h, gfp_mask, nid, nodemask);
1227
1228 /* Fallback to all nodes if page==NULL */
1229 nodemask = NULL;
1230 }
1231
1232 if (!page)
1233 page = dequeue_huge_page_nodemask(h, gfp_mask, nid, nodemask);
1234
3e59fcb0 1235 if (page && !avoid_reserve && vma_has_reserves(vma, chg)) {
d6995da3 1236 SetHPageRestoreReserve(page);
3e59fcb0 1237 h->resv_huge_pages--;
1da177e4 1238 }
cc9a6c87 1239
52cd3b07 1240 mpol_cond_put(mpol);
1da177e4 1241 return page;
cc9a6c87
MG
1242
1243err:
cc9a6c87 1244 return NULL;
1da177e4
LT
1245}
1246
1cac6f2c
LC
1247/*
1248 * common helper functions for hstate_next_node_to_{alloc|free}.
1249 * We may have allocated or freed a huge page based on a different
1250 * nodes_allowed previously, so h->next_node_to_{alloc|free} might
1251 * be outside of *nodes_allowed. Ensure that we use an allowed
1252 * node for alloc or free.
1253 */
1254static int next_node_allowed(int nid, nodemask_t *nodes_allowed)
1255{
0edaf86c 1256 nid = next_node_in(nid, *nodes_allowed);
1cac6f2c
LC
1257 VM_BUG_ON(nid >= MAX_NUMNODES);
1258
1259 return nid;
1260}
1261
1262static int get_valid_node_allowed(int nid, nodemask_t *nodes_allowed)
1263{
1264 if (!node_isset(nid, *nodes_allowed))
1265 nid = next_node_allowed(nid, nodes_allowed);
1266 return nid;
1267}
1268
1269/*
1270 * returns the previously saved node ["this node"] from which to
1271 * allocate a persistent huge page for the pool and advance the
1272 * next node from which to allocate, handling wrap at end of node
1273 * mask.
1274 */
1275static int hstate_next_node_to_alloc(struct hstate *h,
1276 nodemask_t *nodes_allowed)
1277{
1278 int nid;
1279
1280 VM_BUG_ON(!nodes_allowed);
1281
1282 nid = get_valid_node_allowed(h->next_nid_to_alloc, nodes_allowed);
1283 h->next_nid_to_alloc = next_node_allowed(nid, nodes_allowed);
1284
1285 return nid;
1286}
1287
1288/*
10c6ec49 1289 * helper for remove_pool_huge_page() - return the previously saved
1cac6f2c
LC
1290 * node ["this node"] from which to free a huge page. Advance the
1291 * next node id whether or not we find a free huge page to free so
1292 * that the next attempt to free addresses the next node.
1293 */
1294static int hstate_next_node_to_free(struct hstate *h, nodemask_t *nodes_allowed)
1295{
1296 int nid;
1297
1298 VM_BUG_ON(!nodes_allowed);
1299
1300 nid = get_valid_node_allowed(h->next_nid_to_free, nodes_allowed);
1301 h->next_nid_to_free = next_node_allowed(nid, nodes_allowed);
1302
1303 return nid;
1304}
1305
1306#define for_each_node_mask_to_alloc(hs, nr_nodes, node, mask) \
1307 for (nr_nodes = nodes_weight(*mask); \
1308 nr_nodes > 0 && \
1309 ((node = hstate_next_node_to_alloc(hs, mask)) || 1); \
1310 nr_nodes--)
1311
1312#define for_each_node_mask_to_free(hs, nr_nodes, node, mask) \
1313 for (nr_nodes = nodes_weight(*mask); \
1314 nr_nodes > 0 && \
1315 ((node = hstate_next_node_to_free(hs, mask)) || 1); \
1316 nr_nodes--)
1317
8531fc6f 1318/* used to demote non-gigantic_huge pages as well */
34d9e35b
MK
1319static void __destroy_compound_gigantic_page(struct page *page,
1320 unsigned int order, bool demote)
944d9fec
LC
1321{
1322 int i;
1323 int nr_pages = 1 << order;
14455eab 1324 struct page *p;
944d9fec 1325
c8cc708a 1326 atomic_set(compound_mapcount_ptr(page), 0);
5291c09b 1327 atomic_set(compound_pincount_ptr(page), 0);
47e29d32 1328
14455eab
CL
1329 for (i = 1; i < nr_pages; i++) {
1330 p = nth_page(page, i);
a01f4390 1331 p->mapping = NULL;
1d798ca3 1332 clear_compound_head(p);
34d9e35b
MK
1333 if (!demote)
1334 set_page_refcounted(p);
944d9fec
LC
1335 }
1336
1337 set_compound_order(page, 0);
5232c63f 1338#ifdef CONFIG_64BIT
ba9c1201 1339 page[1].compound_nr = 0;
5232c63f 1340#endif
944d9fec
LC
1341 __ClearPageHead(page);
1342}
1343
8531fc6f
MK
1344static void destroy_compound_hugetlb_page_for_demote(struct page *page,
1345 unsigned int order)
1346{
1347 __destroy_compound_gigantic_page(page, order, true);
1348}
1349
1350#ifdef CONFIG_ARCH_HAS_GIGANTIC_PAGE
34d9e35b
MK
1351static void destroy_compound_gigantic_page(struct page *page,
1352 unsigned int order)
1353{
1354 __destroy_compound_gigantic_page(page, order, false);
1355}
1356
d00181b9 1357static void free_gigantic_page(struct page *page, unsigned int order)
944d9fec 1358{
cf11e85f
RG
1359 /*
1360 * If the page isn't allocated using the cma allocator,
1361 * cma_release() returns false.
1362 */
dbda8fea
BS
1363#ifdef CONFIG_CMA
1364 if (cma_release(hugetlb_cma[page_to_nid(page)], page, 1 << order))
cf11e85f 1365 return;
dbda8fea 1366#endif
cf11e85f 1367
944d9fec
LC
1368 free_contig_range(page_to_pfn(page), 1 << order);
1369}
1370
4eb0716e 1371#ifdef CONFIG_CONTIG_ALLOC
d9cc948f
MH
1372static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
1373 int nid, nodemask_t *nodemask)
944d9fec 1374{
04adbc3f 1375 unsigned long nr_pages = pages_per_huge_page(h);
953f064a
LX
1376 if (nid == NUMA_NO_NODE)
1377 nid = numa_mem_id();
944d9fec 1378
dbda8fea
BS
1379#ifdef CONFIG_CMA
1380 {
cf11e85f
RG
1381 struct page *page;
1382 int node;
1383
953f064a
LX
1384 if (hugetlb_cma[nid]) {
1385 page = cma_alloc(hugetlb_cma[nid], nr_pages,
1386 huge_page_order(h), true);
cf11e85f
RG
1387 if (page)
1388 return page;
1389 }
953f064a
LX
1390
1391 if (!(gfp_mask & __GFP_THISNODE)) {
1392 for_each_node_mask(node, *nodemask) {
1393 if (node == nid || !hugetlb_cma[node])
1394 continue;
1395
1396 page = cma_alloc(hugetlb_cma[node], nr_pages,
1397 huge_page_order(h), true);
1398 if (page)
1399 return page;
1400 }
1401 }
cf11e85f 1402 }
dbda8fea 1403#endif
cf11e85f 1404
5e27a2df 1405 return alloc_contig_pages(nr_pages, gfp_mask, nid, nodemask);
944d9fec
LC
1406}
1407
4eb0716e
AG
1408#else /* !CONFIG_CONTIG_ALLOC */
1409static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
1410 int nid, nodemask_t *nodemask)
1411{
1412 return NULL;
1413}
1414#endif /* CONFIG_CONTIG_ALLOC */
944d9fec 1415
e1073d1e 1416#else /* !CONFIG_ARCH_HAS_GIGANTIC_PAGE */
d9cc948f 1417static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
4eb0716e
AG
1418 int nid, nodemask_t *nodemask)
1419{
1420 return NULL;
1421}
d00181b9 1422static inline void free_gigantic_page(struct page *page, unsigned int order) { }
944d9fec 1423static inline void destroy_compound_gigantic_page(struct page *page,
d00181b9 1424 unsigned int order) { }
944d9fec
LC
1425#endif
1426
6eb4e88a
MK
1427/*
1428 * Remove hugetlb page from lists, and update dtor so that page appears
34d9e35b
MK
1429 * as just a compound page.
1430 *
1431 * A reference is held on the page, except in the case of demote.
6eb4e88a
MK
1432 *
1433 * Must be called with hugetlb lock held.
1434 */
34d9e35b
MK
1435static void __remove_hugetlb_page(struct hstate *h, struct page *page,
1436 bool adjust_surplus,
1437 bool demote)
6eb4e88a
MK
1438{
1439 int nid = page_to_nid(page);
1440
1441 VM_BUG_ON_PAGE(hugetlb_cgroup_from_page(page), page);
1442 VM_BUG_ON_PAGE(hugetlb_cgroup_from_page_rsvd(page), page);
1443
9487ca60 1444 lockdep_assert_held(&hugetlb_lock);
6eb4e88a
MK
1445 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
1446 return;
1447
1448 list_del(&page->lru);
1449
1450 if (HPageFreed(page)) {
1451 h->free_huge_pages--;
1452 h->free_huge_pages_node[nid]--;
1453 }
1454 if (adjust_surplus) {
1455 h->surplus_huge_pages--;
1456 h->surplus_huge_pages_node[nid]--;
1457 }
1458
e32d20c0
MK
1459 /*
1460 * Very subtle
1461 *
1462 * For non-gigantic pages set the destructor to the normal compound
1463 * page dtor. This is needed in case someone takes an additional
1464 * temporary ref to the page, and freeing is delayed until they drop
1465 * their reference.
1466 *
1467 * For gigantic pages set the destructor to the null dtor. This
1468 * destructor will never be called. Before freeing the gigantic
1469 * page destroy_compound_gigantic_page will turn the compound page
1470 * into a simple group of pages. After this the destructor does not
1471 * apply.
1472 *
1473 * This handles the case where more than one ref is held when and
1474 * after update_and_free_page is called.
34d9e35b
MK
1475 *
1476 * In the case of demote we do not ref count the page as it will soon
1477 * be turned into a page of smaller size.
e32d20c0 1478 */
34d9e35b
MK
1479 if (!demote)
1480 set_page_refcounted(page);
e32d20c0
MK
1481 if (hstate_is_gigantic(h))
1482 set_compound_page_dtor(page, NULL_COMPOUND_DTOR);
1483 else
1484 set_compound_page_dtor(page, COMPOUND_PAGE_DTOR);
6eb4e88a
MK
1485
1486 h->nr_huge_pages--;
1487 h->nr_huge_pages_node[nid]--;
1488}
1489
34d9e35b
MK
1490static void remove_hugetlb_page(struct hstate *h, struct page *page,
1491 bool adjust_surplus)
1492{
1493 __remove_hugetlb_page(h, page, adjust_surplus, false);
1494}
1495
8531fc6f
MK
1496static void remove_hugetlb_page_for_demote(struct hstate *h, struct page *page,
1497 bool adjust_surplus)
1498{
1499 __remove_hugetlb_page(h, page, adjust_surplus, true);
1500}
1501
ad2fa371
MS
1502static void add_hugetlb_page(struct hstate *h, struct page *page,
1503 bool adjust_surplus)
1504{
1505 int zeroed;
1506 int nid = page_to_nid(page);
1507
1508 VM_BUG_ON_PAGE(!HPageVmemmapOptimized(page), page);
1509
1510 lockdep_assert_held(&hugetlb_lock);
1511
1512 INIT_LIST_HEAD(&page->lru);
1513 h->nr_huge_pages++;
1514 h->nr_huge_pages_node[nid]++;
1515
1516 if (adjust_surplus) {
1517 h->surplus_huge_pages++;
1518 h->surplus_huge_pages_node[nid]++;
1519 }
1520
1521 set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
1522 set_page_private(page, 0);
a9e1eab2
ML
1523 /*
1524 * We have to set HPageVmemmapOptimized again as above
1525 * set_page_private(page, 0) cleared it.
1526 */
ad2fa371
MS
1527 SetHPageVmemmapOptimized(page);
1528
1529 /*
b65a4eda
MK
1530 * This page is about to be managed by the hugetlb allocator and
1531 * should have no users. Drop our reference, and check for others
1532 * just in case.
ad2fa371
MS
1533 */
1534 zeroed = put_page_testzero(page);
b65a4eda
MK
1535 if (!zeroed)
1536 /*
1537 * It is VERY unlikely soneone else has taken a ref on
1538 * the page. In this case, we simply return as the
1539 * hugetlb destructor (free_huge_page) will be called
1540 * when this other ref is dropped.
1541 */
1542 return;
1543
ad2fa371
MS
1544 arch_clear_hugepage_flags(page);
1545 enqueue_huge_page(h, page);
1546}
1547
b65d4adb 1548static void __update_and_free_page(struct hstate *h, struct page *page)
6af2acb6
AL
1549{
1550 int i;
14455eab 1551 struct page *subpage;
a5516438 1552
4eb0716e 1553 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
944d9fec 1554 return;
18229df5 1555
161df60e
NH
1556 /*
1557 * If we don't know which subpages are hwpoisoned, we can't free
1558 * the hugepage, so it's leaked intentionally.
1559 */
1560 if (HPageRawHwpUnreliable(page))
1561 return;
1562
6213834c 1563 if (hugetlb_vmemmap_restore(h, page)) {
ad2fa371
MS
1564 spin_lock_irq(&hugetlb_lock);
1565 /*
1566 * If we cannot allocate vmemmap pages, just refuse to free the
1567 * page and put the page back on the hugetlb free list and treat
1568 * as a surplus page.
1569 */
1570 add_hugetlb_page(h, page, true);
1571 spin_unlock_irq(&hugetlb_lock);
1572 return;
1573 }
1574
161df60e
NH
1575 /*
1576 * Move PageHWPoison flag from head page to the raw error pages,
1577 * which makes any healthy subpages reusable.
1578 */
1579 if (unlikely(PageHWPoison(page)))
1580 hugetlb_clear_page_hwpoison(page);
1581
14455eab
CL
1582 for (i = 0; i < pages_per_huge_page(h); i++) {
1583 subpage = nth_page(page, i);
dbfee5ae 1584 subpage->flags &= ~(1 << PG_locked | 1 << PG_error |
32f84528 1585 1 << PG_referenced | 1 << PG_dirty |
a7407a27
LC
1586 1 << PG_active | 1 << PG_private |
1587 1 << PG_writeback);
6af2acb6 1588 }
a01f4390
MK
1589
1590 /*
1591 * Non-gigantic pages demoted from CMA allocated gigantic pages
1592 * need to be given back to CMA in free_gigantic_page.
1593 */
1594 if (hstate_is_gigantic(h) ||
1595 hugetlb_cma_page(page, huge_page_order(h))) {
944d9fec
LC
1596 destroy_compound_gigantic_page(page, huge_page_order(h));
1597 free_gigantic_page(page, huge_page_order(h));
1598 } else {
944d9fec
LC
1599 __free_pages(page, huge_page_order(h));
1600 }
6af2acb6
AL
1601}
1602
b65d4adb
MS
1603/*
1604 * As update_and_free_page() can be called under any context, so we cannot
1605 * use GFP_KERNEL to allocate vmemmap pages. However, we can defer the
1606 * actual freeing in a workqueue to prevent from using GFP_ATOMIC to allocate
1607 * the vmemmap pages.
1608 *
1609 * free_hpage_workfn() locklessly retrieves the linked list of pages to be
1610 * freed and frees them one-by-one. As the page->mapping pointer is going
1611 * to be cleared in free_hpage_workfn() anyway, it is reused as the llist_node
1612 * structure of a lockless linked list of huge pages to be freed.
1613 */
1614static LLIST_HEAD(hpage_freelist);
1615
1616static void free_hpage_workfn(struct work_struct *work)
1617{
1618 struct llist_node *node;
1619
1620 node = llist_del_all(&hpage_freelist);
1621
1622 while (node) {
1623 struct page *page;
1624 struct hstate *h;
1625
1626 page = container_of((struct address_space **)node,
1627 struct page, mapping);
1628 node = node->next;
1629 page->mapping = NULL;
1630 /*
1631 * The VM_BUG_ON_PAGE(!PageHuge(page), page) in page_hstate()
1632 * is going to trigger because a previous call to
1633 * remove_hugetlb_page() will set_compound_page_dtor(page,
1634 * NULL_COMPOUND_DTOR), so do not use page_hstate() directly.
1635 */
1636 h = size_to_hstate(page_size(page));
1637
1638 __update_and_free_page(h, page);
1639
1640 cond_resched();
1641 }
1642}
1643static DECLARE_WORK(free_hpage_work, free_hpage_workfn);
1644
1645static inline void flush_free_hpage_work(struct hstate *h)
1646{
6213834c 1647 if (hugetlb_vmemmap_optimizable(h))
b65d4adb
MS
1648 flush_work(&free_hpage_work);
1649}
1650
1651static void update_and_free_page(struct hstate *h, struct page *page,
1652 bool atomic)
1653{
ad2fa371 1654 if (!HPageVmemmapOptimized(page) || !atomic) {
b65d4adb
MS
1655 __update_and_free_page(h, page);
1656 return;
1657 }
1658
1659 /*
1660 * Defer freeing to avoid using GFP_ATOMIC to allocate vmemmap pages.
1661 *
1662 * Only call schedule_work() if hpage_freelist is previously
1663 * empty. Otherwise, schedule_work() had been called but the workfn
1664 * hasn't retrieved the list yet.
1665 */
1666 if (llist_add((struct llist_node *)&page->mapping, &hpage_freelist))
1667 schedule_work(&free_hpage_work);
1668}
1669
10c6ec49
MK
1670static void update_and_free_pages_bulk(struct hstate *h, struct list_head *list)
1671{
1672 struct page *page, *t_page;
1673
1674 list_for_each_entry_safe(page, t_page, list, lru) {
b65d4adb 1675 update_and_free_page(h, page, false);
10c6ec49
MK
1676 cond_resched();
1677 }
1678}
1679
e5ff2159
AK
1680struct hstate *size_to_hstate(unsigned long size)
1681{
1682 struct hstate *h;
1683
1684 for_each_hstate(h) {
1685 if (huge_page_size(h) == size)
1686 return h;
1687 }
1688 return NULL;
1689}
1690
db71ef79 1691void free_huge_page(struct page *page)
27a85ef1 1692{
a5516438
AK
1693 /*
1694 * Can't pass hstate in here because it is called from the
1695 * compound page destructor.
1696 */
e5ff2159 1697 struct hstate *h = page_hstate(page);
7893d1d5 1698 int nid = page_to_nid(page);
d6995da3 1699 struct hugepage_subpool *spool = hugetlb_page_subpool(page);
07443a85 1700 bool restore_reserve;
db71ef79 1701 unsigned long flags;
27a85ef1 1702
b4330afb
MK
1703 VM_BUG_ON_PAGE(page_count(page), page);
1704 VM_BUG_ON_PAGE(page_mapcount(page), page);
8ace22bc 1705
d6995da3 1706 hugetlb_set_page_subpool(page, NULL);
78fbe906
DH
1707 if (PageAnon(page))
1708 __ClearPageAnonExclusive(page);
8ace22bc 1709 page->mapping = NULL;
d6995da3
MK
1710 restore_reserve = HPageRestoreReserve(page);
1711 ClearHPageRestoreReserve(page);
27a85ef1 1712
1c5ecae3 1713 /*
d6995da3 1714 * If HPageRestoreReserve was set on page, page allocation consumed a
0919e1b6
MK
1715 * reservation. If the page was associated with a subpool, there
1716 * would have been a page reserved in the subpool before allocation
1717 * via hugepage_subpool_get_pages(). Since we are 'restoring' the
6c26d310 1718 * reservation, do not call hugepage_subpool_put_pages() as this will
0919e1b6 1719 * remove the reserved page from the subpool.
1c5ecae3 1720 */
0919e1b6
MK
1721 if (!restore_reserve) {
1722 /*
1723 * A return code of zero implies that the subpool will be
1724 * under its minimum size if the reservation is not restored
1725 * after page is free. Therefore, force restore_reserve
1726 * operation.
1727 */
1728 if (hugepage_subpool_put_pages(spool, 1) == 0)
1729 restore_reserve = true;
1730 }
1c5ecae3 1731
db71ef79 1732 spin_lock_irqsave(&hugetlb_lock, flags);
8f251a3d 1733 ClearHPageMigratable(page);
6d76dcf4
AK
1734 hugetlb_cgroup_uncharge_page(hstate_index(h),
1735 pages_per_huge_page(h), page);
08cf9faf
MA
1736 hugetlb_cgroup_uncharge_page_rsvd(hstate_index(h),
1737 pages_per_huge_page(h), page);
07443a85
JK
1738 if (restore_reserve)
1739 h->resv_huge_pages++;
1740
9157c311 1741 if (HPageTemporary(page)) {
6eb4e88a 1742 remove_hugetlb_page(h, page, false);
db71ef79 1743 spin_unlock_irqrestore(&hugetlb_lock, flags);
b65d4adb 1744 update_and_free_page(h, page, true);
ab5ac90a 1745 } else if (h->surplus_huge_pages_node[nid]) {
0edaecfa 1746 /* remove the page from active list */
6eb4e88a 1747 remove_hugetlb_page(h, page, true);
db71ef79 1748 spin_unlock_irqrestore(&hugetlb_lock, flags);
b65d4adb 1749 update_and_free_page(h, page, true);
7893d1d5 1750 } else {
5d3a551c 1751 arch_clear_hugepage_flags(page);
a5516438 1752 enqueue_huge_page(h, page);
db71ef79 1753 spin_unlock_irqrestore(&hugetlb_lock, flags);
c77c0a8a 1754 }
c77c0a8a
WL
1755}
1756
d3d99fcc
OS
1757/*
1758 * Must be called with the hugetlb lock held
1759 */
1760static void __prep_account_new_huge_page(struct hstate *h, int nid)
1761{
1762 lockdep_assert_held(&hugetlb_lock);
1763 h->nr_huge_pages++;
1764 h->nr_huge_pages_node[nid]++;
1765}
1766
f41f2ed4 1767static void __prep_new_huge_page(struct hstate *h, struct page *page)
b7ba30c6 1768{
6213834c 1769 hugetlb_vmemmap_optimize(h, page);
0edaecfa 1770 INIT_LIST_HEAD(&page->lru);
f1e61557 1771 set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
ff546117 1772 hugetlb_set_page_subpool(page, NULL);
9dd540e2 1773 set_hugetlb_cgroup(page, NULL);
1adc4d41 1774 set_hugetlb_cgroup_rsvd(page, NULL);
d3d99fcc
OS
1775}
1776
1777static void prep_new_huge_page(struct hstate *h, struct page *page, int nid)
1778{
f41f2ed4 1779 __prep_new_huge_page(h, page);
db71ef79 1780 spin_lock_irq(&hugetlb_lock);
d3d99fcc 1781 __prep_account_new_huge_page(h, nid);
db71ef79 1782 spin_unlock_irq(&hugetlb_lock);
b7ba30c6
AK
1783}
1784
34d9e35b
MK
1785static bool __prep_compound_gigantic_page(struct page *page, unsigned int order,
1786 bool demote)
20a0307c 1787{
7118fc29 1788 int i, j;
20a0307c 1789 int nr_pages = 1 << order;
14455eab 1790 struct page *p;
20a0307c
WF
1791
1792 /* we rely on prep_new_huge_page to set the destructor */
1793 set_compound_order(page, order);
de09d31d 1794 __SetPageHead(page);
2b21624f 1795 for (i = 0; i < nr_pages; i++) {
14455eab
CL
1796 p = nth_page(page, i);
1797
ef5a22be
AA
1798 /*
1799 * For gigantic hugepages allocated through bootmem at
1800 * boot, it's safer to be consistent with the not-gigantic
1801 * hugepages and clear the PG_reserved bit from all tail pages
7c8de358 1802 * too. Otherwise drivers using get_user_pages() to access tail
ef5a22be
AA
1803 * pages may get the reference counting wrong if they see
1804 * PG_reserved set on a tail page (despite the head page not
1805 * having PG_reserved set). Enforcing this consistency between
1806 * head and tail pages allows drivers to optimize away a check
1807 * on the head page when they need know if put_page() is needed
1808 * after get_user_pages().
1809 */
1810 __ClearPageReserved(p);
7118fc29
MK
1811 /*
1812 * Subtle and very unlikely
1813 *
1814 * Gigantic 'page allocators' such as memblock or cma will
1815 * return a set of pages with each page ref counted. We need
1816 * to turn this set of pages into a compound page with tail
1817 * page ref counts set to zero. Code such as speculative page
1818 * cache adding could take a ref on a 'to be' tail page.
1819 * We need to respect any increased ref count, and only set
1820 * the ref count to zero if count is currently 1. If count
416d85ed
MK
1821 * is not 1, we return an error. An error return indicates
1822 * the set of pages can not be converted to a gigantic page.
1823 * The caller who allocated the pages should then discard the
1824 * pages using the appropriate free interface.
34d9e35b
MK
1825 *
1826 * In the case of demote, the ref count will be zero.
7118fc29 1827 */
34d9e35b
MK
1828 if (!demote) {
1829 if (!page_ref_freeze(p, 1)) {
1830 pr_warn("HugeTLB page can not be used due to unexpected inflated ref count\n");
1831 goto out_error;
1832 }
1833 } else {
1834 VM_BUG_ON_PAGE(page_count(p), p);
7118fc29 1835 }
2b21624f
MK
1836 if (i != 0)
1837 set_compound_head(p, page);
20a0307c 1838 }
b4330afb 1839 atomic_set(compound_mapcount_ptr(page), -1);
5291c09b 1840 atomic_set(compound_pincount_ptr(page), 0);
7118fc29
MK
1841 return true;
1842
1843out_error:
2b21624f
MK
1844 /* undo page modifications made above */
1845 for (j = 0; j < i; j++) {
14455eab 1846 p = nth_page(page, j);
2b21624f
MK
1847 if (j != 0)
1848 clear_compound_head(p);
7118fc29
MK
1849 set_page_refcounted(p);
1850 }
1851 /* need to clear PG_reserved on remaining tail pages */
14455eab
CL
1852 for (; j < nr_pages; j++) {
1853 p = nth_page(page, j);
7118fc29 1854 __ClearPageReserved(p);
14455eab 1855 }
7118fc29 1856 set_compound_order(page, 0);
5232c63f 1857#ifdef CONFIG_64BIT
7118fc29 1858 page[1].compound_nr = 0;
5232c63f 1859#endif
7118fc29
MK
1860 __ClearPageHead(page);
1861 return false;
20a0307c
WF
1862}
1863
34d9e35b
MK
1864static bool prep_compound_gigantic_page(struct page *page, unsigned int order)
1865{
1866 return __prep_compound_gigantic_page(page, order, false);
1867}
1868
8531fc6f
MK
1869static bool prep_compound_gigantic_page_for_demote(struct page *page,
1870 unsigned int order)
1871{
1872 return __prep_compound_gigantic_page(page, order, true);
1873}
1874
7795912c
AM
1875/*
1876 * PageHuge() only returns true for hugetlbfs pages, but not for normal or
1877 * transparent huge pages. See the PageTransHuge() documentation for more
1878 * details.
1879 */
20a0307c
WF
1880int PageHuge(struct page *page)
1881{
20a0307c
WF
1882 if (!PageCompound(page))
1883 return 0;
1884
1885 page = compound_head(page);
f1e61557 1886 return page[1].compound_dtor == HUGETLB_PAGE_DTOR;
20a0307c 1887}
43131e14
NH
1888EXPORT_SYMBOL_GPL(PageHuge);
1889
27c73ae7
AA
1890/*
1891 * PageHeadHuge() only returns true for hugetlbfs head page, but not for
1892 * normal or transparent huge pages.
1893 */
1894int PageHeadHuge(struct page *page_head)
1895{
27c73ae7
AA
1896 if (!PageHead(page_head))
1897 return 0;
1898
d4af73e3 1899 return page_head[1].compound_dtor == HUGETLB_PAGE_DTOR;
27c73ae7 1900}
4e936ecc 1901EXPORT_SYMBOL_GPL(PageHeadHuge);
27c73ae7 1902
c0d0381a
MK
1903/*
1904 * Find and lock address space (mapping) in write mode.
1905 *
336bf30e
MK
1906 * Upon entry, the page is locked which means that page_mapping() is
1907 * stable. Due to locking order, we can only trylock_write. If we can
1908 * not get the lock, simply return NULL to caller.
c0d0381a
MK
1909 */
1910struct address_space *hugetlb_page_mapping_lock_write(struct page *hpage)
1911{
336bf30e 1912 struct address_space *mapping = page_mapping(hpage);
c0d0381a 1913
c0d0381a
MK
1914 if (!mapping)
1915 return mapping;
1916
c0d0381a
MK
1917 if (i_mmap_trylock_write(mapping))
1918 return mapping;
1919
336bf30e 1920 return NULL;
c0d0381a
MK
1921}
1922
fe19bd3d 1923pgoff_t hugetlb_basepage_index(struct page *page)
13d60f4b
ZY
1924{
1925 struct page *page_head = compound_head(page);
1926 pgoff_t index = page_index(page_head);
1927 unsigned long compound_idx;
1928
13d60f4b
ZY
1929 if (compound_order(page_head) >= MAX_ORDER)
1930 compound_idx = page_to_pfn(page) - page_to_pfn(page_head);
1931 else
1932 compound_idx = page - page_head;
1933
1934 return (index << compound_order(page_head)) + compound_idx;
1935}
1936
0c397dae 1937static struct page *alloc_buddy_huge_page(struct hstate *h,
f60858f9
MK
1938 gfp_t gfp_mask, int nid, nodemask_t *nmask,
1939 nodemask_t *node_alloc_noretry)
1da177e4 1940{
af0fb9df 1941 int order = huge_page_order(h);
1da177e4 1942 struct page *page;
f60858f9 1943 bool alloc_try_hard = true;
2b21624f 1944 bool retry = true;
f96efd58 1945
f60858f9
MK
1946 /*
1947 * By default we always try hard to allocate the page with
1948 * __GFP_RETRY_MAYFAIL flag. However, if we are allocating pages in
1949 * a loop (to adjust global huge page counts) and previous allocation
1950 * failed, do not continue to try hard on the same node. Use the
1951 * node_alloc_noretry bitmap to manage this state information.
1952 */
1953 if (node_alloc_noretry && node_isset(nid, *node_alloc_noretry))
1954 alloc_try_hard = false;
1955 gfp_mask |= __GFP_COMP|__GFP_NOWARN;
1956 if (alloc_try_hard)
1957 gfp_mask |= __GFP_RETRY_MAYFAIL;
af0fb9df
MH
1958 if (nid == NUMA_NO_NODE)
1959 nid = numa_mem_id();
2b21624f 1960retry:
84172f4b 1961 page = __alloc_pages(gfp_mask, order, nid, nmask);
2b21624f
MK
1962
1963 /* Freeze head page */
1964 if (page && !page_ref_freeze(page, 1)) {
1965 __free_pages(page, order);
1966 if (retry) { /* retry once */
1967 retry = false;
1968 goto retry;
1969 }
1970 /* WOW! twice in a row. */
1971 pr_warn("HugeTLB head page unexpected inflated ref count\n");
1972 page = NULL;
1973 }
1974
af0fb9df
MH
1975 if (page)
1976 __count_vm_event(HTLB_BUDDY_PGALLOC);
1977 else
1978 __count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
63b4613c 1979
f60858f9
MK
1980 /*
1981 * If we did not specify __GFP_RETRY_MAYFAIL, but still got a page this
1982 * indicates an overall state change. Clear bit so that we resume
1983 * normal 'try hard' allocations.
1984 */
1985 if (node_alloc_noretry && page && !alloc_try_hard)
1986 node_clear(nid, *node_alloc_noretry);
1987
1988 /*
1989 * If we tried hard to get a page but failed, set bit so that
1990 * subsequent attempts will not try as hard until there is an
1991 * overall state change.
1992 */
1993 if (node_alloc_noretry && !page && alloc_try_hard)
1994 node_set(nid, *node_alloc_noretry);
1995
63b4613c
NA
1996 return page;
1997}
1998
0c397dae
MH
1999/*
2000 * Common helper to allocate a fresh hugetlb page. All specific allocators
2001 * should use this function to get new hugetlb pages
2b21624f
MK
2002 *
2003 * Note that returned page is 'frozen': ref count of head page and all tail
2004 * pages is zero.
0c397dae
MH
2005 */
2006static struct page *alloc_fresh_huge_page(struct hstate *h,
f60858f9
MK
2007 gfp_t gfp_mask, int nid, nodemask_t *nmask,
2008 nodemask_t *node_alloc_noretry)
0c397dae
MH
2009{
2010 struct page *page;
7118fc29 2011 bool retry = false;
0c397dae 2012
7118fc29 2013retry:
0c397dae
MH
2014 if (hstate_is_gigantic(h))
2015 page = alloc_gigantic_page(h, gfp_mask, nid, nmask);
2016 else
2017 page = alloc_buddy_huge_page(h, gfp_mask,
f60858f9 2018 nid, nmask, node_alloc_noretry);
0c397dae
MH
2019 if (!page)
2020 return NULL;
2021
7118fc29
MK
2022 if (hstate_is_gigantic(h)) {
2023 if (!prep_compound_gigantic_page(page, huge_page_order(h))) {
2024 /*
2025 * Rare failure to convert pages to compound page.
2026 * Free pages and try again - ONCE!
2027 */
2028 free_gigantic_page(page, huge_page_order(h));
2029 if (!retry) {
2030 retry = true;
2031 goto retry;
2032 }
7118fc29
MK
2033 return NULL;
2034 }
2035 }
0c397dae
MH
2036 prep_new_huge_page(h, page, page_to_nid(page));
2037
2038 return page;
2039}
2040
af0fb9df
MH
2041/*
2042 * Allocates a fresh page to the hugetlb allocator pool in the node interleaved
2043 * manner.
2044 */
f60858f9
MK
2045static int alloc_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed,
2046 nodemask_t *node_alloc_noretry)
b2261026
JK
2047{
2048 struct page *page;
2049 int nr_nodes, node;
af0fb9df 2050 gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
b2261026
JK
2051
2052 for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
f60858f9
MK
2053 page = alloc_fresh_huge_page(h, gfp_mask, node, nodes_allowed,
2054 node_alloc_noretry);
af0fb9df 2055 if (page)
b2261026 2056 break;
b2261026
JK
2057 }
2058
af0fb9df
MH
2059 if (!page)
2060 return 0;
b2261026 2061
2b21624f 2062 free_huge_page(page); /* free it into the hugepage allocator */
af0fb9df
MH
2063
2064 return 1;
b2261026
JK
2065}
2066
e8c5c824 2067/*
10c6ec49
MK
2068 * Remove huge page from pool from next node to free. Attempt to keep
2069 * persistent huge pages more or less balanced over allowed nodes.
2070 * This routine only 'removes' the hugetlb page. The caller must make
2071 * an additional call to free the page to low level allocators.
e8c5c824
LS
2072 * Called with hugetlb_lock locked.
2073 */
10c6ec49
MK
2074static struct page *remove_pool_huge_page(struct hstate *h,
2075 nodemask_t *nodes_allowed,
2076 bool acct_surplus)
e8c5c824 2077{
b2261026 2078 int nr_nodes, node;
10c6ec49 2079 struct page *page = NULL;
e8c5c824 2080
9487ca60 2081 lockdep_assert_held(&hugetlb_lock);
b2261026 2082 for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
685f3457
LS
2083 /*
2084 * If we're returning unused surplus pages, only examine
2085 * nodes with surplus pages.
2086 */
b2261026
JK
2087 if ((!acct_surplus || h->surplus_huge_pages_node[node]) &&
2088 !list_empty(&h->hugepage_freelists[node])) {
10c6ec49 2089 page = list_entry(h->hugepage_freelists[node].next,
e8c5c824 2090 struct page, lru);
6eb4e88a 2091 remove_hugetlb_page(h, page, acct_surplus);
9a76db09 2092 break;
e8c5c824 2093 }
b2261026 2094 }
e8c5c824 2095
10c6ec49 2096 return page;
e8c5c824
LS
2097}
2098
c8721bbb
NH
2099/*
2100 * Dissolve a given free hugepage into free buddy pages. This function does
faf53def
NH
2101 * nothing for in-use hugepages and non-hugepages.
2102 * This function returns values like below:
2103 *
ad2fa371
MS
2104 * -ENOMEM: failed to allocate vmemmap pages to free the freed hugepages
2105 * when the system is under memory pressure and the feature of
2106 * freeing unused vmemmap pages associated with each hugetlb page
2107 * is enabled.
2108 * -EBUSY: failed to dissolved free hugepages or the hugepage is in-use
2109 * (allocated or reserved.)
2110 * 0: successfully dissolved free hugepages or the page is not a
2111 * hugepage (considered as already dissolved)
c8721bbb 2112 */
c3114a84 2113int dissolve_free_huge_page(struct page *page)
c8721bbb 2114{
6bc9b564 2115 int rc = -EBUSY;
082d5b6b 2116
7ffddd49 2117retry:
faf53def
NH
2118 /* Not to disrupt normal path by vainly holding hugetlb_lock */
2119 if (!PageHuge(page))
2120 return 0;
2121
db71ef79 2122 spin_lock_irq(&hugetlb_lock);
faf53def
NH
2123 if (!PageHuge(page)) {
2124 rc = 0;
2125 goto out;
2126 }
2127
2128 if (!page_count(page)) {
2247bb33
GS
2129 struct page *head = compound_head(page);
2130 struct hstate *h = page_hstate(head);
8346d69d 2131 if (!available_huge_pages(h))
082d5b6b 2132 goto out;
7ffddd49
MS
2133
2134 /*
2135 * We should make sure that the page is already on the free list
2136 * when it is dissolved.
2137 */
6c037149 2138 if (unlikely(!HPageFreed(head))) {
db71ef79 2139 spin_unlock_irq(&hugetlb_lock);
7ffddd49
MS
2140 cond_resched();
2141
2142 /*
2143 * Theoretically, we should return -EBUSY when we
2144 * encounter this race. In fact, we have a chance
2145 * to successfully dissolve the page if we do a
2146 * retry. Because the race window is quite small.
2147 * If we seize this opportunity, it is an optimization
2148 * for increasing the success rate of dissolving page.
2149 */
2150 goto retry;
2151 }
2152
0c5da357 2153 remove_hugetlb_page(h, head, false);
c1470b33 2154 h->max_huge_pages--;
db71ef79 2155 spin_unlock_irq(&hugetlb_lock);
ad2fa371
MS
2156
2157 /*
2158 * Normally update_and_free_page will allocate required vmemmmap
2159 * before freeing the page. update_and_free_page will fail to
2160 * free the page if it can not allocate required vmemmap. We
2161 * need to adjust max_huge_pages if the page is not freed.
2162 * Attempt to allocate vmemmmap here so that we can take
2163 * appropriate action on failure.
2164 */
6213834c 2165 rc = hugetlb_vmemmap_restore(h, head);
ad2fa371 2166 if (!rc) {
ad2fa371
MS
2167 update_and_free_page(h, head, false);
2168 } else {
2169 spin_lock_irq(&hugetlb_lock);
2170 add_hugetlb_page(h, head, false);
2171 h->max_huge_pages++;
2172 spin_unlock_irq(&hugetlb_lock);
2173 }
2174
2175 return rc;
c8721bbb 2176 }
082d5b6b 2177out:
db71ef79 2178 spin_unlock_irq(&hugetlb_lock);
082d5b6b 2179 return rc;
c8721bbb
NH
2180}
2181
2182/*
2183 * Dissolve free hugepages in a given pfn range. Used by memory hotplug to
2184 * make specified memory blocks removable from the system.
2247bb33
GS
2185 * Note that this will dissolve a free gigantic hugepage completely, if any
2186 * part of it lies within the given range.
082d5b6b
GS
2187 * Also note that if dissolve_free_huge_page() returns with an error, all
2188 * free hugepages that were dissolved before that error are lost.
c8721bbb 2189 */
082d5b6b 2190int dissolve_free_huge_pages(unsigned long start_pfn, unsigned long end_pfn)
c8721bbb 2191{
c8721bbb 2192 unsigned long pfn;
eb03aa00 2193 struct page *page;
082d5b6b 2194 int rc = 0;
dc2628f3
MS
2195 unsigned int order;
2196 struct hstate *h;
c8721bbb 2197
d0177639 2198 if (!hugepages_supported())
082d5b6b 2199 return rc;
d0177639 2200
dc2628f3
MS
2201 order = huge_page_order(&default_hstate);
2202 for_each_hstate(h)
2203 order = min(order, huge_page_order(h));
2204
2205 for (pfn = start_pfn; pfn < end_pfn; pfn += 1 << order) {
eb03aa00 2206 page = pfn_to_page(pfn);
faf53def
NH
2207 rc = dissolve_free_huge_page(page);
2208 if (rc)
2209 break;
eb03aa00 2210 }
082d5b6b
GS
2211
2212 return rc;
c8721bbb
NH
2213}
2214
ab5ac90a
MH
2215/*
2216 * Allocates a fresh surplus page from the page allocator.
2217 */
0c397dae 2218static struct page *alloc_surplus_huge_page(struct hstate *h, gfp_t gfp_mask,
2b21624f 2219 int nid, nodemask_t *nmask)
7893d1d5 2220{
9980d744 2221 struct page *page = NULL;
7893d1d5 2222
bae7f4ae 2223 if (hstate_is_gigantic(h))
aa888a74
AK
2224 return NULL;
2225
db71ef79 2226 spin_lock_irq(&hugetlb_lock);
9980d744
MH
2227 if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages)
2228 goto out_unlock;
db71ef79 2229 spin_unlock_irq(&hugetlb_lock);
d1c3fb1f 2230
f60858f9 2231 page = alloc_fresh_huge_page(h, gfp_mask, nid, nmask, NULL);
9980d744 2232 if (!page)
0c397dae 2233 return NULL;
d1c3fb1f 2234
db71ef79 2235 spin_lock_irq(&hugetlb_lock);
9980d744
MH
2236 /*
2237 * We could have raced with the pool size change.
2238 * Double check that and simply deallocate the new page
2239 * if we would end up overcommiting the surpluses. Abuse
2240 * temporary page to workaround the nasty free_huge_page
2241 * codeflow
2242 */
2243 if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) {
9157c311 2244 SetHPageTemporary(page);
db71ef79 2245 spin_unlock_irq(&hugetlb_lock);
2b21624f 2246 free_huge_page(page);
2bf753e6 2247 return NULL;
7893d1d5 2248 }
9980d744 2249
b65a4eda
MK
2250 h->surplus_huge_pages++;
2251 h->surplus_huge_pages_node[page_to_nid(page)]++;
2252
9980d744 2253out_unlock:
db71ef79 2254 spin_unlock_irq(&hugetlb_lock);
7893d1d5
AL
2255
2256 return page;
2257}
2258
bbe88753 2259static struct page *alloc_migrate_huge_page(struct hstate *h, gfp_t gfp_mask,
9a4e9f3b 2260 int nid, nodemask_t *nmask)
ab5ac90a
MH
2261{
2262 struct page *page;
2263
2264 if (hstate_is_gigantic(h))
2265 return NULL;
2266
f60858f9 2267 page = alloc_fresh_huge_page(h, gfp_mask, nid, nmask, NULL);
ab5ac90a
MH
2268 if (!page)
2269 return NULL;
2270
2b21624f
MK
2271 /* fresh huge pages are frozen */
2272 set_page_refcounted(page);
2273
ab5ac90a
MH
2274 /*
2275 * We do not account these pages as surplus because they are only
2276 * temporary and will be released properly on the last reference
2277 */
9157c311 2278 SetHPageTemporary(page);
ab5ac90a
MH
2279
2280 return page;
2281}
2282
099730d6
DH
2283/*
2284 * Use the VMA's mpolicy to allocate a huge page from the buddy.
2285 */
e0ec90ee 2286static
0c397dae 2287struct page *alloc_buddy_huge_page_with_mpol(struct hstate *h,
099730d6
DH
2288 struct vm_area_struct *vma, unsigned long addr)
2289{
cfcaa66f 2290 struct page *page = NULL;
aaf14e40
MH
2291 struct mempolicy *mpol;
2292 gfp_t gfp_mask = htlb_alloc_mask(h);
2293 int nid;
2294 nodemask_t *nodemask;
2295
2296 nid = huge_node(vma, addr, gfp_mask, &mpol, &nodemask);
cfcaa66f
BW
2297 if (mpol_is_preferred_many(mpol)) {
2298 gfp_t gfp = gfp_mask | __GFP_NOWARN;
2299
2300 gfp &= ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
2b21624f 2301 page = alloc_surplus_huge_page(h, gfp, nid, nodemask);
aaf14e40 2302
cfcaa66f
BW
2303 /* Fallback to all nodes if page==NULL */
2304 nodemask = NULL;
2305 }
2306
2307 if (!page)
2b21624f 2308 page = alloc_surplus_huge_page(h, gfp_mask, nid, nodemask);
cfcaa66f 2309 mpol_cond_put(mpol);
aaf14e40 2310 return page;
099730d6
DH
2311}
2312
ab5ac90a 2313/* page migration callback function */
3e59fcb0 2314struct page *alloc_huge_page_nodemask(struct hstate *h, int preferred_nid,
d92bbc27 2315 nodemask_t *nmask, gfp_t gfp_mask)
4db9b2ef 2316{
db71ef79 2317 spin_lock_irq(&hugetlb_lock);
8346d69d 2318 if (available_huge_pages(h)) {
3e59fcb0
MH
2319 struct page *page;
2320
2321 page = dequeue_huge_page_nodemask(h, gfp_mask, preferred_nid, nmask);
2322 if (page) {
db71ef79 2323 spin_unlock_irq(&hugetlb_lock);
3e59fcb0 2324 return page;
4db9b2ef
MH
2325 }
2326 }
db71ef79 2327 spin_unlock_irq(&hugetlb_lock);
4db9b2ef 2328
0c397dae 2329 return alloc_migrate_huge_page(h, gfp_mask, preferred_nid, nmask);
4db9b2ef
MH
2330}
2331
ebd63723 2332/* mempolicy aware migration callback */
389c8178
MH
2333struct page *alloc_huge_page_vma(struct hstate *h, struct vm_area_struct *vma,
2334 unsigned long address)
ebd63723
MH
2335{
2336 struct mempolicy *mpol;
2337 nodemask_t *nodemask;
2338 struct page *page;
ebd63723
MH
2339 gfp_t gfp_mask;
2340 int node;
2341
ebd63723
MH
2342 gfp_mask = htlb_alloc_mask(h);
2343 node = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
d92bbc27 2344 page = alloc_huge_page_nodemask(h, node, nodemask, gfp_mask);
ebd63723
MH
2345 mpol_cond_put(mpol);
2346
2347 return page;
2348}
2349
e4e574b7 2350/*
25985edc 2351 * Increase the hugetlb pool such that it can accommodate a reservation
e4e574b7
AL
2352 * of size 'delta'.
2353 */
0a4f3d1b 2354static int gather_surplus_pages(struct hstate *h, long delta)
1b2a1e7b 2355 __must_hold(&hugetlb_lock)
e4e574b7 2356{
34665341 2357 LIST_HEAD(surplus_list);
e4e574b7 2358 struct page *page, *tmp;
0a4f3d1b
LX
2359 int ret;
2360 long i;
2361 long needed, allocated;
28073b02 2362 bool alloc_ok = true;
e4e574b7 2363
9487ca60 2364 lockdep_assert_held(&hugetlb_lock);
a5516438 2365 needed = (h->resv_huge_pages + delta) - h->free_huge_pages;
ac09b3a1 2366 if (needed <= 0) {
a5516438 2367 h->resv_huge_pages += delta;
e4e574b7 2368 return 0;
ac09b3a1 2369 }
e4e574b7
AL
2370
2371 allocated = 0;
e4e574b7
AL
2372
2373 ret = -ENOMEM;
2374retry:
db71ef79 2375 spin_unlock_irq(&hugetlb_lock);
e4e574b7 2376 for (i = 0; i < needed; i++) {
0c397dae 2377 page = alloc_surplus_huge_page(h, htlb_alloc_mask(h),
2b21624f 2378 NUMA_NO_NODE, NULL);
28073b02
HD
2379 if (!page) {
2380 alloc_ok = false;
2381 break;
2382 }
e4e574b7 2383 list_add(&page->lru, &surplus_list);
69ed779a 2384 cond_resched();
e4e574b7 2385 }
28073b02 2386 allocated += i;
e4e574b7
AL
2387
2388 /*
2389 * After retaking hugetlb_lock, we need to recalculate 'needed'
2390 * because either resv_huge_pages or free_huge_pages may have changed.
2391 */
db71ef79 2392 spin_lock_irq(&hugetlb_lock);
a5516438
AK
2393 needed = (h->resv_huge_pages + delta) -
2394 (h->free_huge_pages + allocated);
28073b02
HD
2395 if (needed > 0) {
2396 if (alloc_ok)
2397 goto retry;
2398 /*
2399 * We were not able to allocate enough pages to
2400 * satisfy the entire reservation so we free what
2401 * we've allocated so far.
2402 */
2403 goto free;
2404 }
e4e574b7
AL
2405 /*
2406 * The surplus_list now contains _at_least_ the number of extra pages
25985edc 2407 * needed to accommodate the reservation. Add the appropriate number
e4e574b7 2408 * of pages to the hugetlb pool and free the extras back to the buddy
ac09b3a1
AL
2409 * allocator. Commit the entire reservation here to prevent another
2410 * process from stealing the pages as they are added to the pool but
2411 * before they are reserved.
e4e574b7
AL
2412 */
2413 needed += allocated;
a5516438 2414 h->resv_huge_pages += delta;
e4e574b7 2415 ret = 0;
a9869b83 2416
19fc3f0a 2417 /* Free the needed pages to the hugetlb pool */
e4e574b7 2418 list_for_each_entry_safe(page, tmp, &surplus_list, lru) {
19fc3f0a
AL
2419 if ((--needed) < 0)
2420 break;
b65a4eda 2421 /* Add the page to the hugetlb allocator */
a5516438 2422 enqueue_huge_page(h, page);
19fc3f0a 2423 }
28073b02 2424free:
db71ef79 2425 spin_unlock_irq(&hugetlb_lock);
19fc3f0a 2426
b65a4eda
MK
2427 /*
2428 * Free unnecessary surplus pages to the buddy allocator.
2429 * Pages have no ref count, call free_huge_page directly.
2430 */
c0d934ba 2431 list_for_each_entry_safe(page, tmp, &surplus_list, lru)
b65a4eda 2432 free_huge_page(page);
db71ef79 2433 spin_lock_irq(&hugetlb_lock);
e4e574b7
AL
2434
2435 return ret;
2436}
2437
2438/*
e5bbc8a6
MK
2439 * This routine has two main purposes:
2440 * 1) Decrement the reservation count (resv_huge_pages) by the value passed
2441 * in unused_resv_pages. This corresponds to the prior adjustments made
2442 * to the associated reservation map.
2443 * 2) Free any unused surplus pages that may have been allocated to satisfy
2444 * the reservation. As many as unused_resv_pages may be freed.
e4e574b7 2445 */
a5516438
AK
2446static void return_unused_surplus_pages(struct hstate *h,
2447 unsigned long unused_resv_pages)
e4e574b7 2448{
e4e574b7 2449 unsigned long nr_pages;
10c6ec49
MK
2450 struct page *page;
2451 LIST_HEAD(page_list);
2452
9487ca60 2453 lockdep_assert_held(&hugetlb_lock);
10c6ec49
MK
2454 /* Uncommit the reservation */
2455 h->resv_huge_pages -= unused_resv_pages;
e4e574b7 2456
c0531714 2457 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
e5bbc8a6 2458 goto out;
aa888a74 2459
e5bbc8a6
MK
2460 /*
2461 * Part (or even all) of the reservation could have been backed
2462 * by pre-allocated pages. Only free surplus pages.
2463 */
a5516438 2464 nr_pages = min(unused_resv_pages, h->surplus_huge_pages);
e4e574b7 2465
685f3457
LS
2466 /*
2467 * We want to release as many surplus pages as possible, spread
9b5e5d0f
LS
2468 * evenly across all nodes with memory. Iterate across these nodes
2469 * until we can no longer free unreserved surplus pages. This occurs
2470 * when the nodes with surplus pages have no free pages.
10c6ec49 2471 * remove_pool_huge_page() will balance the freed pages across the
9b5e5d0f 2472 * on-line nodes with memory and will handle the hstate accounting.
685f3457
LS
2473 */
2474 while (nr_pages--) {
10c6ec49
MK
2475 page = remove_pool_huge_page(h, &node_states[N_MEMORY], 1);
2476 if (!page)
e5bbc8a6 2477 goto out;
10c6ec49
MK
2478
2479 list_add(&page->lru, &page_list);
e4e574b7 2480 }
e5bbc8a6
MK
2481
2482out:
db71ef79 2483 spin_unlock_irq(&hugetlb_lock);
10c6ec49 2484 update_and_free_pages_bulk(h, &page_list);
db71ef79 2485 spin_lock_irq(&hugetlb_lock);
e4e574b7
AL
2486}
2487
5e911373 2488
c37f9fb1 2489/*
feba16e2 2490 * vma_needs_reservation, vma_commit_reservation and vma_end_reservation
5e911373 2491 * are used by the huge page allocation routines to manage reservations.
cf3ad20b
MK
2492 *
2493 * vma_needs_reservation is called to determine if the huge page at addr
2494 * within the vma has an associated reservation. If a reservation is
2495 * needed, the value 1 is returned. The caller is then responsible for
2496 * managing the global reservation and subpool usage counts. After
2497 * the huge page has been allocated, vma_commit_reservation is called
feba16e2
MK
2498 * to add the page to the reservation map. If the page allocation fails,
2499 * the reservation must be ended instead of committed. vma_end_reservation
2500 * is called in such cases.
cf3ad20b
MK
2501 *
2502 * In the normal case, vma_commit_reservation returns the same value
2503 * as the preceding vma_needs_reservation call. The only time this
2504 * is not the case is if a reserve map was changed between calls. It
2505 * is the responsibility of the caller to notice the difference and
2506 * take appropriate action.
96b96a96
MK
2507 *
2508 * vma_add_reservation is used in error paths where a reservation must
2509 * be restored when a newly allocated huge page must be freed. It is
2510 * to be called after calling vma_needs_reservation to determine if a
2511 * reservation exists.
846be085
MK
2512 *
2513 * vma_del_reservation is used in error paths where an entry in the reserve
2514 * map was created during huge page allocation and must be removed. It is to
2515 * be called after calling vma_needs_reservation to determine if a reservation
2516 * exists.
c37f9fb1 2517 */
5e911373
MK
2518enum vma_resv_mode {
2519 VMA_NEEDS_RESV,
2520 VMA_COMMIT_RESV,
feba16e2 2521 VMA_END_RESV,
96b96a96 2522 VMA_ADD_RESV,
846be085 2523 VMA_DEL_RESV,
5e911373 2524};
cf3ad20b
MK
2525static long __vma_reservation_common(struct hstate *h,
2526 struct vm_area_struct *vma, unsigned long addr,
5e911373 2527 enum vma_resv_mode mode)
c37f9fb1 2528{
4e35f483
JK
2529 struct resv_map *resv;
2530 pgoff_t idx;
cf3ad20b 2531 long ret;
0db9d74e 2532 long dummy_out_regions_needed;
c37f9fb1 2533
4e35f483
JK
2534 resv = vma_resv_map(vma);
2535 if (!resv)
84afd99b 2536 return 1;
c37f9fb1 2537
4e35f483 2538 idx = vma_hugecache_offset(h, vma, addr);
5e911373
MK
2539 switch (mode) {
2540 case VMA_NEEDS_RESV:
0db9d74e
MA
2541 ret = region_chg(resv, idx, idx + 1, &dummy_out_regions_needed);
2542 /* We assume that vma_reservation_* routines always operate on
2543 * 1 page, and that adding to resv map a 1 page entry can only
2544 * ever require 1 region.
2545 */
2546 VM_BUG_ON(dummy_out_regions_needed != 1);
5e911373
MK
2547 break;
2548 case VMA_COMMIT_RESV:
075a61d0 2549 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
0db9d74e
MA
2550 /* region_add calls of range 1 should never fail. */
2551 VM_BUG_ON(ret < 0);
5e911373 2552 break;
feba16e2 2553 case VMA_END_RESV:
0db9d74e 2554 region_abort(resv, idx, idx + 1, 1);
5e911373
MK
2555 ret = 0;
2556 break;
96b96a96 2557 case VMA_ADD_RESV:
0db9d74e 2558 if (vma->vm_flags & VM_MAYSHARE) {
075a61d0 2559 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
0db9d74e
MA
2560 /* region_add calls of range 1 should never fail. */
2561 VM_BUG_ON(ret < 0);
2562 } else {
2563 region_abort(resv, idx, idx + 1, 1);
96b96a96
MK
2564 ret = region_del(resv, idx, idx + 1);
2565 }
2566 break;
846be085
MK
2567 case VMA_DEL_RESV:
2568 if (vma->vm_flags & VM_MAYSHARE) {
2569 region_abort(resv, idx, idx + 1, 1);
2570 ret = region_del(resv, idx, idx + 1);
2571 } else {
2572 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2573 /* region_add calls of range 1 should never fail. */
2574 VM_BUG_ON(ret < 0);
2575 }
2576 break;
5e911373
MK
2577 default:
2578 BUG();
2579 }
84afd99b 2580
846be085 2581 if (vma->vm_flags & VM_MAYSHARE || mode == VMA_DEL_RESV)
cf3ad20b 2582 return ret;
bf3d12b9
ML
2583 /*
2584 * We know private mapping must have HPAGE_RESV_OWNER set.
2585 *
2586 * In most cases, reserves always exist for private mappings.
2587 * However, a file associated with mapping could have been
2588 * hole punched or truncated after reserves were consumed.
2589 * As subsequent fault on such a range will not use reserves.
2590 * Subtle - The reserve map for private mappings has the
2591 * opposite meaning than that of shared mappings. If NO
2592 * entry is in the reserve map, it means a reservation exists.
2593 * If an entry exists in the reserve map, it means the
2594 * reservation has already been consumed. As a result, the
2595 * return value of this routine is the opposite of the
2596 * value returned from reserve map manipulation routines above.
2597 */
2598 if (ret > 0)
2599 return 0;
2600 if (ret == 0)
2601 return 1;
2602 return ret;
c37f9fb1 2603}
cf3ad20b
MK
2604
2605static long vma_needs_reservation(struct hstate *h,
a5516438 2606 struct vm_area_struct *vma, unsigned long addr)
c37f9fb1 2607{
5e911373 2608 return __vma_reservation_common(h, vma, addr, VMA_NEEDS_RESV);
cf3ad20b 2609}
84afd99b 2610
cf3ad20b
MK
2611static long vma_commit_reservation(struct hstate *h,
2612 struct vm_area_struct *vma, unsigned long addr)
2613{
5e911373
MK
2614 return __vma_reservation_common(h, vma, addr, VMA_COMMIT_RESV);
2615}
2616
feba16e2 2617static void vma_end_reservation(struct hstate *h,
5e911373
MK
2618 struct vm_area_struct *vma, unsigned long addr)
2619{
feba16e2 2620 (void)__vma_reservation_common(h, vma, addr, VMA_END_RESV);
c37f9fb1
AW
2621}
2622
96b96a96
MK
2623static long vma_add_reservation(struct hstate *h,
2624 struct vm_area_struct *vma, unsigned long addr)
2625{
2626 return __vma_reservation_common(h, vma, addr, VMA_ADD_RESV);
2627}
2628
846be085
MK
2629static long vma_del_reservation(struct hstate *h,
2630 struct vm_area_struct *vma, unsigned long addr)
2631{
2632 return __vma_reservation_common(h, vma, addr, VMA_DEL_RESV);
2633}
2634
96b96a96 2635/*
846be085
MK
2636 * This routine is called to restore reservation information on error paths.
2637 * It should ONLY be called for pages allocated via alloc_huge_page(), and
2638 * the hugetlb mutex should remain held when calling this routine.
2639 *
2640 * It handles two specific cases:
2641 * 1) A reservation was in place and the page consumed the reservation.
2642 * HPageRestoreReserve is set in the page.
2643 * 2) No reservation was in place for the page, so HPageRestoreReserve is
2644 * not set. However, alloc_huge_page always updates the reserve map.
2645 *
2646 * In case 1, free_huge_page later in the error path will increment the
2647 * global reserve count. But, free_huge_page does not have enough context
2648 * to adjust the reservation map. This case deals primarily with private
2649 * mappings. Adjust the reserve map here to be consistent with global
2650 * reserve count adjustments to be made by free_huge_page. Make sure the
2651 * reserve map indicates there is a reservation present.
2652 *
2653 * In case 2, simply undo reserve map modifications done by alloc_huge_page.
96b96a96 2654 */
846be085
MK
2655void restore_reserve_on_error(struct hstate *h, struct vm_area_struct *vma,
2656 unsigned long address, struct page *page)
96b96a96 2657{
846be085 2658 long rc = vma_needs_reservation(h, vma, address);
96b96a96 2659
846be085
MK
2660 if (HPageRestoreReserve(page)) {
2661 if (unlikely(rc < 0))
96b96a96
MK
2662 /*
2663 * Rare out of memory condition in reserve map
d6995da3 2664 * manipulation. Clear HPageRestoreReserve so that
96b96a96
MK
2665 * global reserve count will not be incremented
2666 * by free_huge_page. This will make it appear
2667 * as though the reservation for this page was
2668 * consumed. This may prevent the task from
2669 * faulting in the page at a later time. This
2670 * is better than inconsistent global huge page
2671 * accounting of reserve counts.
2672 */
d6995da3 2673 ClearHPageRestoreReserve(page);
846be085
MK
2674 else if (rc)
2675 (void)vma_add_reservation(h, vma, address);
2676 else
2677 vma_end_reservation(h, vma, address);
2678 } else {
2679 if (!rc) {
2680 /*
2681 * This indicates there is an entry in the reserve map
c7b1850d 2682 * not added by alloc_huge_page. We know it was added
846be085
MK
2683 * before the alloc_huge_page call, otherwise
2684 * HPageRestoreReserve would be set on the page.
2685 * Remove the entry so that a subsequent allocation
2686 * does not consume a reservation.
2687 */
2688 rc = vma_del_reservation(h, vma, address);
2689 if (rc < 0)
96b96a96 2690 /*
846be085
MK
2691 * VERY rare out of memory condition. Since
2692 * we can not delete the entry, set
2693 * HPageRestoreReserve so that the reserve
2694 * count will be incremented when the page
2695 * is freed. This reserve will be consumed
2696 * on a subsequent allocation.
96b96a96 2697 */
846be085
MK
2698 SetHPageRestoreReserve(page);
2699 } else if (rc < 0) {
2700 /*
2701 * Rare out of memory condition from
2702 * vma_needs_reservation call. Memory allocation is
2703 * only attempted if a new entry is needed. Therefore,
2704 * this implies there is not an entry in the
2705 * reserve map.
2706 *
2707 * For shared mappings, no entry in the map indicates
2708 * no reservation. We are done.
2709 */
2710 if (!(vma->vm_flags & VM_MAYSHARE))
2711 /*
2712 * For private mappings, no entry indicates
2713 * a reservation is present. Since we can
2714 * not add an entry, set SetHPageRestoreReserve
2715 * on the page so reserve count will be
2716 * incremented when freed. This reserve will
2717 * be consumed on a subsequent allocation.
2718 */
2719 SetHPageRestoreReserve(page);
96b96a96 2720 } else
846be085
MK
2721 /*
2722 * No reservation present, do nothing
2723 */
2724 vma_end_reservation(h, vma, address);
96b96a96
MK
2725 }
2726}
2727
369fa227
OS
2728/*
2729 * alloc_and_dissolve_huge_page - Allocate a new page and dissolve the old one
2730 * @h: struct hstate old page belongs to
2731 * @old_page: Old page to dissolve
ae37c7ff 2732 * @list: List to isolate the page in case we need to
369fa227
OS
2733 * Returns 0 on success, otherwise negated error.
2734 */
ae37c7ff
OS
2735static int alloc_and_dissolve_huge_page(struct hstate *h, struct page *old_page,
2736 struct list_head *list)
369fa227
OS
2737{
2738 gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
2739 int nid = page_to_nid(old_page);
2740 struct page *new_page;
2741 int ret = 0;
2742
2743 /*
2744 * Before dissolving the page, we need to allocate a new one for the
f41f2ed4
MS
2745 * pool to remain stable. Here, we allocate the page and 'prep' it
2746 * by doing everything but actually updating counters and adding to
2747 * the pool. This simplifies and let us do most of the processing
2748 * under the lock.
369fa227
OS
2749 */
2750 new_page = alloc_buddy_huge_page(h, gfp_mask, nid, NULL, NULL);
2751 if (!new_page)
2752 return -ENOMEM;
f41f2ed4 2753 __prep_new_huge_page(h, new_page);
369fa227
OS
2754
2755retry:
2756 spin_lock_irq(&hugetlb_lock);
2757 if (!PageHuge(old_page)) {
2758 /*
2759 * Freed from under us. Drop new_page too.
2760 */
2761 goto free_new;
2762 } else if (page_count(old_page)) {
2763 /*
ae37c7ff
OS
2764 * Someone has grabbed the page, try to isolate it here.
2765 * Fail with -EBUSY if not possible.
369fa227 2766 */
ae37c7ff 2767 spin_unlock_irq(&hugetlb_lock);
7ce82f4c 2768 ret = isolate_hugetlb(old_page, list);
ae37c7ff 2769 spin_lock_irq(&hugetlb_lock);
369fa227
OS
2770 goto free_new;
2771 } else if (!HPageFreed(old_page)) {
2772 /*
2773 * Page's refcount is 0 but it has not been enqueued in the
2774 * freelist yet. Race window is small, so we can succeed here if
2775 * we retry.
2776 */
2777 spin_unlock_irq(&hugetlb_lock);
2778 cond_resched();
2779 goto retry;
2780 } else {
2781 /*
2782 * Ok, old_page is still a genuine free hugepage. Remove it from
2783 * the freelist and decrease the counters. These will be
2784 * incremented again when calling __prep_account_new_huge_page()
2785 * and enqueue_huge_page() for new_page. The counters will remain
2786 * stable since this happens under the lock.
2787 */
2788 remove_hugetlb_page(h, old_page, false);
2789
2790 /*
b65a4eda
MK
2791 * Ref count on new page is already zero as it was dropped
2792 * earlier. It can be directly added to the pool free list.
369fa227 2793 */
369fa227 2794 __prep_account_new_huge_page(h, nid);
369fa227
OS
2795 enqueue_huge_page(h, new_page);
2796
2797 /*
2798 * Pages have been replaced, we can safely free the old one.
2799 */
2800 spin_unlock_irq(&hugetlb_lock);
b65d4adb 2801 update_and_free_page(h, old_page, false);
369fa227
OS
2802 }
2803
2804 return ret;
2805
2806free_new:
2807 spin_unlock_irq(&hugetlb_lock);
b65a4eda
MK
2808 /* Page has a zero ref count, but needs a ref to be freed */
2809 set_page_refcounted(new_page);
b65d4adb 2810 update_and_free_page(h, new_page, false);
369fa227
OS
2811
2812 return ret;
2813}
2814
ae37c7ff 2815int isolate_or_dissolve_huge_page(struct page *page, struct list_head *list)
369fa227
OS
2816{
2817 struct hstate *h;
2818 struct page *head;
ae37c7ff 2819 int ret = -EBUSY;
369fa227
OS
2820
2821 /*
2822 * The page might have been dissolved from under our feet, so make sure
2823 * to carefully check the state under the lock.
2824 * Return success when racing as if we dissolved the page ourselves.
2825 */
2826 spin_lock_irq(&hugetlb_lock);
2827 if (PageHuge(page)) {
2828 head = compound_head(page);
2829 h = page_hstate(head);
2830 } else {
2831 spin_unlock_irq(&hugetlb_lock);
2832 return 0;
2833 }
2834 spin_unlock_irq(&hugetlb_lock);
2835
2836 /*
2837 * Fence off gigantic pages as there is a cyclic dependency between
2838 * alloc_contig_range and them. Return -ENOMEM as this has the effect
2839 * of bailing out right away without further retrying.
2840 */
2841 if (hstate_is_gigantic(h))
2842 return -ENOMEM;
2843
7ce82f4c 2844 if (page_count(head) && !isolate_hugetlb(head, list))
ae37c7ff
OS
2845 ret = 0;
2846 else if (!page_count(head))
2847 ret = alloc_and_dissolve_huge_page(h, head, list);
2848
2849 return ret;
369fa227
OS
2850}
2851
70c3547e 2852struct page *alloc_huge_page(struct vm_area_struct *vma,
04f2cbe3 2853 unsigned long addr, int avoid_reserve)
1da177e4 2854{
90481622 2855 struct hugepage_subpool *spool = subpool_vma(vma);
a5516438 2856 struct hstate *h = hstate_vma(vma);
348ea204 2857 struct page *page;
d85f69b0
MK
2858 long map_chg, map_commit;
2859 long gbl_chg;
6d76dcf4
AK
2860 int ret, idx;
2861 struct hugetlb_cgroup *h_cg;
08cf9faf 2862 bool deferred_reserve;
a1e78772 2863
6d76dcf4 2864 idx = hstate_index(h);
a1e78772 2865 /*
d85f69b0
MK
2866 * Examine the region/reserve map to determine if the process
2867 * has a reservation for the page to be allocated. A return
2868 * code of zero indicates a reservation exists (no change).
a1e78772 2869 */
d85f69b0
MK
2870 map_chg = gbl_chg = vma_needs_reservation(h, vma, addr);
2871 if (map_chg < 0)
76dcee75 2872 return ERR_PTR(-ENOMEM);
d85f69b0
MK
2873
2874 /*
2875 * Processes that did not create the mapping will have no
2876 * reserves as indicated by the region/reserve map. Check
2877 * that the allocation will not exceed the subpool limit.
2878 * Allocations for MAP_NORESERVE mappings also need to be
2879 * checked against any subpool limit.
2880 */
2881 if (map_chg || avoid_reserve) {
2882 gbl_chg = hugepage_subpool_get_pages(spool, 1);
2883 if (gbl_chg < 0) {
feba16e2 2884 vma_end_reservation(h, vma, addr);
76dcee75 2885 return ERR_PTR(-ENOSPC);
5e911373 2886 }
1da177e4 2887
d85f69b0
MK
2888 /*
2889 * Even though there was no reservation in the region/reserve
2890 * map, there could be reservations associated with the
2891 * subpool that can be used. This would be indicated if the
2892 * return value of hugepage_subpool_get_pages() is zero.
2893 * However, if avoid_reserve is specified we still avoid even
2894 * the subpool reservations.
2895 */
2896 if (avoid_reserve)
2897 gbl_chg = 1;
2898 }
2899
08cf9faf
MA
2900 /* If this allocation is not consuming a reservation, charge it now.
2901 */
6501fe5f 2902 deferred_reserve = map_chg || avoid_reserve;
08cf9faf
MA
2903 if (deferred_reserve) {
2904 ret = hugetlb_cgroup_charge_cgroup_rsvd(
2905 idx, pages_per_huge_page(h), &h_cg);
2906 if (ret)
2907 goto out_subpool_put;
2908 }
2909
6d76dcf4 2910 ret = hugetlb_cgroup_charge_cgroup(idx, pages_per_huge_page(h), &h_cg);
8f34af6f 2911 if (ret)
08cf9faf 2912 goto out_uncharge_cgroup_reservation;
8f34af6f 2913
db71ef79 2914 spin_lock_irq(&hugetlb_lock);
d85f69b0
MK
2915 /*
2916 * glb_chg is passed to indicate whether or not a page must be taken
2917 * from the global free pool (global change). gbl_chg == 0 indicates
2918 * a reservation exists for the allocation.
2919 */
2920 page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve, gbl_chg);
81a6fcae 2921 if (!page) {
db71ef79 2922 spin_unlock_irq(&hugetlb_lock);
0c397dae 2923 page = alloc_buddy_huge_page_with_mpol(h, vma, addr);
8f34af6f
JZ
2924 if (!page)
2925 goto out_uncharge_cgroup;
a88c7695 2926 if (!avoid_reserve && vma_has_reserves(vma, gbl_chg)) {
d6995da3 2927 SetHPageRestoreReserve(page);
a88c7695
NH
2928 h->resv_huge_pages--;
2929 }
db71ef79 2930 spin_lock_irq(&hugetlb_lock);
15a8d68e 2931 list_add(&page->lru, &h->hugepage_activelist);
2b21624f 2932 set_page_refcounted(page);
81a6fcae 2933 /* Fall through */
68842c9b 2934 }
81a6fcae 2935 hugetlb_cgroup_commit_charge(idx, pages_per_huge_page(h), h_cg, page);
08cf9faf
MA
2936 /* If allocation is not consuming a reservation, also store the
2937 * hugetlb_cgroup pointer on the page.
2938 */
2939 if (deferred_reserve) {
2940 hugetlb_cgroup_commit_charge_rsvd(idx, pages_per_huge_page(h),
2941 h_cg, page);
2942 }
2943
db71ef79 2944 spin_unlock_irq(&hugetlb_lock);
348ea204 2945
d6995da3 2946 hugetlb_set_page_subpool(page, spool);
90d8b7e6 2947
d85f69b0
MK
2948 map_commit = vma_commit_reservation(h, vma, addr);
2949 if (unlikely(map_chg > map_commit)) {
33039678
MK
2950 /*
2951 * The page was added to the reservation map between
2952 * vma_needs_reservation and vma_commit_reservation.
2953 * This indicates a race with hugetlb_reserve_pages.
2954 * Adjust for the subpool count incremented above AND
2955 * in hugetlb_reserve_pages for the same page. Also,
2956 * the reservation count added in hugetlb_reserve_pages
2957 * no longer applies.
2958 */
2959 long rsv_adjust;
2960
2961 rsv_adjust = hugepage_subpool_put_pages(spool, 1);
2962 hugetlb_acct_memory(h, -rsv_adjust);
79aa925b
MK
2963 if (deferred_reserve)
2964 hugetlb_cgroup_uncharge_page_rsvd(hstate_index(h),
2965 pages_per_huge_page(h), page);
33039678 2966 }
90d8b7e6 2967 return page;
8f34af6f
JZ
2968
2969out_uncharge_cgroup:
2970 hugetlb_cgroup_uncharge_cgroup(idx, pages_per_huge_page(h), h_cg);
08cf9faf
MA
2971out_uncharge_cgroup_reservation:
2972 if (deferred_reserve)
2973 hugetlb_cgroup_uncharge_cgroup_rsvd(idx, pages_per_huge_page(h),
2974 h_cg);
8f34af6f 2975out_subpool_put:
d85f69b0 2976 if (map_chg || avoid_reserve)
8f34af6f 2977 hugepage_subpool_put_pages(spool, 1);
feba16e2 2978 vma_end_reservation(h, vma, addr);
8f34af6f 2979 return ERR_PTR(-ENOSPC);
b45b5bd6
DG
2980}
2981
b5389086 2982int alloc_bootmem_huge_page(struct hstate *h, int nid)
e24a1307 2983 __attribute__ ((weak, alias("__alloc_bootmem_huge_page")));
b5389086 2984int __alloc_bootmem_huge_page(struct hstate *h, int nid)
aa888a74 2985{
b5389086 2986 struct huge_bootmem_page *m = NULL; /* initialize for clang */
b2261026 2987 int nr_nodes, node;
aa888a74 2988
b5389086
ZY
2989 /* do node specific alloc */
2990 if (nid != NUMA_NO_NODE) {
2991 m = memblock_alloc_try_nid_raw(huge_page_size(h), huge_page_size(h),
2992 0, MEMBLOCK_ALLOC_ACCESSIBLE, nid);
2993 if (!m)
2994 return 0;
2995 goto found;
2996 }
2997 /* allocate from next node when distributing huge pages */
b2261026 2998 for_each_node_mask_to_alloc(h, nr_nodes, node, &node_states[N_MEMORY]) {
b5389086 2999 m = memblock_alloc_try_nid_raw(
8b89a116 3000 huge_page_size(h), huge_page_size(h),
97ad1087 3001 0, MEMBLOCK_ALLOC_ACCESSIBLE, node);
b5389086
ZY
3002 /*
3003 * Use the beginning of the huge page to store the
3004 * huge_bootmem_page struct (until gather_bootmem
3005 * puts them into the mem_map).
3006 */
3007 if (!m)
3008 return 0;
3009 goto found;
aa888a74 3010 }
aa888a74
AK
3011
3012found:
aa888a74 3013 /* Put them into a private list first because mem_map is not up yet */
330d6e48 3014 INIT_LIST_HEAD(&m->list);
aa888a74
AK
3015 list_add(&m->list, &huge_boot_pages);
3016 m->hstate = h;
3017 return 1;
3018}
3019
48b8d744
MK
3020/*
3021 * Put bootmem huge pages into the standard lists after mem_map is up.
3022 * Note: This only applies to gigantic (order > MAX_ORDER) pages.
3023 */
aa888a74
AK
3024static void __init gather_bootmem_prealloc(void)
3025{
3026 struct huge_bootmem_page *m;
3027
3028 list_for_each_entry(m, &huge_boot_pages, list) {
40d18ebf 3029 struct page *page = virt_to_page(m);
aa888a74 3030 struct hstate *h = m->hstate;
ee8f248d 3031
48b8d744 3032 VM_BUG_ON(!hstate_is_gigantic(h));
aa888a74 3033 WARN_ON(page_count(page) != 1);
7118fc29
MK
3034 if (prep_compound_gigantic_page(page, huge_page_order(h))) {
3035 WARN_ON(PageReserved(page));
3036 prep_new_huge_page(h, page, page_to_nid(page));
2b21624f 3037 free_huge_page(page); /* add to the hugepage allocator */
7118fc29 3038 } else {
416d85ed 3039 /* VERY unlikely inflated ref count on a tail page */
7118fc29 3040 free_gigantic_page(page, huge_page_order(h));
7118fc29 3041 }
af0fb9df 3042
b0320c7b 3043 /*
48b8d744
MK
3044 * We need to restore the 'stolen' pages to totalram_pages
3045 * in order to fix confusing memory reports from free(1) and
3046 * other side-effects, like CommitLimit going negative.
b0320c7b 3047 */
48b8d744 3048 adjust_managed_page_count(page, pages_per_huge_page(h));
520495fe 3049 cond_resched();
aa888a74
AK
3050 }
3051}
b5389086
ZY
3052static void __init hugetlb_hstate_alloc_pages_onenode(struct hstate *h, int nid)
3053{
3054 unsigned long i;
3055 char buf[32];
3056
3057 for (i = 0; i < h->max_huge_pages_node[nid]; ++i) {
3058 if (hstate_is_gigantic(h)) {
3059 if (!alloc_bootmem_huge_page(h, nid))
3060 break;
3061 } else {
3062 struct page *page;
3063 gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
3064
3065 page = alloc_fresh_huge_page(h, gfp_mask, nid,
3066 &node_states[N_MEMORY], NULL);
3067 if (!page)
3068 break;
2b21624f 3069 free_huge_page(page); /* free it into the hugepage allocator */
b5389086
ZY
3070 }
3071 cond_resched();
3072 }
3073 if (i == h->max_huge_pages_node[nid])
3074 return;
3075
3076 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
3077 pr_warn("HugeTLB: allocating %u of page size %s failed node%d. Only allocated %lu hugepages.\n",
3078 h->max_huge_pages_node[nid], buf, nid, i);
3079 h->max_huge_pages -= (h->max_huge_pages_node[nid] - i);
3080 h->max_huge_pages_node[nid] = i;
3081}
aa888a74 3082
8faa8b07 3083static void __init hugetlb_hstate_alloc_pages(struct hstate *h)
1da177e4
LT
3084{
3085 unsigned long i;
f60858f9 3086 nodemask_t *node_alloc_noretry;
b5389086
ZY
3087 bool node_specific_alloc = false;
3088
3089 /* skip gigantic hugepages allocation if hugetlb_cma enabled */
3090 if (hstate_is_gigantic(h) && hugetlb_cma_size) {
3091 pr_warn_once("HugeTLB: hugetlb_cma is enabled, skip boot time allocation\n");
3092 return;
3093 }
3094
3095 /* do node specific alloc */
0a7a0f6f 3096 for_each_online_node(i) {
b5389086
ZY
3097 if (h->max_huge_pages_node[i] > 0) {
3098 hugetlb_hstate_alloc_pages_onenode(h, i);
3099 node_specific_alloc = true;
3100 }
3101 }
f60858f9 3102
b5389086
ZY
3103 if (node_specific_alloc)
3104 return;
3105
3106 /* below will do all node balanced alloc */
f60858f9
MK
3107 if (!hstate_is_gigantic(h)) {
3108 /*
3109 * Bit mask controlling how hard we retry per-node allocations.
3110 * Ignore errors as lower level routines can deal with
3111 * node_alloc_noretry == NULL. If this kmalloc fails at boot
3112 * time, we are likely in bigger trouble.
3113 */
3114 node_alloc_noretry = kmalloc(sizeof(*node_alloc_noretry),
3115 GFP_KERNEL);
3116 } else {
3117 /* allocations done at boot time */
3118 node_alloc_noretry = NULL;
3119 }
3120
3121 /* bit mask controlling how hard we retry per-node allocations */
3122 if (node_alloc_noretry)
3123 nodes_clear(*node_alloc_noretry);
a5516438 3124
e5ff2159 3125 for (i = 0; i < h->max_huge_pages; ++i) {
bae7f4ae 3126 if (hstate_is_gigantic(h)) {
b5389086 3127 if (!alloc_bootmem_huge_page(h, NUMA_NO_NODE))
aa888a74 3128 break;
0c397dae 3129 } else if (!alloc_pool_huge_page(h,
f60858f9
MK
3130 &node_states[N_MEMORY],
3131 node_alloc_noretry))
1da177e4 3132 break;
69ed779a 3133 cond_resched();
1da177e4 3134 }
d715cf80
LH
3135 if (i < h->max_huge_pages) {
3136 char buf[32];
3137
c6247f72 3138 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
d715cf80
LH
3139 pr_warn("HugeTLB: allocating %lu of page size %s failed. Only allocated %lu hugepages.\n",
3140 h->max_huge_pages, buf, i);
3141 h->max_huge_pages = i;
3142 }
f60858f9 3143 kfree(node_alloc_noretry);
e5ff2159
AK
3144}
3145
3146static void __init hugetlb_init_hstates(void)
3147{
79dfc695 3148 struct hstate *h, *h2;
e5ff2159
AK
3149
3150 for_each_hstate(h) {
8faa8b07 3151 /* oversize hugepages were init'ed in early boot */
bae7f4ae 3152 if (!hstate_is_gigantic(h))
8faa8b07 3153 hugetlb_hstate_alloc_pages(h);
79dfc695
MK
3154
3155 /*
3156 * Set demote order for each hstate. Note that
3157 * h->demote_order is initially 0.
3158 * - We can not demote gigantic pages if runtime freeing
3159 * is not supported, so skip this.
a01f4390
MK
3160 * - If CMA allocation is possible, we can not demote
3161 * HUGETLB_PAGE_ORDER or smaller size pages.
79dfc695
MK
3162 */
3163 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
3164 continue;
a01f4390
MK
3165 if (hugetlb_cma_size && h->order <= HUGETLB_PAGE_ORDER)
3166 continue;
79dfc695
MK
3167 for_each_hstate(h2) {
3168 if (h2 == h)
3169 continue;
3170 if (h2->order < h->order &&
3171 h2->order > h->demote_order)
3172 h->demote_order = h2->order;
3173 }
e5ff2159
AK
3174 }
3175}
3176
3177static void __init report_hugepages(void)
3178{
3179 struct hstate *h;
3180
3181 for_each_hstate(h) {
4abd32db 3182 char buf[32];
c6247f72
MW
3183
3184 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
6213834c 3185 pr_info("HugeTLB: registered %s page size, pre-allocated %ld pages\n",
c6247f72 3186 buf, h->free_huge_pages);
6213834c
MS
3187 pr_info("HugeTLB: %d KiB vmemmap can be freed for a %s page\n",
3188 hugetlb_vmemmap_optimizable_size(h) / SZ_1K, buf);
e5ff2159
AK
3189 }
3190}
3191
1da177e4 3192#ifdef CONFIG_HIGHMEM
6ae11b27
LS
3193static void try_to_free_low(struct hstate *h, unsigned long count,
3194 nodemask_t *nodes_allowed)
1da177e4 3195{
4415cc8d 3196 int i;
1121828a 3197 LIST_HEAD(page_list);
4415cc8d 3198
9487ca60 3199 lockdep_assert_held(&hugetlb_lock);
bae7f4ae 3200 if (hstate_is_gigantic(h))
aa888a74
AK
3201 return;
3202
1121828a
MK
3203 /*
3204 * Collect pages to be freed on a list, and free after dropping lock
3205 */
6ae11b27 3206 for_each_node_mask(i, *nodes_allowed) {
10c6ec49 3207 struct page *page, *next;
a5516438
AK
3208 struct list_head *freel = &h->hugepage_freelists[i];
3209 list_for_each_entry_safe(page, next, freel, lru) {
3210 if (count >= h->nr_huge_pages)
1121828a 3211 goto out;
1da177e4
LT
3212 if (PageHighMem(page))
3213 continue;
6eb4e88a 3214 remove_hugetlb_page(h, page, false);
1121828a 3215 list_add(&page->lru, &page_list);
1da177e4
LT
3216 }
3217 }
1121828a
MK
3218
3219out:
db71ef79 3220 spin_unlock_irq(&hugetlb_lock);
10c6ec49 3221 update_and_free_pages_bulk(h, &page_list);
db71ef79 3222 spin_lock_irq(&hugetlb_lock);
1da177e4
LT
3223}
3224#else
6ae11b27
LS
3225static inline void try_to_free_low(struct hstate *h, unsigned long count,
3226 nodemask_t *nodes_allowed)
1da177e4
LT
3227{
3228}
3229#endif
3230
20a0307c
WF
3231/*
3232 * Increment or decrement surplus_huge_pages. Keep node-specific counters
3233 * balanced by operating on them in a round-robin fashion.
3234 * Returns 1 if an adjustment was made.
3235 */
6ae11b27
LS
3236static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed,
3237 int delta)
20a0307c 3238{
b2261026 3239 int nr_nodes, node;
20a0307c 3240
9487ca60 3241 lockdep_assert_held(&hugetlb_lock);
20a0307c 3242 VM_BUG_ON(delta != -1 && delta != 1);
20a0307c 3243
b2261026
JK
3244 if (delta < 0) {
3245 for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
3246 if (h->surplus_huge_pages_node[node])
3247 goto found;
e8c5c824 3248 }
b2261026
JK
3249 } else {
3250 for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
3251 if (h->surplus_huge_pages_node[node] <
3252 h->nr_huge_pages_node[node])
3253 goto found;
e8c5c824 3254 }
b2261026
JK
3255 }
3256 return 0;
20a0307c 3257
b2261026
JK
3258found:
3259 h->surplus_huge_pages += delta;
3260 h->surplus_huge_pages_node[node] += delta;
3261 return 1;
20a0307c
WF
3262}
3263
a5516438 3264#define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages)
fd875dca 3265static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,
4eb0716e 3266 nodemask_t *nodes_allowed)
1da177e4 3267{
7893d1d5 3268 unsigned long min_count, ret;
10c6ec49
MK
3269 struct page *page;
3270 LIST_HEAD(page_list);
f60858f9
MK
3271 NODEMASK_ALLOC(nodemask_t, node_alloc_noretry, GFP_KERNEL);
3272
3273 /*
3274 * Bit mask controlling how hard we retry per-node allocations.
3275 * If we can not allocate the bit mask, do not attempt to allocate
3276 * the requested huge pages.
3277 */
3278 if (node_alloc_noretry)
3279 nodes_clear(*node_alloc_noretry);
3280 else
3281 return -ENOMEM;
1da177e4 3282
29383967
MK
3283 /*
3284 * resize_lock mutex prevents concurrent adjustments to number of
3285 * pages in hstate via the proc/sysfs interfaces.
3286 */
3287 mutex_lock(&h->resize_lock);
b65d4adb 3288 flush_free_hpage_work(h);
db71ef79 3289 spin_lock_irq(&hugetlb_lock);
4eb0716e 3290
fd875dca
MK
3291 /*
3292 * Check for a node specific request.
3293 * Changing node specific huge page count may require a corresponding
3294 * change to the global count. In any case, the passed node mask
3295 * (nodes_allowed) will restrict alloc/free to the specified node.
3296 */
3297 if (nid != NUMA_NO_NODE) {
3298 unsigned long old_count = count;
3299
3300 count += h->nr_huge_pages - h->nr_huge_pages_node[nid];
3301 /*
3302 * User may have specified a large count value which caused the
3303 * above calculation to overflow. In this case, they wanted
3304 * to allocate as many huge pages as possible. Set count to
3305 * largest possible value to align with their intention.
3306 */
3307 if (count < old_count)
3308 count = ULONG_MAX;
3309 }
3310
4eb0716e
AG
3311 /*
3312 * Gigantic pages runtime allocation depend on the capability for large
3313 * page range allocation.
3314 * If the system does not provide this feature, return an error when
3315 * the user tries to allocate gigantic pages but let the user free the
3316 * boottime allocated gigantic pages.
3317 */
3318 if (hstate_is_gigantic(h) && !IS_ENABLED(CONFIG_CONTIG_ALLOC)) {
3319 if (count > persistent_huge_pages(h)) {
db71ef79 3320 spin_unlock_irq(&hugetlb_lock);
29383967 3321 mutex_unlock(&h->resize_lock);
f60858f9 3322 NODEMASK_FREE(node_alloc_noretry);
4eb0716e
AG
3323 return -EINVAL;
3324 }
3325 /* Fall through to decrease pool */
3326 }
aa888a74 3327
7893d1d5
AL
3328 /*
3329 * Increase the pool size
3330 * First take pages out of surplus state. Then make up the
3331 * remaining difference by allocating fresh huge pages.
d1c3fb1f 3332 *
0c397dae 3333 * We might race with alloc_surplus_huge_page() here and be unable
d1c3fb1f
NA
3334 * to convert a surplus huge page to a normal huge page. That is
3335 * not critical, though, it just means the overall size of the
3336 * pool might be one hugepage larger than it needs to be, but
3337 * within all the constraints specified by the sysctls.
7893d1d5 3338 */
a5516438 3339 while (h->surplus_huge_pages && count > persistent_huge_pages(h)) {
6ae11b27 3340 if (!adjust_pool_surplus(h, nodes_allowed, -1))
7893d1d5
AL
3341 break;
3342 }
3343
a5516438 3344 while (count > persistent_huge_pages(h)) {
7893d1d5
AL
3345 /*
3346 * If this allocation races such that we no longer need the
3347 * page, free_huge_page will handle it by freeing the page
3348 * and reducing the surplus.
3349 */
db71ef79 3350 spin_unlock_irq(&hugetlb_lock);
649920c6
JH
3351
3352 /* yield cpu to avoid soft lockup */
3353 cond_resched();
3354
f60858f9
MK
3355 ret = alloc_pool_huge_page(h, nodes_allowed,
3356 node_alloc_noretry);
db71ef79 3357 spin_lock_irq(&hugetlb_lock);
7893d1d5
AL
3358 if (!ret)
3359 goto out;
3360
536240f2
MG
3361 /* Bail for signals. Probably ctrl-c from user */
3362 if (signal_pending(current))
3363 goto out;
7893d1d5 3364 }
7893d1d5
AL
3365
3366 /*
3367 * Decrease the pool size
3368 * First return free pages to the buddy allocator (being careful
3369 * to keep enough around to satisfy reservations). Then place
3370 * pages into surplus state as needed so the pool will shrink
3371 * to the desired size as pages become free.
d1c3fb1f
NA
3372 *
3373 * By placing pages into the surplus state independent of the
3374 * overcommit value, we are allowing the surplus pool size to
3375 * exceed overcommit. There are few sane options here. Since
0c397dae 3376 * alloc_surplus_huge_page() is checking the global counter,
d1c3fb1f
NA
3377 * though, we'll note that we're not allowed to exceed surplus
3378 * and won't grow the pool anywhere else. Not until one of the
3379 * sysctls are changed, or the surplus pages go out of use.
7893d1d5 3380 */
a5516438 3381 min_count = h->resv_huge_pages + h->nr_huge_pages - h->free_huge_pages;
6b0c880d 3382 min_count = max(count, min_count);
6ae11b27 3383 try_to_free_low(h, min_count, nodes_allowed);
10c6ec49
MK
3384
3385 /*
3386 * Collect pages to be removed on list without dropping lock
3387 */
a5516438 3388 while (min_count < persistent_huge_pages(h)) {
10c6ec49
MK
3389 page = remove_pool_huge_page(h, nodes_allowed, 0);
3390 if (!page)
1da177e4 3391 break;
10c6ec49
MK
3392
3393 list_add(&page->lru, &page_list);
1da177e4 3394 }
10c6ec49 3395 /* free the pages after dropping lock */
db71ef79 3396 spin_unlock_irq(&hugetlb_lock);
10c6ec49 3397 update_and_free_pages_bulk(h, &page_list);
b65d4adb 3398 flush_free_hpage_work(h);
db71ef79 3399 spin_lock_irq(&hugetlb_lock);
10c6ec49 3400
a5516438 3401 while (count < persistent_huge_pages(h)) {
6ae11b27 3402 if (!adjust_pool_surplus(h, nodes_allowed, 1))
7893d1d5
AL
3403 break;
3404 }
3405out:
4eb0716e 3406 h->max_huge_pages = persistent_huge_pages(h);
db71ef79 3407 spin_unlock_irq(&hugetlb_lock);
29383967 3408 mutex_unlock(&h->resize_lock);
4eb0716e 3409
f60858f9
MK
3410 NODEMASK_FREE(node_alloc_noretry);
3411
4eb0716e 3412 return 0;
1da177e4
LT
3413}
3414
8531fc6f
MK
3415static int demote_free_huge_page(struct hstate *h, struct page *page)
3416{
3417 int i, nid = page_to_nid(page);
3418 struct hstate *target_hstate;
31731452 3419 struct page *subpage;
8531fc6f
MK
3420 int rc = 0;
3421
3422 target_hstate = size_to_hstate(PAGE_SIZE << h->demote_order);
3423
3424 remove_hugetlb_page_for_demote(h, page, false);
3425 spin_unlock_irq(&hugetlb_lock);
3426
6213834c 3427 rc = hugetlb_vmemmap_restore(h, page);
8531fc6f
MK
3428 if (rc) {
3429 /* Allocation of vmemmmap failed, we can not demote page */
3430 spin_lock_irq(&hugetlb_lock);
3431 set_page_refcounted(page);
3432 add_hugetlb_page(h, page, false);
3433 return rc;
3434 }
3435
3436 /*
3437 * Use destroy_compound_hugetlb_page_for_demote for all huge page
3438 * sizes as it will not ref count pages.
3439 */
3440 destroy_compound_hugetlb_page_for_demote(page, huge_page_order(h));
3441
3442 /*
3443 * Taking target hstate mutex synchronizes with set_max_huge_pages.
3444 * Without the mutex, pages added to target hstate could be marked
3445 * as surplus.
3446 *
3447 * Note that we already hold h->resize_lock. To prevent deadlock,
3448 * use the convention of always taking larger size hstate mutex first.
3449 */
3450 mutex_lock(&target_hstate->resize_lock);
3451 for (i = 0; i < pages_per_huge_page(h);
3452 i += pages_per_huge_page(target_hstate)) {
31731452 3453 subpage = nth_page(page, i);
8531fc6f 3454 if (hstate_is_gigantic(target_hstate))
31731452 3455 prep_compound_gigantic_page_for_demote(subpage,
8531fc6f
MK
3456 target_hstate->order);
3457 else
31731452
DB
3458 prep_compound_page(subpage, target_hstate->order);
3459 set_page_private(subpage, 0);
31731452 3460 prep_new_huge_page(target_hstate, subpage, nid);
2b21624f 3461 free_huge_page(subpage);
8531fc6f
MK
3462 }
3463 mutex_unlock(&target_hstate->resize_lock);
3464
3465 spin_lock_irq(&hugetlb_lock);
3466
3467 /*
3468 * Not absolutely necessary, but for consistency update max_huge_pages
3469 * based on pool changes for the demoted page.
3470 */
3471 h->max_huge_pages--;
a43a83c7
ML
3472 target_hstate->max_huge_pages +=
3473 pages_per_huge_page(h) / pages_per_huge_page(target_hstate);
8531fc6f
MK
3474
3475 return rc;
3476}
3477
79dfc695
MK
3478static int demote_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed)
3479 __must_hold(&hugetlb_lock)
3480{
8531fc6f
MK
3481 int nr_nodes, node;
3482 struct page *page;
79dfc695
MK
3483
3484 lockdep_assert_held(&hugetlb_lock);
3485
3486 /* We should never get here if no demote order */
3487 if (!h->demote_order) {
3488 pr_warn("HugeTLB: NULL demote order passed to demote_pool_huge_page.\n");
3489 return -EINVAL; /* internal error */
3490 }
3491
8531fc6f 3492 for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
5a317412
MK
3493 list_for_each_entry(page, &h->hugepage_freelists[node], lru) {
3494 if (PageHWPoison(page))
3495 continue;
3496
3497 return demote_free_huge_page(h, page);
8531fc6f
MK
3498 }
3499 }
3500
5a317412
MK
3501 /*
3502 * Only way to get here is if all pages on free lists are poisoned.
3503 * Return -EBUSY so that caller will not retry.
3504 */
3505 return -EBUSY;
79dfc695
MK
3506}
3507
a3437870
NA
3508#define HSTATE_ATTR_RO(_name) \
3509 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
3510
79dfc695
MK
3511#define HSTATE_ATTR_WO(_name) \
3512 static struct kobj_attribute _name##_attr = __ATTR_WO(_name)
3513
a3437870 3514#define HSTATE_ATTR(_name) \
98bc26ac 3515 static struct kobj_attribute _name##_attr = __ATTR_RW(_name)
a3437870
NA
3516
3517static struct kobject *hugepages_kobj;
3518static struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
3519
9a305230
LS
3520static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp);
3521
3522static struct hstate *kobj_to_hstate(struct kobject *kobj, int *nidp)
a3437870
NA
3523{
3524 int i;
9a305230 3525
a3437870 3526 for (i = 0; i < HUGE_MAX_HSTATE; i++)
9a305230
LS
3527 if (hstate_kobjs[i] == kobj) {
3528 if (nidp)
3529 *nidp = NUMA_NO_NODE;
a3437870 3530 return &hstates[i];
9a305230
LS
3531 }
3532
3533 return kobj_to_node_hstate(kobj, nidp);
a3437870
NA
3534}
3535
06808b08 3536static ssize_t nr_hugepages_show_common(struct kobject *kobj,
a3437870
NA
3537 struct kobj_attribute *attr, char *buf)
3538{
9a305230
LS
3539 struct hstate *h;
3540 unsigned long nr_huge_pages;
3541 int nid;
3542
3543 h = kobj_to_hstate(kobj, &nid);
3544 if (nid == NUMA_NO_NODE)
3545 nr_huge_pages = h->nr_huge_pages;
3546 else
3547 nr_huge_pages = h->nr_huge_pages_node[nid];
3548
ae7a927d 3549 return sysfs_emit(buf, "%lu\n", nr_huge_pages);
a3437870 3550}
adbe8726 3551
238d3c13
DR
3552static ssize_t __nr_hugepages_store_common(bool obey_mempolicy,
3553 struct hstate *h, int nid,
3554 unsigned long count, size_t len)
a3437870
NA
3555{
3556 int err;
2d0adf7e 3557 nodemask_t nodes_allowed, *n_mask;
a3437870 3558
2d0adf7e
OS
3559 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
3560 return -EINVAL;
adbe8726 3561
9a305230
LS
3562 if (nid == NUMA_NO_NODE) {
3563 /*
3564 * global hstate attribute
3565 */
3566 if (!(obey_mempolicy &&
2d0adf7e
OS
3567 init_nodemask_of_mempolicy(&nodes_allowed)))
3568 n_mask = &node_states[N_MEMORY];
3569 else
3570 n_mask = &nodes_allowed;
3571 } else {
9a305230 3572 /*
fd875dca
MK
3573 * Node specific request. count adjustment happens in
3574 * set_max_huge_pages() after acquiring hugetlb_lock.
9a305230 3575 */
2d0adf7e
OS
3576 init_nodemask_of_node(&nodes_allowed, nid);
3577 n_mask = &nodes_allowed;
fd875dca 3578 }
9a305230 3579
2d0adf7e 3580 err = set_max_huge_pages(h, count, nid, n_mask);
06808b08 3581
4eb0716e 3582 return err ? err : len;
06808b08
LS
3583}
3584
238d3c13
DR
3585static ssize_t nr_hugepages_store_common(bool obey_mempolicy,
3586 struct kobject *kobj, const char *buf,
3587 size_t len)
3588{
3589 struct hstate *h;
3590 unsigned long count;
3591 int nid;
3592 int err;
3593
3594 err = kstrtoul(buf, 10, &count);
3595 if (err)
3596 return err;
3597
3598 h = kobj_to_hstate(kobj, &nid);
3599 return __nr_hugepages_store_common(obey_mempolicy, h, nid, count, len);
3600}
3601
06808b08
LS
3602static ssize_t nr_hugepages_show(struct kobject *kobj,
3603 struct kobj_attribute *attr, char *buf)
3604{
3605 return nr_hugepages_show_common(kobj, attr, buf);
3606}
3607
3608static ssize_t nr_hugepages_store(struct kobject *kobj,
3609 struct kobj_attribute *attr, const char *buf, size_t len)
3610{
238d3c13 3611 return nr_hugepages_store_common(false, kobj, buf, len);
a3437870
NA
3612}
3613HSTATE_ATTR(nr_hugepages);
3614
06808b08
LS
3615#ifdef CONFIG_NUMA
3616
3617/*
3618 * hstate attribute for optionally mempolicy-based constraint on persistent
3619 * huge page alloc/free.
3620 */
3621static ssize_t nr_hugepages_mempolicy_show(struct kobject *kobj,
ae7a927d
JP
3622 struct kobj_attribute *attr,
3623 char *buf)
06808b08
LS
3624{
3625 return nr_hugepages_show_common(kobj, attr, buf);
3626}
3627
3628static ssize_t nr_hugepages_mempolicy_store(struct kobject *kobj,
3629 struct kobj_attribute *attr, const char *buf, size_t len)
3630{
238d3c13 3631 return nr_hugepages_store_common(true, kobj, buf, len);
06808b08
LS
3632}
3633HSTATE_ATTR(nr_hugepages_mempolicy);
3634#endif
3635
3636
a3437870
NA
3637static ssize_t nr_overcommit_hugepages_show(struct kobject *kobj,
3638 struct kobj_attribute *attr, char *buf)
3639{
9a305230 3640 struct hstate *h = kobj_to_hstate(kobj, NULL);
ae7a927d 3641 return sysfs_emit(buf, "%lu\n", h->nr_overcommit_huge_pages);
a3437870 3642}
adbe8726 3643
a3437870
NA
3644static ssize_t nr_overcommit_hugepages_store(struct kobject *kobj,
3645 struct kobj_attribute *attr, const char *buf, size_t count)
3646{
3647 int err;
3648 unsigned long input;
9a305230 3649 struct hstate *h = kobj_to_hstate(kobj, NULL);
a3437870 3650
bae7f4ae 3651 if (hstate_is_gigantic(h))
adbe8726
EM
3652 return -EINVAL;
3653
3dbb95f7 3654 err = kstrtoul(buf, 10, &input);
a3437870 3655 if (err)
73ae31e5 3656 return err;
a3437870 3657
db71ef79 3658 spin_lock_irq(&hugetlb_lock);
a3437870 3659 h->nr_overcommit_huge_pages = input;
db71ef79 3660 spin_unlock_irq(&hugetlb_lock);
a3437870
NA
3661
3662 return count;
3663}
3664HSTATE_ATTR(nr_overcommit_hugepages);
3665
3666static ssize_t free_hugepages_show(struct kobject *kobj,
3667 struct kobj_attribute *attr, char *buf)
3668{
9a305230
LS
3669 struct hstate *h;
3670 unsigned long free_huge_pages;
3671 int nid;
3672
3673 h = kobj_to_hstate(kobj, &nid);
3674 if (nid == NUMA_NO_NODE)
3675 free_huge_pages = h->free_huge_pages;
3676 else
3677 free_huge_pages = h->free_huge_pages_node[nid];
3678
ae7a927d 3679 return sysfs_emit(buf, "%lu\n", free_huge_pages);
a3437870
NA
3680}
3681HSTATE_ATTR_RO(free_hugepages);
3682
3683static ssize_t resv_hugepages_show(struct kobject *kobj,
3684 struct kobj_attribute *attr, char *buf)
3685{
9a305230 3686 struct hstate *h = kobj_to_hstate(kobj, NULL);
ae7a927d 3687 return sysfs_emit(buf, "%lu\n", h->resv_huge_pages);
a3437870
NA
3688}
3689HSTATE_ATTR_RO(resv_hugepages);
3690
3691static ssize_t surplus_hugepages_show(struct kobject *kobj,
3692 struct kobj_attribute *attr, char *buf)
3693{
9a305230
LS
3694 struct hstate *h;
3695 unsigned long surplus_huge_pages;
3696 int nid;
3697
3698 h = kobj_to_hstate(kobj, &nid);
3699 if (nid == NUMA_NO_NODE)
3700 surplus_huge_pages = h->surplus_huge_pages;
3701 else
3702 surplus_huge_pages = h->surplus_huge_pages_node[nid];
3703
ae7a927d 3704 return sysfs_emit(buf, "%lu\n", surplus_huge_pages);
a3437870
NA
3705}
3706HSTATE_ATTR_RO(surplus_hugepages);
3707
79dfc695
MK
3708static ssize_t demote_store(struct kobject *kobj,
3709 struct kobj_attribute *attr, const char *buf, size_t len)
3710{
3711 unsigned long nr_demote;
3712 unsigned long nr_available;
3713 nodemask_t nodes_allowed, *n_mask;
3714 struct hstate *h;
8eeda55f 3715 int err;
79dfc695
MK
3716 int nid;
3717
3718 err = kstrtoul(buf, 10, &nr_demote);
3719 if (err)
3720 return err;
3721 h = kobj_to_hstate(kobj, &nid);
3722
3723 if (nid != NUMA_NO_NODE) {
3724 init_nodemask_of_node(&nodes_allowed, nid);
3725 n_mask = &nodes_allowed;
3726 } else {
3727 n_mask = &node_states[N_MEMORY];
3728 }
3729
3730 /* Synchronize with other sysfs operations modifying huge pages */
3731 mutex_lock(&h->resize_lock);
3732 spin_lock_irq(&hugetlb_lock);
3733
3734 while (nr_demote) {
3735 /*
3736 * Check for available pages to demote each time thorough the
3737 * loop as demote_pool_huge_page will drop hugetlb_lock.
79dfc695
MK
3738 */
3739 if (nid != NUMA_NO_NODE)
3740 nr_available = h->free_huge_pages_node[nid];
3741 else
3742 nr_available = h->free_huge_pages;
3743 nr_available -= h->resv_huge_pages;
3744 if (!nr_available)
3745 break;
3746
3747 err = demote_pool_huge_page(h, n_mask);
3748 if (err)
3749 break;
3750
3751 nr_demote--;
3752 }
3753
3754 spin_unlock_irq(&hugetlb_lock);
3755 mutex_unlock(&h->resize_lock);
3756
3757 if (err)
3758 return err;
3759 return len;
3760}
3761HSTATE_ATTR_WO(demote);
3762
3763static ssize_t demote_size_show(struct kobject *kobj,
3764 struct kobj_attribute *attr, char *buf)
3765{
12658abf 3766 struct hstate *h = kobj_to_hstate(kobj, NULL);
79dfc695
MK
3767 unsigned long demote_size = (PAGE_SIZE << h->demote_order) / SZ_1K;
3768
3769 return sysfs_emit(buf, "%lukB\n", demote_size);
3770}
3771
3772static ssize_t demote_size_store(struct kobject *kobj,
3773 struct kobj_attribute *attr,
3774 const char *buf, size_t count)
3775{
3776 struct hstate *h, *demote_hstate;
3777 unsigned long demote_size;
3778 unsigned int demote_order;
79dfc695
MK
3779
3780 demote_size = (unsigned long)memparse(buf, NULL);
3781
3782 demote_hstate = size_to_hstate(demote_size);
3783 if (!demote_hstate)
3784 return -EINVAL;
3785 demote_order = demote_hstate->order;
a01f4390
MK
3786 if (demote_order < HUGETLB_PAGE_ORDER)
3787 return -EINVAL;
79dfc695
MK
3788
3789 /* demote order must be smaller than hstate order */
12658abf 3790 h = kobj_to_hstate(kobj, NULL);
79dfc695
MK
3791 if (demote_order >= h->order)
3792 return -EINVAL;
3793
3794 /* resize_lock synchronizes access to demote size and writes */
3795 mutex_lock(&h->resize_lock);
3796 h->demote_order = demote_order;
3797 mutex_unlock(&h->resize_lock);
3798
3799 return count;
3800}
3801HSTATE_ATTR(demote_size);
3802
a3437870
NA
3803static struct attribute *hstate_attrs[] = {
3804 &nr_hugepages_attr.attr,
3805 &nr_overcommit_hugepages_attr.attr,
3806 &free_hugepages_attr.attr,
3807 &resv_hugepages_attr.attr,
3808 &surplus_hugepages_attr.attr,
06808b08
LS
3809#ifdef CONFIG_NUMA
3810 &nr_hugepages_mempolicy_attr.attr,
3811#endif
a3437870
NA
3812 NULL,
3813};
3814
67e5ed96 3815static const struct attribute_group hstate_attr_group = {
a3437870
NA
3816 .attrs = hstate_attrs,
3817};
3818
79dfc695
MK
3819static struct attribute *hstate_demote_attrs[] = {
3820 &demote_size_attr.attr,
3821 &demote_attr.attr,
3822 NULL,
3823};
3824
3825static const struct attribute_group hstate_demote_attr_group = {
3826 .attrs = hstate_demote_attrs,
3827};
3828
094e9539
JM
3829static int hugetlb_sysfs_add_hstate(struct hstate *h, struct kobject *parent,
3830 struct kobject **hstate_kobjs,
67e5ed96 3831 const struct attribute_group *hstate_attr_group)
a3437870
NA
3832{
3833 int retval;
972dc4de 3834 int hi = hstate_index(h);
a3437870 3835
9a305230
LS
3836 hstate_kobjs[hi] = kobject_create_and_add(h->name, parent);
3837 if (!hstate_kobjs[hi])
a3437870
NA
3838 return -ENOMEM;
3839
9a305230 3840 retval = sysfs_create_group(hstate_kobjs[hi], hstate_attr_group);
cc2205a6 3841 if (retval) {
9a305230 3842 kobject_put(hstate_kobjs[hi]);
cc2205a6 3843 hstate_kobjs[hi] = NULL;
3a6bdda0 3844 return retval;
cc2205a6 3845 }
a3437870 3846
79dfc695 3847 if (h->demote_order) {
01088a60
ML
3848 retval = sysfs_create_group(hstate_kobjs[hi],
3849 &hstate_demote_attr_group);
3850 if (retval) {
79dfc695 3851 pr_warn("HugeTLB unable to create demote interfaces for %s\n", h->name);
01088a60
ML
3852 sysfs_remove_group(hstate_kobjs[hi], hstate_attr_group);
3853 kobject_put(hstate_kobjs[hi]);
3854 hstate_kobjs[hi] = NULL;
3855 return retval;
3856 }
79dfc695
MK
3857 }
3858
01088a60 3859 return 0;
a3437870
NA
3860}
3861
9a305230 3862#ifdef CONFIG_NUMA
a4a00b45 3863static bool hugetlb_sysfs_initialized __ro_after_init;
9a305230
LS
3864
3865/*
3866 * node_hstate/s - associate per node hstate attributes, via their kobjects,
10fbcf4c
KS
3867 * with node devices in node_devices[] using a parallel array. The array
3868 * index of a node device or _hstate == node id.
3869 * This is here to avoid any static dependency of the node device driver, in
9a305230
LS
3870 * the base kernel, on the hugetlb module.
3871 */
3872struct node_hstate {
3873 struct kobject *hugepages_kobj;
3874 struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
3875};
b4e289a6 3876static struct node_hstate node_hstates[MAX_NUMNODES];
9a305230
LS
3877
3878/*
10fbcf4c 3879 * A subset of global hstate attributes for node devices
9a305230
LS
3880 */
3881static struct attribute *per_node_hstate_attrs[] = {
3882 &nr_hugepages_attr.attr,
3883 &free_hugepages_attr.attr,
3884 &surplus_hugepages_attr.attr,
3885 NULL,
3886};
3887
67e5ed96 3888static const struct attribute_group per_node_hstate_attr_group = {
9a305230
LS
3889 .attrs = per_node_hstate_attrs,
3890};
3891
3892/*
10fbcf4c 3893 * kobj_to_node_hstate - lookup global hstate for node device hstate attr kobj.
9a305230
LS
3894 * Returns node id via non-NULL nidp.
3895 */
3896static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
3897{
3898 int nid;
3899
3900 for (nid = 0; nid < nr_node_ids; nid++) {
3901 struct node_hstate *nhs = &node_hstates[nid];
3902 int i;
3903 for (i = 0; i < HUGE_MAX_HSTATE; i++)
3904 if (nhs->hstate_kobjs[i] == kobj) {
3905 if (nidp)
3906 *nidp = nid;
3907 return &hstates[i];
3908 }
3909 }
3910
3911 BUG();
3912 return NULL;
3913}
3914
3915/*
10fbcf4c 3916 * Unregister hstate attributes from a single node device.
9a305230
LS
3917 * No-op if no hstate attributes attached.
3918 */
a4a00b45 3919void hugetlb_unregister_node(struct node *node)
9a305230
LS
3920{
3921 struct hstate *h;
10fbcf4c 3922 struct node_hstate *nhs = &node_hstates[node->dev.id];
9a305230
LS
3923
3924 if (!nhs->hugepages_kobj)
9b5e5d0f 3925 return; /* no hstate attributes */
9a305230 3926
972dc4de
AK
3927 for_each_hstate(h) {
3928 int idx = hstate_index(h);
01088a60
ML
3929 struct kobject *hstate_kobj = nhs->hstate_kobjs[idx];
3930
3931 if (!hstate_kobj)
3932 continue;
3933 if (h->demote_order)
3934 sysfs_remove_group(hstate_kobj, &hstate_demote_attr_group);
3935 sysfs_remove_group(hstate_kobj, &per_node_hstate_attr_group);
3936 kobject_put(hstate_kobj);
3937 nhs->hstate_kobjs[idx] = NULL;
972dc4de 3938 }
9a305230
LS
3939
3940 kobject_put(nhs->hugepages_kobj);
3941 nhs->hugepages_kobj = NULL;
3942}
3943
9a305230
LS
3944
3945/*
10fbcf4c 3946 * Register hstate attributes for a single node device.
9a305230
LS
3947 * No-op if attributes already registered.
3948 */
a4a00b45 3949void hugetlb_register_node(struct node *node)
9a305230
LS
3950{
3951 struct hstate *h;
10fbcf4c 3952 struct node_hstate *nhs = &node_hstates[node->dev.id];
9a305230
LS
3953 int err;
3954
a4a00b45
MS
3955 if (!hugetlb_sysfs_initialized)
3956 return;
3957
9a305230
LS
3958 if (nhs->hugepages_kobj)
3959 return; /* already allocated */
3960
3961 nhs->hugepages_kobj = kobject_create_and_add("hugepages",
10fbcf4c 3962 &node->dev.kobj);
9a305230
LS
3963 if (!nhs->hugepages_kobj)
3964 return;
3965
3966 for_each_hstate(h) {
3967 err = hugetlb_sysfs_add_hstate(h, nhs->hugepages_kobj,
3968 nhs->hstate_kobjs,
3969 &per_node_hstate_attr_group);
3970 if (err) {
282f4214 3971 pr_err("HugeTLB: Unable to add hstate %s for node %d\n",
ffb22af5 3972 h->name, node->dev.id);
9a305230
LS
3973 hugetlb_unregister_node(node);
3974 break;
3975 }
3976 }
3977}
3978
3979/*
9b5e5d0f 3980 * hugetlb init time: register hstate attributes for all registered node
10fbcf4c
KS
3981 * devices of nodes that have memory. All on-line nodes should have
3982 * registered their associated device by this time.
9a305230 3983 */
7d9ca000 3984static void __init hugetlb_register_all_nodes(void)
9a305230
LS
3985{
3986 int nid;
3987
a4a00b45 3988 for_each_online_node(nid)
b958d4d0 3989 hugetlb_register_node(node_devices[nid]);
9a305230
LS
3990}
3991#else /* !CONFIG_NUMA */
3992
3993static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
3994{
3995 BUG();
3996 if (nidp)
3997 *nidp = -1;
3998 return NULL;
3999}
4000
9a305230
LS
4001static void hugetlb_register_all_nodes(void) { }
4002
4003#endif
4004
263b8998
ML
4005#ifdef CONFIG_CMA
4006static void __init hugetlb_cma_check(void);
4007#else
4008static inline __init void hugetlb_cma_check(void)
4009{
4010}
4011#endif
4012
a4a00b45
MS
4013static void __init hugetlb_sysfs_init(void)
4014{
4015 struct hstate *h;
4016 int err;
4017
4018 hugepages_kobj = kobject_create_and_add("hugepages", mm_kobj);
4019 if (!hugepages_kobj)
4020 return;
4021
4022 for_each_hstate(h) {
4023 err = hugetlb_sysfs_add_hstate(h, hugepages_kobj,
4024 hstate_kobjs, &hstate_attr_group);
4025 if (err)
4026 pr_err("HugeTLB: Unable to add hstate %s", h->name);
4027 }
4028
4029#ifdef CONFIG_NUMA
4030 hugetlb_sysfs_initialized = true;
4031#endif
4032 hugetlb_register_all_nodes();
4033}
4034
a3437870
NA
4035static int __init hugetlb_init(void)
4036{
8382d914
DB
4037 int i;
4038
d6995da3
MK
4039 BUILD_BUG_ON(sizeof_field(struct page, private) * BITS_PER_BYTE <
4040 __NR_HPAGEFLAGS);
4041
c2833a5b
MK
4042 if (!hugepages_supported()) {
4043 if (hugetlb_max_hstate || default_hstate_max_huge_pages)
4044 pr_warn("HugeTLB: huge pages not supported, ignoring associated command-line parameters\n");
0ef89d25 4045 return 0;
c2833a5b 4046 }
a3437870 4047
282f4214
MK
4048 /*
4049 * Make sure HPAGE_SIZE (HUGETLB_PAGE_ORDER) hstate exists. Some
4050 * architectures depend on setup being done here.
4051 */
4052 hugetlb_add_hstate(HUGETLB_PAGE_ORDER);
4053 if (!parsed_default_hugepagesz) {
4054 /*
4055 * If we did not parse a default huge page size, set
4056 * default_hstate_idx to HPAGE_SIZE hstate. And, if the
4057 * number of huge pages for this default size was implicitly
4058 * specified, set that here as well.
4059 * Note that the implicit setting will overwrite an explicit
4060 * setting. A warning will be printed in this case.
4061 */
4062 default_hstate_idx = hstate_index(size_to_hstate(HPAGE_SIZE));
4063 if (default_hstate_max_huge_pages) {
4064 if (default_hstate.max_huge_pages) {
4065 char buf[32];
4066
4067 string_get_size(huge_page_size(&default_hstate),
4068 1, STRING_UNITS_2, buf, 32);
4069 pr_warn("HugeTLB: Ignoring hugepages=%lu associated with %s page size\n",
4070 default_hstate.max_huge_pages, buf);
4071 pr_warn("HugeTLB: Using hugepages=%lu for number of default huge pages\n",
4072 default_hstate_max_huge_pages);
4073 }
4074 default_hstate.max_huge_pages =
4075 default_hstate_max_huge_pages;
b5389086 4076
0a7a0f6f 4077 for_each_online_node(i)
b5389086
ZY
4078 default_hstate.max_huge_pages_node[i] =
4079 default_hugepages_in_node[i];
d715cf80 4080 }
f8b74815 4081 }
a3437870 4082
cf11e85f 4083 hugetlb_cma_check();
a3437870 4084 hugetlb_init_hstates();
aa888a74 4085 gather_bootmem_prealloc();
a3437870
NA
4086 report_hugepages();
4087
4088 hugetlb_sysfs_init();
7179e7bf 4089 hugetlb_cgroup_file_init();
9a305230 4090
8382d914
DB
4091#ifdef CONFIG_SMP
4092 num_fault_mutexes = roundup_pow_of_two(8 * num_possible_cpus());
4093#else
4094 num_fault_mutexes = 1;
4095#endif
c672c7f2 4096 hugetlb_fault_mutex_table =
6da2ec56
KC
4097 kmalloc_array(num_fault_mutexes, sizeof(struct mutex),
4098 GFP_KERNEL);
c672c7f2 4099 BUG_ON(!hugetlb_fault_mutex_table);
8382d914
DB
4100
4101 for (i = 0; i < num_fault_mutexes; i++)
c672c7f2 4102 mutex_init(&hugetlb_fault_mutex_table[i]);
a3437870
NA
4103 return 0;
4104}
3e89e1c5 4105subsys_initcall(hugetlb_init);
a3437870 4106
ae94da89
MK
4107/* Overwritten by architectures with more huge page sizes */
4108bool __init __attribute((weak)) arch_hugetlb_valid_size(unsigned long size)
9fee021d 4109{
ae94da89 4110 return size == HPAGE_SIZE;
9fee021d
VT
4111}
4112
d00181b9 4113void __init hugetlb_add_hstate(unsigned int order)
a3437870
NA
4114{
4115 struct hstate *h;
8faa8b07
AK
4116 unsigned long i;
4117
a3437870 4118 if (size_to_hstate(PAGE_SIZE << order)) {
a3437870
NA
4119 return;
4120 }
47d38344 4121 BUG_ON(hugetlb_max_hstate >= HUGE_MAX_HSTATE);
a3437870 4122 BUG_ON(order == 0);
47d38344 4123 h = &hstates[hugetlb_max_hstate++];
29383967 4124 mutex_init(&h->resize_lock);
a3437870 4125 h->order = order;
aca78307 4126 h->mask = ~(huge_page_size(h) - 1);
8faa8b07
AK
4127 for (i = 0; i < MAX_NUMNODES; ++i)
4128 INIT_LIST_HEAD(&h->hugepage_freelists[i]);
0edaecfa 4129 INIT_LIST_HEAD(&h->hugepage_activelist);
54f18d35
AM
4130 h->next_nid_to_alloc = first_memory_node;
4131 h->next_nid_to_free = first_memory_node;
a3437870 4132 snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB",
c2c3a60a 4133 huge_page_size(h)/SZ_1K);
8faa8b07 4134
a3437870
NA
4135 parsed_hstate = h;
4136}
4137
b5389086
ZY
4138bool __init __weak hugetlb_node_alloc_supported(void)
4139{
4140 return true;
4141}
f87442f4
PL
4142
4143static void __init hugepages_clear_pages_in_node(void)
4144{
4145 if (!hugetlb_max_hstate) {
4146 default_hstate_max_huge_pages = 0;
4147 memset(default_hugepages_in_node, 0,
10395680 4148 sizeof(default_hugepages_in_node));
f87442f4
PL
4149 } else {
4150 parsed_hstate->max_huge_pages = 0;
4151 memset(parsed_hstate->max_huge_pages_node, 0,
10395680 4152 sizeof(parsed_hstate->max_huge_pages_node));
f87442f4
PL
4153 }
4154}
4155
282f4214
MK
4156/*
4157 * hugepages command line processing
4158 * hugepages normally follows a valid hugepagsz or default_hugepagsz
4159 * specification. If not, ignore the hugepages value. hugepages can also
4160 * be the first huge page command line option in which case it implicitly
4161 * specifies the number of huge pages for the default size.
4162 */
4163static int __init hugepages_setup(char *s)
a3437870
NA
4164{
4165 unsigned long *mhp;
8faa8b07 4166 static unsigned long *last_mhp;
b5389086
ZY
4167 int node = NUMA_NO_NODE;
4168 int count;
4169 unsigned long tmp;
4170 char *p = s;
a3437870 4171
9fee021d 4172 if (!parsed_valid_hugepagesz) {
282f4214 4173 pr_warn("HugeTLB: hugepages=%s does not follow a valid hugepagesz, ignoring\n", s);
9fee021d 4174 parsed_valid_hugepagesz = true;
f81f6e4b 4175 return 1;
9fee021d 4176 }
282f4214 4177
a3437870 4178 /*
282f4214
MK
4179 * !hugetlb_max_hstate means we haven't parsed a hugepagesz= parameter
4180 * yet, so this hugepages= parameter goes to the "default hstate".
4181 * Otherwise, it goes with the previously parsed hugepagesz or
4182 * default_hugepagesz.
a3437870 4183 */
9fee021d 4184 else if (!hugetlb_max_hstate)
a3437870
NA
4185 mhp = &default_hstate_max_huge_pages;
4186 else
4187 mhp = &parsed_hstate->max_huge_pages;
4188
8faa8b07 4189 if (mhp == last_mhp) {
282f4214 4190 pr_warn("HugeTLB: hugepages= specified twice without interleaving hugepagesz=, ignoring hugepages=%s\n", s);
f81f6e4b 4191 return 1;
8faa8b07
AK
4192 }
4193
b5389086
ZY
4194 while (*p) {
4195 count = 0;
4196 if (sscanf(p, "%lu%n", &tmp, &count) != 1)
4197 goto invalid;
4198 /* Parameter is node format */
4199 if (p[count] == ':') {
4200 if (!hugetlb_node_alloc_supported()) {
4201 pr_warn("HugeTLB: architecture can't support node specific alloc, ignoring!\n");
f81f6e4b 4202 return 1;
b5389086 4203 }
0a7a0f6f 4204 if (tmp >= MAX_NUMNODES || !node_online(tmp))
e79ce983 4205 goto invalid;
0a7a0f6f 4206 node = array_index_nospec(tmp, MAX_NUMNODES);
b5389086 4207 p += count + 1;
b5389086
ZY
4208 /* Parse hugepages */
4209 if (sscanf(p, "%lu%n", &tmp, &count) != 1)
4210 goto invalid;
4211 if (!hugetlb_max_hstate)
4212 default_hugepages_in_node[node] = tmp;
4213 else
4214 parsed_hstate->max_huge_pages_node[node] = tmp;
4215 *mhp += tmp;
4216 /* Go to parse next node*/
4217 if (p[count] == ',')
4218 p += count + 1;
4219 else
4220 break;
4221 } else {
4222 if (p != s)
4223 goto invalid;
4224 *mhp = tmp;
4225 break;
4226 }
4227 }
a3437870 4228
8faa8b07
AK
4229 /*
4230 * Global state is always initialized later in hugetlb_init.
04adbc3f 4231 * But we need to allocate gigantic hstates here early to still
8faa8b07
AK
4232 * use the bootmem allocator.
4233 */
04adbc3f 4234 if (hugetlb_max_hstate && hstate_is_gigantic(parsed_hstate))
8faa8b07
AK
4235 hugetlb_hstate_alloc_pages(parsed_hstate);
4236
4237 last_mhp = mhp;
4238
a3437870 4239 return 1;
b5389086
ZY
4240
4241invalid:
4242 pr_warn("HugeTLB: Invalid hugepages parameter %s\n", p);
f87442f4 4243 hugepages_clear_pages_in_node();
f81f6e4b 4244 return 1;
a3437870 4245}
282f4214 4246__setup("hugepages=", hugepages_setup);
e11bfbfc 4247
282f4214
MK
4248/*
4249 * hugepagesz command line processing
4250 * A specific huge page size can only be specified once with hugepagesz.
4251 * hugepagesz is followed by hugepages on the command line. The global
4252 * variable 'parsed_valid_hugepagesz' is used to determine if prior
4253 * hugepagesz argument was valid.
4254 */
359f2544 4255static int __init hugepagesz_setup(char *s)
e11bfbfc 4256{
359f2544 4257 unsigned long size;
282f4214
MK
4258 struct hstate *h;
4259
4260 parsed_valid_hugepagesz = false;
359f2544
MK
4261 size = (unsigned long)memparse(s, NULL);
4262
4263 if (!arch_hugetlb_valid_size(size)) {
282f4214 4264 pr_err("HugeTLB: unsupported hugepagesz=%s\n", s);
f81f6e4b 4265 return 1;
359f2544
MK
4266 }
4267
282f4214
MK
4268 h = size_to_hstate(size);
4269 if (h) {
4270 /*
4271 * hstate for this size already exists. This is normally
4272 * an error, but is allowed if the existing hstate is the
4273 * default hstate. More specifically, it is only allowed if
4274 * the number of huge pages for the default hstate was not
4275 * previously specified.
4276 */
4277 if (!parsed_default_hugepagesz || h != &default_hstate ||
4278 default_hstate.max_huge_pages) {
4279 pr_warn("HugeTLB: hugepagesz=%s specified twice, ignoring\n", s);
f81f6e4b 4280 return 1;
282f4214
MK
4281 }
4282
4283 /*
4284 * No need to call hugetlb_add_hstate() as hstate already
4285 * exists. But, do set parsed_hstate so that a following
4286 * hugepages= parameter will be applied to this hstate.
4287 */
4288 parsed_hstate = h;
4289 parsed_valid_hugepagesz = true;
4290 return 1;
38237830
MK
4291 }
4292
359f2544 4293 hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
282f4214 4294 parsed_valid_hugepagesz = true;
e11bfbfc
NP
4295 return 1;
4296}
359f2544
MK
4297__setup("hugepagesz=", hugepagesz_setup);
4298
282f4214
MK
4299/*
4300 * default_hugepagesz command line input
4301 * Only one instance of default_hugepagesz allowed on command line.
4302 */
ae94da89 4303static int __init default_hugepagesz_setup(char *s)
e11bfbfc 4304{
ae94da89 4305 unsigned long size;
b5389086 4306 int i;
ae94da89 4307
282f4214 4308 parsed_valid_hugepagesz = false;
282f4214
MK
4309 if (parsed_default_hugepagesz) {
4310 pr_err("HugeTLB: default_hugepagesz previously specified, ignoring %s\n", s);
f81f6e4b 4311 return 1;
282f4214
MK
4312 }
4313
ae94da89
MK
4314 size = (unsigned long)memparse(s, NULL);
4315
4316 if (!arch_hugetlb_valid_size(size)) {
282f4214 4317 pr_err("HugeTLB: unsupported default_hugepagesz=%s\n", s);
f81f6e4b 4318 return 1;
ae94da89
MK
4319 }
4320
282f4214
MK
4321 hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
4322 parsed_valid_hugepagesz = true;
4323 parsed_default_hugepagesz = true;
4324 default_hstate_idx = hstate_index(size_to_hstate(size));
4325
4326 /*
4327 * The number of default huge pages (for this size) could have been
4328 * specified as the first hugetlb parameter: hugepages=X. If so,
4329 * then default_hstate_max_huge_pages is set. If the default huge
4330 * page size is gigantic (>= MAX_ORDER), then the pages must be
4331 * allocated here from bootmem allocator.
4332 */
4333 if (default_hstate_max_huge_pages) {
4334 default_hstate.max_huge_pages = default_hstate_max_huge_pages;
0a7a0f6f 4335 for_each_online_node(i)
b5389086
ZY
4336 default_hstate.max_huge_pages_node[i] =
4337 default_hugepages_in_node[i];
282f4214
MK
4338 if (hstate_is_gigantic(&default_hstate))
4339 hugetlb_hstate_alloc_pages(&default_hstate);
4340 default_hstate_max_huge_pages = 0;
4341 }
4342
e11bfbfc
NP
4343 return 1;
4344}
ae94da89 4345__setup("default_hugepagesz=", default_hugepagesz_setup);
a3437870 4346
d2226ebd
FT
4347static nodemask_t *policy_mbind_nodemask(gfp_t gfp)
4348{
4349#ifdef CONFIG_NUMA
4350 struct mempolicy *mpol = get_task_policy(current);
4351
4352 /*
4353 * Only enforce MPOL_BIND policy which overlaps with cpuset policy
4354 * (from policy_nodemask) specifically for hugetlb case
4355 */
4356 if (mpol->mode == MPOL_BIND &&
4357 (apply_policy_zone(mpol, gfp_zone(gfp)) &&
4358 cpuset_nodemask_valid_mems_allowed(&mpol->nodes)))
4359 return &mpol->nodes;
4360#endif
4361 return NULL;
4362}
4363
8ca39e68 4364static unsigned int allowed_mems_nr(struct hstate *h)
8a213460
NA
4365{
4366 int node;
4367 unsigned int nr = 0;
d2226ebd 4368 nodemask_t *mbind_nodemask;
8ca39e68
MS
4369 unsigned int *array = h->free_huge_pages_node;
4370 gfp_t gfp_mask = htlb_alloc_mask(h);
4371
d2226ebd 4372 mbind_nodemask = policy_mbind_nodemask(gfp_mask);
8ca39e68 4373 for_each_node_mask(node, cpuset_current_mems_allowed) {
d2226ebd 4374 if (!mbind_nodemask || node_isset(node, *mbind_nodemask))
8ca39e68
MS
4375 nr += array[node];
4376 }
8a213460
NA
4377
4378 return nr;
4379}
4380
4381#ifdef CONFIG_SYSCTL
17743798
MS
4382static int proc_hugetlb_doulongvec_minmax(struct ctl_table *table, int write,
4383 void *buffer, size_t *length,
4384 loff_t *ppos, unsigned long *out)
4385{
4386 struct ctl_table dup_table;
4387
4388 /*
4389 * In order to avoid races with __do_proc_doulongvec_minmax(), we
4390 * can duplicate the @table and alter the duplicate of it.
4391 */
4392 dup_table = *table;
4393 dup_table.data = out;
4394
4395 return proc_doulongvec_minmax(&dup_table, write, buffer, length, ppos);
4396}
4397
06808b08
LS
4398static int hugetlb_sysctl_handler_common(bool obey_mempolicy,
4399 struct ctl_table *table, int write,
32927393 4400 void *buffer, size_t *length, loff_t *ppos)
1da177e4 4401{
e5ff2159 4402 struct hstate *h = &default_hstate;
238d3c13 4403 unsigned long tmp = h->max_huge_pages;
08d4a246 4404 int ret;
e5ff2159 4405
457c1b27 4406 if (!hugepages_supported())
86613628 4407 return -EOPNOTSUPP;
457c1b27 4408
17743798
MS
4409 ret = proc_hugetlb_doulongvec_minmax(table, write, buffer, length, ppos,
4410 &tmp);
08d4a246
MH
4411 if (ret)
4412 goto out;
e5ff2159 4413
238d3c13
DR
4414 if (write)
4415 ret = __nr_hugepages_store_common(obey_mempolicy, h,
4416 NUMA_NO_NODE, tmp, *length);
08d4a246
MH
4417out:
4418 return ret;
1da177e4 4419}
396faf03 4420
06808b08 4421int hugetlb_sysctl_handler(struct ctl_table *table, int write,
32927393 4422 void *buffer, size_t *length, loff_t *ppos)
06808b08
LS
4423{
4424
4425 return hugetlb_sysctl_handler_common(false, table, write,
4426 buffer, length, ppos);
4427}
4428
4429#ifdef CONFIG_NUMA
4430int hugetlb_mempolicy_sysctl_handler(struct ctl_table *table, int write,
32927393 4431 void *buffer, size_t *length, loff_t *ppos)
06808b08
LS
4432{
4433 return hugetlb_sysctl_handler_common(true, table, write,
4434 buffer, length, ppos);
4435}
4436#endif /* CONFIG_NUMA */
4437
a3d0c6aa 4438int hugetlb_overcommit_handler(struct ctl_table *table, int write,
32927393 4439 void *buffer, size_t *length, loff_t *ppos)
a3d0c6aa 4440{
a5516438 4441 struct hstate *h = &default_hstate;
e5ff2159 4442 unsigned long tmp;
08d4a246 4443 int ret;
e5ff2159 4444
457c1b27 4445 if (!hugepages_supported())
86613628 4446 return -EOPNOTSUPP;
457c1b27 4447
c033a93c 4448 tmp = h->nr_overcommit_huge_pages;
e5ff2159 4449
bae7f4ae 4450 if (write && hstate_is_gigantic(h))
adbe8726
EM
4451 return -EINVAL;
4452
17743798
MS
4453 ret = proc_hugetlb_doulongvec_minmax(table, write, buffer, length, ppos,
4454 &tmp);
08d4a246
MH
4455 if (ret)
4456 goto out;
e5ff2159
AK
4457
4458 if (write) {
db71ef79 4459 spin_lock_irq(&hugetlb_lock);
e5ff2159 4460 h->nr_overcommit_huge_pages = tmp;
db71ef79 4461 spin_unlock_irq(&hugetlb_lock);
e5ff2159 4462 }
08d4a246
MH
4463out:
4464 return ret;
a3d0c6aa
NA
4465}
4466
1da177e4
LT
4467#endif /* CONFIG_SYSCTL */
4468
e1759c21 4469void hugetlb_report_meminfo(struct seq_file *m)
1da177e4 4470{
fcb2b0c5
RG
4471 struct hstate *h;
4472 unsigned long total = 0;
4473
457c1b27
NA
4474 if (!hugepages_supported())
4475 return;
fcb2b0c5
RG
4476
4477 for_each_hstate(h) {
4478 unsigned long count = h->nr_huge_pages;
4479
aca78307 4480 total += huge_page_size(h) * count;
fcb2b0c5
RG
4481
4482 if (h == &default_hstate)
4483 seq_printf(m,
4484 "HugePages_Total: %5lu\n"
4485 "HugePages_Free: %5lu\n"
4486 "HugePages_Rsvd: %5lu\n"
4487 "HugePages_Surp: %5lu\n"
4488 "Hugepagesize: %8lu kB\n",
4489 count,
4490 h->free_huge_pages,
4491 h->resv_huge_pages,
4492 h->surplus_huge_pages,
aca78307 4493 huge_page_size(h) / SZ_1K);
fcb2b0c5
RG
4494 }
4495
aca78307 4496 seq_printf(m, "Hugetlb: %8lu kB\n", total / SZ_1K);
1da177e4
LT
4497}
4498
7981593b 4499int hugetlb_report_node_meminfo(char *buf, int len, int nid)
1da177e4 4500{
a5516438 4501 struct hstate *h = &default_hstate;
7981593b 4502
457c1b27
NA
4503 if (!hugepages_supported())
4504 return 0;
7981593b
JP
4505
4506 return sysfs_emit_at(buf, len,
4507 "Node %d HugePages_Total: %5u\n"
4508 "Node %d HugePages_Free: %5u\n"
4509 "Node %d HugePages_Surp: %5u\n",
4510 nid, h->nr_huge_pages_node[nid],
4511 nid, h->free_huge_pages_node[nid],
4512 nid, h->surplus_huge_pages_node[nid]);
1da177e4
LT
4513}
4514
dcadcf1c 4515void hugetlb_show_meminfo_node(int nid)
949f7ec5
DR
4516{
4517 struct hstate *h;
949f7ec5 4518
457c1b27
NA
4519 if (!hugepages_supported())
4520 return;
4521
dcadcf1c
GL
4522 for_each_hstate(h)
4523 printk("Node %d hugepages_total=%u hugepages_free=%u hugepages_surp=%u hugepages_size=%lukB\n",
4524 nid,
4525 h->nr_huge_pages_node[nid],
4526 h->free_huge_pages_node[nid],
4527 h->surplus_huge_pages_node[nid],
4528 huge_page_size(h) / SZ_1K);
949f7ec5
DR
4529}
4530
5d317b2b
NH
4531void hugetlb_report_usage(struct seq_file *m, struct mm_struct *mm)
4532{
4533 seq_printf(m, "HugetlbPages:\t%8lu kB\n",
4534 atomic_long_read(&mm->hugetlb_usage) << (PAGE_SHIFT - 10));
4535}
4536
1da177e4
LT
4537/* Return the number pages of memory we physically have, in PAGE_SIZE units. */
4538unsigned long hugetlb_total_pages(void)
4539{
d0028588
WL
4540 struct hstate *h;
4541 unsigned long nr_total_pages = 0;
4542
4543 for_each_hstate(h)
4544 nr_total_pages += h->nr_huge_pages * pages_per_huge_page(h);
4545 return nr_total_pages;
1da177e4 4546}
1da177e4 4547
a5516438 4548static int hugetlb_acct_memory(struct hstate *h, long delta)
fc1b8a73
MG
4549{
4550 int ret = -ENOMEM;
4551
0aa7f354
ML
4552 if (!delta)
4553 return 0;
4554
db71ef79 4555 spin_lock_irq(&hugetlb_lock);
fc1b8a73
MG
4556 /*
4557 * When cpuset is configured, it breaks the strict hugetlb page
4558 * reservation as the accounting is done on a global variable. Such
4559 * reservation is completely rubbish in the presence of cpuset because
4560 * the reservation is not checked against page availability for the
4561 * current cpuset. Application can still potentially OOM'ed by kernel
4562 * with lack of free htlb page in cpuset that the task is in.
4563 * Attempt to enforce strict accounting with cpuset is almost
4564 * impossible (or too ugly) because cpuset is too fluid that
4565 * task or memory node can be dynamically moved between cpusets.
4566 *
4567 * The change of semantics for shared hugetlb mapping with cpuset is
4568 * undesirable. However, in order to preserve some of the semantics,
4569 * we fall back to check against current free page availability as
4570 * a best attempt and hopefully to minimize the impact of changing
4571 * semantics that cpuset has.
8ca39e68
MS
4572 *
4573 * Apart from cpuset, we also have memory policy mechanism that
4574 * also determines from which node the kernel will allocate memory
4575 * in a NUMA system. So similar to cpuset, we also should consider
4576 * the memory policy of the current task. Similar to the description
4577 * above.
fc1b8a73
MG
4578 */
4579 if (delta > 0) {
a5516438 4580 if (gather_surplus_pages(h, delta) < 0)
fc1b8a73
MG
4581 goto out;
4582
8ca39e68 4583 if (delta > allowed_mems_nr(h)) {
a5516438 4584 return_unused_surplus_pages(h, delta);
fc1b8a73
MG
4585 goto out;
4586 }
4587 }
4588
4589 ret = 0;
4590 if (delta < 0)
a5516438 4591 return_unused_surplus_pages(h, (unsigned long) -delta);
fc1b8a73
MG
4592
4593out:
db71ef79 4594 spin_unlock_irq(&hugetlb_lock);
fc1b8a73
MG
4595 return ret;
4596}
4597
84afd99b
AW
4598static void hugetlb_vm_op_open(struct vm_area_struct *vma)
4599{
f522c3ac 4600 struct resv_map *resv = vma_resv_map(vma);
84afd99b
AW
4601
4602 /*
4603 * This new VMA should share its siblings reservation map if present.
4604 * The VMA will only ever have a valid reservation map pointer where
4605 * it is being copied for another still existing VMA. As that VMA
25985edc 4606 * has a reference to the reservation map it cannot disappear until
84afd99b
AW
4607 * after this open call completes. It is therefore safe to take a
4608 * new reference here without additional locking.
4609 */
09a26e83
MK
4610 if (resv && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
4611 resv_map_dup_hugetlb_cgroup_uncharge_info(resv);
f522c3ac 4612 kref_get(&resv->refs);
09a26e83 4613 }
8d9bfb26
MK
4614
4615 hugetlb_vma_lock_alloc(vma);
84afd99b
AW
4616}
4617
a1e78772
MG
4618static void hugetlb_vm_op_close(struct vm_area_struct *vma)
4619{
a5516438 4620 struct hstate *h = hstate_vma(vma);
8d9bfb26 4621 struct resv_map *resv;
90481622 4622 struct hugepage_subpool *spool = subpool_vma(vma);
4e35f483 4623 unsigned long reserve, start, end;
1c5ecae3 4624 long gbl_reserve;
84afd99b 4625
8d9bfb26
MK
4626 hugetlb_vma_lock_free(vma);
4627
4628 resv = vma_resv_map(vma);
4e35f483
JK
4629 if (!resv || !is_vma_resv_set(vma, HPAGE_RESV_OWNER))
4630 return;
84afd99b 4631
4e35f483
JK
4632 start = vma_hugecache_offset(h, vma, vma->vm_start);
4633 end = vma_hugecache_offset(h, vma, vma->vm_end);
84afd99b 4634
4e35f483 4635 reserve = (end - start) - region_count(resv, start, end);
e9fe92ae 4636 hugetlb_cgroup_uncharge_counter(resv, start, end);
4e35f483 4637 if (reserve) {
1c5ecae3
MK
4638 /*
4639 * Decrement reserve counts. The global reserve count may be
4640 * adjusted if the subpool has a minimum size.
4641 */
4642 gbl_reserve = hugepage_subpool_put_pages(spool, reserve);
4643 hugetlb_acct_memory(h, -gbl_reserve);
84afd99b 4644 }
e9fe92ae
MA
4645
4646 kref_put(&resv->refs, resv_map_release);
a1e78772
MG
4647}
4648
31383c68
DW
4649static int hugetlb_vm_op_split(struct vm_area_struct *vma, unsigned long addr)
4650{
4651 if (addr & ~(huge_page_mask(hstate_vma(vma))))
4652 return -EINVAL;
4653 return 0;
4654}
4655
05ea8860
DW
4656static unsigned long hugetlb_vm_op_pagesize(struct vm_area_struct *vma)
4657{
aca78307 4658 return huge_page_size(hstate_vma(vma));
05ea8860
DW
4659}
4660
1da177e4
LT
4661/*
4662 * We cannot handle pagefaults against hugetlb pages at all. They cause
4663 * handle_mm_fault() to try to instantiate regular-sized pages in the
6c26d310 4664 * hugepage VMA. do_page_fault() is supposed to trap this, so BUG is we get
1da177e4
LT
4665 * this far.
4666 */
b3ec9f33 4667static vm_fault_t hugetlb_vm_op_fault(struct vm_fault *vmf)
1da177e4
LT
4668{
4669 BUG();
d0217ac0 4670 return 0;
1da177e4
LT
4671}
4672
eec3636a
JC
4673/*
4674 * When a new function is introduced to vm_operations_struct and added
4675 * to hugetlb_vm_ops, please consider adding the function to shm_vm_ops.
4676 * This is because under System V memory model, mappings created via
4677 * shmget/shmat with "huge page" specified are backed by hugetlbfs files,
4678 * their original vm_ops are overwritten with shm_vm_ops.
4679 */
f0f37e2f 4680const struct vm_operations_struct hugetlb_vm_ops = {
d0217ac0 4681 .fault = hugetlb_vm_op_fault,
84afd99b 4682 .open = hugetlb_vm_op_open,
a1e78772 4683 .close = hugetlb_vm_op_close,
dd3b614f 4684 .may_split = hugetlb_vm_op_split,
05ea8860 4685 .pagesize = hugetlb_vm_op_pagesize,
1da177e4
LT
4686};
4687
1e8f889b
DG
4688static pte_t make_huge_pte(struct vm_area_struct *vma, struct page *page,
4689 int writable)
63551ae0
DG
4690{
4691 pte_t entry;
79c1c594 4692 unsigned int shift = huge_page_shift(hstate_vma(vma));
63551ae0 4693
1e8f889b 4694 if (writable) {
106c992a
GS
4695 entry = huge_pte_mkwrite(huge_pte_mkdirty(mk_huge_pte(page,
4696 vma->vm_page_prot)));
63551ae0 4697 } else {
106c992a
GS
4698 entry = huge_pte_wrprotect(mk_huge_pte(page,
4699 vma->vm_page_prot));
63551ae0
DG
4700 }
4701 entry = pte_mkyoung(entry);
79c1c594 4702 entry = arch_make_huge_pte(entry, shift, vma->vm_flags);
63551ae0
DG
4703
4704 return entry;
4705}
4706
1e8f889b
DG
4707static void set_huge_ptep_writable(struct vm_area_struct *vma,
4708 unsigned long address, pte_t *ptep)
4709{
4710 pte_t entry;
4711
106c992a 4712 entry = huge_pte_mkwrite(huge_pte_mkdirty(huge_ptep_get(ptep)));
32f84528 4713 if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1))
4b3073e1 4714 update_mmu_cache(vma, address, ptep);
1e8f889b
DG
4715}
4716
d5ed7444 4717bool is_hugetlb_entry_migration(pte_t pte)
4a705fef
NH
4718{
4719 swp_entry_t swp;
4720
4721 if (huge_pte_none(pte) || pte_present(pte))
d5ed7444 4722 return false;
4a705fef 4723 swp = pte_to_swp_entry(pte);
d79d176a 4724 if (is_migration_entry(swp))
d5ed7444 4725 return true;
4a705fef 4726 else
d5ed7444 4727 return false;
4a705fef
NH
4728}
4729
3e5c3600 4730static bool is_hugetlb_entry_hwpoisoned(pte_t pte)
4a705fef
NH
4731{
4732 swp_entry_t swp;
4733
4734 if (huge_pte_none(pte) || pte_present(pte))
3e5c3600 4735 return false;
4a705fef 4736 swp = pte_to_swp_entry(pte);
d79d176a 4737 if (is_hwpoison_entry(swp))
3e5c3600 4738 return true;
4a705fef 4739 else
3e5c3600 4740 return false;
4a705fef 4741}
1e8f889b 4742
4eae4efa
PX
4743static void
4744hugetlb_install_page(struct vm_area_struct *vma, pte_t *ptep, unsigned long addr,
4745 struct page *new_page)
4746{
4747 __SetPageUptodate(new_page);
4eae4efa 4748 hugepage_add_new_anon_rmap(new_page, vma, addr);
1eba86c0 4749 set_huge_pte_at(vma->vm_mm, addr, ptep, make_huge_pte(vma, new_page, 1));
4eae4efa
PX
4750 hugetlb_count_add(pages_per_huge_page(hstate_vma(vma)), vma->vm_mm);
4751 ClearHPageRestoreReserve(new_page);
4752 SetHPageMigratable(new_page);
4753}
4754
63551ae0 4755int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src,
bc70fbf2
PX
4756 struct vm_area_struct *dst_vma,
4757 struct vm_area_struct *src_vma)
63551ae0 4758{
3aa4ed80 4759 pte_t *src_pte, *dst_pte, entry;
63551ae0 4760 struct page *ptepage;
1c59827d 4761 unsigned long addr;
bc70fbf2
PX
4762 bool cow = is_cow_mapping(src_vma->vm_flags);
4763 struct hstate *h = hstate_vma(src_vma);
a5516438 4764 unsigned long sz = huge_page_size(h);
4eae4efa 4765 unsigned long npages = pages_per_huge_page(h);
ac46d4f3 4766 struct mmu_notifier_range range;
e95a9851 4767 unsigned long last_addr_mask;
e8569dd2 4768 int ret = 0;
1e8f889b 4769
ac46d4f3 4770 if (cow) {
bc70fbf2
PX
4771 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, src_vma, src,
4772 src_vma->vm_start,
4773 src_vma->vm_end);
ac46d4f3 4774 mmu_notifier_invalidate_range_start(&range);
623a1ddf
DH
4775 mmap_assert_write_locked(src);
4776 raw_write_seqcount_begin(&src->write_protect_seq);
40549ba8
MK
4777 } else {
4778 /*
4779 * For shared mappings the vma lock must be held before
4780 * calling huge_pte_offset in the src vma. Otherwise, the
4781 * returned ptep could go away if part of a shared pmd and
4782 * another thread calls huge_pmd_unshare.
4783 */
4784 hugetlb_vma_lock_read(src_vma);
ac46d4f3 4785 }
e8569dd2 4786
e95a9851 4787 last_addr_mask = hugetlb_mask_last_page(h);
bc70fbf2 4788 for (addr = src_vma->vm_start; addr < src_vma->vm_end; addr += sz) {
cb900f41 4789 spinlock_t *src_ptl, *dst_ptl;
7868a208 4790 src_pte = huge_pte_offset(src, addr, sz);
e95a9851
MK
4791 if (!src_pte) {
4792 addr |= last_addr_mask;
c74df32c 4793 continue;
e95a9851 4794 }
bc70fbf2 4795 dst_pte = huge_pte_alloc(dst, dst_vma, addr, sz);
e8569dd2
AS
4796 if (!dst_pte) {
4797 ret = -ENOMEM;
4798 break;
4799 }
c5c99429 4800
5e41540c
MK
4801 /*
4802 * If the pagetables are shared don't copy or take references.
5e41540c 4803 *
3aa4ed80 4804 * dst_pte == src_pte is the common case of src/dest sharing.
5e41540c 4805 * However, src could have 'unshared' and dst shares with
3aa4ed80
ML
4806 * another vma. So page_count of ptep page is checked instead
4807 * to reliably determine whether pte is shared.
5e41540c 4808 */
3aa4ed80 4809 if (page_count(virt_to_page(dst_pte)) > 1) {
e95a9851 4810 addr |= last_addr_mask;
c5c99429 4811 continue;
e95a9851 4812 }
c5c99429 4813
cb900f41
KS
4814 dst_ptl = huge_pte_lock(h, dst, dst_pte);
4815 src_ptl = huge_pte_lockptr(h, src, src_pte);
4816 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
4a705fef 4817 entry = huge_ptep_get(src_pte);
4eae4efa 4818again:
3aa4ed80 4819 if (huge_pte_none(entry)) {
5e41540c 4820 /*
3aa4ed80 4821 * Skip if src entry none.
5e41540c 4822 */
4a705fef 4823 ;
c2cb0dcc
NH
4824 } else if (unlikely(is_hugetlb_entry_hwpoisoned(entry))) {
4825 bool uffd_wp = huge_pte_uffd_wp(entry);
4826
4827 if (!userfaultfd_wp(dst_vma) && uffd_wp)
4828 entry = huge_pte_clear_uffd_wp(entry);
4829 set_huge_pte_at(dst, addr, dst_pte, entry);
4830 } else if (unlikely(is_hugetlb_entry_migration(entry))) {
4a705fef 4831 swp_entry_t swp_entry = pte_to_swp_entry(entry);
bc70fbf2 4832 bool uffd_wp = huge_pte_uffd_wp(entry);
4a705fef 4833
6c287605 4834 if (!is_readable_migration_entry(swp_entry) && cow) {
4a705fef
NH
4835 /*
4836 * COW mappings require pages in both
4837 * parent and child to be set to read.
4838 */
4dd845b5
AP
4839 swp_entry = make_readable_migration_entry(
4840 swp_offset(swp_entry));
4a705fef 4841 entry = swp_entry_to_pte(swp_entry);
bc70fbf2
PX
4842 if (userfaultfd_wp(src_vma) && uffd_wp)
4843 entry = huge_pte_mkuffd_wp(entry);
18f39629 4844 set_huge_pte_at(src, addr, src_pte, entry);
4a705fef 4845 }
bc70fbf2
PX
4846 if (!userfaultfd_wp(dst_vma) && uffd_wp)
4847 entry = huge_pte_clear_uffd_wp(entry);
18f39629 4848 set_huge_pte_at(dst, addr, dst_pte, entry);
bc70fbf2
PX
4849 } else if (unlikely(is_pte_marker(entry))) {
4850 /*
4851 * We copy the pte marker only if the dst vma has
4852 * uffd-wp enabled.
4853 */
4854 if (userfaultfd_wp(dst_vma))
4855 set_huge_pte_at(dst, addr, dst_pte, entry);
4a705fef 4856 } else {
4eae4efa
PX
4857 entry = huge_ptep_get(src_pte);
4858 ptepage = pte_page(entry);
4859 get_page(ptepage);
4860
4861 /*
fb3d824d
DH
4862 * Failing to duplicate the anon rmap is a rare case
4863 * where we see pinned hugetlb pages while they're
4864 * prone to COW. We need to do the COW earlier during
4865 * fork.
4eae4efa
PX
4866 *
4867 * When pre-allocating the page or copying data, we
4868 * need to be without the pgtable locks since we could
4869 * sleep during the process.
4870 */
fb3d824d
DH
4871 if (!PageAnon(ptepage)) {
4872 page_dup_file_rmap(ptepage, true);
bc70fbf2
PX
4873 } else if (page_try_dup_anon_rmap(ptepage, true,
4874 src_vma)) {
4eae4efa
PX
4875 pte_t src_pte_old = entry;
4876 struct page *new;
4877
4878 spin_unlock(src_ptl);
4879 spin_unlock(dst_ptl);
4880 /* Do not use reserve as it's private owned */
bc70fbf2 4881 new = alloc_huge_page(dst_vma, addr, 1);
4eae4efa
PX
4882 if (IS_ERR(new)) {
4883 put_page(ptepage);
4884 ret = PTR_ERR(new);
4885 break;
4886 }
bc70fbf2 4887 copy_user_huge_page(new, ptepage, addr, dst_vma,
4eae4efa
PX
4888 npages);
4889 put_page(ptepage);
4890
4891 /* Install the new huge page if src pte stable */
4892 dst_ptl = huge_pte_lock(h, dst, dst_pte);
4893 src_ptl = huge_pte_lockptr(h, src, src_pte);
4894 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
4895 entry = huge_ptep_get(src_pte);
4896 if (!pte_same(src_pte_old, entry)) {
bc70fbf2 4897 restore_reserve_on_error(h, dst_vma, addr,
846be085 4898 new);
4eae4efa 4899 put_page(new);
3aa4ed80 4900 /* huge_ptep of dst_pte won't change as in child */
4eae4efa
PX
4901 goto again;
4902 }
bc70fbf2 4903 hugetlb_install_page(dst_vma, dst_pte, addr, new);
4eae4efa
PX
4904 spin_unlock(src_ptl);
4905 spin_unlock(dst_ptl);
4906 continue;
4907 }
4908
34ee645e 4909 if (cow) {
0f10851e
JG
4910 /*
4911 * No need to notify as we are downgrading page
4912 * table protection not changing it to point
4913 * to a new page.
4914 *
ee65728e 4915 * See Documentation/mm/mmu_notifier.rst
0f10851e 4916 */
7f2e9525 4917 huge_ptep_set_wrprotect(src, addr, src_pte);
84894e1c 4918 entry = huge_pte_wrprotect(entry);
34ee645e 4919 }
4eae4efa 4920
1c59827d 4921 set_huge_pte_at(dst, addr, dst_pte, entry);
4eae4efa 4922 hugetlb_count_add(npages, dst);
1c59827d 4923 }
cb900f41
KS
4924 spin_unlock(src_ptl);
4925 spin_unlock(dst_ptl);
63551ae0 4926 }
63551ae0 4927
623a1ddf
DH
4928 if (cow) {
4929 raw_write_seqcount_end(&src->write_protect_seq);
ac46d4f3 4930 mmu_notifier_invalidate_range_end(&range);
40549ba8
MK
4931 } else {
4932 hugetlb_vma_unlock_read(src_vma);
623a1ddf 4933 }
e8569dd2
AS
4934
4935 return ret;
63551ae0
DG
4936}
4937
550a7d60 4938static void move_huge_pte(struct vm_area_struct *vma, unsigned long old_addr,
db110a99 4939 unsigned long new_addr, pte_t *src_pte, pte_t *dst_pte)
550a7d60
MA
4940{
4941 struct hstate *h = hstate_vma(vma);
4942 struct mm_struct *mm = vma->vm_mm;
550a7d60 4943 spinlock_t *src_ptl, *dst_ptl;
db110a99 4944 pte_t pte;
550a7d60 4945
550a7d60
MA
4946 dst_ptl = huge_pte_lock(h, mm, dst_pte);
4947 src_ptl = huge_pte_lockptr(h, mm, src_pte);
4948
4949 /*
4950 * We don't have to worry about the ordering of src and dst ptlocks
4951 * because exclusive mmap_sem (or the i_mmap_lock) prevents deadlock.
4952 */
4953 if (src_ptl != dst_ptl)
4954 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
4955
4956 pte = huge_ptep_get_and_clear(mm, old_addr, src_pte);
4957 set_huge_pte_at(mm, new_addr, dst_pte, pte);
4958
4959 if (src_ptl != dst_ptl)
4960 spin_unlock(src_ptl);
4961 spin_unlock(dst_ptl);
4962}
4963
4964int move_hugetlb_page_tables(struct vm_area_struct *vma,
4965 struct vm_area_struct *new_vma,
4966 unsigned long old_addr, unsigned long new_addr,
4967 unsigned long len)
4968{
4969 struct hstate *h = hstate_vma(vma);
4970 struct address_space *mapping = vma->vm_file->f_mapping;
4971 unsigned long sz = huge_page_size(h);
4972 struct mm_struct *mm = vma->vm_mm;
4973 unsigned long old_end = old_addr + len;
e95a9851 4974 unsigned long last_addr_mask;
550a7d60
MA
4975 pte_t *src_pte, *dst_pte;
4976 struct mmu_notifier_range range;
3d0b95cd 4977 bool shared_pmd = false;
550a7d60
MA
4978
4979 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm, old_addr,
4980 old_end);
4981 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
3d0b95cd
BW
4982 /*
4983 * In case of shared PMDs, we should cover the maximum possible
4984 * range.
4985 */
4986 flush_cache_range(vma, range.start, range.end);
4987
550a7d60 4988 mmu_notifier_invalidate_range_start(&range);
e95a9851 4989 last_addr_mask = hugetlb_mask_last_page(h);
550a7d60 4990 /* Prevent race with file truncation */
40549ba8 4991 hugetlb_vma_lock_write(vma);
550a7d60
MA
4992 i_mmap_lock_write(mapping);
4993 for (; old_addr < old_end; old_addr += sz, new_addr += sz) {
4994 src_pte = huge_pte_offset(mm, old_addr, sz);
e95a9851
MK
4995 if (!src_pte) {
4996 old_addr |= last_addr_mask;
4997 new_addr |= last_addr_mask;
550a7d60 4998 continue;
e95a9851 4999 }
550a7d60
MA
5000 if (huge_pte_none(huge_ptep_get(src_pte)))
5001 continue;
5002
4ddb4d91 5003 if (huge_pmd_unshare(mm, vma, old_addr, src_pte)) {
3d0b95cd 5004 shared_pmd = true;
4ddb4d91
MK
5005 old_addr |= last_addr_mask;
5006 new_addr |= last_addr_mask;
550a7d60 5007 continue;
3d0b95cd 5008 }
550a7d60
MA
5009
5010 dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz);
5011 if (!dst_pte)
5012 break;
5013
db110a99 5014 move_huge_pte(vma, old_addr, new_addr, src_pte, dst_pte);
550a7d60 5015 }
3d0b95cd
BW
5016
5017 if (shared_pmd)
5018 flush_tlb_range(vma, range.start, range.end);
5019 else
5020 flush_tlb_range(vma, old_end - len, old_end);
550a7d60 5021 mmu_notifier_invalidate_range_end(&range);
13e4ad2c 5022 i_mmap_unlock_write(mapping);
40549ba8 5023 hugetlb_vma_unlock_write(vma);
550a7d60
MA
5024
5025 return len + old_addr - old_end;
5026}
5027
73c54763
PX
5028static void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
5029 unsigned long start, unsigned long end,
05e90bd0 5030 struct page *ref_page, zap_flags_t zap_flags)
63551ae0
DG
5031{
5032 struct mm_struct *mm = vma->vm_mm;
5033 unsigned long address;
c7546f8f 5034 pte_t *ptep;
63551ae0 5035 pte_t pte;
cb900f41 5036 spinlock_t *ptl;
63551ae0 5037 struct page *page;
a5516438
AK
5038 struct hstate *h = hstate_vma(vma);
5039 unsigned long sz = huge_page_size(h);
ac46d4f3 5040 struct mmu_notifier_range range;
e95a9851 5041 unsigned long last_addr_mask;
a4a118f2 5042 bool force_flush = false;
a5516438 5043
63551ae0 5044 WARN_ON(!is_vm_hugetlb_page(vma));
a5516438
AK
5045 BUG_ON(start & ~huge_page_mask(h));
5046 BUG_ON(end & ~huge_page_mask(h));
63551ae0 5047
07e32661
AK
5048 /*
5049 * This is a hugetlb vma, all the pte entries should point
5050 * to huge page.
5051 */
ed6a7935 5052 tlb_change_page_size(tlb, sz);
24669e58 5053 tlb_start_vma(tlb, vma);
dff11abe
MK
5054
5055 /*
5056 * If sharing possible, alert mmu notifiers of worst case.
5057 */
6f4f13e8
JG
5058 mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, mm, start,
5059 end);
ac46d4f3
JG
5060 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
5061 mmu_notifier_invalidate_range_start(&range);
e95a9851 5062 last_addr_mask = hugetlb_mask_last_page(h);
569f48b8 5063 address = start;
569f48b8 5064 for (; address < end; address += sz) {
7868a208 5065 ptep = huge_pte_offset(mm, address, sz);
e95a9851
MK
5066 if (!ptep) {
5067 address |= last_addr_mask;
c7546f8f 5068 continue;
e95a9851 5069 }
c7546f8f 5070
cb900f41 5071 ptl = huge_pte_lock(h, mm, ptep);
4ddb4d91 5072 if (huge_pmd_unshare(mm, vma, address, ptep)) {
31d49da5 5073 spin_unlock(ptl);
a4a118f2
NA
5074 tlb_flush_pmd_range(tlb, address & PUD_MASK, PUD_SIZE);
5075 force_flush = true;
4ddb4d91 5076 address |= last_addr_mask;
31d49da5
AK
5077 continue;
5078 }
39dde65c 5079
6629326b 5080 pte = huge_ptep_get(ptep);
31d49da5
AK
5081 if (huge_pte_none(pte)) {
5082 spin_unlock(ptl);
5083 continue;
5084 }
6629326b
HD
5085
5086 /*
9fbc1f63
NH
5087 * Migrating hugepage or HWPoisoned hugepage is already
5088 * unmapped and its refcount is dropped, so just clear pte here.
6629326b 5089 */
9fbc1f63 5090 if (unlikely(!pte_present(pte))) {
05e90bd0
PX
5091 /*
5092 * If the pte was wr-protected by uffd-wp in any of the
5093 * swap forms, meanwhile the caller does not want to
5094 * drop the uffd-wp bit in this zap, then replace the
5095 * pte with a marker.
5096 */
5097 if (pte_swp_uffd_wp_any(pte) &&
5098 !(zap_flags & ZAP_FLAG_DROP_MARKER))
5099 set_huge_pte_at(mm, address, ptep,
5100 make_pte_marker(PTE_MARKER_UFFD_WP));
5101 else
5102 huge_pte_clear(mm, address, ptep, sz);
31d49da5
AK
5103 spin_unlock(ptl);
5104 continue;
8c4894c6 5105 }
6629326b
HD
5106
5107 page = pte_page(pte);
04f2cbe3
MG
5108 /*
5109 * If a reference page is supplied, it is because a specific
5110 * page is being unmapped, not a range. Ensure the page we
5111 * are about to unmap is the actual page of interest.
5112 */
5113 if (ref_page) {
31d49da5
AK
5114 if (page != ref_page) {
5115 spin_unlock(ptl);
5116 continue;
5117 }
04f2cbe3
MG
5118 /*
5119 * Mark the VMA as having unmapped its page so that
5120 * future faults in this VMA will fail rather than
5121 * looking like data was lost
5122 */
5123 set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED);
5124 }
5125
c7546f8f 5126 pte = huge_ptep_get_and_clear(mm, address, ptep);
b528e4b6 5127 tlb_remove_huge_tlb_entry(h, tlb, ptep, address);
106c992a 5128 if (huge_pte_dirty(pte))
6649a386 5129 set_page_dirty(page);
05e90bd0
PX
5130 /* Leave a uffd-wp pte marker if needed */
5131 if (huge_pte_uffd_wp(pte) &&
5132 !(zap_flags & ZAP_FLAG_DROP_MARKER))
5133 set_huge_pte_at(mm, address, ptep,
5134 make_pte_marker(PTE_MARKER_UFFD_WP));
5d317b2b 5135 hugetlb_count_sub(pages_per_huge_page(h), mm);
cea86fe2 5136 page_remove_rmap(page, vma, true);
31d49da5 5137
cb900f41 5138 spin_unlock(ptl);
e77b0852 5139 tlb_remove_page_size(tlb, page, huge_page_size(h));
31d49da5
AK
5140 /*
5141 * Bail out after unmapping reference page if supplied
5142 */
5143 if (ref_page)
5144 break;
fe1668ae 5145 }
ac46d4f3 5146 mmu_notifier_invalidate_range_end(&range);
24669e58 5147 tlb_end_vma(tlb, vma);
a4a118f2
NA
5148
5149 /*
5150 * If we unshared PMDs, the TLB flush was not recorded in mmu_gather. We
5151 * could defer the flush until now, since by holding i_mmap_rwsem we
5152 * guaranteed that the last refernece would not be dropped. But we must
5153 * do the flushing before we return, as otherwise i_mmap_rwsem will be
5154 * dropped and the last reference to the shared PMDs page might be
5155 * dropped as well.
5156 *
5157 * In theory we could defer the freeing of the PMD pages as well, but
5158 * huge_pmd_unshare() relies on the exact page_count for the PMD page to
5159 * detect sharing, so we cannot defer the release of the page either.
5160 * Instead, do flush now.
5161 */
5162 if (force_flush)
5163 tlb_flush_mmu_tlbonly(tlb);
1da177e4 5164}
63551ae0 5165
d833352a
MG
5166void __unmap_hugepage_range_final(struct mmu_gather *tlb,
5167 struct vm_area_struct *vma, unsigned long start,
05e90bd0
PX
5168 unsigned long end, struct page *ref_page,
5169 zap_flags_t zap_flags)
d833352a 5170{
05e90bd0 5171 __unmap_hugepage_range(tlb, vma, start, end, ref_page, zap_flags);
d833352a
MG
5172
5173 /*
5174 * Clear this flag so that x86's huge_pmd_share page_table_shareable
5175 * test will fail on a vma being torn down, and not grab a page table
5176 * on its way out. We're lucky that the flag has such an appropriate
5177 * name, and can in fact be safely cleared here. We could clear it
5178 * before the __unmap_hugepage_range above, but all that's necessary
c8c06efa 5179 * is to clear it before releasing the i_mmap_rwsem. This works
d833352a 5180 * because in the context this is called, the VMA is about to be
c8c06efa 5181 * destroyed and the i_mmap_rwsem is held.
d833352a
MG
5182 */
5183 vma->vm_flags &= ~VM_MAYSHARE;
5184}
5185
502717f4 5186void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
05e90bd0
PX
5187 unsigned long end, struct page *ref_page,
5188 zap_flags_t zap_flags)
502717f4 5189{
24669e58 5190 struct mmu_gather tlb;
dff11abe 5191
a72afd87 5192 tlb_gather_mmu(&tlb, vma->vm_mm);
05e90bd0 5193 __unmap_hugepage_range(&tlb, vma, start, end, ref_page, zap_flags);
ae8eba8b 5194 tlb_finish_mmu(&tlb);
502717f4
CK
5195}
5196
04f2cbe3
MG
5197/*
5198 * This is called when the original mapper is failing to COW a MAP_PRIVATE
578b7725 5199 * mapping it owns the reserve page for. The intention is to unmap the page
04f2cbe3
MG
5200 * from other VMAs and let the children be SIGKILLed if they are faulting the
5201 * same region.
5202 */
2f4612af
DB
5203static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,
5204 struct page *page, unsigned long address)
04f2cbe3 5205{
7526674d 5206 struct hstate *h = hstate_vma(vma);
04f2cbe3
MG
5207 struct vm_area_struct *iter_vma;
5208 struct address_space *mapping;
04f2cbe3
MG
5209 pgoff_t pgoff;
5210
5211 /*
5212 * vm_pgoff is in PAGE_SIZE units, hence the different calculation
5213 * from page cache lookup which is in HPAGE_SIZE units.
5214 */
7526674d 5215 address = address & huge_page_mask(h);
36e4f20a
MH
5216 pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) +
5217 vma->vm_pgoff;
93c76a3d 5218 mapping = vma->vm_file->f_mapping;
04f2cbe3 5219
4eb2b1dc
MG
5220 /*
5221 * Take the mapping lock for the duration of the table walk. As
5222 * this mapping should be shared between all the VMAs,
5223 * __unmap_hugepage_range() is called as the lock is already held
5224 */
83cde9e8 5225 i_mmap_lock_write(mapping);
6b2dbba8 5226 vma_interval_tree_foreach(iter_vma, &mapping->i_mmap, pgoff, pgoff) {
04f2cbe3
MG
5227 /* Do not unmap the current VMA */
5228 if (iter_vma == vma)
5229 continue;
5230
2f84a899
MG
5231 /*
5232 * Shared VMAs have their own reserves and do not affect
5233 * MAP_PRIVATE accounting but it is possible that a shared
5234 * VMA is using the same page so check and skip such VMAs.
5235 */
5236 if (iter_vma->vm_flags & VM_MAYSHARE)
5237 continue;
5238
04f2cbe3
MG
5239 /*
5240 * Unmap the page from other VMAs without their own reserves.
5241 * They get marked to be SIGKILLed if they fault in these
5242 * areas. This is because a future no-page fault on this VMA
5243 * could insert a zeroed page instead of the data existing
5244 * from the time of fork. This would look like data corruption
5245 */
5246 if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER))
24669e58 5247 unmap_hugepage_range(iter_vma, address,
05e90bd0 5248 address + huge_page_size(h), page, 0);
04f2cbe3 5249 }
83cde9e8 5250 i_mmap_unlock_write(mapping);
04f2cbe3
MG
5251}
5252
0fe6e20b 5253/*
c89357e2 5254 * hugetlb_wp() should be called with page lock of the original hugepage held.
aa6d2e8c 5255 * Called with hugetlb_fault_mutex_table held and pte_page locked so we
ef009b25
MH
5256 * cannot race with other handlers or page migration.
5257 * Keep the pte_same checks anyway to make transition from the mutex easier.
0fe6e20b 5258 */
c89357e2
DH
5259static vm_fault_t hugetlb_wp(struct mm_struct *mm, struct vm_area_struct *vma,
5260 unsigned long address, pte_t *ptep, unsigned int flags,
3999f52e 5261 struct page *pagecache_page, spinlock_t *ptl)
1e8f889b 5262{
c89357e2 5263 const bool unshare = flags & FAULT_FLAG_UNSHARE;
3999f52e 5264 pte_t pte;
a5516438 5265 struct hstate *h = hstate_vma(vma);
1e8f889b 5266 struct page *old_page, *new_page;
2b740303
SJ
5267 int outside_reserve = 0;
5268 vm_fault_t ret = 0;
974e6d66 5269 unsigned long haddr = address & huge_page_mask(h);
ac46d4f3 5270 struct mmu_notifier_range range;
1e8f889b 5271
c89357e2
DH
5272 VM_BUG_ON(unshare && (flags & FOLL_WRITE));
5273 VM_BUG_ON(!unshare && !(flags & FOLL_WRITE));
5274
1d8d1464
DH
5275 /*
5276 * hugetlb does not support FOLL_FORCE-style write faults that keep the
5277 * PTE mapped R/O such as maybe_mkwrite() would do.
5278 */
5279 if (WARN_ON_ONCE(!unshare && !(vma->vm_flags & VM_WRITE)))
5280 return VM_FAULT_SIGSEGV;
5281
5282 /* Let's take out MAP_SHARED mappings first. */
5283 if (vma->vm_flags & VM_MAYSHARE) {
5284 if (unlikely(unshare))
5285 return 0;
5286 set_huge_ptep_writable(vma, haddr, ptep);
5287 return 0;
5288 }
5289
3999f52e 5290 pte = huge_ptep_get(ptep);
1e8f889b
DG
5291 old_page = pte_page(pte);
5292
662ce1dc
YY
5293 delayacct_wpcopy_start();
5294
04f2cbe3 5295retry_avoidcopy:
c89357e2
DH
5296 /*
5297 * If no-one else is actually using this page, we're the exclusive
5298 * owner and can reuse this page.
5299 */
37a2140d 5300 if (page_mapcount(old_page) == 1 && PageAnon(old_page)) {
c89357e2
DH
5301 if (!PageAnonExclusive(old_page))
5302 page_move_anon_rmap(old_page, vma);
5303 if (likely(!unshare))
5304 set_huge_ptep_writable(vma, haddr, ptep);
662ce1dc
YY
5305
5306 delayacct_wpcopy_end();
83c54070 5307 return 0;
1e8f889b 5308 }
6c287605
DH
5309 VM_BUG_ON_PAGE(PageAnon(old_page) && PageAnonExclusive(old_page),
5310 old_page);
1e8f889b 5311
04f2cbe3
MG
5312 /*
5313 * If the process that created a MAP_PRIVATE mapping is about to
5314 * perform a COW due to a shared page count, attempt to satisfy
5315 * the allocation without using the existing reserves. The pagecache
5316 * page is used to determine if the reserve at this address was
5317 * consumed or not. If reserves were used, a partial faulted mapping
5318 * at the time of fork() could consume its reserves on COW instead
5319 * of the full address range.
5320 */
5944d011 5321 if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) &&
04f2cbe3
MG
5322 old_page != pagecache_page)
5323 outside_reserve = 1;
5324
09cbfeaf 5325 get_page(old_page);
b76c8cfb 5326
ad4404a2
DB
5327 /*
5328 * Drop page table lock as buddy allocator may be called. It will
5329 * be acquired again before returning to the caller, as expected.
5330 */
cb900f41 5331 spin_unlock(ptl);
5b7a1d40 5332 new_page = alloc_huge_page(vma, haddr, outside_reserve);
1e8f889b 5333
2fc39cec 5334 if (IS_ERR(new_page)) {
04f2cbe3
MG
5335 /*
5336 * If a process owning a MAP_PRIVATE mapping fails to COW,
5337 * it is due to references held by a child and an insufficient
5338 * huge page pool. To guarantee the original mappers
5339 * reliability, unmap the page from child processes. The child
5340 * may get SIGKILLed if it later faults.
5341 */
5342 if (outside_reserve) {
40549ba8
MK
5343 struct address_space *mapping = vma->vm_file->f_mapping;
5344 pgoff_t idx;
5345 u32 hash;
5346
09cbfeaf 5347 put_page(old_page);
40549ba8
MK
5348 /*
5349 * Drop hugetlb_fault_mutex and vma_lock before
5350 * unmapping. unmapping needs to hold vma_lock
5351 * in write mode. Dropping vma_lock in read mode
5352 * here is OK as COW mappings do not interact with
5353 * PMD sharing.
5354 *
5355 * Reacquire both after unmap operation.
5356 */
5357 idx = vma_hugecache_offset(h, vma, haddr);
5358 hash = hugetlb_fault_mutex_hash(mapping, idx);
5359 hugetlb_vma_unlock_read(vma);
5360 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
5361
5b7a1d40 5362 unmap_ref_private(mm, vma, old_page, haddr);
40549ba8
MK
5363
5364 mutex_lock(&hugetlb_fault_mutex_table[hash]);
5365 hugetlb_vma_lock_read(vma);
2f4612af 5366 spin_lock(ptl);
5b7a1d40 5367 ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
2f4612af
DB
5368 if (likely(ptep &&
5369 pte_same(huge_ptep_get(ptep), pte)))
5370 goto retry_avoidcopy;
5371 /*
5372 * race occurs while re-acquiring page table
5373 * lock, and our job is done.
5374 */
662ce1dc 5375 delayacct_wpcopy_end();
2f4612af 5376 return 0;
04f2cbe3
MG
5377 }
5378
2b740303 5379 ret = vmf_error(PTR_ERR(new_page));
ad4404a2 5380 goto out_release_old;
1e8f889b
DG
5381 }
5382
0fe6e20b
NH
5383 /*
5384 * When the original hugepage is shared one, it does not have
5385 * anon_vma prepared.
5386 */
44e2aa93 5387 if (unlikely(anon_vma_prepare(vma))) {
ad4404a2
DB
5388 ret = VM_FAULT_OOM;
5389 goto out_release_all;
44e2aa93 5390 }
0fe6e20b 5391
974e6d66 5392 copy_user_huge_page(new_page, old_page, address, vma,
47ad8475 5393 pages_per_huge_page(h));
0ed361de 5394 __SetPageUptodate(new_page);
1e8f889b 5395
7269f999 5396 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm, haddr,
6f4f13e8 5397 haddr + huge_page_size(h));
ac46d4f3 5398 mmu_notifier_invalidate_range_start(&range);
ad4404a2 5399
b76c8cfb 5400 /*
cb900f41 5401 * Retake the page table lock to check for racing updates
b76c8cfb
LW
5402 * before the page tables are altered
5403 */
cb900f41 5404 spin_lock(ptl);
5b7a1d40 5405 ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
a9af0c5d 5406 if (likely(ptep && pte_same(huge_ptep_get(ptep), pte))) {
d6995da3 5407 ClearHPageRestoreReserve(new_page);
07443a85 5408
c89357e2 5409 /* Break COW or unshare */
5b7a1d40 5410 huge_ptep_clear_flush(vma, haddr, ptep);
ac46d4f3 5411 mmu_notifier_invalidate_range(mm, range.start, range.end);
cea86fe2 5412 page_remove_rmap(old_page, vma, true);
5b7a1d40 5413 hugepage_add_new_anon_rmap(new_page, vma, haddr);
1eba86c0 5414 set_huge_pte_at(mm, haddr, ptep,
c89357e2 5415 make_huge_pte(vma, new_page, !unshare));
8f251a3d 5416 SetHPageMigratable(new_page);
1e8f889b
DG
5417 /* Make the old page be freed below */
5418 new_page = old_page;
5419 }
cb900f41 5420 spin_unlock(ptl);
ac46d4f3 5421 mmu_notifier_invalidate_range_end(&range);
ad4404a2 5422out_release_all:
c89357e2
DH
5423 /*
5424 * No restore in case of successful pagetable update (Break COW or
5425 * unshare)
5426 */
c7b1850d
MK
5427 if (new_page != old_page)
5428 restore_reserve_on_error(h, vma, haddr, new_page);
09cbfeaf 5429 put_page(new_page);
ad4404a2 5430out_release_old:
09cbfeaf 5431 put_page(old_page);
8312034f 5432
ad4404a2 5433 spin_lock(ptl); /* Caller expects lock to be held */
662ce1dc
YY
5434
5435 delayacct_wpcopy_end();
ad4404a2 5436 return ret;
1e8f889b
DG
5437}
5438
3ae77f43
HD
5439/*
5440 * Return whether there is a pagecache page to back given address within VMA.
5441 * Caller follow_hugetlb_page() holds page_table_lock so we cannot lock_page.
5442 */
5443static bool hugetlbfs_pagecache_present(struct hstate *h,
2a15efc9
HD
5444 struct vm_area_struct *vma, unsigned long address)
5445{
5446 struct address_space *mapping;
5447 pgoff_t idx;
5448 struct page *page;
5449
5450 mapping = vma->vm_file->f_mapping;
5451 idx = vma_hugecache_offset(h, vma, address);
5452
5453 page = find_get_page(mapping, idx);
5454 if (page)
5455 put_page(page);
5456 return page != NULL;
5457}
5458
7e1813d4 5459int hugetlb_add_to_page_cache(struct page *page, struct address_space *mapping,
ab76ad54
MK
5460 pgoff_t idx)
5461{
d9ef44de 5462 struct folio *folio = page_folio(page);
ab76ad54
MK
5463 struct inode *inode = mapping->host;
5464 struct hstate *h = hstate_inode(inode);
d9ef44de 5465 int err;
ab76ad54 5466
d9ef44de
MWO
5467 __folio_set_locked(folio);
5468 err = __filemap_add_folio(mapping, folio, idx, GFP_KERNEL, NULL);
5469
5470 if (unlikely(err)) {
5471 __folio_clear_locked(folio);
ab76ad54 5472 return err;
d9ef44de 5473 }
d6995da3 5474 ClearHPageRestoreReserve(page);
ab76ad54 5475
22146c3c 5476 /*
d9ef44de 5477 * mark folio dirty so that it will not be removed from cache/file
22146c3c
MK
5478 * by non-hugetlbfs specific code paths.
5479 */
d9ef44de 5480 folio_mark_dirty(folio);
22146c3c 5481
ab76ad54
MK
5482 spin_lock(&inode->i_lock);
5483 inode->i_blocks += blocks_per_huge_page(h);
5484 spin_unlock(&inode->i_lock);
5485 return 0;
5486}
5487
7677f7fd
AR
5488static inline vm_fault_t hugetlb_handle_userfault(struct vm_area_struct *vma,
5489 struct address_space *mapping,
5490 pgoff_t idx,
5491 unsigned int flags,
5492 unsigned long haddr,
824ddc60 5493 unsigned long addr,
7677f7fd
AR
5494 unsigned long reason)
5495{
7677f7fd
AR
5496 u32 hash;
5497 struct vm_fault vmf = {
5498 .vma = vma,
5499 .address = haddr,
824ddc60 5500 .real_address = addr,
7677f7fd
AR
5501 .flags = flags,
5502
5503 /*
5504 * Hard to debug if it ends up being
5505 * used by a callee that assumes
5506 * something about the other
5507 * uninitialized fields... same as in
5508 * memory.c
5509 */
5510 };
5511
5512 /*
958f32ce
LS
5513 * vma_lock and hugetlb_fault_mutex must be dropped before handling
5514 * userfault. Also mmap_lock could be dropped due to handling
5515 * userfault, any vma operation should be careful from here.
7677f7fd 5516 */
40549ba8 5517 hugetlb_vma_unlock_read(vma);
7677f7fd
AR
5518 hash = hugetlb_fault_mutex_hash(mapping, idx);
5519 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
958f32ce 5520 return handle_userfault(&vmf, reason);
7677f7fd
AR
5521}
5522
2b740303
SJ
5523static vm_fault_t hugetlb_no_page(struct mm_struct *mm,
5524 struct vm_area_struct *vma,
5525 struct address_space *mapping, pgoff_t idx,
c64e912c
PX
5526 unsigned long address, pte_t *ptep,
5527 pte_t old_pte, unsigned int flags)
ac9b9c66 5528{
a5516438 5529 struct hstate *h = hstate_vma(vma);
2b740303 5530 vm_fault_t ret = VM_FAULT_SIGBUS;
409eb8c2 5531 int anon_rmap = 0;
4c887265 5532 unsigned long size;
4c887265 5533 struct page *page;
1e8f889b 5534 pte_t new_pte;
cb900f41 5535 spinlock_t *ptl;
285b8dca 5536 unsigned long haddr = address & huge_page_mask(h);
c7b1850d 5537 bool new_page, new_pagecache_page = false;
958f32ce 5538 u32 hash = hugetlb_fault_mutex_hash(mapping, idx);
4c887265 5539
04f2cbe3
MG
5540 /*
5541 * Currently, we are forced to kill the process in the event the
5542 * original mapper has unmapped pages from the child due to a failed
c89357e2
DH
5543 * COW/unsharing. Warn that such a situation has occurred as it may not
5544 * be obvious.
04f2cbe3
MG
5545 */
5546 if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) {
910154d5 5547 pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n",
ffb22af5 5548 current->pid);
958f32ce 5549 goto out;
04f2cbe3
MG
5550 }
5551
4c887265 5552 /*
188a3972
MK
5553 * Use page lock to guard against racing truncation
5554 * before we get page_table_lock.
4c887265 5555 */
c7b1850d 5556 new_page = false;
6bda666a
CL
5557 page = find_lock_page(mapping, idx);
5558 if (!page) {
188a3972
MK
5559 size = i_size_read(mapping->host) >> huge_page_shift(h);
5560 if (idx >= size)
5561 goto out;
7677f7fd 5562 /* Check for page in userfault range */
958f32ce
LS
5563 if (userfaultfd_missing(vma))
5564 return hugetlb_handle_userfault(vma, mapping, idx,
824ddc60 5565 flags, haddr, address,
7677f7fd 5566 VM_UFFD_MISSING);
1a1aad8a 5567
285b8dca 5568 page = alloc_huge_page(vma, haddr, 0);
2fc39cec 5569 if (IS_ERR(page)) {
4643d67e
MK
5570 /*
5571 * Returning error will result in faulting task being
5572 * sent SIGBUS. The hugetlb fault mutex prevents two
5573 * tasks from racing to fault in the same page which
5574 * could result in false unable to allocate errors.
5575 * Page migration does not take the fault mutex, but
5576 * does a clear then write of pte's under page table
5577 * lock. Page fault code could race with migration,
5578 * notice the clear pte and try to allocate a page
5579 * here. Before returning error, get ptl and make
5580 * sure there really is no pte entry.
5581 */
5582 ptl = huge_pte_lock(h, mm, ptep);
d83e6c8a
ML
5583 ret = 0;
5584 if (huge_pte_none(huge_ptep_get(ptep)))
5585 ret = vmf_error(PTR_ERR(page));
4643d67e 5586 spin_unlock(ptl);
6bda666a
CL
5587 goto out;
5588 }
47ad8475 5589 clear_huge_page(page, address, pages_per_huge_page(h));
0ed361de 5590 __SetPageUptodate(page);
cb6acd01 5591 new_page = true;
ac9b9c66 5592
f83a275d 5593 if (vma->vm_flags & VM_MAYSHARE) {
7e1813d4 5594 int err = hugetlb_add_to_page_cache(page, mapping, idx);
6bda666a 5595 if (err) {
3a5497a2
ML
5596 /*
5597 * err can't be -EEXIST which implies someone
5598 * else consumed the reservation since hugetlb
5599 * fault mutex is held when add a hugetlb page
5600 * to the page cache. So it's safe to call
5601 * restore_reserve_on_error() here.
5602 */
5603 restore_reserve_on_error(h, vma, haddr, page);
6bda666a 5604 put_page(page);
6bda666a
CL
5605 goto out;
5606 }
c7b1850d 5607 new_pagecache_page = true;
23be7468 5608 } else {
6bda666a 5609 lock_page(page);
0fe6e20b
NH
5610 if (unlikely(anon_vma_prepare(vma))) {
5611 ret = VM_FAULT_OOM;
5612 goto backout_unlocked;
5613 }
409eb8c2 5614 anon_rmap = 1;
23be7468 5615 }
0fe6e20b 5616 } else {
998b4382
NH
5617 /*
5618 * If memory error occurs between mmap() and fault, some process
5619 * don't have hwpoisoned swap entry for errored virtual address.
5620 * So we need to block hugepage fault by PG_hwpoison bit check.
5621 */
5622 if (unlikely(PageHWPoison(page))) {
0eb98f15 5623 ret = VM_FAULT_HWPOISON_LARGE |
972dc4de 5624 VM_FAULT_SET_HINDEX(hstate_index(h));
998b4382
NH
5625 goto backout_unlocked;
5626 }
7677f7fd
AR
5627
5628 /* Check for page in userfault range. */
5629 if (userfaultfd_minor(vma)) {
5630 unlock_page(page);
5631 put_page(page);
958f32ce 5632 return hugetlb_handle_userfault(vma, mapping, idx,
824ddc60 5633 flags, haddr, address,
7677f7fd 5634 VM_UFFD_MINOR);
7677f7fd 5635 }
6bda666a 5636 }
1e8f889b 5637
57303d80
AW
5638 /*
5639 * If we are going to COW a private mapping later, we examine the
5640 * pending reservations for this page now. This will ensure that
5641 * any allocations necessary to record that reservation occur outside
5642 * the spinlock.
5643 */
5e911373 5644 if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
285b8dca 5645 if (vma_needs_reservation(h, vma, haddr) < 0) {
2b26736c
AW
5646 ret = VM_FAULT_OOM;
5647 goto backout_unlocked;
5648 }
5e911373 5649 /* Just decrements count, does not deallocate */
285b8dca 5650 vma_end_reservation(h, vma, haddr);
5e911373 5651 }
57303d80 5652
8bea8052 5653 ptl = huge_pte_lock(h, mm, ptep);
83c54070 5654 ret = 0;
c64e912c
PX
5655 /* If pte changed from under us, retry */
5656 if (!pte_same(huge_ptep_get(ptep), old_pte))
4c887265
AL
5657 goto backout;
5658
07443a85 5659 if (anon_rmap) {
d6995da3 5660 ClearHPageRestoreReserve(page);
285b8dca 5661 hugepage_add_new_anon_rmap(page, vma, haddr);
ac714904 5662 } else
fb3d824d 5663 page_dup_file_rmap(page, true);
1e8f889b
DG
5664 new_pte = make_huge_pte(vma, page, ((vma->vm_flags & VM_WRITE)
5665 && (vma->vm_flags & VM_SHARED)));
c64e912c
PX
5666 /*
5667 * If this pte was previously wr-protected, keep it wr-protected even
5668 * if populated.
5669 */
5670 if (unlikely(pte_marker_uffd_wp(old_pte)))
5671 new_pte = huge_pte_wrprotect(huge_pte_mkuffd_wp(new_pte));
285b8dca 5672 set_huge_pte_at(mm, haddr, ptep, new_pte);
1e8f889b 5673
5d317b2b 5674 hugetlb_count_add(pages_per_huge_page(h), mm);
788c7df4 5675 if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
1e8f889b 5676 /* Optimization, do the COW without a second fault */
c89357e2 5677 ret = hugetlb_wp(mm, vma, address, ptep, flags, page, ptl);
1e8f889b
DG
5678 }
5679
cb900f41 5680 spin_unlock(ptl);
cb6acd01
MK
5681
5682 /*
8f251a3d
MK
5683 * Only set HPageMigratable in newly allocated pages. Existing pages
5684 * found in the pagecache may not have HPageMigratableset if they have
5685 * been isolated for migration.
cb6acd01
MK
5686 */
5687 if (new_page)
8f251a3d 5688 SetHPageMigratable(page);
cb6acd01 5689
4c887265
AL
5690 unlock_page(page);
5691out:
958f32ce
LS
5692 hugetlb_vma_unlock_read(vma);
5693 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
ac9b9c66 5694 return ret;
4c887265
AL
5695
5696backout:
cb900f41 5697 spin_unlock(ptl);
2b26736c 5698backout_unlocked:
c7b1850d
MK
5699 if (new_page && !new_pagecache_page)
5700 restore_reserve_on_error(h, vma, haddr, page);
fa27759a
MK
5701
5702 unlock_page(page);
4c887265
AL
5703 put_page(page);
5704 goto out;
ac9b9c66
HD
5705}
5706
8382d914 5707#ifdef CONFIG_SMP
188b04a7 5708u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
8382d914
DB
5709{
5710 unsigned long key[2];
5711 u32 hash;
5712
1b426bac
MK
5713 key[0] = (unsigned long) mapping;
5714 key[1] = idx;
8382d914 5715
55254636 5716 hash = jhash2((u32 *)&key, sizeof(key)/(sizeof(u32)), 0);
8382d914
DB
5717
5718 return hash & (num_fault_mutexes - 1);
5719}
5720#else
5721/*
6c26d310 5722 * For uniprocessor systems we always use a single mutex, so just
8382d914
DB
5723 * return 0 and avoid the hashing overhead.
5724 */
188b04a7 5725u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
8382d914
DB
5726{
5727 return 0;
5728}
5729#endif
5730
2b740303 5731vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,
788c7df4 5732 unsigned long address, unsigned int flags)
86e5216f 5733{
8382d914 5734 pte_t *ptep, entry;
cb900f41 5735 spinlock_t *ptl;
2b740303 5736 vm_fault_t ret;
8382d914
DB
5737 u32 hash;
5738 pgoff_t idx;
0fe6e20b 5739 struct page *page = NULL;
57303d80 5740 struct page *pagecache_page = NULL;
a5516438 5741 struct hstate *h = hstate_vma(vma);
8382d914 5742 struct address_space *mapping;
0f792cf9 5743 int need_wait_lock = 0;
285b8dca 5744 unsigned long haddr = address & huge_page_mask(h);
86e5216f 5745
285b8dca 5746 ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
fd6a03ed 5747 if (ptep) {
40549ba8
MK
5748 /*
5749 * Since we hold no locks, ptep could be stale. That is
5750 * OK as we are only making decisions based on content and
5751 * not actually modifying content here.
5752 */
fd6a03ed 5753 entry = huge_ptep_get(ptep);
290408d4 5754 if (unlikely(is_hugetlb_entry_migration(entry))) {
ad1ac596 5755 migration_entry_wait_huge(vma, ptep);
290408d4
NH
5756 return 0;
5757 } else if (unlikely(is_hugetlb_entry_hwpoisoned(entry)))
32f84528 5758 return VM_FAULT_HWPOISON_LARGE |
972dc4de 5759 VM_FAULT_SET_HINDEX(hstate_index(h));
fd6a03ed
NH
5760 }
5761
3935baa9
DG
5762 /*
5763 * Serialize hugepage allocation and instantiation, so that we don't
5764 * get spurious allocation failures if two CPUs race to instantiate
5765 * the same page in the page cache.
5766 */
40549ba8
MK
5767 mapping = vma->vm_file->f_mapping;
5768 idx = vma_hugecache_offset(h, vma, haddr);
188b04a7 5769 hash = hugetlb_fault_mutex_hash(mapping, idx);
c672c7f2 5770 mutex_lock(&hugetlb_fault_mutex_table[hash]);
8382d914 5771
40549ba8
MK
5772 /*
5773 * Acquire vma lock before calling huge_pte_alloc and hold
5774 * until finished with ptep. This prevents huge_pmd_unshare from
5775 * being called elsewhere and making the ptep no longer valid.
5776 *
5777 * ptep could have already be assigned via huge_pte_offset. That
5778 * is OK, as huge_pte_alloc will return the same value unless
5779 * something has changed.
5780 */
5781 hugetlb_vma_lock_read(vma);
5782 ptep = huge_pte_alloc(mm, vma, haddr, huge_page_size(h));
5783 if (!ptep) {
5784 hugetlb_vma_unlock_read(vma);
5785 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
5786 return VM_FAULT_OOM;
5787 }
5788
7f2e9525 5789 entry = huge_ptep_get(ptep);
c64e912c 5790 /* PTE markers should be handled the same way as none pte */
958f32ce
LS
5791 if (huge_pte_none_mostly(entry))
5792 /*
5793 * hugetlb_no_page will drop vma lock and hugetlb fault
5794 * mutex internally, which make us return immediately.
5795 */
5796 return hugetlb_no_page(mm, vma, mapping, idx, address, ptep,
c64e912c 5797 entry, flags);
86e5216f 5798
83c54070 5799 ret = 0;
1e8f889b 5800
0f792cf9
NH
5801 /*
5802 * entry could be a migration/hwpoison entry at this point, so this
5803 * check prevents the kernel from going below assuming that we have
7c8de358
EP
5804 * an active hugepage in pagecache. This goto expects the 2nd page
5805 * fault, and is_hugetlb_entry_(migration|hwpoisoned) check will
5806 * properly handle it.
0f792cf9
NH
5807 */
5808 if (!pte_present(entry))
5809 goto out_mutex;
5810
57303d80 5811 /*
c89357e2
DH
5812 * If we are going to COW/unshare the mapping later, we examine the
5813 * pending reservations for this page now. This will ensure that any
57303d80 5814 * allocations necessary to record that reservation occur outside the
1d8d1464
DH
5815 * spinlock. Also lookup the pagecache page now as it is used to
5816 * determine if a reservation has been consumed.
57303d80 5817 */
c89357e2 5818 if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) &&
1d8d1464 5819 !(vma->vm_flags & VM_MAYSHARE) && !huge_pte_write(entry)) {
285b8dca 5820 if (vma_needs_reservation(h, vma, haddr) < 0) {
2b26736c 5821 ret = VM_FAULT_OOM;
b4d1d99f 5822 goto out_mutex;
2b26736c 5823 }
5e911373 5824 /* Just decrements count, does not deallocate */
285b8dca 5825 vma_end_reservation(h, vma, haddr);
57303d80 5826
29be8426 5827 pagecache_page = find_lock_page(mapping, idx);
57303d80
AW
5828 }
5829
0f792cf9
NH
5830 ptl = huge_pte_lock(h, mm, ptep);
5831
c89357e2 5832 /* Check for a racing update before calling hugetlb_wp() */
0f792cf9
NH
5833 if (unlikely(!pte_same(entry, huge_ptep_get(ptep))))
5834 goto out_ptl;
5835
166f3ecc
PX
5836 /* Handle userfault-wp first, before trying to lock more pages */
5837 if (userfaultfd_wp(vma) && huge_pte_uffd_wp(huge_ptep_get(ptep)) &&
5838 (flags & FAULT_FLAG_WRITE) && !huge_pte_write(entry)) {
5839 struct vm_fault vmf = {
5840 .vma = vma,
5841 .address = haddr,
5842 .real_address = address,
5843 .flags = flags,
5844 };
5845
5846 spin_unlock(ptl);
5847 if (pagecache_page) {
5848 unlock_page(pagecache_page);
5849 put_page(pagecache_page);
5850 }
40549ba8 5851 hugetlb_vma_unlock_read(vma);
166f3ecc 5852 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
166f3ecc
PX
5853 return handle_userfault(&vmf, VM_UFFD_WP);
5854 }
5855
56c9cfb1 5856 /*
c89357e2 5857 * hugetlb_wp() requires page locks of pte_page(entry) and
56c9cfb1
NH
5858 * pagecache_page, so here we need take the former one
5859 * when page != pagecache_page or !pagecache_page.
56c9cfb1
NH
5860 */
5861 page = pte_page(entry);
5862 if (page != pagecache_page)
0f792cf9
NH
5863 if (!trylock_page(page)) {
5864 need_wait_lock = 1;
5865 goto out_ptl;
5866 }
b4d1d99f 5867
0f792cf9 5868 get_page(page);
b4d1d99f 5869
c89357e2 5870 if (flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) {
106c992a 5871 if (!huge_pte_write(entry)) {
c89357e2
DH
5872 ret = hugetlb_wp(mm, vma, address, ptep, flags,
5873 pagecache_page, ptl);
0f792cf9 5874 goto out_put_page;
c89357e2
DH
5875 } else if (likely(flags & FAULT_FLAG_WRITE)) {
5876 entry = huge_pte_mkdirty(entry);
b4d1d99f 5877 }
b4d1d99f
DG
5878 }
5879 entry = pte_mkyoung(entry);
285b8dca 5880 if (huge_ptep_set_access_flags(vma, haddr, ptep, entry,
788c7df4 5881 flags & FAULT_FLAG_WRITE))
285b8dca 5882 update_mmu_cache(vma, haddr, ptep);
0f792cf9
NH
5883out_put_page:
5884 if (page != pagecache_page)
5885 unlock_page(page);
5886 put_page(page);
cb900f41
KS
5887out_ptl:
5888 spin_unlock(ptl);
57303d80
AW
5889
5890 if (pagecache_page) {
5891 unlock_page(pagecache_page);
5892 put_page(pagecache_page);
5893 }
b4d1d99f 5894out_mutex:
40549ba8 5895 hugetlb_vma_unlock_read(vma);
c672c7f2 5896 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
0f792cf9
NH
5897 /*
5898 * Generally it's safe to hold refcount during waiting page lock. But
5899 * here we just wait to defer the next page fault to avoid busy loop and
5900 * the page is not used after unlocked before returning from the current
5901 * page fault. So we are safe from accessing freed page, even if we wait
5902 * here without taking refcount.
5903 */
5904 if (need_wait_lock)
5905 wait_on_page_locked(page);
1e8f889b 5906 return ret;
86e5216f
AL
5907}
5908
714c1891 5909#ifdef CONFIG_USERFAULTFD
8fb5debc
MK
5910/*
5911 * Used by userfaultfd UFFDIO_COPY. Based on mcopy_atomic_pte with
5912 * modifications for huge pages.
5913 */
5914int hugetlb_mcopy_atomic_pte(struct mm_struct *dst_mm,
5915 pte_t *dst_pte,
5916 struct vm_area_struct *dst_vma,
5917 unsigned long dst_addr,
5918 unsigned long src_addr,
f6191471 5919 enum mcopy_atomic_mode mode,
6041c691
PX
5920 struct page **pagep,
5921 bool wp_copy)
8fb5debc 5922{
f6191471 5923 bool is_continue = (mode == MCOPY_ATOMIC_CONTINUE);
8cc5fcbb
MA
5924 struct hstate *h = hstate_vma(dst_vma);
5925 struct address_space *mapping = dst_vma->vm_file->f_mapping;
5926 pgoff_t idx = vma_hugecache_offset(h, dst_vma, dst_addr);
1e392147 5927 unsigned long size;
1c9e8def 5928 int vm_shared = dst_vma->vm_flags & VM_SHARED;
8fb5debc
MK
5929 pte_t _dst_pte;
5930 spinlock_t *ptl;
8cc5fcbb 5931 int ret = -ENOMEM;
8fb5debc 5932 struct page *page;
f6191471 5933 int writable;
cc30042d 5934 bool page_in_pagecache = false;
8fb5debc 5935
f6191471
AR
5936 if (is_continue) {
5937 ret = -EFAULT;
5938 page = find_lock_page(mapping, idx);
5939 if (!page)
5940 goto out;
cc30042d 5941 page_in_pagecache = true;
f6191471 5942 } else if (!*pagep) {
d84cf06e
MA
5943 /* If a page already exists, then it's UFFDIO_COPY for
5944 * a non-missing case. Return -EEXIST.
5945 */
5946 if (vm_shared &&
5947 hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
5948 ret = -EEXIST;
5949 goto out;
5950 }
5951
8fb5debc 5952 page = alloc_huge_page(dst_vma, dst_addr, 0);
d84cf06e
MA
5953 if (IS_ERR(page)) {
5954 ret = -ENOMEM;
8fb5debc 5955 goto out;
d84cf06e 5956 }
8fb5debc
MK
5957
5958 ret = copy_huge_page_from_user(page,
5959 (const void __user *) src_addr,
810a56b9 5960 pages_per_huge_page(h), false);
8fb5debc 5961
c1e8d7c6 5962 /* fallback to copy_from_user outside mmap_lock */
8fb5debc 5963 if (unlikely(ret)) {
9e368259 5964 ret = -ENOENT;
8cc5fcbb
MA
5965 /* Free the allocated page which may have
5966 * consumed a reservation.
5967 */
5968 restore_reserve_on_error(h, dst_vma, dst_addr, page);
5969 put_page(page);
5970
5971 /* Allocate a temporary page to hold the copied
5972 * contents.
5973 */
5974 page = alloc_huge_page_vma(h, dst_vma, dst_addr);
5975 if (!page) {
5976 ret = -ENOMEM;
5977 goto out;
5978 }
8fb5debc 5979 *pagep = page;
8cc5fcbb
MA
5980 /* Set the outparam pagep and return to the caller to
5981 * copy the contents outside the lock. Don't free the
5982 * page.
5983 */
8fb5debc
MK
5984 goto out;
5985 }
5986 } else {
8cc5fcbb
MA
5987 if (vm_shared &&
5988 hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
5989 put_page(*pagep);
5990 ret = -EEXIST;
5991 *pagep = NULL;
5992 goto out;
5993 }
5994
5995 page = alloc_huge_page(dst_vma, dst_addr, 0);
5996 if (IS_ERR(page)) {
da9a298f 5997 put_page(*pagep);
8cc5fcbb
MA
5998 ret = -ENOMEM;
5999 *pagep = NULL;
6000 goto out;
6001 }
34892366
MS
6002 copy_user_huge_page(page, *pagep, dst_addr, dst_vma,
6003 pages_per_huge_page(h));
8cc5fcbb 6004 put_page(*pagep);
8fb5debc
MK
6005 *pagep = NULL;
6006 }
6007
6008 /*
6009 * The memory barrier inside __SetPageUptodate makes sure that
6010 * preceding stores to the page contents become visible before
6011 * the set_pte_at() write.
6012 */
6013 __SetPageUptodate(page);
8fb5debc 6014
f6191471
AR
6015 /* Add shared, newly allocated pages to the page cache. */
6016 if (vm_shared && !is_continue) {
1e392147
AA
6017 size = i_size_read(mapping->host) >> huge_page_shift(h);
6018 ret = -EFAULT;
6019 if (idx >= size)
6020 goto out_release_nounlock;
1c9e8def 6021
1e392147
AA
6022 /*
6023 * Serialization between remove_inode_hugepages() and
7e1813d4 6024 * hugetlb_add_to_page_cache() below happens through the
1e392147
AA
6025 * hugetlb_fault_mutex_table that here must be hold by
6026 * the caller.
6027 */
7e1813d4 6028 ret = hugetlb_add_to_page_cache(page, mapping, idx);
1c9e8def
MK
6029 if (ret)
6030 goto out_release_nounlock;
cc30042d 6031 page_in_pagecache = true;
1c9e8def
MK
6032 }
6033
bcc66543 6034 ptl = huge_pte_lock(h, dst_mm, dst_pte);
8fb5debc 6035
6041c691
PX
6036 /*
6037 * We allow to overwrite a pte marker: consider when both MISSING|WP
6038 * registered, we firstly wr-protect a none pte which has no page cache
6039 * page backing it, then access the page.
6040 */
fa27759a 6041 ret = -EEXIST;
6041c691 6042 if (!huge_pte_none_mostly(huge_ptep_get(dst_pte)))
8fb5debc
MK
6043 goto out_release_unlock;
6044
ab74ef70 6045 if (page_in_pagecache) {
fb3d824d 6046 page_dup_file_rmap(page, true);
1c9e8def 6047 } else {
d6995da3 6048 ClearHPageRestoreReserve(page);
1c9e8def
MK
6049 hugepage_add_new_anon_rmap(page, dst_vma, dst_addr);
6050 }
8fb5debc 6051
6041c691
PX
6052 /*
6053 * For either: (1) CONTINUE on a non-shared VMA, or (2) UFFDIO_COPY
6054 * with wp flag set, don't set pte write bit.
6055 */
6056 if (wp_copy || (is_continue && !vm_shared))
f6191471
AR
6057 writable = 0;
6058 else
6059 writable = dst_vma->vm_flags & VM_WRITE;
6060
6061 _dst_pte = make_huge_pte(dst_vma, page, writable);
6041c691
PX
6062 /*
6063 * Always mark UFFDIO_COPY page dirty; note that this may not be
6064 * extremely important for hugetlbfs for now since swapping is not
6065 * supported, but we should still be clear in that this page cannot be
6066 * thrown away at will, even if write bit not set.
6067 */
6068 _dst_pte = huge_pte_mkdirty(_dst_pte);
8fb5debc
MK
6069 _dst_pte = pte_mkyoung(_dst_pte);
6070
6041c691
PX
6071 if (wp_copy)
6072 _dst_pte = huge_pte_mkuffd_wp(_dst_pte);
6073
8fb5debc
MK
6074 set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
6075
8fb5debc
MK
6076 hugetlb_count_add(pages_per_huge_page(h), dst_mm);
6077
6078 /* No need to invalidate - it was non-present before */
6079 update_mmu_cache(dst_vma, dst_addr, dst_pte);
6080
6081 spin_unlock(ptl);
f6191471
AR
6082 if (!is_continue)
6083 SetHPageMigratable(page);
6084 if (vm_shared || is_continue)
1c9e8def 6085 unlock_page(page);
8fb5debc
MK
6086 ret = 0;
6087out:
6088 return ret;
6089out_release_unlock:
6090 spin_unlock(ptl);
f6191471 6091 if (vm_shared || is_continue)
1c9e8def 6092 unlock_page(page);
5af10dfd 6093out_release_nounlock:
cc30042d 6094 if (!page_in_pagecache)
c7b1850d 6095 restore_reserve_on_error(h, dst_vma, dst_addr, page);
8fb5debc
MK
6096 put_page(page);
6097 goto out;
6098}
714c1891 6099#endif /* CONFIG_USERFAULTFD */
8fb5debc 6100
82e5d378
JM
6101static void record_subpages_vmas(struct page *page, struct vm_area_struct *vma,
6102 int refs, struct page **pages,
6103 struct vm_area_struct **vmas)
6104{
6105 int nr;
6106
6107 for (nr = 0; nr < refs; nr++) {
6108 if (likely(pages))
14455eab 6109 pages[nr] = nth_page(page, nr);
82e5d378
JM
6110 if (vmas)
6111 vmas[nr] = vma;
6112 }
6113}
6114
a7f22660
DH
6115static inline bool __follow_hugetlb_must_fault(unsigned int flags, pte_t *pte,
6116 bool *unshare)
6117{
6118 pte_t pteval = huge_ptep_get(pte);
6119
6120 *unshare = false;
6121 if (is_swap_pte(pteval))
6122 return true;
6123 if (huge_pte_write(pteval))
6124 return false;
6125 if (flags & FOLL_WRITE)
6126 return true;
6127 if (gup_must_unshare(flags, pte_page(pteval))) {
6128 *unshare = true;
6129 return true;
6130 }
6131 return false;
6132}
6133
28a35716
ML
6134long follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma,
6135 struct page **pages, struct vm_area_struct **vmas,
6136 unsigned long *position, unsigned long *nr_pages,
4f6da934 6137 long i, unsigned int flags, int *locked)
63551ae0 6138{
d5d4b0aa
CK
6139 unsigned long pfn_offset;
6140 unsigned long vaddr = *position;
28a35716 6141 unsigned long remainder = *nr_pages;
a5516438 6142 struct hstate *h = hstate_vma(vma);
0fa5bc40 6143 int err = -EFAULT, refs;
63551ae0 6144
63551ae0 6145 while (vaddr < vma->vm_end && remainder) {
4c887265 6146 pte_t *pte;
cb900f41 6147 spinlock_t *ptl = NULL;
a7f22660 6148 bool unshare = false;
2a15efc9 6149 int absent;
4c887265 6150 struct page *page;
63551ae0 6151
02057967
DR
6152 /*
6153 * If we have a pending SIGKILL, don't keep faulting pages and
6154 * potentially allocating memory.
6155 */
fa45f116 6156 if (fatal_signal_pending(current)) {
02057967
DR
6157 remainder = 0;
6158 break;
6159 }
6160
4c887265
AL
6161 /*
6162 * Some archs (sparc64, sh*) have multiple pte_ts to
2a15efc9 6163 * each hugepage. We have to make sure we get the
4c887265 6164 * first, for the page indexing below to work.
cb900f41
KS
6165 *
6166 * Note that page table lock is not held when pte is null.
4c887265 6167 */
7868a208
PA
6168 pte = huge_pte_offset(mm, vaddr & huge_page_mask(h),
6169 huge_page_size(h));
cb900f41
KS
6170 if (pte)
6171 ptl = huge_pte_lock(h, mm, pte);
2a15efc9
HD
6172 absent = !pte || huge_pte_none(huge_ptep_get(pte));
6173
6174 /*
6175 * When coredumping, it suits get_dump_page if we just return
3ae77f43
HD
6176 * an error where there's an empty slot with no huge pagecache
6177 * to back it. This way, we avoid allocating a hugepage, and
6178 * the sparse dumpfile avoids allocating disk blocks, but its
6179 * huge holes still show up with zeroes where they need to be.
2a15efc9 6180 */
3ae77f43
HD
6181 if (absent && (flags & FOLL_DUMP) &&
6182 !hugetlbfs_pagecache_present(h, vma, vaddr)) {
cb900f41
KS
6183 if (pte)
6184 spin_unlock(ptl);
2a15efc9
HD
6185 remainder = 0;
6186 break;
6187 }
63551ae0 6188
9cc3a5bd
NH
6189 /*
6190 * We need call hugetlb_fault for both hugepages under migration
6191 * (in which case hugetlb_fault waits for the migration,) and
6192 * hwpoisoned hugepages (in which case we need to prevent the
6193 * caller from accessing to them.) In order to do this, we use
6194 * here is_swap_pte instead of is_hugetlb_entry_migration and
6195 * is_hugetlb_entry_hwpoisoned. This is because it simply covers
6196 * both cases, and because we can't follow correct pages
6197 * directly from any kind of swap entries.
6198 */
a7f22660
DH
6199 if (absent ||
6200 __follow_hugetlb_must_fault(flags, pte, &unshare)) {
2b740303 6201 vm_fault_t ret;
87ffc118 6202 unsigned int fault_flags = 0;
63551ae0 6203
cb900f41
KS
6204 if (pte)
6205 spin_unlock(ptl);
87ffc118
AA
6206 if (flags & FOLL_WRITE)
6207 fault_flags |= FAULT_FLAG_WRITE;
a7f22660
DH
6208 else if (unshare)
6209 fault_flags |= FAULT_FLAG_UNSHARE;
4f6da934 6210 if (locked)
71335f37
PX
6211 fault_flags |= FAULT_FLAG_ALLOW_RETRY |
6212 FAULT_FLAG_KILLABLE;
87ffc118
AA
6213 if (flags & FOLL_NOWAIT)
6214 fault_flags |= FAULT_FLAG_ALLOW_RETRY |
6215 FAULT_FLAG_RETRY_NOWAIT;
6216 if (flags & FOLL_TRIED) {
4426e945
PX
6217 /*
6218 * Note: FAULT_FLAG_ALLOW_RETRY and
6219 * FAULT_FLAG_TRIED can co-exist
6220 */
87ffc118
AA
6221 fault_flags |= FAULT_FLAG_TRIED;
6222 }
6223 ret = hugetlb_fault(mm, vma, vaddr, fault_flags);
6224 if (ret & VM_FAULT_ERROR) {
2be7cfed 6225 err = vm_fault_to_errno(ret, flags);
87ffc118
AA
6226 remainder = 0;
6227 break;
6228 }
6229 if (ret & VM_FAULT_RETRY) {
4f6da934 6230 if (locked &&
1ac25013 6231 !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
4f6da934 6232 *locked = 0;
87ffc118
AA
6233 *nr_pages = 0;
6234 /*
6235 * VM_FAULT_RETRY must not return an
6236 * error, it will return zero
6237 * instead.
6238 *
6239 * No need to update "position" as the
6240 * caller will not check it after
6241 * *nr_pages is set to 0.
6242 */
6243 return i;
6244 }
6245 continue;
4c887265
AL
6246 }
6247
a5516438 6248 pfn_offset = (vaddr & ~huge_page_mask(h)) >> PAGE_SHIFT;
7f2e9525 6249 page = pte_page(huge_ptep_get(pte));
8fde12ca 6250
b6a2619c
DH
6251 VM_BUG_ON_PAGE((flags & FOLL_PIN) && PageAnon(page) &&
6252 !PageAnonExclusive(page), page);
6253
acbfb087
ZL
6254 /*
6255 * If subpage information not requested, update counters
6256 * and skip the same_page loop below.
6257 */
6258 if (!pages && !vmas && !pfn_offset &&
6259 (vaddr + huge_page_size(h) < vma->vm_end) &&
6260 (remainder >= pages_per_huge_page(h))) {
6261 vaddr += huge_page_size(h);
6262 remainder -= pages_per_huge_page(h);
6263 i += pages_per_huge_page(h);
6264 spin_unlock(ptl);
6265 continue;
6266 }
6267
d08af0a5
JM
6268 /* vaddr may not be aligned to PAGE_SIZE */
6269 refs = min3(pages_per_huge_page(h) - pfn_offset, remainder,
6270 (vma->vm_end - ALIGN_DOWN(vaddr, PAGE_SIZE)) >> PAGE_SHIFT);
0fa5bc40 6271
82e5d378 6272 if (pages || vmas)
14455eab 6273 record_subpages_vmas(nth_page(page, pfn_offset),
82e5d378
JM
6274 vma, refs,
6275 likely(pages) ? pages + i : NULL,
6276 vmas ? vmas + i : NULL);
63551ae0 6277
82e5d378 6278 if (pages) {
0fa5bc40 6279 /*
822951d8 6280 * try_grab_folio() should always succeed here,
0fa5bc40
JM
6281 * because: a) we hold the ptl lock, and b) we've just
6282 * checked that the huge page is present in the page
6283 * tables. If the huge page is present, then the tail
6284 * pages must also be present. The ptl prevents the
6285 * head page and tail pages from being rearranged in
6286 * any way. So this page must be available at this
6287 * point, unless the page refcount overflowed:
6288 */
822951d8
MWO
6289 if (WARN_ON_ONCE(!try_grab_folio(pages[i], refs,
6290 flags))) {
0fa5bc40
JM
6291 spin_unlock(ptl);
6292 remainder = 0;
6293 err = -ENOMEM;
6294 break;
6295 }
d5d4b0aa 6296 }
82e5d378
JM
6297
6298 vaddr += (refs << PAGE_SHIFT);
6299 remainder -= refs;
6300 i += refs;
6301
cb900f41 6302 spin_unlock(ptl);
63551ae0 6303 }
28a35716 6304 *nr_pages = remainder;
87ffc118
AA
6305 /*
6306 * setting position is actually required only if remainder is
6307 * not zero but it's faster not to add a "if (remainder)"
6308 * branch.
6309 */
63551ae0
DG
6310 *position = vaddr;
6311
2be7cfed 6312 return i ? i : err;
63551ae0 6313}
8f860591 6314
7da4d641 6315unsigned long hugetlb_change_protection(struct vm_area_struct *vma,
5a90d5a1
PX
6316 unsigned long address, unsigned long end,
6317 pgprot_t newprot, unsigned long cp_flags)
8f860591
ZY
6318{
6319 struct mm_struct *mm = vma->vm_mm;
6320 unsigned long start = address;
6321 pte_t *ptep;
6322 pte_t pte;
a5516438 6323 struct hstate *h = hstate_vma(vma);
60dfaad6 6324 unsigned long pages = 0, psize = huge_page_size(h);
dff11abe 6325 bool shared_pmd = false;
ac46d4f3 6326 struct mmu_notifier_range range;
e95a9851 6327 unsigned long last_addr_mask;
5a90d5a1
PX
6328 bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
6329 bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
dff11abe
MK
6330
6331 /*
6332 * In the case of shared PMDs, the area to flush could be beyond
ac46d4f3 6333 * start/end. Set range.start/range.end to cover the maximum possible
dff11abe
MK
6334 * range if PMD sharing is possible.
6335 */
7269f999
JG
6336 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_VMA,
6337 0, vma, mm, start, end);
ac46d4f3 6338 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
8f860591
ZY
6339
6340 BUG_ON(address >= end);
ac46d4f3 6341 flush_cache_range(vma, range.start, range.end);
8f860591 6342
ac46d4f3 6343 mmu_notifier_invalidate_range_start(&range);
40549ba8 6344 hugetlb_vma_lock_write(vma);
83cde9e8 6345 i_mmap_lock_write(vma->vm_file->f_mapping);
40549ba8 6346 last_addr_mask = hugetlb_mask_last_page(h);
60dfaad6 6347 for (; address < end; address += psize) {
cb900f41 6348 spinlock_t *ptl;
60dfaad6 6349 ptep = huge_pte_offset(mm, address, psize);
e95a9851
MK
6350 if (!ptep) {
6351 address |= last_addr_mask;
8f860591 6352 continue;
e95a9851 6353 }
cb900f41 6354 ptl = huge_pte_lock(h, mm, ptep);
4ddb4d91 6355 if (huge_pmd_unshare(mm, vma, address, ptep)) {
60dfaad6
PX
6356 /*
6357 * When uffd-wp is enabled on the vma, unshare
6358 * shouldn't happen at all. Warn about it if it
6359 * happened due to some reason.
6360 */
6361 WARN_ON_ONCE(uffd_wp || uffd_wp_resolve);
7da4d641 6362 pages++;
cb900f41 6363 spin_unlock(ptl);
dff11abe 6364 shared_pmd = true;
4ddb4d91 6365 address |= last_addr_mask;
39dde65c 6366 continue;
7da4d641 6367 }
a8bda28d
NH
6368 pte = huge_ptep_get(ptep);
6369 if (unlikely(is_hugetlb_entry_hwpoisoned(pte))) {
6370 spin_unlock(ptl);
6371 continue;
6372 }
6373 if (unlikely(is_hugetlb_entry_migration(pte))) {
6374 swp_entry_t entry = pte_to_swp_entry(pte);
6c287605 6375 struct page *page = pfn_swap_entry_to_page(entry);
a8bda28d 6376
6c287605 6377 if (!is_readable_migration_entry(entry)) {
a8bda28d
NH
6378 pte_t newpte;
6379
6c287605
DH
6380 if (PageAnon(page))
6381 entry = make_readable_exclusive_migration_entry(
6382 swp_offset(entry));
6383 else
6384 entry = make_readable_migration_entry(
6385 swp_offset(entry));
a8bda28d 6386 newpte = swp_entry_to_pte(entry);
5a90d5a1
PX
6387 if (uffd_wp)
6388 newpte = pte_swp_mkuffd_wp(newpte);
6389 else if (uffd_wp_resolve)
6390 newpte = pte_swp_clear_uffd_wp(newpte);
18f39629 6391 set_huge_pte_at(mm, address, ptep, newpte);
a8bda28d
NH
6392 pages++;
6393 }
6394 spin_unlock(ptl);
6395 continue;
6396 }
60dfaad6
PX
6397 if (unlikely(pte_marker_uffd_wp(pte))) {
6398 /*
6399 * This is changing a non-present pte into a none pte,
6400 * no need for huge_ptep_modify_prot_start/commit().
6401 */
6402 if (uffd_wp_resolve)
6403 huge_pte_clear(mm, address, ptep, psize);
6404 }
a8bda28d 6405 if (!huge_pte_none(pte)) {
023bdd00 6406 pte_t old_pte;
79c1c594 6407 unsigned int shift = huge_page_shift(hstate_vma(vma));
023bdd00
AK
6408
6409 old_pte = huge_ptep_modify_prot_start(vma, address, ptep);
16785bd7 6410 pte = huge_pte_modify(old_pte, newprot);
79c1c594 6411 pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
5a90d5a1
PX
6412 if (uffd_wp)
6413 pte = huge_pte_mkuffd_wp(huge_pte_wrprotect(pte));
6414 else if (uffd_wp_resolve)
6415 pte = huge_pte_clear_uffd_wp(pte);
023bdd00 6416 huge_ptep_modify_prot_commit(vma, address, ptep, old_pte, pte);
7da4d641 6417 pages++;
60dfaad6
PX
6418 } else {
6419 /* None pte */
6420 if (unlikely(uffd_wp))
6421 /* Safe to modify directly (none->non-present). */
6422 set_huge_pte_at(mm, address, ptep,
6423 make_pte_marker(PTE_MARKER_UFFD_WP));
8f860591 6424 }
cb900f41 6425 spin_unlock(ptl);
8f860591 6426 }
d833352a 6427 /*
c8c06efa 6428 * Must flush TLB before releasing i_mmap_rwsem: x86's huge_pmd_unshare
d833352a 6429 * may have cleared our pud entry and done put_page on the page table:
c8c06efa 6430 * once we release i_mmap_rwsem, another task can do the final put_page
dff11abe
MK
6431 * and that page table be reused and filled with junk. If we actually
6432 * did unshare a page of pmds, flush the range corresponding to the pud.
d833352a 6433 */
dff11abe 6434 if (shared_pmd)
ac46d4f3 6435 flush_hugetlb_tlb_range(vma, range.start, range.end);
dff11abe
MK
6436 else
6437 flush_hugetlb_tlb_range(vma, start, end);
0f10851e
JG
6438 /*
6439 * No need to call mmu_notifier_invalidate_range() we are downgrading
6440 * page table protection not changing it to point to a new page.
6441 *
ee65728e 6442 * See Documentation/mm/mmu_notifier.rst
0f10851e 6443 */
83cde9e8 6444 i_mmap_unlock_write(vma->vm_file->f_mapping);
40549ba8 6445 hugetlb_vma_unlock_write(vma);
ac46d4f3 6446 mmu_notifier_invalidate_range_end(&range);
7da4d641
PZ
6447
6448 return pages << h->order;
8f860591
ZY
6449}
6450
33b8f84a
MK
6451/* Return true if reservation was successful, false otherwise. */
6452bool hugetlb_reserve_pages(struct inode *inode,
a1e78772 6453 long from, long to,
5a6fe125 6454 struct vm_area_struct *vma,
ca16d140 6455 vm_flags_t vm_flags)
e4e574b7 6456{
33b8f84a 6457 long chg, add = -1;
a5516438 6458 struct hstate *h = hstate_inode(inode);
90481622 6459 struct hugepage_subpool *spool = subpool_inode(inode);
9119a41e 6460 struct resv_map *resv_map;
075a61d0 6461 struct hugetlb_cgroup *h_cg = NULL;
0db9d74e 6462 long gbl_reserve, regions_needed = 0;
e4e574b7 6463
63489f8e
MK
6464 /* This should never happen */
6465 if (from > to) {
6466 VM_WARN(1, "%s called with a negative range\n", __func__);
33b8f84a 6467 return false;
63489f8e
MK
6468 }
6469
8d9bfb26
MK
6470 /*
6471 * vma specific semaphore used for pmd sharing synchronization
6472 */
6473 hugetlb_vma_lock_alloc(vma);
6474
17c9d12e
MG
6475 /*
6476 * Only apply hugepage reservation if asked. At fault time, an
6477 * attempt will be made for VM_NORESERVE to allocate a page
90481622 6478 * without using reserves
17c9d12e 6479 */
ca16d140 6480 if (vm_flags & VM_NORESERVE)
33b8f84a 6481 return true;
17c9d12e 6482
a1e78772
MG
6483 /*
6484 * Shared mappings base their reservation on the number of pages that
6485 * are already allocated on behalf of the file. Private mappings need
6486 * to reserve the full area even if read-only as mprotect() may be
6487 * called to make the mapping read-write. Assume !vma is a shm mapping
6488 */
9119a41e 6489 if (!vma || vma->vm_flags & VM_MAYSHARE) {
f27a5136
MK
6490 /*
6491 * resv_map can not be NULL as hugetlb_reserve_pages is only
6492 * called for inodes for which resv_maps were created (see
6493 * hugetlbfs_get_inode).
6494 */
4e35f483 6495 resv_map = inode_resv_map(inode);
9119a41e 6496
0db9d74e 6497 chg = region_chg(resv_map, from, to, &regions_needed);
9119a41e 6498 } else {
e9fe92ae 6499 /* Private mapping. */
9119a41e 6500 resv_map = resv_map_alloc();
17c9d12e 6501 if (!resv_map)
8d9bfb26 6502 goto out_err;
17c9d12e 6503
a1e78772 6504 chg = to - from;
84afd99b 6505
17c9d12e
MG
6506 set_vma_resv_map(vma, resv_map);
6507 set_vma_resv_flags(vma, HPAGE_RESV_OWNER);
6508 }
6509
33b8f84a 6510 if (chg < 0)
c50ac050 6511 goto out_err;
8a630112 6512
33b8f84a
MK
6513 if (hugetlb_cgroup_charge_cgroup_rsvd(hstate_index(h),
6514 chg * pages_per_huge_page(h), &h_cg) < 0)
075a61d0 6515 goto out_err;
075a61d0
MA
6516
6517 if (vma && !(vma->vm_flags & VM_MAYSHARE) && h_cg) {
6518 /* For private mappings, the hugetlb_cgroup uncharge info hangs
6519 * of the resv_map.
6520 */
6521 resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, h_cg, h);
6522 }
6523
1c5ecae3
MK
6524 /*
6525 * There must be enough pages in the subpool for the mapping. If
6526 * the subpool has a minimum size, there may be some global
6527 * reservations already in place (gbl_reserve).
6528 */
6529 gbl_reserve = hugepage_subpool_get_pages(spool, chg);
33b8f84a 6530 if (gbl_reserve < 0)
075a61d0 6531 goto out_uncharge_cgroup;
5a6fe125
MG
6532
6533 /*
17c9d12e 6534 * Check enough hugepages are available for the reservation.
90481622 6535 * Hand the pages back to the subpool if there are not
5a6fe125 6536 */
33b8f84a 6537 if (hugetlb_acct_memory(h, gbl_reserve) < 0)
075a61d0 6538 goto out_put_pages;
17c9d12e
MG
6539
6540 /*
6541 * Account for the reservations made. Shared mappings record regions
6542 * that have reservations as they are shared by multiple VMAs.
6543 * When the last VMA disappears, the region map says how much
6544 * the reservation was and the page cache tells how much of
6545 * the reservation was consumed. Private mappings are per-VMA and
6546 * only the consumed reservations are tracked. When the VMA
6547 * disappears, the original reservation is the VMA size and the
6548 * consumed reservations are stored in the map. Hence, nothing
6549 * else has to be done for private mappings here
6550 */
33039678 6551 if (!vma || vma->vm_flags & VM_MAYSHARE) {
075a61d0 6552 add = region_add(resv_map, from, to, regions_needed, h, h_cg);
0db9d74e
MA
6553
6554 if (unlikely(add < 0)) {
6555 hugetlb_acct_memory(h, -gbl_reserve);
075a61d0 6556 goto out_put_pages;
0db9d74e 6557 } else if (unlikely(chg > add)) {
33039678
MK
6558 /*
6559 * pages in this range were added to the reserve
6560 * map between region_chg and region_add. This
6561 * indicates a race with alloc_huge_page. Adjust
6562 * the subpool and reserve counts modified above
6563 * based on the difference.
6564 */
6565 long rsv_adjust;
6566
d85aecf2
ML
6567 /*
6568 * hugetlb_cgroup_uncharge_cgroup_rsvd() will put the
6569 * reference to h_cg->css. See comment below for detail.
6570 */
075a61d0
MA
6571 hugetlb_cgroup_uncharge_cgroup_rsvd(
6572 hstate_index(h),
6573 (chg - add) * pages_per_huge_page(h), h_cg);
6574
33039678
MK
6575 rsv_adjust = hugepage_subpool_put_pages(spool,
6576 chg - add);
6577 hugetlb_acct_memory(h, -rsv_adjust);
d85aecf2
ML
6578 } else if (h_cg) {
6579 /*
6580 * The file_regions will hold their own reference to
6581 * h_cg->css. So we should release the reference held
6582 * via hugetlb_cgroup_charge_cgroup_rsvd() when we are
6583 * done.
6584 */
6585 hugetlb_cgroup_put_rsvd_cgroup(h_cg);
33039678
MK
6586 }
6587 }
33b8f84a
MK
6588 return true;
6589
075a61d0
MA
6590out_put_pages:
6591 /* put back original number of pages, chg */
6592 (void)hugepage_subpool_put_pages(spool, chg);
6593out_uncharge_cgroup:
6594 hugetlb_cgroup_uncharge_cgroup_rsvd(hstate_index(h),
6595 chg * pages_per_huge_page(h), h_cg);
c50ac050 6596out_err:
8d9bfb26 6597 hugetlb_vma_lock_free(vma);
5e911373 6598 if (!vma || vma->vm_flags & VM_MAYSHARE)
0db9d74e
MA
6599 /* Only call region_abort if the region_chg succeeded but the
6600 * region_add failed or didn't run.
6601 */
6602 if (chg >= 0 && add < 0)
6603 region_abort(resv_map, from, to, regions_needed);
f031dd27
JK
6604 if (vma && is_vma_resv_set(vma, HPAGE_RESV_OWNER))
6605 kref_put(&resv_map->refs, resv_map_release);
33b8f84a 6606 return false;
a43a8c39
CK
6607}
6608
b5cec28d
MK
6609long hugetlb_unreserve_pages(struct inode *inode, long start, long end,
6610 long freed)
a43a8c39 6611{
a5516438 6612 struct hstate *h = hstate_inode(inode);
4e35f483 6613 struct resv_map *resv_map = inode_resv_map(inode);
9119a41e 6614 long chg = 0;
90481622 6615 struct hugepage_subpool *spool = subpool_inode(inode);
1c5ecae3 6616 long gbl_reserve;
45c682a6 6617
f27a5136
MK
6618 /*
6619 * Since this routine can be called in the evict inode path for all
6620 * hugetlbfs inodes, resv_map could be NULL.
6621 */
b5cec28d
MK
6622 if (resv_map) {
6623 chg = region_del(resv_map, start, end);
6624 /*
6625 * region_del() can fail in the rare case where a region
6626 * must be split and another region descriptor can not be
6627 * allocated. If end == LONG_MAX, it will not fail.
6628 */
6629 if (chg < 0)
6630 return chg;
6631 }
6632
45c682a6 6633 spin_lock(&inode->i_lock);
e4c6f8be 6634 inode->i_blocks -= (blocks_per_huge_page(h) * freed);
45c682a6
KC
6635 spin_unlock(&inode->i_lock);
6636
1c5ecae3
MK
6637 /*
6638 * If the subpool has a minimum size, the number of global
6639 * reservations to be released may be adjusted.
dddf31a4
ML
6640 *
6641 * Note that !resv_map implies freed == 0. So (chg - freed)
6642 * won't go negative.
1c5ecae3
MK
6643 */
6644 gbl_reserve = hugepage_subpool_put_pages(spool, (chg - freed));
6645 hugetlb_acct_memory(h, -gbl_reserve);
b5cec28d
MK
6646
6647 return 0;
a43a8c39 6648}
93f70f90 6649
3212b535
SC
6650#ifdef CONFIG_ARCH_WANT_HUGE_PMD_SHARE
6651static unsigned long page_table_shareable(struct vm_area_struct *svma,
6652 struct vm_area_struct *vma,
6653 unsigned long addr, pgoff_t idx)
6654{
6655 unsigned long saddr = ((idx - svma->vm_pgoff) << PAGE_SHIFT) +
6656 svma->vm_start;
6657 unsigned long sbase = saddr & PUD_MASK;
6658 unsigned long s_end = sbase + PUD_SIZE;
6659
6660 /* Allow segments to share if only one is marked locked */
de60f5f1
EM
6661 unsigned long vm_flags = vma->vm_flags & VM_LOCKED_CLEAR_MASK;
6662 unsigned long svm_flags = svma->vm_flags & VM_LOCKED_CLEAR_MASK;
3212b535
SC
6663
6664 /*
6665 * match the virtual addresses, permission and the alignment of the
6666 * page table page.
6667 */
6668 if (pmd_index(addr) != pmd_index(saddr) ||
6669 vm_flags != svm_flags ||
07e51edf 6670 !range_in_vma(svma, sbase, s_end))
3212b535
SC
6671 return 0;
6672
6673 return saddr;
6674}
6675
12710fd6 6676static bool __vma_aligned_range_pmd_shareable(struct vm_area_struct *vma,
8d9bfb26
MK
6677 unsigned long start, unsigned long end,
6678 bool check_vma_lock)
3212b535 6679{
8d9bfb26
MK
6680#ifdef CONFIG_USERFAULTFD
6681 if (uffd_disable_huge_pmd_share(vma))
6682 return false;
6683#endif
3212b535
SC
6684 /*
6685 * check on proper vm_flags and page table alignment
6686 */
8d9bfb26
MK
6687 if (!(vma->vm_flags & VM_MAYSHARE))
6688 return false;
6689 if (check_vma_lock && !vma->vm_private_data)
6690 return false;
6691 if (!range_in_vma(vma, start, end))
6692 return false;
6693 return true;
6694}
6695
6696static bool vma_pmd_shareable(struct vm_area_struct *vma)
6697{
6698 unsigned long start = ALIGN(vma->vm_start, PUD_SIZE),
6699 end = ALIGN_DOWN(vma->vm_end, PUD_SIZE);
6700
6701 if (start >= end)
6702 return false;
6703
6704 return __vma_aligned_range_pmd_shareable(vma, start, end, false);
3212b535
SC
6705}
6706
12710fd6
MK
6707static bool vma_addr_pmd_shareable(struct vm_area_struct *vma,
6708 unsigned long addr)
6709{
6710 unsigned long start = addr & PUD_MASK;
6711 unsigned long end = start + PUD_SIZE;
6712
8d9bfb26 6713 return __vma_aligned_range_pmd_shareable(vma, start, end, true);
12710fd6
MK
6714}
6715
c1991e07
PX
6716bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
6717{
12710fd6 6718 return vma_addr_pmd_shareable(vma, addr);
c1991e07
PX
6719}
6720
017b1660
MK
6721/*
6722 * Determine if start,end range within vma could be mapped by shared pmd.
6723 * If yes, adjust start and end to cover range associated with possible
6724 * shared pmd mappings.
6725 */
6726void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
6727 unsigned long *start, unsigned long *end)
6728{
a1ba9da8
LX
6729 unsigned long v_start = ALIGN(vma->vm_start, PUD_SIZE),
6730 v_end = ALIGN_DOWN(vma->vm_end, PUD_SIZE);
017b1660 6731
a1ba9da8 6732 /*
f0953a1b
IM
6733 * vma needs to span at least one aligned PUD size, and the range
6734 * must be at least partially within in.
a1ba9da8
LX
6735 */
6736 if (!(vma->vm_flags & VM_MAYSHARE) || !(v_end > v_start) ||
6737 (*end <= v_start) || (*start >= v_end))
017b1660
MK
6738 return;
6739
75802ca6 6740 /* Extend the range to be PUD aligned for a worst case scenario */
a1ba9da8
LX
6741 if (*start > v_start)
6742 *start = ALIGN_DOWN(*start, PUD_SIZE);
017b1660 6743
a1ba9da8
LX
6744 if (*end < v_end)
6745 *end = ALIGN(*end, PUD_SIZE);
017b1660
MK
6746}
6747
8d9bfb26
MK
6748static bool __vma_shareable_flags_pmd(struct vm_area_struct *vma)
6749{
6750 return vma->vm_flags & (VM_MAYSHARE | VM_SHARED) &&
6751 vma->vm_private_data;
6752}
6753
6754void hugetlb_vma_lock_read(struct vm_area_struct *vma)
6755{
6756 if (__vma_shareable_flags_pmd(vma)) {
6757 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
6758
6759 down_read(&vma_lock->rw_sema);
6760 }
6761}
6762
6763void hugetlb_vma_unlock_read(struct vm_area_struct *vma)
6764{
6765 if (__vma_shareable_flags_pmd(vma)) {
6766 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
6767
6768 up_read(&vma_lock->rw_sema);
6769 }
6770}
6771
6772void hugetlb_vma_lock_write(struct vm_area_struct *vma)
6773{
6774 if (__vma_shareable_flags_pmd(vma)) {
6775 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
6776
6777 down_write(&vma_lock->rw_sema);
6778 }
6779}
6780
6781void hugetlb_vma_unlock_write(struct vm_area_struct *vma)
6782{
6783 if (__vma_shareable_flags_pmd(vma)) {
6784 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
6785
6786 up_write(&vma_lock->rw_sema);
6787 }
6788}
6789
6790int hugetlb_vma_trylock_write(struct vm_area_struct *vma)
6791{
6792 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
6793
6794 if (!__vma_shareable_flags_pmd(vma))
6795 return 1;
6796
6797 return down_write_trylock(&vma_lock->rw_sema);
6798}
6799
6800void hugetlb_vma_assert_locked(struct vm_area_struct *vma)
6801{
6802 if (__vma_shareable_flags_pmd(vma)) {
6803 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
6804
6805 lockdep_assert_held(&vma_lock->rw_sema);
6806 }
6807}
6808
6809void hugetlb_vma_lock_release(struct kref *kref)
6810{
6811 struct hugetlb_vma_lock *vma_lock = container_of(kref,
6812 struct hugetlb_vma_lock, refs);
6813
6814 kfree(vma_lock);
6815}
6816
6817static void hugetlb_vma_lock_free(struct vm_area_struct *vma)
6818{
6819 /*
6820 * Only present in sharable vmas. See comment in
6821 * __unmap_hugepage_range_final about how VM_SHARED could
6822 * be set without VM_MAYSHARE. As a result, we need to
6823 * check if either is set in the free path.
6824 */
6825 if (!vma || !(vma->vm_flags & (VM_MAYSHARE | VM_SHARED)))
6826 return;
6827
6828 if (vma->vm_private_data) {
6829 struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
6830
6831 /*
6832 * vma_lock structure may or not be released, but it
6833 * certainly will no longer be attached to vma so clear
6834 * pointer.
6835 */
6836 vma_lock->vma = NULL;
6837 kref_put(&vma_lock->refs, hugetlb_vma_lock_release);
6838 vma->vm_private_data = NULL;
6839 }
6840}
6841
6842static void hugetlb_vma_lock_alloc(struct vm_area_struct *vma)
6843{
6844 struct hugetlb_vma_lock *vma_lock;
6845
6846 /* Only establish in (flags) sharable vmas */
6847 if (!vma || !(vma->vm_flags & VM_MAYSHARE))
6848 return;
6849
6850 /* Should never get here with non-NULL vm_private_data */
6851 if (vma->vm_private_data)
6852 return;
6853
6854 /* Check size/alignment for pmd sharing possible */
6855 if (!vma_pmd_shareable(vma))
6856 return;
6857
6858 vma_lock = kmalloc(sizeof(*vma_lock), GFP_KERNEL);
6859 if (!vma_lock)
6860 /*
6861 * If we can not allocate structure, then vma can not
6862 * participate in pmd sharing.
6863 */
6864 return;
6865
6866 kref_init(&vma_lock->refs);
6867 init_rwsem(&vma_lock->rw_sema);
6868 vma_lock->vma = vma;
6869 vma->vm_private_data = vma_lock;
6870}
6871
3212b535
SC
6872/*
6873 * Search for a shareable pmd page for hugetlb. In any case calls pmd_alloc()
6874 * and returns the corresponding pte. While this is not necessary for the
6875 * !shared pmd case because we can allocate the pmd later as well, it makes the
3a47c54f
MK
6876 * code much cleaner. pmd allocation is essential for the shared case because
6877 * pud has to be populated inside the same i_mmap_rwsem section - otherwise
6878 * racing tasks could either miss the sharing (see huge_pte_offset) or select a
6879 * bad pmd for sharing.
3212b535 6880 */
aec44e0f
PX
6881pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
6882 unsigned long addr, pud_t *pud)
3212b535 6883{
3212b535
SC
6884 struct address_space *mapping = vma->vm_file->f_mapping;
6885 pgoff_t idx = ((addr - vma->vm_start) >> PAGE_SHIFT) +
6886 vma->vm_pgoff;
6887 struct vm_area_struct *svma;
6888 unsigned long saddr;
6889 pte_t *spte = NULL;
6890 pte_t *pte;
cb900f41 6891 spinlock_t *ptl;
3212b535 6892
3a47c54f 6893 i_mmap_lock_read(mapping);
3212b535
SC
6894 vma_interval_tree_foreach(svma, &mapping->i_mmap, idx, idx) {
6895 if (svma == vma)
6896 continue;
6897
6898 saddr = page_table_shareable(svma, vma, addr, idx);
6899 if (saddr) {
7868a208
PA
6900 spte = huge_pte_offset(svma->vm_mm, saddr,
6901 vma_mmu_pagesize(svma));
3212b535
SC
6902 if (spte) {
6903 get_page(virt_to_page(spte));
6904 break;
6905 }
6906 }
6907 }
6908
6909 if (!spte)
6910 goto out;
6911
8bea8052 6912 ptl = huge_pte_lock(hstate_vma(vma), mm, spte);
dc6c9a35 6913 if (pud_none(*pud)) {
3212b535
SC
6914 pud_populate(mm, pud,
6915 (pmd_t *)((unsigned long)spte & PAGE_MASK));
c17b1f42 6916 mm_inc_nr_pmds(mm);
dc6c9a35 6917 } else {
3212b535 6918 put_page(virt_to_page(spte));
dc6c9a35 6919 }
cb900f41 6920 spin_unlock(ptl);
3212b535
SC
6921out:
6922 pte = (pte_t *)pmd_alloc(mm, pud, addr);
3a47c54f 6923 i_mmap_unlock_read(mapping);
3212b535
SC
6924 return pte;
6925}
6926
6927/*
6928 * unmap huge page backed by shared pte.
6929 *
6930 * Hugetlb pte page is ref counted at the time of mapping. If pte is shared
6931 * indicated by page_count > 1, unmap is achieved by clearing pud and
6932 * decrementing the ref count. If count == 1, the pte page is not shared.
6933 *
3a47c54f 6934 * Called with page table lock held.
3212b535
SC
6935 *
6936 * returns: 1 successfully unmapped a shared pte page
6937 * 0 the underlying pte page is not shared, or it is the last user
6938 */
34ae204f 6939int huge_pmd_unshare(struct mm_struct *mm, struct vm_area_struct *vma,
4ddb4d91 6940 unsigned long addr, pte_t *ptep)
3212b535 6941{
4ddb4d91
MK
6942 pgd_t *pgd = pgd_offset(mm, addr);
6943 p4d_t *p4d = p4d_offset(pgd, addr);
6944 pud_t *pud = pud_offset(p4d, addr);
3212b535 6945
34ae204f 6946 i_mmap_assert_write_locked(vma->vm_file->f_mapping);
40549ba8 6947 hugetlb_vma_assert_locked(vma);
3212b535
SC
6948 BUG_ON(page_count(virt_to_page(ptep)) == 0);
6949 if (page_count(virt_to_page(ptep)) == 1)
6950 return 0;
6951
6952 pud_clear(pud);
6953 put_page(virt_to_page(ptep));
dc6c9a35 6954 mm_dec_nr_pmds(mm);
3212b535
SC
6955 return 1;
6956}
c1991e07 6957
9e5fc74c 6958#else /* !CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
8d9bfb26 6959
40549ba8
MK
6960void hugetlb_vma_lock_read(struct vm_area_struct *vma)
6961{
6962}
6963
6964void hugetlb_vma_unlock_read(struct vm_area_struct *vma)
6965{
6966}
6967
6968void hugetlb_vma_lock_write(struct vm_area_struct *vma)
6969{
6970}
6971
6972void hugetlb_vma_unlock_write(struct vm_area_struct *vma)
6973{
6974}
6975
6976int hugetlb_vma_trylock_write(struct vm_area_struct *vma)
6977{
6978 return 1;
6979}
6980
6981void hugetlb_vma_assert_locked(struct vm_area_struct *vma)
6982{
6983}
6984
8d9bfb26
MK
6985void hugetlb_vma_lock_release(struct kref *kref)
6986{
6987}
6988
6989static void hugetlb_vma_lock_free(struct vm_area_struct *vma)
6990{
6991}
6992
6993static void hugetlb_vma_lock_alloc(struct vm_area_struct *vma)
6994{
6995}
6996
aec44e0f
PX
6997pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
6998 unsigned long addr, pud_t *pud)
9e5fc74c
SC
6999{
7000 return NULL;
7001}
e81f2d22 7002
34ae204f 7003int huge_pmd_unshare(struct mm_struct *mm, struct vm_area_struct *vma,
4ddb4d91 7004 unsigned long addr, pte_t *ptep)
e81f2d22
ZZ
7005{
7006 return 0;
7007}
017b1660
MK
7008
7009void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
7010 unsigned long *start, unsigned long *end)
7011{
7012}
c1991e07
PX
7013
7014bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
7015{
7016 return false;
7017}
3212b535
SC
7018#endif /* CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
7019
9e5fc74c 7020#ifdef CONFIG_ARCH_WANT_GENERAL_HUGETLB
aec44e0f 7021pte_t *huge_pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma,
9e5fc74c
SC
7022 unsigned long addr, unsigned long sz)
7023{
7024 pgd_t *pgd;
c2febafc 7025 p4d_t *p4d;
9e5fc74c
SC
7026 pud_t *pud;
7027 pte_t *pte = NULL;
7028
7029 pgd = pgd_offset(mm, addr);
f4f0a3d8
KS
7030 p4d = p4d_alloc(mm, pgd, addr);
7031 if (!p4d)
7032 return NULL;
c2febafc 7033 pud = pud_alloc(mm, p4d, addr);
9e5fc74c
SC
7034 if (pud) {
7035 if (sz == PUD_SIZE) {
7036 pte = (pte_t *)pud;
7037 } else {
7038 BUG_ON(sz != PMD_SIZE);
c1991e07 7039 if (want_pmd_share(vma, addr) && pud_none(*pud))
aec44e0f 7040 pte = huge_pmd_share(mm, vma, addr, pud);
9e5fc74c
SC
7041 else
7042 pte = (pte_t *)pmd_alloc(mm, pud, addr);
7043 }
7044 }
4e666314 7045 BUG_ON(pte && pte_present(*pte) && !pte_huge(*pte));
9e5fc74c
SC
7046
7047 return pte;
7048}
7049
9b19df29
PA
7050/*
7051 * huge_pte_offset() - Walk the page table to resolve the hugepage
7052 * entry at address @addr
7053 *
8ac0b81a
LX
7054 * Return: Pointer to page table entry (PUD or PMD) for
7055 * address @addr, or NULL if a !p*d_present() entry is encountered and the
9b19df29
PA
7056 * size @sz doesn't match the hugepage size at this level of the page
7057 * table.
7058 */
7868a208
PA
7059pte_t *huge_pte_offset(struct mm_struct *mm,
7060 unsigned long addr, unsigned long sz)
9e5fc74c
SC
7061{
7062 pgd_t *pgd;
c2febafc 7063 p4d_t *p4d;
8ac0b81a
LX
7064 pud_t *pud;
7065 pmd_t *pmd;
9e5fc74c
SC
7066
7067 pgd = pgd_offset(mm, addr);
c2febafc
KS
7068 if (!pgd_present(*pgd))
7069 return NULL;
7070 p4d = p4d_offset(pgd, addr);
7071 if (!p4d_present(*p4d))
7072 return NULL;
9b19df29 7073
c2febafc 7074 pud = pud_offset(p4d, addr);
8ac0b81a
LX
7075 if (sz == PUD_SIZE)
7076 /* must be pud huge, non-present or none */
c2febafc 7077 return (pte_t *)pud;
8ac0b81a 7078 if (!pud_present(*pud))
9b19df29 7079 return NULL;
8ac0b81a 7080 /* must have a valid entry and size to go further */
9b19df29 7081
8ac0b81a
LX
7082 pmd = pmd_offset(pud, addr);
7083 /* must be pmd huge, non-present or none */
7084 return (pte_t *)pmd;
9e5fc74c
SC
7085}
7086
e95a9851
MK
7087/*
7088 * Return a mask that can be used to update an address to the last huge
7089 * page in a page table page mapping size. Used to skip non-present
7090 * page table entries when linearly scanning address ranges. Architectures
7091 * with unique huge page to page table relationships can define their own
7092 * version of this routine.
7093 */
7094unsigned long hugetlb_mask_last_page(struct hstate *h)
7095{
7096 unsigned long hp_size = huge_page_size(h);
7097
7098 if (hp_size == PUD_SIZE)
7099 return P4D_SIZE - PUD_SIZE;
7100 else if (hp_size == PMD_SIZE)
7101 return PUD_SIZE - PMD_SIZE;
7102 else
7103 return 0UL;
7104}
7105
7106#else
7107
7108/* See description above. Architectures can provide their own version. */
7109__weak unsigned long hugetlb_mask_last_page(struct hstate *h)
7110{
4ddb4d91
MK
7111#ifdef CONFIG_ARCH_WANT_HUGE_PMD_SHARE
7112 if (huge_page_size(h) == PMD_SIZE)
7113 return PUD_SIZE - PMD_SIZE;
7114#endif
e95a9851
MK
7115 return 0UL;
7116}
7117
61f77eda
NH
7118#endif /* CONFIG_ARCH_WANT_GENERAL_HUGETLB */
7119
7120/*
7121 * These functions are overwritable if your architecture needs its own
7122 * behavior.
7123 */
7124struct page * __weak
7125follow_huge_addr(struct mm_struct *mm, unsigned long address,
7126 int write)
7127{
7128 return ERR_PTR(-EINVAL);
7129}
7130
4dc71451
AK
7131struct page * __weak
7132follow_huge_pd(struct vm_area_struct *vma,
7133 unsigned long address, hugepd_t hpd, int flags, int pdshift)
7134{
7135 WARN(1, "hugepd follow called with no support for hugepage directory format\n");
7136 return NULL;
7137}
7138
61f77eda 7139struct page * __weak
9e5fc74c 7140follow_huge_pmd(struct mm_struct *mm, unsigned long address,
e66f17ff 7141 pmd_t *pmd, int flags)
9e5fc74c 7142{
e66f17ff
NH
7143 struct page *page = NULL;
7144 spinlock_t *ptl;
c9d398fa 7145 pte_t pte;
3faa52c0 7146
8909691b
DH
7147 /*
7148 * FOLL_PIN is not supported for follow_page(). Ordinary GUP goes via
7149 * follow_hugetlb_page().
7150 */
7151 if (WARN_ON_ONCE(flags & FOLL_PIN))
3faa52c0
JH
7152 return NULL;
7153
e66f17ff
NH
7154retry:
7155 ptl = pmd_lockptr(mm, pmd);
7156 spin_lock(ptl);
7157 /*
7158 * make sure that the address range covered by this pmd is not
7159 * unmapped from other threads.
7160 */
7161 if (!pmd_huge(*pmd))
7162 goto out;
c9d398fa
NH
7163 pte = huge_ptep_get((pte_t *)pmd);
7164 if (pte_present(pte)) {
97534127 7165 page = pmd_page(*pmd) + ((address & ~PMD_MASK) >> PAGE_SHIFT);
3faa52c0
JH
7166 /*
7167 * try_grab_page() should always succeed here, because: a) we
7168 * hold the pmd (ptl) lock, and b) we've just checked that the
7169 * huge pmd (head) page is present in the page tables. The ptl
7170 * prevents the head page and tail pages from being rearranged
7171 * in any way. So this page must be available at this point,
7172 * unless the page refcount overflowed:
7173 */
7174 if (WARN_ON_ONCE(!try_grab_page(page, flags))) {
7175 page = NULL;
7176 goto out;
7177 }
e66f17ff 7178 } else {
c9d398fa 7179 if (is_hugetlb_entry_migration(pte)) {
e66f17ff 7180 spin_unlock(ptl);
ad1ac596 7181 __migration_entry_wait_huge((pte_t *)pmd, ptl);
e66f17ff
NH
7182 goto retry;
7183 }
7184 /*
7185 * hwpoisoned entry is treated as no_page_table in
7186 * follow_page_mask().
7187 */
7188 }
7189out:
7190 spin_unlock(ptl);
9e5fc74c
SC
7191 return page;
7192}
7193
61f77eda 7194struct page * __weak
9e5fc74c 7195follow_huge_pud(struct mm_struct *mm, unsigned long address,
e66f17ff 7196 pud_t *pud, int flags)
9e5fc74c 7197{
3a194f3f
NH
7198 struct page *page = NULL;
7199 spinlock_t *ptl;
7200 pte_t pte;
7201
7202 if (WARN_ON_ONCE(flags & FOLL_PIN))
e66f17ff 7203 return NULL;
9e5fc74c 7204
3a194f3f
NH
7205retry:
7206 ptl = huge_pte_lock(hstate_sizelog(PUD_SHIFT), mm, (pte_t *)pud);
7207 if (!pud_huge(*pud))
7208 goto out;
7209 pte = huge_ptep_get((pte_t *)pud);
7210 if (pte_present(pte)) {
7211 page = pud_page(*pud) + ((address & ~PUD_MASK) >> PAGE_SHIFT);
7212 if (WARN_ON_ONCE(!try_grab_page(page, flags))) {
7213 page = NULL;
7214 goto out;
7215 }
7216 } else {
7217 if (is_hugetlb_entry_migration(pte)) {
7218 spin_unlock(ptl);
7219 __migration_entry_wait(mm, (pte_t *)pud, ptl);
7220 goto retry;
7221 }
7222 /*
7223 * hwpoisoned entry is treated as no_page_table in
7224 * follow_page_mask().
7225 */
7226 }
7227out:
7228 spin_unlock(ptl);
7229 return page;
9e5fc74c
SC
7230}
7231
faaa5b62
AK
7232struct page * __weak
7233follow_huge_pgd(struct mm_struct *mm, unsigned long address, pgd_t *pgd, int flags)
7234{
3faa52c0 7235 if (flags & (FOLL_GET | FOLL_PIN))
faaa5b62
AK
7236 return NULL;
7237
7238 return pte_page(*(pte_t *)pgd) + ((address & ~PGDIR_MASK) >> PAGE_SHIFT);
7239}
7240
7ce82f4c 7241int isolate_hugetlb(struct page *page, struct list_head *list)
31caf665 7242{
7ce82f4c 7243 int ret = 0;
bcc54222 7244
db71ef79 7245 spin_lock_irq(&hugetlb_lock);
8f251a3d
MK
7246 if (!PageHeadHuge(page) ||
7247 !HPageMigratable(page) ||
0eb2df2b 7248 !get_page_unless_zero(page)) {
7ce82f4c 7249 ret = -EBUSY;
bcc54222
NH
7250 goto unlock;
7251 }
8f251a3d 7252 ClearHPageMigratable(page);
31caf665 7253 list_move_tail(&page->lru, list);
bcc54222 7254unlock:
db71ef79 7255 spin_unlock_irq(&hugetlb_lock);
bcc54222 7256 return ret;
31caf665
NH
7257}
7258
25182f05
NH
7259int get_hwpoison_huge_page(struct page *page, bool *hugetlb)
7260{
7261 int ret = 0;
7262
7263 *hugetlb = false;
7264 spin_lock_irq(&hugetlb_lock);
7265 if (PageHeadHuge(page)) {
7266 *hugetlb = true;
b283d983
NH
7267 if (HPageFreed(page))
7268 ret = 0;
7269 else if (HPageMigratable(page))
25182f05 7270 ret = get_page_unless_zero(page);
0ed950d1
NH
7271 else
7272 ret = -EBUSY;
25182f05
NH
7273 }
7274 spin_unlock_irq(&hugetlb_lock);
7275 return ret;
7276}
7277
405ce051
NH
7278int get_huge_page_for_hwpoison(unsigned long pfn, int flags)
7279{
7280 int ret;
7281
7282 spin_lock_irq(&hugetlb_lock);
7283 ret = __get_huge_page_for_hwpoison(pfn, flags);
7284 spin_unlock_irq(&hugetlb_lock);
7285 return ret;
7286}
7287
31caf665
NH
7288void putback_active_hugepage(struct page *page)
7289{
db71ef79 7290 spin_lock_irq(&hugetlb_lock);
8f251a3d 7291 SetHPageMigratable(page);
31caf665 7292 list_move_tail(&page->lru, &(page_hstate(page))->hugepage_activelist);
db71ef79 7293 spin_unlock_irq(&hugetlb_lock);
31caf665
NH
7294 put_page(page);
7295}
ab5ac90a
MH
7296
7297void move_hugetlb_state(struct page *oldpage, struct page *newpage, int reason)
7298{
7299 struct hstate *h = page_hstate(oldpage);
7300
7301 hugetlb_cgroup_migrate(oldpage, newpage);
7302 set_page_owner_migrate_reason(newpage, reason);
7303
7304 /*
7305 * transfer temporary state of the new huge page. This is
7306 * reverse to other transitions because the newpage is going to
7307 * be final while the old one will be freed so it takes over
7308 * the temporary status.
7309 *
7310 * Also note that we have to transfer the per-node surplus state
7311 * here as well otherwise the global surplus count will not match
7312 * the per-node's.
7313 */
9157c311 7314 if (HPageTemporary(newpage)) {
ab5ac90a
MH
7315 int old_nid = page_to_nid(oldpage);
7316 int new_nid = page_to_nid(newpage);
7317
9157c311
MK
7318 SetHPageTemporary(oldpage);
7319 ClearHPageTemporary(newpage);
ab5ac90a 7320
5af1ab1d
ML
7321 /*
7322 * There is no need to transfer the per-node surplus state
7323 * when we do not cross the node.
7324 */
7325 if (new_nid == old_nid)
7326 return;
db71ef79 7327 spin_lock_irq(&hugetlb_lock);
ab5ac90a
MH
7328 if (h->surplus_huge_pages_node[old_nid]) {
7329 h->surplus_huge_pages_node[old_nid]--;
7330 h->surplus_huge_pages_node[new_nid]++;
7331 }
db71ef79 7332 spin_unlock_irq(&hugetlb_lock);
ab5ac90a
MH
7333 }
7334}
cf11e85f 7335
6dfeaff9
PX
7336/*
7337 * This function will unconditionally remove all the shared pmd pgtable entries
7338 * within the specific vma for a hugetlbfs memory range.
7339 */
7340void hugetlb_unshare_all_pmds(struct vm_area_struct *vma)
7341{
7342 struct hstate *h = hstate_vma(vma);
7343 unsigned long sz = huge_page_size(h);
7344 struct mm_struct *mm = vma->vm_mm;
7345 struct mmu_notifier_range range;
7346 unsigned long address, start, end;
7347 spinlock_t *ptl;
7348 pte_t *ptep;
7349
7350 if (!(vma->vm_flags & VM_MAYSHARE))
7351 return;
7352
7353 start = ALIGN(vma->vm_start, PUD_SIZE);
7354 end = ALIGN_DOWN(vma->vm_end, PUD_SIZE);
7355
7356 if (start >= end)
7357 return;
7358
9c8bbfac 7359 flush_cache_range(vma, start, end);
6dfeaff9
PX
7360 /*
7361 * No need to call adjust_range_if_pmd_sharing_possible(), because
7362 * we have already done the PUD_SIZE alignment.
7363 */
7364 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
7365 start, end);
7366 mmu_notifier_invalidate_range_start(&range);
40549ba8 7367 hugetlb_vma_lock_write(vma);
6dfeaff9
PX
7368 i_mmap_lock_write(vma->vm_file->f_mapping);
7369 for (address = start; address < end; address += PUD_SIZE) {
6dfeaff9
PX
7370 ptep = huge_pte_offset(mm, address, sz);
7371 if (!ptep)
7372 continue;
7373 ptl = huge_pte_lock(h, mm, ptep);
4ddb4d91 7374 huge_pmd_unshare(mm, vma, address, ptep);
6dfeaff9
PX
7375 spin_unlock(ptl);
7376 }
7377 flush_hugetlb_tlb_range(vma, start, end);
7378 i_mmap_unlock_write(vma->vm_file->f_mapping);
40549ba8 7379 hugetlb_vma_unlock_write(vma);
6dfeaff9
PX
7380 /*
7381 * No need to call mmu_notifier_invalidate_range(), see
ee65728e 7382 * Documentation/mm/mmu_notifier.rst.
6dfeaff9
PX
7383 */
7384 mmu_notifier_invalidate_range_end(&range);
7385}
7386
cf11e85f 7387#ifdef CONFIG_CMA
cf11e85f
RG
7388static bool cma_reserve_called __initdata;
7389
7390static int __init cmdline_parse_hugetlb_cma(char *p)
7391{
38e719ab
BW
7392 int nid, count = 0;
7393 unsigned long tmp;
7394 char *s = p;
7395
7396 while (*s) {
7397 if (sscanf(s, "%lu%n", &tmp, &count) != 1)
7398 break;
7399
7400 if (s[count] == ':') {
f9317f77 7401 if (tmp >= MAX_NUMNODES)
38e719ab 7402 break;
f9317f77 7403 nid = array_index_nospec(tmp, MAX_NUMNODES);
38e719ab
BW
7404
7405 s += count + 1;
7406 tmp = memparse(s, &s);
7407 hugetlb_cma_size_in_node[nid] = tmp;
7408 hugetlb_cma_size += tmp;
7409
7410 /*
7411 * Skip the separator if have one, otherwise
7412 * break the parsing.
7413 */
7414 if (*s == ',')
7415 s++;
7416 else
7417 break;
7418 } else {
7419 hugetlb_cma_size = memparse(p, &p);
7420 break;
7421 }
7422 }
7423
cf11e85f
RG
7424 return 0;
7425}
7426
7427early_param("hugetlb_cma", cmdline_parse_hugetlb_cma);
7428
7429void __init hugetlb_cma_reserve(int order)
7430{
7431 unsigned long size, reserved, per_node;
38e719ab 7432 bool node_specific_cma_alloc = false;
cf11e85f
RG
7433 int nid;
7434
7435 cma_reserve_called = true;
7436
38e719ab
BW
7437 if (!hugetlb_cma_size)
7438 return;
7439
7440 for (nid = 0; nid < MAX_NUMNODES; nid++) {
7441 if (hugetlb_cma_size_in_node[nid] == 0)
7442 continue;
7443
30a51400 7444 if (!node_online(nid)) {
38e719ab
BW
7445 pr_warn("hugetlb_cma: invalid node %d specified\n", nid);
7446 hugetlb_cma_size -= hugetlb_cma_size_in_node[nid];
7447 hugetlb_cma_size_in_node[nid] = 0;
7448 continue;
7449 }
7450
7451 if (hugetlb_cma_size_in_node[nid] < (PAGE_SIZE << order)) {
7452 pr_warn("hugetlb_cma: cma area of node %d should be at least %lu MiB\n",
7453 nid, (PAGE_SIZE << order) / SZ_1M);
7454 hugetlb_cma_size -= hugetlb_cma_size_in_node[nid];
7455 hugetlb_cma_size_in_node[nid] = 0;
7456 } else {
7457 node_specific_cma_alloc = true;
7458 }
7459 }
7460
7461 /* Validate the CMA size again in case some invalid nodes specified. */
cf11e85f
RG
7462 if (!hugetlb_cma_size)
7463 return;
7464
7465 if (hugetlb_cma_size < (PAGE_SIZE << order)) {
7466 pr_warn("hugetlb_cma: cma area should be at least %lu MiB\n",
7467 (PAGE_SIZE << order) / SZ_1M);
a01f4390 7468 hugetlb_cma_size = 0;
cf11e85f
RG
7469 return;
7470 }
7471
38e719ab
BW
7472 if (!node_specific_cma_alloc) {
7473 /*
7474 * If 3 GB area is requested on a machine with 4 numa nodes,
7475 * let's allocate 1 GB on first three nodes and ignore the last one.
7476 */
7477 per_node = DIV_ROUND_UP(hugetlb_cma_size, nr_online_nodes);
7478 pr_info("hugetlb_cma: reserve %lu MiB, up to %lu MiB per node\n",
7479 hugetlb_cma_size / SZ_1M, per_node / SZ_1M);
7480 }
cf11e85f
RG
7481
7482 reserved = 0;
30a51400 7483 for_each_online_node(nid) {
cf11e85f 7484 int res;
2281f797 7485 char name[CMA_MAX_NAME];
cf11e85f 7486
38e719ab
BW
7487 if (node_specific_cma_alloc) {
7488 if (hugetlb_cma_size_in_node[nid] == 0)
7489 continue;
7490
7491 size = hugetlb_cma_size_in_node[nid];
7492 } else {
7493 size = min(per_node, hugetlb_cma_size - reserved);
7494 }
7495
cf11e85f
RG
7496 size = round_up(size, PAGE_SIZE << order);
7497
2281f797 7498 snprintf(name, sizeof(name), "hugetlb%d", nid);
a01f4390
MK
7499 /*
7500 * Note that 'order per bit' is based on smallest size that
7501 * may be returned to CMA allocator in the case of
7502 * huge page demotion.
7503 */
7504 res = cma_declare_contiguous_nid(0, size, 0,
7505 PAGE_SIZE << HUGETLB_PAGE_ORDER,
29d0f41d 7506 0, false, name,
cf11e85f
RG
7507 &hugetlb_cma[nid], nid);
7508 if (res) {
7509 pr_warn("hugetlb_cma: reservation failed: err %d, node %d",
7510 res, nid);
7511 continue;
7512 }
7513
7514 reserved += size;
7515 pr_info("hugetlb_cma: reserved %lu MiB on node %d\n",
7516 size / SZ_1M, nid);
7517
7518 if (reserved >= hugetlb_cma_size)
7519 break;
7520 }
a01f4390
MK
7521
7522 if (!reserved)
7523 /*
7524 * hugetlb_cma_size is used to determine if allocations from
7525 * cma are possible. Set to zero if no cma regions are set up.
7526 */
7527 hugetlb_cma_size = 0;
cf11e85f
RG
7528}
7529
263b8998 7530static void __init hugetlb_cma_check(void)
cf11e85f
RG
7531{
7532 if (!hugetlb_cma_size || cma_reserve_called)
7533 return;
7534
7535 pr_warn("hugetlb_cma: the option isn't supported by current arch\n");
7536}
7537
7538#endif /* CONFIG_CMA */