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