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