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