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