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