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