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