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