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