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