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