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