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