xref: /linux/mm/hugetlb.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
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 		if (!adjust_surplus)
1996 			h->max_huge_pages--;
1997 		spin_unlock_irq(&hugetlb_lock);
1998 
1999 		/*
2000 		 * Normally update_and_free_hugtlb_folio will allocate required vmemmmap
2001 		 * before freeing the page.  update_and_free_hugtlb_folio will fail to
2002 		 * free the page if it can not allocate required vmemmap.  We
2003 		 * need to adjust max_huge_pages if the page is not freed.
2004 		 * Attempt to allocate vmemmmap here so that we can take
2005 		 * appropriate action on failure.
2006 		 *
2007 		 * The folio_test_hugetlb check here is because
2008 		 * remove_hugetlb_folio will clear hugetlb folio flag for
2009 		 * non-vmemmap optimized hugetlb folios.
2010 		 */
2011 		if (folio_test_hugetlb(folio)) {
2012 			rc = hugetlb_vmemmap_restore_folio(h, folio);
2013 			if (rc) {
2014 				spin_lock_irq(&hugetlb_lock);
2015 				add_hugetlb_folio(h, folio, adjust_surplus);
2016 				if (!adjust_surplus)
2017 					h->max_huge_pages++;
2018 				goto out;
2019 			}
2020 		} else {
2021 			rc = 0;
2022 		}
2023 
2024 		update_and_free_hugetlb_folio(h, folio, false);
2025 		return rc;
2026 	}
2027 out:
2028 	spin_unlock_irq(&hugetlb_lock);
2029 	return rc;
2030 }
2031 
2032 /*
2033  * Dissolve free hugepages in a given pfn range. Used by memory hotplug to
2034  * make specified memory blocks removable from the system.
2035  * Note that this will dissolve a free gigantic hugepage completely, if any
2036  * part of it lies within the given range.
2037  * Also note that if dissolve_free_hugetlb_folio() returns with an error, all
2038  * free hugetlb folios that were dissolved before that error are lost.
2039  */
2040 int dissolve_free_hugetlb_folios(unsigned long start_pfn, unsigned long end_pfn)
2041 {
2042 	unsigned long pfn;
2043 	struct folio *folio;
2044 	int rc = 0;
2045 	unsigned int order;
2046 	struct hstate *h;
2047 
2048 	if (!hugepages_supported())
2049 		return rc;
2050 
2051 	order = huge_page_order(&default_hstate);
2052 	for_each_hstate(h)
2053 		order = min(order, huge_page_order(h));
2054 
2055 	for (pfn = start_pfn; pfn < end_pfn; pfn += 1 << order) {
2056 		folio = pfn_folio(pfn);
2057 		rc = dissolve_free_hugetlb_folio(folio);
2058 		if (rc)
2059 			break;
2060 	}
2061 
2062 	return rc;
2063 }
2064 
2065 /*
2066  * Allocates a fresh surplus page from the page allocator.
2067  */
2068 static struct folio *alloc_surplus_hugetlb_folio(struct hstate *h,
2069 				gfp_t gfp_mask,	int nid, nodemask_t *nmask)
2070 {
2071 	struct folio *folio = NULL;
2072 
2073 	if (hstate_is_gigantic_no_runtime(h))
2074 		return NULL;
2075 
2076 	spin_lock_irq(&hugetlb_lock);
2077 	if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages)
2078 		goto out_unlock;
2079 	spin_unlock_irq(&hugetlb_lock);
2080 
2081 	folio = alloc_fresh_hugetlb_folio(h, gfp_mask, nid, nmask);
2082 	if (!folio)
2083 		return NULL;
2084 
2085 	spin_lock_irq(&hugetlb_lock);
2086 	/*
2087 	 * nr_huge_pages needs to be adjusted within the same lock cycle
2088 	 * as surplus_pages, otherwise it might confuse
2089 	 * persistent_huge_pages() momentarily.
2090 	 */
2091 	account_new_hugetlb_folio(h, folio);
2092 
2093 	/*
2094 	 * We could have raced with the pool size change.
2095 	 * Double check that and simply deallocate the new page
2096 	 * if we would end up overcommiting the surpluses. Abuse
2097 	 * temporary page to workaround the nasty free_huge_folio
2098 	 * codeflow
2099 	 */
2100 	if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) {
2101 		folio_set_hugetlb_temporary(folio);
2102 		spin_unlock_irq(&hugetlb_lock);
2103 		free_huge_folio(folio);
2104 		return NULL;
2105 	}
2106 
2107 	h->surplus_huge_pages++;
2108 	h->surplus_huge_pages_node[folio_nid(folio)]++;
2109 
2110 out_unlock:
2111 	spin_unlock_irq(&hugetlb_lock);
2112 
2113 	return folio;
2114 }
2115 
2116 static struct folio *alloc_migrate_hugetlb_folio(struct hstate *h, gfp_t gfp_mask,
2117 				     int nid, nodemask_t *nmask)
2118 {
2119 	struct folio *folio;
2120 
2121 	if (hstate_is_gigantic(h))
2122 		return NULL;
2123 
2124 	folio = alloc_fresh_hugetlb_folio(h, gfp_mask, nid, nmask);
2125 	if (!folio)
2126 		return NULL;
2127 
2128 	spin_lock_irq(&hugetlb_lock);
2129 	account_new_hugetlb_folio(h, folio);
2130 	spin_unlock_irq(&hugetlb_lock);
2131 
2132 	/* fresh huge pages are frozen */
2133 	folio_ref_unfreeze(folio, 1);
2134 	/*
2135 	 * We do not account these pages as surplus because they are only
2136 	 * temporary and will be released properly on the last reference
2137 	 */
2138 	folio_set_hugetlb_temporary(folio);
2139 
2140 	return folio;
2141 }
2142 
2143 static
2144 struct folio *alloc_buddy_hugetlb_folio(struct hstate *h,
2145 		gfp_t gfp_mask, struct mempolicy_interpreted *mpoli)
2146 {
2147 	struct folio *folio = NULL;
2148 	nodemask_t *nodemask = mpoli->nodemask;
2149 
2150 	if (mpoli->mode == MPOL_PREFERRED_MANY) {
2151 		gfp_t gfp = gfp_mask & ~(__GFP_DIRECT_RECLAIM | __GFP_NOFAIL);
2152 
2153 		folio = alloc_surplus_hugetlb_folio(h, gfp, mpoli->nid,
2154 						    nodemask);
2155 
2156 		/* Fallback to all nodes if page==NULL */
2157 		nodemask = NULL;
2158 	}
2159 
2160 	if (!folio) {
2161 		folio = alloc_surplus_hugetlb_folio(h, gfp_mask, mpoli->nid,
2162 						    nodemask);
2163 	}
2164 
2165 	return folio;
2166 }
2167 
2168 struct folio *alloc_hugetlb_folio_reserve(struct hstate *h, int preferred_nid,
2169 		nodemask_t *nmask, gfp_t gfp_mask)
2170 {
2171 	struct folio *folio;
2172 
2173 	spin_lock_irq(&hugetlb_lock);
2174 	if (!h->resv_huge_pages) {
2175 		spin_unlock_irq(&hugetlb_lock);
2176 		return NULL;
2177 	}
2178 
2179 	folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask, preferred_nid,
2180 					       nmask);
2181 	if (folio)
2182 		h->resv_huge_pages--;
2183 
2184 	spin_unlock_irq(&hugetlb_lock);
2185 	return folio;
2186 }
2187 
2188 /* folio migration callback function */
2189 struct folio *alloc_hugetlb_folio_nodemask(struct hstate *h, int preferred_nid,
2190 		nodemask_t *nmask, gfp_t gfp_mask, bool allow_alloc_fallback)
2191 {
2192 	spin_lock_irq(&hugetlb_lock);
2193 	if (available_huge_pages(h)) {
2194 		struct folio *folio;
2195 
2196 		folio = dequeue_hugetlb_folio_nodemask(h, gfp_mask,
2197 						preferred_nid, nmask);
2198 		if (folio) {
2199 			spin_unlock_irq(&hugetlb_lock);
2200 			return folio;
2201 		}
2202 	}
2203 	spin_unlock_irq(&hugetlb_lock);
2204 
2205 	/* We cannot fallback to other nodes, as we could break the per-node pool. */
2206 	if (!allow_alloc_fallback)
2207 		gfp_mask |= __GFP_THISNODE;
2208 
2209 	return alloc_migrate_hugetlb_folio(h, gfp_mask, preferred_nid, nmask);
2210 }
2211 
2212 static nodemask_t *policy_mbind_nodemask(gfp_t gfp)
2213 {
2214 #ifdef CONFIG_NUMA
2215 	struct mempolicy *mpol = get_task_policy(current);
2216 
2217 	/*
2218 	 * Only enforce MPOL_BIND policy which overlaps with cpuset policy
2219 	 * (from policy_nodemask) specifically for hugetlb case
2220 	 */
2221 	if (mpol->mode == MPOL_BIND &&
2222 		(apply_policy_zone(mpol, gfp_zone(gfp)) &&
2223 		 cpuset_nodemask_valid_mems_allowed(&mpol->nodes)))
2224 		return &mpol->nodes;
2225 #endif
2226 	return NULL;
2227 }
2228 
2229 /*
2230  * Increase the hugetlb pool such that it can accommodate a reservation
2231  * of size 'delta'.
2232  */
2233 static int gather_surplus_pages(struct hstate *h, long delta)
2234 	__must_hold(&hugetlb_lock)
2235 {
2236 	LIST_HEAD(surplus_list);
2237 	struct folio *folio, *tmp;
2238 	int ret;
2239 	long i;
2240 	long needed, allocated;
2241 	bool alloc_ok = true;
2242 	nodemask_t *mbind_nodemask, alloc_nodemask;
2243 
2244 	mbind_nodemask = policy_mbind_nodemask(htlb_alloc_mask(h));
2245 	if (mbind_nodemask)
2246 		nodes_and(alloc_nodemask, *mbind_nodemask, cpuset_current_mems_allowed);
2247 	else
2248 		alloc_nodemask = cpuset_current_mems_allowed;
2249 
2250 	lockdep_assert_held(&hugetlb_lock);
2251 	needed = (h->resv_huge_pages + delta) - h->free_huge_pages;
2252 	if (needed <= 0) {
2253 		h->resv_huge_pages += delta;
2254 		return 0;
2255 	}
2256 
2257 	allocated = 0;
2258 
2259 	ret = -ENOMEM;
2260 retry:
2261 	spin_unlock_irq(&hugetlb_lock);
2262 	for (i = 0; i < needed; i++) {
2263 		folio = NULL;
2264 
2265 		/*
2266 		 * It is okay to use NUMA_NO_NODE because we use numa_mem_id()
2267 		 * down the road to pick the current node if that is the case.
2268 		 */
2269 		folio = alloc_surplus_hugetlb_folio(h, htlb_alloc_mask(h),
2270 						    NUMA_NO_NODE, &alloc_nodemask);
2271 		if (!folio) {
2272 			alloc_ok = false;
2273 			break;
2274 		}
2275 		list_add(&folio->lru, &surplus_list);
2276 		cond_resched();
2277 	}
2278 	allocated += i;
2279 
2280 	/*
2281 	 * After retaking hugetlb_lock, we need to recalculate 'needed'
2282 	 * because either resv_huge_pages or free_huge_pages may have changed.
2283 	 */
2284 	spin_lock_irq(&hugetlb_lock);
2285 	needed = (h->resv_huge_pages + delta) -
2286 			(h->free_huge_pages + allocated);
2287 	if (needed > 0) {
2288 		if (alloc_ok)
2289 			goto retry;
2290 		/*
2291 		 * We were not able to allocate enough pages to
2292 		 * satisfy the entire reservation so we free what
2293 		 * we've allocated so far.
2294 		 */
2295 		goto free;
2296 	}
2297 	/*
2298 	 * The surplus_list now contains _at_least_ the number of extra pages
2299 	 * needed to accommodate the reservation.  Add the appropriate number
2300 	 * of pages to the hugetlb pool and free the extras back to the buddy
2301 	 * allocator.  Commit the entire reservation here to prevent another
2302 	 * process from stealing the pages as they are added to the pool but
2303 	 * before they are reserved.
2304 	 */
2305 	needed += allocated;
2306 	h->resv_huge_pages += delta;
2307 	ret = 0;
2308 
2309 	/* Free the needed pages to the hugetlb pool */
2310 	list_for_each_entry_safe(folio, tmp, &surplus_list, lru) {
2311 		if ((--needed) < 0)
2312 			break;
2313 		/* Add the page to the hugetlb allocator */
2314 		enqueue_hugetlb_folio(h, folio);
2315 	}
2316 free:
2317 	spin_unlock_irq(&hugetlb_lock);
2318 
2319 	/*
2320 	 * Free unnecessary surplus pages to the buddy allocator.
2321 	 * Pages have no ref count, call free_huge_folio directly.
2322 	 */
2323 	list_for_each_entry_safe(folio, tmp, &surplus_list, lru)
2324 		free_huge_folio(folio);
2325 	spin_lock_irq(&hugetlb_lock);
2326 
2327 	return ret;
2328 }
2329 
2330 /*
2331  * This routine has two main purposes:
2332  * 1) Decrement the reservation count (resv_huge_pages) by the value passed
2333  *    in unused_resv_pages.  This corresponds to the prior adjustments made
2334  *    to the associated reservation map.
2335  * 2) Free any unused surplus pages that may have been allocated to satisfy
2336  *    the reservation.  As many as unused_resv_pages may be freed.
2337  */
2338 static void return_unused_surplus_pages(struct hstate *h,
2339 					unsigned long unused_resv_pages)
2340 {
2341 	unsigned long nr_pages;
2342 	LIST_HEAD(page_list);
2343 
2344 	lockdep_assert_held(&hugetlb_lock);
2345 	/* Uncommit the reservation */
2346 	h->resv_huge_pages -= unused_resv_pages;
2347 
2348 	if (hstate_is_gigantic_no_runtime(h))
2349 		goto out;
2350 
2351 	/*
2352 	 * Part (or even all) of the reservation could have been backed
2353 	 * by pre-allocated pages. Only free surplus pages.
2354 	 */
2355 	nr_pages = min(unused_resv_pages, h->surplus_huge_pages);
2356 
2357 	/*
2358 	 * We want to release as many surplus pages as possible, spread
2359 	 * evenly across all nodes with memory. Iterate across these nodes
2360 	 * until we can no longer free unreserved surplus pages. This occurs
2361 	 * when the nodes with surplus pages have no free pages.
2362 	 * remove_pool_hugetlb_folio() will balance the freed pages across the
2363 	 * on-line nodes with memory and will handle the hstate accounting.
2364 	 */
2365 	while (nr_pages--) {
2366 		struct folio *folio;
2367 
2368 		folio = remove_pool_hugetlb_folio(h, &node_states[N_MEMORY], 1);
2369 		if (!folio)
2370 			goto out;
2371 
2372 		list_add(&folio->lru, &page_list);
2373 	}
2374 
2375 out:
2376 	spin_unlock_irq(&hugetlb_lock);
2377 	update_and_free_pages_bulk(h, &page_list);
2378 	spin_lock_irq(&hugetlb_lock);
2379 }
2380 
2381 
2382 /*
2383  * vma_needs_reservation, vma_commit_reservation and vma_end_reservation
2384  * are used by the huge page allocation routines to manage reservations.
2385  *
2386  * vma_needs_reservation is called to determine if the huge page at addr
2387  * within the vma has an associated reservation.  If a reservation is
2388  * needed, the value 1 is returned.  The caller is then responsible for
2389  * managing the global reservation and subpool usage counts.  After
2390  * the huge page has been allocated, vma_commit_reservation is called
2391  * to add the page to the reservation map.  If the page allocation fails,
2392  * the reservation must be ended instead of committed.  vma_end_reservation
2393  * is called in such cases.
2394  *
2395  * In the normal case, vma_commit_reservation returns the same value
2396  * as the preceding vma_needs_reservation call.  The only time this
2397  * is not the case is if a reserve map was changed between calls.  It
2398  * is the responsibility of the caller to notice the difference and
2399  * take appropriate action.
2400  *
2401  * vma_add_reservation is used in error paths where a reservation must
2402  * be restored when a newly allocated huge page must be freed.  It is
2403  * to be called after calling vma_needs_reservation to determine if a
2404  * reservation exists.
2405  *
2406  * vma_del_reservation is used in error paths where an entry in the reserve
2407  * map was created during huge page allocation and must be removed.  It is to
2408  * be called after calling vma_needs_reservation to determine if a reservation
2409  * exists.
2410  */
2411 enum vma_resv_mode {
2412 	VMA_NEEDS_RESV,
2413 	VMA_COMMIT_RESV,
2414 	VMA_END_RESV,
2415 	VMA_ADD_RESV,
2416 	VMA_DEL_RESV,
2417 };
2418 static long __vma_reservation_common(struct hstate *h,
2419 				struct vm_area_struct *vma, unsigned long addr,
2420 				enum vma_resv_mode mode)
2421 {
2422 	struct resv_map *resv;
2423 	pgoff_t idx;
2424 	long ret;
2425 	long dummy_out_regions_needed;
2426 
2427 	resv = vma_resv_map(vma);
2428 	if (!resv)
2429 		return 1;
2430 
2431 	idx = vma_hugecache_offset(h, vma, addr);
2432 	switch (mode) {
2433 	case VMA_NEEDS_RESV:
2434 		ret = region_chg(resv, idx, idx + 1, &dummy_out_regions_needed);
2435 		/* We assume that vma_reservation_* routines always operate on
2436 		 * 1 page, and that adding to resv map a 1 page entry can only
2437 		 * ever require 1 region.
2438 		 */
2439 		VM_BUG_ON(dummy_out_regions_needed != 1);
2440 		break;
2441 	case VMA_COMMIT_RESV:
2442 		ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2443 		/* region_add calls of range 1 should never fail. */
2444 		VM_BUG_ON(ret < 0);
2445 		break;
2446 	case VMA_END_RESV:
2447 		region_abort(resv, idx, idx + 1, 1);
2448 		ret = 0;
2449 		break;
2450 	case VMA_ADD_RESV:
2451 		if (vma->vm_flags & VM_MAYSHARE) {
2452 			ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2453 			/* region_add calls of range 1 should never fail. */
2454 			VM_BUG_ON(ret < 0);
2455 		} else {
2456 			region_abort(resv, idx, idx + 1, 1);
2457 			ret = region_del(resv, idx, idx + 1);
2458 		}
2459 		break;
2460 	case VMA_DEL_RESV:
2461 		if (vma->vm_flags & VM_MAYSHARE) {
2462 			region_abort(resv, idx, idx + 1, 1);
2463 			ret = region_del(resv, idx, idx + 1);
2464 		} else {
2465 			ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2466 			/* region_add calls of range 1 should never fail. */
2467 			VM_BUG_ON(ret < 0);
2468 		}
2469 		break;
2470 	default:
2471 		BUG();
2472 	}
2473 
2474 	if (vma->vm_flags & VM_MAYSHARE || mode == VMA_DEL_RESV)
2475 		return ret;
2476 	/*
2477 	 * We know private mapping must have HPAGE_RESV_OWNER set.
2478 	 *
2479 	 * In most cases, reserves always exist for private mappings.
2480 	 * However, a file associated with mapping could have been
2481 	 * hole punched or truncated after reserves were consumed.
2482 	 * As subsequent fault on such a range will not use reserves.
2483 	 * Subtle - The reserve map for private mappings has the
2484 	 * opposite meaning than that of shared mappings.  If NO
2485 	 * entry is in the reserve map, it means a reservation exists.
2486 	 * If an entry exists in the reserve map, it means the
2487 	 * reservation has already been consumed.  As a result, the
2488 	 * return value of this routine is the opposite of the
2489 	 * value returned from reserve map manipulation routines above.
2490 	 */
2491 	if (ret > 0)
2492 		return 0;
2493 	if (ret == 0)
2494 		return 1;
2495 	return ret;
2496 }
2497 
2498 static long vma_needs_reservation(struct hstate *h,
2499 			struct vm_area_struct *vma, unsigned long addr)
2500 {
2501 	return __vma_reservation_common(h, vma, addr, VMA_NEEDS_RESV);
2502 }
2503 
2504 static long vma_commit_reservation(struct hstate *h,
2505 			struct vm_area_struct *vma, unsigned long addr)
2506 {
2507 	return __vma_reservation_common(h, vma, addr, VMA_COMMIT_RESV);
2508 }
2509 
2510 static void vma_end_reservation(struct hstate *h,
2511 			struct vm_area_struct *vma, unsigned long addr)
2512 {
2513 	(void)__vma_reservation_common(h, vma, addr, VMA_END_RESV);
2514 }
2515 
2516 static long vma_add_reservation(struct hstate *h,
2517 			struct vm_area_struct *vma, unsigned long addr)
2518 {
2519 	return __vma_reservation_common(h, vma, addr, VMA_ADD_RESV);
2520 }
2521 
2522 static long vma_del_reservation(struct hstate *h,
2523 			struct vm_area_struct *vma, unsigned long addr)
2524 {
2525 	return __vma_reservation_common(h, vma, addr, VMA_DEL_RESV);
2526 }
2527 
2528 /*
2529  * This routine is called to restore reservation information on error paths.
2530  * It should ONLY be called for folios allocated via alloc_hugetlb_folio(),
2531  * and the hugetlb mutex should remain held when calling this routine.
2532  *
2533  * It handles two specific cases:
2534  * 1) A reservation was in place and the folio consumed the reservation.
2535  *    hugetlb_restore_reserve is set in the folio.
2536  * 2) No reservation was in place for the page, so hugetlb_restore_reserve is
2537  *    not set.  However, alloc_hugetlb_folio always updates the reserve map.
2538  *
2539  * In case 1, free_huge_folio later in the error path will increment the
2540  * global reserve count.  But, free_huge_folio does not have enough context
2541  * to adjust the reservation map.  This case deals primarily with private
2542  * mappings.  Adjust the reserve map here to be consistent with global
2543  * reserve count adjustments to be made by free_huge_folio.  Make sure the
2544  * reserve map indicates there is a reservation present.
2545  *
2546  * In case 2, simply undo reserve map modifications done by alloc_hugetlb_folio.
2547  */
2548 void restore_reserve_on_error(struct hstate *h, struct vm_area_struct *vma,
2549 			unsigned long address, struct folio *folio)
2550 {
2551 	long rc = vma_needs_reservation(h, vma, address);
2552 
2553 	if (folio_test_hugetlb_restore_reserve(folio)) {
2554 		if (unlikely(rc < 0))
2555 			/*
2556 			 * Rare out of memory condition in reserve map
2557 			 * manipulation.  Clear hugetlb_restore_reserve so
2558 			 * that global reserve count will not be incremented
2559 			 * by free_huge_folio.  This will make it appear
2560 			 * as though the reservation for this folio was
2561 			 * consumed.  This may prevent the task from
2562 			 * faulting in the folio at a later time.  This
2563 			 * is better than inconsistent global huge page
2564 			 * accounting of reserve counts.
2565 			 */
2566 			folio_clear_hugetlb_restore_reserve(folio);
2567 		else if (rc)
2568 			(void)vma_add_reservation(h, vma, address);
2569 		else
2570 			vma_end_reservation(h, vma, address);
2571 	} else {
2572 		if (!rc) {
2573 			/*
2574 			 * This indicates there is an entry in the reserve map
2575 			 * not added by alloc_hugetlb_folio.  We know it was added
2576 			 * before the alloc_hugetlb_folio call, otherwise
2577 			 * hugetlb_restore_reserve would be set on the folio.
2578 			 * Remove the entry so that a subsequent allocation
2579 			 * does not consume a reservation.
2580 			 */
2581 			rc = vma_del_reservation(h, vma, address);
2582 			if (rc < 0)
2583 				/*
2584 				 * VERY rare out of memory condition.  Since
2585 				 * we can not delete the entry, set
2586 				 * hugetlb_restore_reserve so that the reserve
2587 				 * count will be incremented when the folio
2588 				 * is freed.  This reserve will be consumed
2589 				 * on a subsequent allocation.
2590 				 */
2591 				folio_set_hugetlb_restore_reserve(folio);
2592 		} else if (rc < 0) {
2593 			/*
2594 			 * Rare out of memory condition from
2595 			 * vma_needs_reservation call.  Memory allocation is
2596 			 * only attempted if a new entry is needed.  Therefore,
2597 			 * this implies there is not an entry in the
2598 			 * reserve map.
2599 			 *
2600 			 * For shared mappings, no entry in the map indicates
2601 			 * no reservation.  We are done.
2602 			 */
2603 			if (!(vma->vm_flags & VM_MAYSHARE))
2604 				/*
2605 				 * For private mappings, no entry indicates
2606 				 * a reservation is present.  Since we can
2607 				 * not add an entry, set hugetlb_restore_reserve
2608 				 * on the folio so reserve count will be
2609 				 * incremented when freed.  This reserve will
2610 				 * be consumed on a subsequent allocation.
2611 				 */
2612 				folio_set_hugetlb_restore_reserve(folio);
2613 		} else {
2614 			/*
2615 			 * No reservation present, do nothing
2616 			 */
2617 			vma_end_reservation(h, vma, address);
2618 		}
2619 	}
2620 }
2621 
2622 /*
2623  * alloc_and_dissolve_hugetlb_folio - Allocate a new folio and dissolve
2624  * the old one
2625  * @old_folio: Old folio to dissolve
2626  * @list: List to isolate the page in case we need to
2627  * Returns 0 on success, otherwise negated error.
2628  */
2629 static int alloc_and_dissolve_hugetlb_folio(struct folio *old_folio,
2630 			struct list_head *list)
2631 {
2632 	gfp_t gfp_mask;
2633 	struct hstate *h;
2634 	int nid = folio_nid(old_folio);
2635 	struct folio *new_folio = NULL;
2636 	int ret = 0;
2637 
2638 retry:
2639 	/*
2640 	 * The old_folio might have been dissolved from under our feet, so make sure
2641 	 * to carefully check the state under the lock.
2642 	 */
2643 	spin_lock_irq(&hugetlb_lock);
2644 	if (!folio_test_hugetlb(old_folio)) {
2645 		/*
2646 		 * Freed from under us. Drop new_folio too.
2647 		 */
2648 		goto free_new;
2649 	} else if (folio_ref_count(old_folio)) {
2650 		bool isolated;
2651 
2652 		/*
2653 		 * Someone has grabbed the folio, try to isolate it here.
2654 		 * Fail with -EBUSY if not possible.
2655 		 */
2656 		spin_unlock_irq(&hugetlb_lock);
2657 		isolated = folio_isolate_hugetlb(old_folio, list);
2658 		ret = isolated ? 0 : -EBUSY;
2659 		spin_lock_irq(&hugetlb_lock);
2660 		goto free_new;
2661 	} else if (!folio_test_hugetlb_freed(old_folio)) {
2662 		/*
2663 		 * Folio's refcount is 0 but it has not been enqueued in the
2664 		 * freelist yet. Race window is small, so we can succeed here if
2665 		 * we retry.
2666 		 */
2667 		spin_unlock_irq(&hugetlb_lock);
2668 		cond_resched();
2669 		goto retry;
2670 	} else {
2671 		h = folio_hstate(old_folio);
2672 		if (!new_folio) {
2673 			spin_unlock_irq(&hugetlb_lock);
2674 			gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
2675 			new_folio = alloc_fresh_hugetlb_folio(h, gfp_mask,
2676 							      nid, NULL);
2677 			if (!new_folio)
2678 				return -ENOMEM;
2679 			goto retry;
2680 		}
2681 
2682 		/*
2683 		 * Ok, old_folio is still a genuine free hugepage. Remove it from
2684 		 * the freelist and decrease the counters. These will be
2685 		 * incremented again when calling account_new_hugetlb_folio()
2686 		 * and enqueue_hugetlb_folio() for new_folio. The counters will
2687 		 * remain stable since this happens under the lock.
2688 		 */
2689 		remove_hugetlb_folio(h, old_folio, false);
2690 
2691 		/*
2692 		 * Ref count on new_folio is already zero as it was dropped
2693 		 * earlier.  It can be directly added to the pool free list.
2694 		 */
2695 		account_new_hugetlb_folio(h, new_folio);
2696 		enqueue_hugetlb_folio(h, new_folio);
2697 
2698 		/*
2699 		 * Folio has been replaced, we can safely free the old one.
2700 		 */
2701 		spin_unlock_irq(&hugetlb_lock);
2702 		update_and_free_hugetlb_folio(h, old_folio, false);
2703 	}
2704 
2705 	return ret;
2706 
2707 free_new:
2708 	spin_unlock_irq(&hugetlb_lock);
2709 	if (new_folio)
2710 		update_and_free_hugetlb_folio(h, new_folio, false);
2711 
2712 	return ret;
2713 }
2714 
2715 int isolate_or_dissolve_huge_folio(struct folio *folio, struct list_head *list)
2716 {
2717 	int ret = -EBUSY;
2718 
2719 	/* Not to disrupt normal path by vainly holding hugetlb_lock */
2720 	if (!folio_test_hugetlb(folio))
2721 		return 0;
2722 
2723 	/*
2724 	 * Fence off gigantic pages as there is a cyclic dependency between
2725 	 * alloc_contig_range and them. Return -ENOMEM as this has the effect
2726 	 * of bailing out right away without further retrying.
2727 	 */
2728 	if (order_is_gigantic(folio_order(folio)))
2729 		return -ENOMEM;
2730 
2731 	if (folio_ref_count(folio) && folio_isolate_hugetlb(folio, list))
2732 		ret = 0;
2733 	else if (!folio_ref_count(folio))
2734 		ret = alloc_and_dissolve_hugetlb_folio(folio, list);
2735 
2736 	return ret;
2737 }
2738 
2739 /*
2740  *  replace_free_hugepage_folios - Replace free hugepage folios in a given pfn
2741  *  range with new folios.
2742  *  @start_pfn: start pfn of the given pfn range
2743  *  @end_pfn: end pfn of the given pfn range
2744  *  Returns 0 on success, otherwise negated error.
2745  */
2746 int replace_free_hugepage_folios(unsigned long start_pfn, unsigned long end_pfn)
2747 {
2748 	unsigned long nr = 0;
2749 	struct page *page;
2750 	struct hstate *h;
2751 	LIST_HEAD(list);
2752 	int ret = 0;
2753 
2754 	/* Avoid pfn iterations if no free non-gigantic huge pages */
2755 	for_each_hstate(h) {
2756 		if (hstate_is_gigantic(h))
2757 			continue;
2758 
2759 		nr += h->free_huge_pages;
2760 		if (nr)
2761 			break;
2762 	}
2763 
2764 	if (!nr)
2765 		return 0;
2766 
2767 	while (start_pfn < end_pfn) {
2768 		page = pfn_to_page(start_pfn);
2769 		nr = 1;
2770 
2771 		if (PageHuge(page) || PageCompound(page)) {
2772 			struct folio *folio = page_folio(page);
2773 
2774 			nr = folio_nr_pages(folio) - folio_page_idx(folio, page);
2775 
2776 			/*
2777 			 * Don't disrupt normal path by vainly holding
2778 			 * hugetlb_lock
2779 			 */
2780 			if (folio_test_hugetlb(folio) && !folio_ref_count(folio)) {
2781 				if (order_is_gigantic(folio_order(folio))) {
2782 					ret = -ENOMEM;
2783 					break;
2784 				}
2785 
2786 				ret = alloc_and_dissolve_hugetlb_folio(folio, &list);
2787 				if (ret)
2788 					break;
2789 
2790 				putback_movable_pages(&list);
2791 			}
2792 		} else if (PageBuddy(page)) {
2793 			/*
2794 			 * Buddy order check without zone lock is unsafe and
2795 			 * the order is maybe invalid, but race should be
2796 			 * small, and the worst thing is skipping free hugetlb.
2797 			 */
2798 			const unsigned int order = buddy_order_unsafe(page);
2799 
2800 			if (order <= MAX_PAGE_ORDER)
2801 				nr = 1UL << order;
2802 		}
2803 		start_pfn += nr;
2804 	}
2805 
2806 	return ret;
2807 }
2808 
2809 void wait_for_freed_hugetlb_folios(void)
2810 {
2811 	if (llist_empty(&hpage_freelist))
2812 		return;
2813 
2814 	flush_work(&free_hpage_work);
2815 }
2816 
2817 /**
2818  * hugetlb_alloc_folio - Allocate a hugetlb folio.
2819  * @h: Hugetlb state control block.
2820  * @mpoli: Interpreted memory policy to use for allocation.
2821  * @alloc_flags: Flags controlling the allocation behavior.
2822  *
2823  * Allocates a hugetlb folio and handles cgroup charging and global hstate
2824  * reservations.
2825  *
2826  * Return: A pointer to the allocated folio, or an ERR_PTR on failure.
2827  *         -ENOSPC if cgroup charging fails or no folio is available.
2828  *         -ENOMEM if mem cgroup charging fails.
2829  */
2830 struct folio *hugetlb_alloc_folio(struct hstate *h,
2831 		struct mempolicy_interpreted *mpoli, u8 alloc_flags)
2832 {
2833 	bool charge_hugetlb_cgroup_rsvd = alloc_flags &
2834 					  HUGETLB_ALLOC_CHARG_CGROUP_RSVD;
2835 	bool use_global_reservation = alloc_flags &
2836 				      HUGETLB_ALLOC_USE_GLOBAL_RESERVATIONS;
2837 	size_t nr_pages = pages_per_huge_page(h);
2838 	struct hugetlb_cgroup *h_cg_rsvd = NULL;
2839 	struct hugetlb_cgroup *h_cg = NULL;
2840 	gfp_t gfp = htlb_alloc_mask(h);
2841 	int idx = hstate_index(h);
2842 	struct folio *folio;
2843 	int ret;
2844 
2845 	if (charge_hugetlb_cgroup_rsvd &&
2846 	    hugetlb_cgroup_charge_cgroup_rsvd(idx, nr_pages, &h_cg_rsvd))
2847 		return ERR_PTR(-ENOSPC);
2848 
2849 	if (hugetlb_cgroup_charge_cgroup(idx, nr_pages, &h_cg)) {
2850 		ret = -ENOSPC;
2851 		goto err_uncharge_hugetlb_cgroup_rsvd;
2852 	}
2853 
2854 	spin_lock_irq(&hugetlb_lock);
2855 
2856 	folio = NULL;
2857 	if (use_global_reservation || available_huge_pages(h))
2858 		folio = dequeue_hugetlb_folio(h, gfp, mpoli);
2859 
2860 	if (!folio) {
2861 		spin_unlock_irq(&hugetlb_lock);
2862 		folio = alloc_buddy_hugetlb_folio(h, gfp, mpoli);
2863 		if (!folio) {
2864 			ret = -ENOSPC;
2865 			goto err_uncharge_hugetlb_cgroup;
2866 		}
2867 		spin_lock_irq(&hugetlb_lock);
2868 		list_add(&folio->lru, &h->hugepage_activelist);
2869 		folio_ref_unfreeze(folio, 1);
2870 	}
2871 
2872 	if (use_global_reservation) {
2873 		folio_set_hugetlb_restore_reserve(folio);
2874 		h->resv_huge_pages--;
2875 	}
2876 
2877 	hugetlb_cgroup_commit_charge(idx, nr_pages, h_cg, folio);
2878 
2879 	if (charge_hugetlb_cgroup_rsvd) {
2880 		hugetlb_cgroup_commit_charge_rsvd(idx, nr_pages, h_cg_rsvd,
2881 						  folio);
2882 	}
2883 
2884 	spin_unlock_irq(&hugetlb_lock);
2885 
2886 	ret = mem_cgroup_charge_hugetlb(folio, gfp | __GFP_RETRY_MAYFAIL);
2887 	/*
2888 	 * Unconditionally increment NR_HUGETLB here because if
2889 	 * mem_cgroup_charge_hugetlb failed, freeing the page will
2890 	 * decrement NR_HUGETLB.
2891 	 */
2892 	lruvec_stat_mod_folio(folio, NR_HUGETLB, nr_pages);
2893 
2894 	if (ret == -ENOMEM) {
2895 		free_huge_folio(folio);
2896 		/*
2897 		 * Skip uncharging hugetlb_cgroup since the charges
2898 		 * were committed to the folio and freeing the folio
2899 		 * would have cleared those up.
2900 		 */
2901 		return ERR_PTR(ret);
2902 	}
2903 
2904 	return folio;
2905 
2906  err_uncharge_hugetlb_cgroup:
2907 	hugetlb_cgroup_uncharge_cgroup(idx, nr_pages, h_cg);
2908  err_uncharge_hugetlb_cgroup_rsvd:
2909 	if (charge_hugetlb_cgroup_rsvd)
2910 		hugetlb_cgroup_uncharge_cgroup_rsvd(idx, nr_pages, h_cg_rsvd);
2911 
2912 	return ERR_PTR(ret);
2913 }
2914 
2915 typedef enum {
2916 	/*
2917 	 * For either 0/1: we checked the per-vma resv map, and one resv
2918 	 * count either can be reused (0), or an extra needed (1).
2919 	 */
2920 	MAP_CHG_REUSE = 0,
2921 	MAP_CHG_NEEDED = 1,
2922 	/*
2923 	 * Cannot use per-vma resv count can be used, hence a new resv
2924 	 * count is enforced.
2925 	 *
2926 	 * NOTE: This is mostly identical to MAP_CHG_NEEDED, except
2927 	 * that currently vma_needs_reservation() has an unwanted side
2928 	 * effect to either use end() or commit() to complete the
2929 	 * transaction. Hence it needs to differentiate from NEEDED.
2930 	 */
2931 	MAP_CHG_ENFORCED = 2,
2932 } map_chg_state;
2933 
2934 /*
2935  * NOTE! "cow_from_owner" represents a very hacky usage only used in CoW
2936  * faults of hugetlb private mappings on top of a non-page-cache folio (in
2937  * which case even if there's a private vma resv map it won't cover such
2938  * allocation).  New call sites should (probably) never set it to true!!
2939  * When it's set, the allocation will bypass all vma level reservations.
2940  */
2941 struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
2942 				    unsigned long addr, bool cow_from_owner)
2943 {
2944 	struct hugepage_subpool *spool = subpool_vma(vma);
2945 	struct hstate *h = hstate_vma(vma);
2946 	struct folio *folio;
2947 	long retval, gbl_chg, gbl_reserve;
2948 	map_chg_state map_chg;
2949 	struct mempolicy_interpreted mpoli;
2950 	gfp_t gfp = htlb_alloc_mask(h);
2951 	struct mempolicy *mpol;
2952 	nodemask_t *nodemask;
2953 	u8 alloc_flags = 0;
2954 	int nid;
2955 	int ret;
2956 
2957 	/* Whether we need a separate per-vma reservation? */
2958 	if (cow_from_owner) {
2959 		/*
2960 		 * Special case!  Since it's a CoW on top of a reserved
2961 		 * page, the private resv map doesn't count.  So it cannot
2962 		 * consume the per-vma resv map even if it's reserved.
2963 		 */
2964 		map_chg = MAP_CHG_ENFORCED;
2965 	} else {
2966 		/*
2967 		 * Examine the region/reserve map to determine if the process
2968 		 * has a reservation for the page to be allocated.  A return
2969 		 * code of zero indicates a reservation exists (no change).
2970 		 */
2971 		retval = vma_needs_reservation(h, vma, addr);
2972 		if (retval < 0)
2973 			return ERR_PTR(-ENOMEM);
2974 		map_chg = retval ? MAP_CHG_NEEDED : MAP_CHG_REUSE;
2975 	}
2976 
2977 	/*
2978 	 * Whether we need a separate global reservation?
2979 	 *
2980 	 * Processes that did not create the mapping will have no
2981 	 * reserves as indicated by the region/reserve map. Check
2982 	 * that the allocation will not exceed the subpool limit.
2983 	 * Or if it can get one from the pool reservation directly.
2984 	 */
2985 	if (map_chg) {
2986 		gbl_chg = hugepage_subpool_get_pages(spool, 1);
2987 		if (gbl_chg < 0) {
2988 			ret = -ENOSPC;
2989 			goto out_end_reservation;
2990 		}
2991 	} else {
2992 		/*
2993 		 * If we have the vma reservation ready, no need for extra
2994 		 * global reservation.
2995 		 */
2996 		gbl_chg = 0;
2997 	}
2998 
2999 	/*
3000 	 * If allocation doesn't reuse a reservation in the resv_map,
3001 	 * charge for the reservation.
3002 	 */
3003 	if (map_chg != MAP_CHG_REUSE)
3004 		alloc_flags |= HUGETLB_ALLOC_CHARG_CGROUP_RSVD;
3005 
3006 	/*
3007 	 * gbl_chg == 0 indicates a reservation exists for this
3008 	 * allocation, so try to use it.
3009 	 */
3010 	if (gbl_chg == 0)
3011 		alloc_flags |= HUGETLB_ALLOC_USE_GLOBAL_RESERVATIONS;
3012 
3013 	/* Takes reference on mpol. */
3014 	nid = huge_node(vma, addr, gfp, &mpol, &nodemask);
3015 	mpoli = (struct mempolicy_interpreted){
3016 		.nid = nid,
3017 #ifdef CONFIG_NUMA
3018 		.mode = mpol ? mpol->mode : MPOL_DEFAULT,
3019 #else
3020 		.mode = MPOL_DEFAULT,
3021 #endif
3022 		.nodemask = nodemask,
3023 	};
3024 
3025 	folio = hugetlb_alloc_folio(h, &mpoli, alloc_flags);
3026 
3027 	mpol_cond_put(mpol);
3028 
3029 	if (IS_ERR(folio)) {
3030 		ret = PTR_ERR(folio);
3031 		goto out_subpool_put;
3032 	}
3033 
3034 	hugetlb_set_folio_subpool(folio, spool);
3035 
3036 	if (map_chg != MAP_CHG_ENFORCED) {
3037 		/* commit() is only needed if the map_chg is not enforced */
3038 		retval = vma_commit_reservation(h, vma, addr);
3039 		/*
3040 		 * Check for possible race conditions. When it happens..
3041 		 * The page was added to the reservation map between
3042 		 * vma_needs_reservation and vma_commit_reservation.
3043 		 * This indicates a race with hugetlb_reserve_pages.
3044 		 * Adjust for the subpool count incremented above AND
3045 		 * in hugetlb_reserve_pages for the same page.	Also,
3046 		 * the reservation count added in hugetlb_reserve_pages
3047 		 * no longer applies.
3048 		 */
3049 		if (unlikely(map_chg == MAP_CHG_NEEDED && retval == 0)) {
3050 			long rsv_adjust;
3051 
3052 			rsv_adjust = hugepage_subpool_put_pages(spool, 1);
3053 			hugetlb_acct_memory(h, -rsv_adjust);
3054 			spin_lock_irq(&hugetlb_lock);
3055 			hugetlb_cgroup_uncharge_folio_rsvd(
3056 			    hstate_index(h), pages_per_huge_page(h), folio);
3057 			spin_unlock_irq(&hugetlb_lock);
3058 		}
3059 	}
3060 
3061 	return folio;
3062 
3063 out_subpool_put:
3064 	/*
3065 	 * put page to subpool iff the quota of subpool's rsv_hpages is used
3066 	 * during hugepage_subpool_get_pages.
3067 	 */
3068 	if (map_chg && !gbl_chg) {
3069 		gbl_reserve = hugepage_subpool_put_pages(spool, 1);
3070 		hugetlb_acct_memory(h, -gbl_reserve);
3071 	}
3072 
3073 out_end_reservation:
3074 	if (map_chg != MAP_CHG_ENFORCED)
3075 		vma_end_reservation(h, vma, addr);
3076 	return ERR_PTR(ret);
3077 }
3078 
3079 static __init void *alloc_bootmem(struct hstate *h, int nid, bool node_exact)
3080 {
3081 	if (hugetlb_early_cma(h))
3082 		return hugetlb_cma_alloc_bootmem(h, nid, node_exact);
3083 
3084 	return memblock_alloc_hugetlb(huge_page_size(h), nid, node_exact);
3085 }
3086 
3087 void *__init arch_alloc_bootmem_huge_page(struct hstate *h, int nid)
3088 	__attribute__ ((weak, alias("__alloc_bootmem_huge_page")));
3089 void *__init __alloc_bootmem_huge_page(struct hstate *h, int nid)
3090 {
3091 	int nr_nodes, node = nid;
3092 
3093 	/* do node specific alloc */
3094 	if (nid != NUMA_NO_NODE)
3095 		return alloc_bootmem(h, node, true);
3096 
3097 	/* allocate from next node when distributing huge pages */
3098 	for_each_node_mask_to_alloc(&h->next_nid_to_alloc, nr_nodes, node,
3099 				    &hugetlb_bootmem_nodes)
3100 		return alloc_bootmem(h, node, false);
3101 
3102 	return NULL;
3103 }
3104 
3105 static bool __init alloc_bootmem_huge_page(struct hstate *h, int nid)
3106 {
3107 	unsigned long pfn;
3108 	unsigned int nid_request = nid;
3109 	struct huge_bootmem_page *m = arch_alloc_bootmem_huge_page(h, nid);
3110 
3111 	if (!m)
3112 		return false;
3113 
3114 	pfn = PHYS_PFN(__pa(m));
3115 	nid = early_pfn_to_nid(pfn);
3116 	/*
3117 	 * Use the beginning of the huge page to store the huge_bootmem_page
3118 	 * struct (until gather_bootmem puts them into the mem_map).
3119 	 *
3120 	 * Put them into a private list first because mem_map is not up yet.
3121 	 */
3122 	INIT_LIST_HEAD(&m->list);
3123 	m->hstate = h;
3124 	m->flags = hugetlb_early_cma(h) ? HUGE_BOOTMEM_CMA : 0;
3125 
3126 	/* CMA pages: zone-crossing is validated in hugetlb_cma_reserve(). */
3127 	if (!hugetlb_early_cma(h) &&
3128 	    pfn_range_intersects_zones(nid, pfn, pages_per_huge_page(h))) {
3129 		/*
3130 		 * If the allocated page is on a different node than requested
3131 		 * (e.g., on PowerPC LPARs), put it on the requested node's list,
3132 		 * because hugetlb_free_cross_zone_pages() only frees cross-zone
3133 		 * pages belonging to the requested node.
3134 		 */
3135 		if (WARN_ON_ONCE(nid_request != NUMA_NO_NODE && nid != nid_request))
3136 			list_add(&m->list, &huge_boot_pages[nid_request]);
3137 		else
3138 			list_add(&m->list, &huge_boot_pages[nid]);
3139 	} else {
3140 		list_add_tail(&m->list, &huge_boot_pages[nid]);
3141 		m->flags |= HUGE_BOOTMEM_ZONES_VALID;
3142 		/*
3143 		 * Only initialize the head struct page in memmap_init_reserved_pages,
3144 		 * rest of the struct pages will be initialized by the HugeTLB
3145 		 * subsystem itself.
3146 		 * The head struct page is used to get folio information by the HugeTLB
3147 		 * subsystem like zone id and node id.
3148 		 */
3149 		memblock_reserved_mark_noinit(__pa((void *)m + PAGE_SIZE),
3150 				huge_page_size(h) - PAGE_SIZE);
3151 	}
3152 
3153 	return true;
3154 }
3155 
3156 /* Initialize [start_page:end_page_number] tail struct pages of a hugepage */
3157 static void __init hugetlb_folio_init_tail_vmemmap(struct folio *folio,
3158 					struct hstate *h,
3159 					unsigned long start_page_number,
3160 					unsigned long end_page_number)
3161 {
3162 	enum zone_type zone = folio_zonenum(folio);
3163 	int nid = folio_nid(folio);
3164 	struct page *page = folio_page(folio, start_page_number);
3165 	unsigned long head_pfn = folio_pfn(folio);
3166 	unsigned long pfn, end_pfn = head_pfn + end_page_number;
3167 	unsigned int order = huge_page_order(h);
3168 
3169 	/*
3170 	 * As we marked all tail pages with memblock_reserved_mark_noinit(),
3171 	 * we must initialize them ourselves here.
3172 	 */
3173 	for (pfn = head_pfn + start_page_number; pfn < end_pfn; page++, pfn++) {
3174 		__init_single_page(page, pfn, zone, nid);
3175 		prep_compound_tail(page, &folio->page, order);
3176 		set_page_count(page, 0);
3177 	}
3178 }
3179 
3180 static void __init hugetlb_folio_init_vmemmap(struct folio *folio,
3181 					      struct hstate *h,
3182 					      unsigned long nr_pages)
3183 {
3184 	int ret;
3185 
3186 	/*
3187 	 * This is an open-coded prep_compound_page() whereby we avoid
3188 	 * walking pages twice by initializing/preparing+freezing them in the
3189 	 * same go.
3190 	 */
3191 	__folio_clear_reserved(folio);
3192 	__folio_set_head(folio);
3193 	ret = folio_ref_freeze(folio, 1);
3194 	VM_BUG_ON(!ret);
3195 	hugetlb_folio_init_tail_vmemmap(folio, h, 1, nr_pages);
3196 	prep_compound_head(&folio->page, huge_page_order(h));
3197 }
3198 
3199 static bool __init hugetlb_bootmem_page_prehvo(struct huge_bootmem_page *m)
3200 {
3201 	return m->flags & HUGE_BOOTMEM_HVO;
3202 }
3203 
3204 static bool __init hugetlb_bootmem_page_earlycma(struct huge_bootmem_page *m)
3205 {
3206 	return m->flags & HUGE_BOOTMEM_CMA;
3207 }
3208 
3209 /*
3210  * memblock-allocated pageblocks might not have the migrate type set
3211  * if marked with the 'noinit' flag. Set it to the default (MIGRATE_MOVABLE)
3212  * here, or MIGRATE_CMA if this was a page allocated through an early CMA
3213  * reservation.
3214  *
3215  * In case of vmemmap optimized folios, the tail vmemmap pages are mapped
3216  * read-only, but that's ok - for sparse vmemmap this does not write to
3217  * the page structure.
3218  */
3219 static void __init hugetlb_bootmem_init_migratetype(struct folio *folio,
3220 							  struct hstate *h)
3221 {
3222 	unsigned long nr_pages = pages_per_huge_page(h), i;
3223 
3224 	WARN_ON_ONCE(!pageblock_aligned(folio_pfn(folio)));
3225 
3226 	for (i = 0; i < nr_pages; i += pageblock_nr_pages) {
3227 		if (folio_test_hugetlb_cma(folio))
3228 			init_cma_pageblock(folio_page(folio, i));
3229 		else
3230 			init_pageblock_migratetype(folio_page(folio, i),
3231 					  MIGRATE_MOVABLE, false);
3232 	}
3233 }
3234 
3235 static void __init prep_and_add_bootmem_folios(struct hstate *h,
3236 					struct list_head *folio_list)
3237 {
3238 	unsigned long flags;
3239 	struct folio *folio, *tmp_f;
3240 
3241 	/* Send list for bulk vmemmap optimization processing */
3242 	hugetlb_vmemmap_optimize_bootmem_folios(h, folio_list);
3243 
3244 	list_for_each_entry_safe(folio, tmp_f, folio_list, lru) {
3245 		if (!folio_test_hugetlb_vmemmap_optimized(folio)) {
3246 			/*
3247 			 * If HVO fails, initialize all tail struct pages
3248 			 * We do not worry about potential long lock hold
3249 			 * time as this is early in boot and there should
3250 			 * be no contention.
3251 			 */
3252 			hugetlb_folio_init_tail_vmemmap(folio, h,
3253 					HUGETLB_VMEMMAP_RESERVE_PAGES,
3254 					pages_per_huge_page(h));
3255 		}
3256 		hugetlb_bootmem_init_migratetype(folio, h);
3257 		/* Subdivide locks to achieve better parallel performance */
3258 		spin_lock_irqsave(&hugetlb_lock, flags);
3259 		account_new_hugetlb_folio(h, folio);
3260 		enqueue_hugetlb_folio(h, folio);
3261 		spin_unlock_irqrestore(&hugetlb_lock, flags);
3262 	}
3263 }
3264 
3265 /*
3266  * Put bootmem huge pages into the standard lists after mem_map is up.
3267  * Note: This only applies to gigantic (order > MAX_PAGE_ORDER) pages.
3268  */
3269 static void __init gather_bootmem_prealloc_node(unsigned long nid)
3270 {
3271 	LIST_HEAD(folio_list);
3272 	struct huge_bootmem_page *m, *tm;
3273 	struct hstate *h = NULL, *prev_h = NULL;
3274 
3275 	list_for_each_entry_safe(m, tm, &huge_boot_pages[nid], list) {
3276 		struct page *page = virt_to_page(m);
3277 		struct folio *folio = (void *)page;
3278 
3279 		h = m->hstate;
3280 		/*
3281 		 * It is possible to have multiple huge page sizes (hstates)
3282 		 * in this list.  If so, process each size separately.
3283 		 */
3284 		if (h != prev_h && prev_h != NULL)
3285 			prep_and_add_bootmem_folios(prev_h, &folio_list);
3286 		prev_h = h;
3287 
3288 		VM_BUG_ON(!hstate_is_gigantic(h));
3289 		WARN_ON(folio_ref_count(folio) != 1);
3290 
3291 		hugetlb_folio_init_vmemmap(folio, h,
3292 					   HUGETLB_VMEMMAP_RESERVE_PAGES);
3293 		init_new_hugetlb_folio(folio);
3294 
3295 		if (hugetlb_bootmem_page_prehvo(m))
3296 			/*
3297 			 * If pre-HVO was done, just set the
3298 			 * flag, the HVO code will then skip
3299 			 * this folio.
3300 			 */
3301 			folio_set_hugetlb_vmemmap_optimized(folio);
3302 
3303 		if (hugetlb_bootmem_page_earlycma(m))
3304 			folio_set_hugetlb_cma(folio);
3305 
3306 		list_add(&folio->lru, &folio_list);
3307 
3308 		/*
3309 		 * We need to restore the 'stolen' pages to totalram_pages
3310 		 * in order to fix confusing memory reports from free(1) and
3311 		 * other side-effects, like CommitLimit going negative.
3312 		 *
3313 		 * For CMA pages, this is done in init_cma_pageblock
3314 		 * (via hugetlb_bootmem_init_migratetype), so skip it here.
3315 		 */
3316 		if (!folio_test_hugetlb_cma(folio))
3317 			adjust_managed_page_count(page, pages_per_huge_page(h));
3318 		cond_resched();
3319 	}
3320 
3321 	prep_and_add_bootmem_folios(h, &folio_list);
3322 }
3323 
3324 static void __init gather_bootmem_prealloc_parallel(unsigned long start,
3325 						    unsigned long end, void *arg)
3326 {
3327 	int nid;
3328 
3329 	for (nid = start; nid < end; nid++)
3330 		gather_bootmem_prealloc_node(nid);
3331 }
3332 
3333 void __init hugetlb_bootmem_struct_page_init(void)
3334 {
3335 	struct padata_mt_job job = {
3336 		.thread_fn	= gather_bootmem_prealloc_parallel,
3337 		.fn_arg		= NULL,
3338 		.start		= 0,
3339 		.size		= nr_node_ids,
3340 		.align		= 1,
3341 		.min_chunk	= 1,
3342 		.max_threads	= num_node_state(N_MEMORY),
3343 		.numa_aware	= true,
3344 	};
3345 #ifdef CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP
3346 	struct zone *zone;
3347 
3348 	for_each_zone(zone) {
3349 		for (int i = 0; i < NR_VMEMMAP_TAILS; i++) {
3350 			struct page *tail, *p;
3351 			unsigned int order;
3352 
3353 			tail = zone->vmemmap_tails[i];
3354 			if (!tail)
3355 				continue;
3356 
3357 			order = i + VMEMMAP_TAIL_MIN_ORDER;
3358 			p = page_to_virt(tail);
3359 			/*
3360 			 * prep_and_add_bootmem_folios() can access pageblock
3361 			 * flags on bootmem HugeTLB pages, so initialize the
3362 			 * shared tail struct pages here before bootmem folios
3363 			 * start using them.
3364 			 */
3365 			for (int j = 0; j < PAGE_SIZE / sizeof(struct page); j++)
3366 				init_compound_tail(p + j, NULL, order, zone);
3367 		}
3368 	}
3369 #endif
3370 
3371 	padata_do_multithreaded(&job);
3372 }
3373 
3374 static unsigned long __init hugetlb_free_cross_zone_pages(struct hstate *h, int nid)
3375 {
3376 	unsigned long freed = 0;
3377 	struct huge_bootmem_page *m, *tmp;
3378 
3379 	if (!hstate_is_gigantic(h))
3380 		return freed;
3381 
3382 	list_for_each_entry_safe(m, tmp, &huge_boot_pages[nid], list) {
3383 		if (m->flags & HUGE_BOOTMEM_ZONES_VALID)
3384 			break;
3385 
3386 		list_del(&m->list);
3387 		memblock_free(m, huge_page_size(h));
3388 		freed++;
3389 	}
3390 
3391 	if (freed) {
3392 		char buf[32];
3393 
3394 		string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, sizeof(buf));
3395 		pr_warn("HugeTLB: freed %lu cross-zone hugepages of size %s on node %d.\n",
3396 			freed, buf, nid);
3397 	}
3398 
3399 	return freed;
3400 }
3401 
3402 static void __init hugetlb_hstate_alloc_pages_onenode(struct hstate *h, int nid)
3403 {
3404 	unsigned long i;
3405 	char buf[32];
3406 	LIST_HEAD(folio_list);
3407 
3408 	for (i = 0; i < h->max_huge_pages_node[nid]; ++i) {
3409 		if (hstate_is_gigantic(h)) {
3410 			if (!alloc_bootmem_huge_page(h, nid))
3411 				break;
3412 		} else {
3413 			struct folio *folio;
3414 			gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
3415 
3416 			folio = only_alloc_fresh_hugetlb_folio(h, gfp_mask, nid,
3417 					&node_states[N_MEMORY], NULL);
3418 			if (!folio && !list_empty(&folio_list) &&
3419 			    hugetlb_vmemmap_optimizable_size(h)) {
3420 				prep_and_add_allocated_folios(h, &folio_list);
3421 				INIT_LIST_HEAD(&folio_list);
3422 				folio = only_alloc_fresh_hugetlb_folio(h, gfp_mask, nid,
3423 						&node_states[N_MEMORY], NULL);
3424 			}
3425 			if (!folio)
3426 				break;
3427 			list_add(&folio->lru, &folio_list);
3428 		}
3429 		cond_resched();
3430 	}
3431 
3432 	i -= hugetlb_free_cross_zone_pages(h, nid);
3433 
3434 	if (!list_empty(&folio_list))
3435 		prep_and_add_allocated_folios(h, &folio_list);
3436 
3437 	if (i == h->max_huge_pages_node[nid])
3438 		return;
3439 
3440 	string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
3441 	pr_warn("HugeTLB: allocating %u of page size %s failed node%d.  Only allocated %lu hugepages.\n",
3442 		h->max_huge_pages_node[nid], buf, nid, i);
3443 	h->max_huge_pages -= (h->max_huge_pages_node[nid] - i);
3444 	h->max_huge_pages_node[nid] = i;
3445 }
3446 
3447 static bool __init hugetlb_hstate_alloc_pages_specific_nodes(struct hstate *h)
3448 {
3449 	int i;
3450 	bool node_specific_alloc = false;
3451 
3452 	for_each_online_node(i) {
3453 		if (h->max_huge_pages_node[i] > 0) {
3454 			hugetlb_hstate_alloc_pages_onenode(h, i);
3455 			node_specific_alloc = true;
3456 		}
3457 	}
3458 
3459 	return node_specific_alloc;
3460 }
3461 
3462 static void __init hugetlb_hstate_alloc_pages_errcheck(unsigned long allocated, struct hstate *h)
3463 {
3464 	if (allocated < h->max_huge_pages) {
3465 		char buf[32];
3466 
3467 		string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
3468 		pr_warn("HugeTLB: allocating %lu of page size %s failed.  Only allocated %lu hugepages.\n",
3469 			h->max_huge_pages, buf, allocated);
3470 		h->max_huge_pages = allocated;
3471 	}
3472 }
3473 
3474 static void __init hugetlb_pages_alloc_boot_node(unsigned long start, unsigned long end, void *arg)
3475 {
3476 	struct hstate *h = (struct hstate *)arg;
3477 	int i, num = end - start;
3478 	nodemask_t node_alloc_noretry;
3479 	LIST_HEAD(folio_list);
3480 	int next_node = first_online_node;
3481 
3482 	/* Bit mask controlling how hard we retry per-node allocations.*/
3483 	nodes_clear(node_alloc_noretry);
3484 
3485 	for (i = 0; i < num; ++i) {
3486 		struct folio *folio;
3487 
3488 		if (hugetlb_vmemmap_optimizable_size(h) &&
3489 		    (si_mem_available() == 0) && !list_empty(&folio_list)) {
3490 			prep_and_add_allocated_folios(h, &folio_list);
3491 			INIT_LIST_HEAD(&folio_list);
3492 		}
3493 		folio = alloc_pool_huge_folio(h, &node_states[N_MEMORY],
3494 						&node_alloc_noretry, &next_node);
3495 		if (!folio)
3496 			break;
3497 
3498 		list_move(&folio->lru, &folio_list);
3499 		cond_resched();
3500 	}
3501 
3502 	prep_and_add_allocated_folios(h, &folio_list);
3503 }
3504 
3505 static unsigned long __init hugetlb_gigantic_pages_alloc_boot(struct hstate *h)
3506 {
3507 	int nid;
3508 	unsigned long i;
3509 
3510 	for (i = 0; i < h->max_huge_pages; ++i) {
3511 		if (!alloc_bootmem_huge_page(h, NUMA_NO_NODE))
3512 			break;
3513 		cond_resched();
3514 	}
3515 
3516 	for_each_node(nid)
3517 		i -= hugetlb_free_cross_zone_pages(h, nid);
3518 
3519 	return i;
3520 }
3521 
3522 static unsigned long __init hugetlb_pages_alloc_boot(struct hstate *h)
3523 {
3524 	struct padata_mt_job job = {
3525 		.fn_arg		= h,
3526 		.align		= 1,
3527 		.numa_aware	= true
3528 	};
3529 
3530 	unsigned long jiffies_start;
3531 	unsigned long jiffies_end;
3532 	unsigned long remaining;
3533 
3534 	job.thread_fn	= hugetlb_pages_alloc_boot_node;
3535 
3536 	/*
3537 	 * job.max_threads is 25% of the available cpu threads by default.
3538 	 *
3539 	 * On large servers with terabytes of memory, huge page allocation
3540 	 * can consume a considerably amount of time.
3541 	 *
3542 	 * Tests below show how long it takes to allocate 1 TiB of memory with 2MiB huge pages.
3543 	 * 2MiB huge pages. Using more threads can significantly improve allocation time.
3544 	 *
3545 	 * +-----------------------+-------+-------+-------+-------+-------+
3546 	 * | threads               |   8   |   16  |   32  |   64  |   128 |
3547 	 * +-----------------------+-------+-------+-------+-------+-------+
3548 	 * | skylake      144 cpus |   44s |   22s |   16s |   19s |   20s |
3549 	 * | cascade lake 192 cpus |   39s |   20s |   11s |   10s |    9s |
3550 	 * +-----------------------+-------+-------+-------+-------+-------+
3551 	 */
3552 	if (hugepage_allocation_threads == 0) {
3553 		hugepage_allocation_threads = num_online_cpus() / 4;
3554 		hugepage_allocation_threads = max(hugepage_allocation_threads, 1);
3555 	}
3556 
3557 	job.max_threads	= hugepage_allocation_threads;
3558 
3559 	jiffies_start = jiffies;
3560 	do {
3561 		remaining = h->max_huge_pages - h->nr_huge_pages;
3562 
3563 		job.start     = h->nr_huge_pages;
3564 		job.size      = remaining;
3565 		job.min_chunk = remaining / hugepage_allocation_threads;
3566 		padata_do_multithreaded(&job);
3567 
3568 		if (h->nr_huge_pages == h->max_huge_pages)
3569 			break;
3570 
3571 		/*
3572 		 * Retry only if the vmemmap optimization might have been able to free
3573 		 * some memory back to the system.
3574 		 */
3575 		if (!hugetlb_vmemmap_optimizable(h))
3576 			break;
3577 
3578 		/* Continue if progress was made in last iteration */
3579 	} while (remaining != (h->max_huge_pages - h->nr_huge_pages));
3580 
3581 	jiffies_end = jiffies;
3582 
3583 	pr_info("HugeTLB: allocation took %dms with hugepage_allocation_threads=%ld\n",
3584 		jiffies_to_msecs(jiffies_end - jiffies_start),
3585 		hugepage_allocation_threads);
3586 
3587 	return h->nr_huge_pages;
3588 }
3589 
3590 /*
3591  * NOTE: this routine is called in different contexts for gigantic and
3592  * non-gigantic pages.
3593  * - For gigantic pages, this is called early in the boot process and
3594  *   pages are allocated from memblock allocated or something similar.
3595  *   Gigantic pages are actually added to pools later with the routine
3596  *   hugetlb_bootmem_struct_page_init.
3597  * - For non-gigantic pages, this is called later in the boot process after
3598  *   all of mm is up and functional.  Pages are allocated from buddy and
3599  *   then added to hugetlb pools.
3600  */
3601 static void __init hugetlb_hstate_alloc_pages(struct hstate *h)
3602 {
3603 	unsigned long allocated;
3604 
3605 	/*
3606 	 * Skip gigantic hugepages allocation if early CMA
3607 	 * reservations are not available.
3608 	 */
3609 	if (hstate_is_gigantic(h) && hugetlb_cma_total_size() &&
3610 	    !hugetlb_early_cma(h)) {
3611 		pr_warn_once("HugeTLB: hugetlb_cma is enabled, skip boot time allocation\n");
3612 		return;
3613 	}
3614 
3615 	if (!h->max_huge_pages)
3616 		return;
3617 
3618 	/* do node specific alloc */
3619 	if (hugetlb_hstate_alloc_pages_specific_nodes(h))
3620 		return;
3621 
3622 	/* below will do all node balanced alloc */
3623 	if (hstate_is_gigantic(h))
3624 		allocated = hugetlb_gigantic_pages_alloc_boot(h);
3625 	else
3626 		allocated = hugetlb_pages_alloc_boot(h);
3627 
3628 	hugetlb_hstate_alloc_pages_errcheck(allocated, h);
3629 }
3630 
3631 static void __init hugetlb_init_hstates(void)
3632 {
3633 	struct hstate *h, *h2;
3634 
3635 	for_each_hstate(h) {
3636 		/*
3637 		 * Always reset to first_memory_node here, even if
3638 		 * next_nid_to_alloc was set before - we can't
3639 		 * reference hugetlb_bootmem_nodes after init, and
3640 		 * first_memory_node is right for all further allocations.
3641 		 */
3642 		h->next_nid_to_alloc = first_memory_node;
3643 		h->next_nid_to_free = first_memory_node;
3644 
3645 		/* oversize hugepages were init'ed in early boot */
3646 		if (!hstate_is_gigantic(h))
3647 			hugetlb_hstate_alloc_pages(h);
3648 
3649 		/*
3650 		 * Set demote order for each hstate.  Note that
3651 		 * h->demote_order is initially 0.
3652 		 * - We can not demote gigantic pages if runtime freeing
3653 		 *   is not supported, so skip this.
3654 		 * - If CMA allocation is possible, we can not demote
3655 		 *   HUGETLB_PAGE_ORDER or smaller size pages.
3656 		 */
3657 		if (hstate_is_gigantic_no_runtime(h))
3658 			continue;
3659 		if (hugetlb_cma_total_size() && h->order <= HUGETLB_PAGE_ORDER)
3660 			continue;
3661 		for_each_hstate(h2) {
3662 			if (h2 == h)
3663 				continue;
3664 			if (h2->order < h->order &&
3665 			    h2->order > h->demote_order)
3666 				h->demote_order = h2->order;
3667 		}
3668 	}
3669 }
3670 
3671 static void __init report_hugepages(void)
3672 {
3673 	struct hstate *h;
3674 
3675 	for_each_hstate(h) {
3676 		char buf[32];
3677 
3678 		string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
3679 		pr_info("HugeTLB: registered %s page size, pre-allocated %ld pages\n",
3680 			buf, h->nr_huge_pages);
3681 		pr_info("HugeTLB: %d KiB vmemmap can be freed for a %s page\n",
3682 			hugetlb_vmemmap_optimizable_size(h) / SZ_1K, buf);
3683 	}
3684 }
3685 
3686 #ifdef CONFIG_HIGHMEM
3687 static void try_to_free_low(struct hstate *h, unsigned long count,
3688 						nodemask_t *nodes_allowed)
3689 {
3690 	int i;
3691 	LIST_HEAD(page_list);
3692 
3693 	lockdep_assert_held(&hugetlb_lock);
3694 	if (hstate_is_gigantic(h))
3695 		return;
3696 
3697 	/*
3698 	 * Collect pages to be freed on a list, and free after dropping lock
3699 	 */
3700 	for_each_node_mask(i, *nodes_allowed) {
3701 		struct folio *folio, *next;
3702 		struct list_head *freel = &h->hugepage_freelists[i];
3703 		list_for_each_entry_safe(folio, next, freel, lru) {
3704 			if (count >= h->nr_huge_pages)
3705 				goto out;
3706 			if (folio_test_highmem(folio))
3707 				continue;
3708 			remove_hugetlb_folio(h, folio, false);
3709 			list_add(&folio->lru, &page_list);
3710 		}
3711 	}
3712 
3713 out:
3714 	spin_unlock_irq(&hugetlb_lock);
3715 	update_and_free_pages_bulk(h, &page_list);
3716 	spin_lock_irq(&hugetlb_lock);
3717 }
3718 #else
3719 static inline void try_to_free_low(struct hstate *h, unsigned long count,
3720 						nodemask_t *nodes_allowed)
3721 {
3722 }
3723 #endif
3724 
3725 /*
3726  * Increment or decrement surplus_huge_pages.  Keep node-specific counters
3727  * balanced by operating on them in a round-robin fashion.
3728  * Returns 1 if an adjustment was made.
3729  */
3730 static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed,
3731 				int delta)
3732 {
3733 	int nr_nodes, node;
3734 
3735 	lockdep_assert_held(&hugetlb_lock);
3736 	VM_BUG_ON(delta != -1 && delta != 1);
3737 
3738 	if (delta < 0) {
3739 		for_each_node_mask_to_alloc(&h->next_nid_to_alloc, nr_nodes, node, nodes_allowed) {
3740 			if (h->surplus_huge_pages_node[node])
3741 				goto found;
3742 		}
3743 	} else {
3744 		for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
3745 			if (h->surplus_huge_pages_node[node] <
3746 					h->nr_huge_pages_node[node])
3747 				goto found;
3748 		}
3749 	}
3750 	return 0;
3751 
3752 found:
3753 	h->surplus_huge_pages += delta;
3754 	h->surplus_huge_pages_node[node] += delta;
3755 	return 1;
3756 }
3757 
3758 #define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages)
3759 static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,
3760 			      nodemask_t *nodes_allowed)
3761 {
3762 	unsigned long persistent_free_count;
3763 	unsigned long min_count;
3764 	unsigned long allocated;
3765 	struct folio *folio;
3766 	LIST_HEAD(page_list);
3767 	NODEMASK_ALLOC(nodemask_t, node_alloc_noretry, GFP_KERNEL);
3768 
3769 	/*
3770 	 * Bit mask controlling how hard we retry per-node allocations.
3771 	 * If we can not allocate the bit mask, do not attempt to allocate
3772 	 * the requested huge pages.
3773 	 */
3774 	if (node_alloc_noretry)
3775 		nodes_clear(*node_alloc_noretry);
3776 	else
3777 		return -ENOMEM;
3778 
3779 	/*
3780 	 * resize_lock mutex prevents concurrent adjustments to number of
3781 	 * pages in hstate via the proc/sysfs interfaces.
3782 	 */
3783 	mutex_lock(&h->resize_lock);
3784 	flush_free_hpage_work(h);
3785 	spin_lock_irq(&hugetlb_lock);
3786 
3787 	/*
3788 	 * Check for a node specific request.
3789 	 * Changing node specific huge page count may require a corresponding
3790 	 * change to the global count.  In any case, the passed node mask
3791 	 * (nodes_allowed) will restrict alloc/free to the specified node.
3792 	 */
3793 	if (nid != NUMA_NO_NODE) {
3794 		unsigned long old_count = count;
3795 
3796 		count += persistent_huge_pages(h) -
3797 			 (h->nr_huge_pages_node[nid] -
3798 			  h->surplus_huge_pages_node[nid]);
3799 		/*
3800 		 * User may have specified a large count value which caused the
3801 		 * above calculation to overflow.  In this case, they wanted
3802 		 * to allocate as many huge pages as possible.  Set count to
3803 		 * largest possible value to align with their intention.
3804 		 */
3805 		if (count < old_count)
3806 			count = ULONG_MAX;
3807 	}
3808 
3809 	/*
3810 	 * Gigantic pages runtime allocation depend on the capability for large
3811 	 * page range allocation.
3812 	 * If the system does not provide this feature, return an error when
3813 	 * the user tries to allocate gigantic pages but let the user free the
3814 	 * boottime allocated gigantic pages.
3815 	 */
3816 	if (hstate_is_gigantic(h) && !IS_ENABLED(CONFIG_CONTIG_ALLOC)) {
3817 		if (count > persistent_huge_pages(h)) {
3818 			spin_unlock_irq(&hugetlb_lock);
3819 			mutex_unlock(&h->resize_lock);
3820 			NODEMASK_FREE(node_alloc_noretry);
3821 			return -EINVAL;
3822 		}
3823 		/* Fall through to decrease pool */
3824 	}
3825 
3826 	/*
3827 	 * Increase the pool size
3828 	 * First take pages out of surplus state.  Then make up the
3829 	 * remaining difference by allocating fresh huge pages.
3830 	 *
3831 	 * We might race with alloc_surplus_hugetlb_folio() here and be unable
3832 	 * to convert a surplus huge page to a normal huge page. That is
3833 	 * not critical, though, it just means the overall size of the
3834 	 * pool might be one hugepage larger than it needs to be, but
3835 	 * within all the constraints specified by the sysctls.
3836 	 */
3837 	while (h->surplus_huge_pages && count > persistent_huge_pages(h)) {
3838 		if (!adjust_pool_surplus(h, nodes_allowed, -1))
3839 			break;
3840 	}
3841 
3842 	allocated = 0;
3843 	while (count > (persistent_huge_pages(h) + allocated)) {
3844 		/*
3845 		 * If this allocation races such that we no longer need the
3846 		 * page, free_huge_folio will handle it by freeing the page
3847 		 * and reducing the surplus.
3848 		 */
3849 		spin_unlock_irq(&hugetlb_lock);
3850 
3851 		/* yield cpu to avoid soft lockup */
3852 		cond_resched();
3853 
3854 		folio = alloc_pool_huge_folio(h, nodes_allowed,
3855 						node_alloc_noretry,
3856 						&h->next_nid_to_alloc);
3857 		if (!folio) {
3858 			prep_and_add_allocated_folios(h, &page_list);
3859 			spin_lock_irq(&hugetlb_lock);
3860 			goto out;
3861 		}
3862 
3863 		list_add(&folio->lru, &page_list);
3864 		allocated++;
3865 
3866 		/* Bail for signals. Probably ctrl-c from user */
3867 		if (signal_pending(current)) {
3868 			prep_and_add_allocated_folios(h, &page_list);
3869 			spin_lock_irq(&hugetlb_lock);
3870 			goto out;
3871 		}
3872 
3873 		spin_lock_irq(&hugetlb_lock);
3874 	}
3875 
3876 	/* Add allocated pages to the pool */
3877 	if (!list_empty(&page_list)) {
3878 		spin_unlock_irq(&hugetlb_lock);
3879 		prep_and_add_allocated_folios(h, &page_list);
3880 		spin_lock_irq(&hugetlb_lock);
3881 	}
3882 
3883 	/*
3884 	 * Decrease the pool size
3885 	 * First return free pages to the buddy allocator (being careful
3886 	 * to keep enough around to satisfy reservations).  Then place
3887 	 * pages into surplus state as needed so the pool will shrink
3888 	 * to the desired size as pages become free.
3889 	 *
3890 	 * By placing pages into the surplus state independent of the
3891 	 * overcommit value, we are allowing the surplus pool size to
3892 	 * exceed overcommit. There are few sane options here. Since
3893 	 * alloc_surplus_hugetlb_folio() is checking the global counter,
3894 	 * though, we'll note that we're not allowed to exceed surplus
3895 	 * and won't grow the pool anywhere else. Not until one of the
3896 	 * sysctls are changed, or the surplus pages go out of use.
3897 	 *
3898 	 * min_count is the expected number of persistent pages, we
3899 	 * shouldn't calculate min_count by using
3900 	 * resv_huge_pages + persistent_huge_pages() - free_huge_pages,
3901 	 * because there may exist free surplus huge pages, and this will
3902 	 * lead to subtracting twice. Free surplus huge pages come from HVO
3903 	 * failing to restore vmemmap, see comments in the callers of
3904 	 * hugetlb_vmemmap_restore_folio(). Thus, we should calculate
3905 	 * persistent free count first.
3906 	 */
3907 	persistent_free_count = h->free_huge_pages;
3908 	if (h->free_huge_pages > persistent_huge_pages(h)) {
3909 		if (h->free_huge_pages > h->surplus_huge_pages)
3910 			persistent_free_count -= h->surplus_huge_pages;
3911 		else
3912 			persistent_free_count = 0;
3913 	}
3914 	min_count = h->resv_huge_pages + persistent_huge_pages(h) - persistent_free_count;
3915 	min_count = max(count, min_count);
3916 	try_to_free_low(h, min_count, nodes_allowed);
3917 
3918 	/*
3919 	 * Collect pages to be removed on list without dropping lock
3920 	 */
3921 	while (min_count < persistent_huge_pages(h)) {
3922 		folio = remove_pool_hugetlb_folio(h, nodes_allowed, 0);
3923 		if (!folio)
3924 			break;
3925 
3926 		list_add(&folio->lru, &page_list);
3927 	}
3928 	/* free the pages after dropping lock */
3929 	spin_unlock_irq(&hugetlb_lock);
3930 	update_and_free_pages_bulk(h, &page_list);
3931 	flush_free_hpage_work(h);
3932 	spin_lock_irq(&hugetlb_lock);
3933 
3934 	while (count < persistent_huge_pages(h)) {
3935 		if (!adjust_pool_surplus(h, nodes_allowed, 1))
3936 			break;
3937 	}
3938 out:
3939 	h->max_huge_pages = persistent_huge_pages(h);
3940 	spin_unlock_irq(&hugetlb_lock);
3941 	mutex_unlock(&h->resize_lock);
3942 
3943 	NODEMASK_FREE(node_alloc_noretry);
3944 
3945 	return 0;
3946 }
3947 
3948 static long demote_free_hugetlb_folios(struct hstate *src, struct hstate *dst,
3949 				       struct list_head *src_list)
3950 {
3951 	long rc;
3952 	struct folio *folio, *next;
3953 	LIST_HEAD(dst_list);
3954 	LIST_HEAD(ret_list);
3955 
3956 	rc = hugetlb_vmemmap_restore_folios(src, src_list, &ret_list);
3957 	list_splice_init(&ret_list, src_list);
3958 
3959 	/*
3960 	 * Taking target hstate mutex synchronizes with set_max_huge_pages.
3961 	 * Without the mutex, pages added to target hstate could be marked
3962 	 * as surplus.
3963 	 *
3964 	 * Note that we already hold src->resize_lock.  To prevent deadlock,
3965 	 * use the convention of always taking larger size hstate mutex first.
3966 	 */
3967 	mutex_lock(&dst->resize_lock);
3968 
3969 	list_for_each_entry_safe(folio, next, src_list, lru) {
3970 		int i;
3971 		bool cma;
3972 
3973 		if (folio_test_hugetlb_vmemmap_optimized(folio))
3974 			continue;
3975 
3976 		cma = folio_test_hugetlb_cma(folio);
3977 
3978 		list_del(&folio->lru);
3979 
3980 		split_page_owner(&folio->page, huge_page_order(src), huge_page_order(dst));
3981 		pgalloc_tag_split(folio, huge_page_order(src), huge_page_order(dst));
3982 
3983 		for (i = 0; i < pages_per_huge_page(src); i += pages_per_huge_page(dst)) {
3984 			struct page *page = folio_page(folio, i);
3985 			/* Careful: see __split_huge_page_tail() */
3986 			struct folio *new_folio = (struct folio *)page;
3987 
3988 			clear_compound_head(page);
3989 			prep_compound_page(page, dst->order);
3990 
3991 			new_folio->mapping = NULL;
3992 			init_new_hugetlb_folio(new_folio);
3993 			/* Copy the CMA flag so that it is freed correctly */
3994 			if (cma)
3995 				folio_set_hugetlb_cma(new_folio);
3996 			list_add(&new_folio->lru, &dst_list);
3997 		}
3998 	}
3999 
4000 	prep_and_add_allocated_folios(dst, &dst_list);
4001 
4002 	mutex_unlock(&dst->resize_lock);
4003 
4004 	return rc;
4005 }
4006 
4007 long demote_pool_huge_page(struct hstate *src, nodemask_t *nodes_allowed,
4008 			   unsigned long nr_to_demote)
4009 	__must_hold(&hugetlb_lock)
4010 {
4011 	int nr_nodes, node;
4012 	struct hstate *dst;
4013 	long rc = 0;
4014 	long nr_demoted = 0;
4015 
4016 	lockdep_assert_held(&hugetlb_lock);
4017 
4018 	/* We should never get here if no demote order */
4019 	if (!src->demote_order) {
4020 		pr_warn("HugeTLB: NULL demote order passed to demote_pool_huge_page.\n");
4021 		return -EINVAL;		/* internal error */
4022 	}
4023 	dst = size_to_hstate(PAGE_SIZE << src->demote_order);
4024 
4025 	for_each_node_mask_to_free(src, nr_nodes, node, nodes_allowed) {
4026 		LIST_HEAD(list);
4027 		struct folio *folio, *next;
4028 
4029 		list_for_each_entry_safe(folio, next, &src->hugepage_freelists[node], lru) {
4030 			if (folio_test_hwpoison(folio))
4031 				continue;
4032 
4033 			remove_hugetlb_folio(src, folio, false);
4034 			list_add(&folio->lru, &list);
4035 
4036 			if (++nr_demoted == nr_to_demote)
4037 				break;
4038 		}
4039 
4040 		spin_unlock_irq(&hugetlb_lock);
4041 
4042 		rc = demote_free_hugetlb_folios(src, dst, &list);
4043 
4044 		spin_lock_irq(&hugetlb_lock);
4045 
4046 		list_for_each_entry_safe(folio, next, &list, lru) {
4047 			list_del(&folio->lru);
4048 			add_hugetlb_folio(src, folio, false);
4049 
4050 			nr_demoted--;
4051 		}
4052 
4053 		if (rc < 0 || nr_demoted == nr_to_demote)
4054 			break;
4055 	}
4056 
4057 	/*
4058 	 * Not absolutely necessary, but for consistency update max_huge_pages
4059 	 * based on pool changes for the demoted page.
4060 	 */
4061 	src->max_huge_pages -= nr_demoted;
4062 	dst->max_huge_pages += nr_demoted << (huge_page_order(src) - huge_page_order(dst));
4063 
4064 	if (rc < 0)
4065 		return rc;
4066 
4067 	if (nr_demoted)
4068 		return nr_demoted;
4069 	/*
4070 	 * Only way to get here is if all pages on free lists are poisoned.
4071 	 * Return -EBUSY so that caller will not retry.
4072 	 */
4073 	return -EBUSY;
4074 }
4075 
4076 ssize_t __nr_hugepages_store_common(bool obey_mempolicy,
4077 					   struct hstate *h, int nid,
4078 					   unsigned long count, size_t len)
4079 {
4080 	int err;
4081 	nodemask_t nodes_allowed, *n_mask;
4082 
4083 	if (hstate_is_gigantic_no_runtime(h))
4084 		return -EINVAL;
4085 
4086 	if (nid == NUMA_NO_NODE) {
4087 		/*
4088 		 * global hstate attribute
4089 		 */
4090 		if (!(obey_mempolicy &&
4091 				init_nodemask_of_mempolicy(&nodes_allowed)))
4092 			n_mask = &node_states[N_MEMORY];
4093 		else
4094 			n_mask = &nodes_allowed;
4095 	} else {
4096 		/*
4097 		 * Node specific request.  count adjustment happens in
4098 		 * set_max_huge_pages() after acquiring hugetlb_lock.
4099 		 */
4100 		init_nodemask_of_node(&nodes_allowed, nid);
4101 		n_mask = &nodes_allowed;
4102 	}
4103 
4104 	err = set_max_huge_pages(h, count, nid, n_mask);
4105 
4106 	return err ? err : len;
4107 }
4108 
4109 static int __init hugetlb_init(void)
4110 {
4111 	int i;
4112 
4113 	BUILD_BUG_ON(sizeof_field(struct page, private) * BITS_PER_BYTE <
4114 			__NR_HPAGEFLAGS);
4115 	BUILD_BUG_ON_INVALID(HUGETLB_PAGE_ORDER > MAX_FOLIO_ORDER);
4116 
4117 	if (!hugepages_supported()) {
4118 		if (hugetlb_max_hstate || default_hstate_max_huge_pages)
4119 			pr_warn("HugeTLB: huge pages not supported, ignoring associated command-line parameters\n");
4120 		return 0;
4121 	}
4122 
4123 	/*
4124 	 * Make sure HPAGE_SIZE (HUGETLB_PAGE_ORDER) hstate exists.  Some
4125 	 * architectures depend on setup being done here.
4126 	 */
4127 	hugetlb_add_hstate(HUGETLB_PAGE_ORDER);
4128 	if (!parsed_default_hugepagesz) {
4129 		/*
4130 		 * If we did not parse a default huge page size, set
4131 		 * default_hstate_idx to HPAGE_SIZE hstate. And, if the
4132 		 * number of huge pages for this default size was implicitly
4133 		 * specified, set that here as well.
4134 		 * Note that the implicit setting will overwrite an explicit
4135 		 * setting.  A warning will be printed in this case.
4136 		 */
4137 		default_hstate_idx = hstate_index(size_to_hstate(HPAGE_SIZE));
4138 		if (default_hstate_max_huge_pages) {
4139 			if (default_hstate.max_huge_pages) {
4140 				char buf[32];
4141 
4142 				string_get_size(huge_page_size(&default_hstate),
4143 					1, STRING_UNITS_2, buf, 32);
4144 				pr_warn("HugeTLB: Ignoring hugepages=%lu associated with %s page size\n",
4145 					default_hstate.max_huge_pages, buf);
4146 				pr_warn("HugeTLB: Using hugepages=%lu for number of default huge pages\n",
4147 					default_hstate_max_huge_pages);
4148 			}
4149 			default_hstate.max_huge_pages =
4150 				default_hstate_max_huge_pages;
4151 
4152 			for_each_online_node(i)
4153 				default_hstate.max_huge_pages_node[i] =
4154 					default_hugepages_in_node[i];
4155 		}
4156 	}
4157 
4158 	hugetlb_init_hstates();
4159 	report_hugepages();
4160 
4161 	hugetlb_sysfs_init();
4162 	hugetlb_cgroup_file_init();
4163 	hugetlb_sysctl_init();
4164 
4165 #ifdef CONFIG_SMP
4166 	num_fault_mutexes = roundup_pow_of_two(8 * num_possible_cpus());
4167 #else
4168 	num_fault_mutexes = 1;
4169 #endif
4170 	hugetlb_fault_mutex_table =
4171 		kmalloc_objs(struct mutex, num_fault_mutexes);
4172 	BUG_ON(!hugetlb_fault_mutex_table);
4173 
4174 	for (i = 0; i < num_fault_mutexes; i++)
4175 		mutex_init(&hugetlb_fault_mutex_table[i]);
4176 	return 0;
4177 }
4178 subsys_initcall(hugetlb_init);
4179 
4180 /* Overwritten by architectures with more huge page sizes */
4181 bool __init __attribute((weak)) arch_hugetlb_valid_size(unsigned long size)
4182 {
4183 	return size == HPAGE_SIZE;
4184 }
4185 
4186 void __init hugetlb_add_hstate(unsigned int order)
4187 {
4188 	struct hstate *h;
4189 	unsigned long i;
4190 
4191 	if (size_to_hstate(PAGE_SIZE << order)) {
4192 		return;
4193 	}
4194 	BUG_ON(hugetlb_max_hstate >= HUGE_MAX_HSTATE);
4195 	BUG_ON(order < order_base_2(__NR_USED_SUBPAGE));
4196 	WARN_ON(order > MAX_FOLIO_ORDER);
4197 	h = &hstates[hugetlb_max_hstate++];
4198 	__mutex_init(&h->resize_lock, "resize mutex", &h->resize_key);
4199 	h->order = order;
4200 	h->mask = ~(huge_page_size(h) - 1);
4201 	for (i = 0; i < MAX_NUMNODES; ++i)
4202 		INIT_LIST_HEAD(&h->hugepage_freelists[i]);
4203 	INIT_LIST_HEAD(&h->hugepage_activelist);
4204 	snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB",
4205 					huge_page_size(h)/SZ_1K);
4206 
4207 	parsed_hstate = h;
4208 }
4209 
4210 bool __init __weak hugetlb_node_alloc_supported(void)
4211 {
4212 	return true;
4213 }
4214 
4215 static void __init hugepages_clear_pages_in_node(void)
4216 {
4217 	if (!hugetlb_max_hstate) {
4218 		default_hstate_max_huge_pages = 0;
4219 		memset(default_hugepages_in_node, 0,
4220 			sizeof(default_hugepages_in_node));
4221 	} else {
4222 		parsed_hstate->max_huge_pages = 0;
4223 		memset(parsed_hstate->max_huge_pages_node, 0,
4224 			sizeof(parsed_hstate->max_huge_pages_node));
4225 	}
4226 }
4227 
4228 static __init int hugetlb_add_param(char *s, int (*setup)(char *))
4229 {
4230 	size_t len;
4231 	char *p;
4232 
4233 	if (!s)
4234 		return -EINVAL;
4235 
4236 	if (hugetlb_param_index >= HUGE_MAX_CMDLINE_ARGS)
4237 		return -EINVAL;
4238 
4239 	len = strlen(s) + 1;
4240 	if (len + hstate_cmdline_index > sizeof(hstate_cmdline_buf))
4241 		return -EINVAL;
4242 
4243 	p = &hstate_cmdline_buf[hstate_cmdline_index];
4244 	memcpy(p, s, len);
4245 	hstate_cmdline_index += len;
4246 
4247 	hugetlb_params[hugetlb_param_index].val = p;
4248 	hugetlb_params[hugetlb_param_index].setup = setup;
4249 
4250 	hugetlb_param_index++;
4251 
4252 	return 0;
4253 }
4254 
4255 static __init void hugetlb_parse_params(void)
4256 {
4257 	int i;
4258 	struct hugetlb_cmdline *hcp;
4259 
4260 	for (i = 0; i < hugetlb_param_index; i++) {
4261 		hcp = &hugetlb_params[i];
4262 
4263 		hcp->setup(hcp->val);
4264 	}
4265 
4266 	hugetlb_cma_validate_params();
4267 }
4268 
4269 /*
4270  * hugepages command line processing
4271  * hugepages normally follows a valid hugepagsz or default_hugepagsz
4272  * specification.  If not, ignore the hugepages value.  hugepages can also
4273  * be the first huge page command line  option in which case it implicitly
4274  * specifies the number of huge pages for the default size.
4275  */
4276 static int __init hugepages_setup(char *s)
4277 {
4278 	unsigned long *mhp;
4279 	static unsigned long *last_mhp;
4280 	int node = NUMA_NO_NODE;
4281 	int count;
4282 	unsigned long tmp;
4283 	char *p = s;
4284 
4285 	if (!hugepages_supported()) {
4286 		pr_warn("HugeTLB: hugepages unsupported, ignoring hugepages=%s cmdline\n", s);
4287 		return 0;
4288 	}
4289 
4290 	if (!parsed_valid_hugepagesz) {
4291 		pr_warn("HugeTLB: hugepages=%s does not follow a valid hugepagesz, ignoring\n", s);
4292 		parsed_valid_hugepagesz = true;
4293 		return -EINVAL;
4294 	}
4295 
4296 	/*
4297 	 * !hugetlb_max_hstate means we haven't parsed a hugepagesz= parameter
4298 	 * yet, so this hugepages= parameter goes to the "default hstate".
4299 	 * Otherwise, it goes with the previously parsed hugepagesz or
4300 	 * default_hugepagesz.
4301 	 */
4302 	else if (!hugetlb_max_hstate)
4303 		mhp = &default_hstate_max_huge_pages;
4304 	else
4305 		mhp = &parsed_hstate->max_huge_pages;
4306 
4307 	if (mhp == last_mhp) {
4308 		pr_warn("HugeTLB: hugepages= specified twice without interleaving hugepagesz=, ignoring hugepages=%s\n", s);
4309 		return 1;
4310 	}
4311 
4312 	while (*p) {
4313 		count = 0;
4314 		if (sscanf(p, "%lu%n", &tmp, &count) != 1)
4315 			goto invalid;
4316 		/* Parameter is node format */
4317 		if (p[count] == ':') {
4318 			if (!hugetlb_node_alloc_supported()) {
4319 				pr_warn("HugeTLB: architecture can't support node specific alloc, ignoring!\n");
4320 				return 1;
4321 			}
4322 			if (tmp >= MAX_NUMNODES || !node_online(tmp))
4323 				goto invalid;
4324 			node = array_index_nospec(tmp, MAX_NUMNODES);
4325 			p += count + 1;
4326 			/* Parse hugepages */
4327 			if (sscanf(p, "%lu%n", &tmp, &count) != 1)
4328 				goto invalid;
4329 			if (!hugetlb_max_hstate)
4330 				default_hugepages_in_node[node] = tmp;
4331 			else
4332 				parsed_hstate->max_huge_pages_node[node] = tmp;
4333 			*mhp += tmp;
4334 			/* Go to parse next node*/
4335 			if (p[count] == ',')
4336 				p += count + 1;
4337 			else
4338 				break;
4339 		} else {
4340 			if (p != s)
4341 				goto invalid;
4342 			*mhp = tmp;
4343 			break;
4344 		}
4345 	}
4346 
4347 	last_mhp = mhp;
4348 
4349 	return 0;
4350 
4351 invalid:
4352 	pr_warn("HugeTLB: Invalid hugepages parameter %s\n", p);
4353 	hugepages_clear_pages_in_node();
4354 	return -EINVAL;
4355 }
4356 hugetlb_early_param("hugepages", hugepages_setup);
4357 
4358 /*
4359  * hugepagesz command line processing
4360  * A specific huge page size can only be specified once with hugepagesz.
4361  * hugepagesz is followed by hugepages on the command line.  The global
4362  * variable 'parsed_valid_hugepagesz' is used to determine if prior
4363  * hugepagesz argument was valid.
4364  */
4365 static int __init hugepagesz_setup(char *s)
4366 {
4367 	unsigned long size;
4368 	struct hstate *h;
4369 
4370 	if (!hugepages_supported()) {
4371 		pr_warn("HugeTLB: hugepages unsupported, ignoring hugepagesz=%s cmdline\n", s);
4372 		return 0;
4373 	}
4374 
4375 	parsed_valid_hugepagesz = false;
4376 	size = (unsigned long)memparse(s, NULL);
4377 
4378 	if (!arch_hugetlb_valid_size(size)) {
4379 		pr_err("HugeTLB: unsupported hugepagesz=%s\n", s);
4380 		return -EINVAL;
4381 	}
4382 
4383 	h = size_to_hstate(size);
4384 	if (h) {
4385 		/*
4386 		 * hstate for this size already exists.  This is normally
4387 		 * an error, but is allowed if the existing hstate is the
4388 		 * default hstate.  More specifically, it is only allowed if
4389 		 * the number of huge pages for the default hstate was not
4390 		 * previously specified.
4391 		 */
4392 		if (!parsed_default_hugepagesz ||  h != &default_hstate ||
4393 		    default_hstate.max_huge_pages) {
4394 			pr_warn("HugeTLB: hugepagesz=%s specified twice, ignoring\n", s);
4395 			return -EINVAL;
4396 		}
4397 
4398 		/*
4399 		 * No need to call hugetlb_add_hstate() as hstate already
4400 		 * exists.  But, do set parsed_hstate so that a following
4401 		 * hugepages= parameter will be applied to this hstate.
4402 		 */
4403 		parsed_hstate = h;
4404 		parsed_valid_hugepagesz = true;
4405 		return 0;
4406 	}
4407 
4408 	hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
4409 	parsed_valid_hugepagesz = true;
4410 	return 0;
4411 }
4412 hugetlb_early_param("hugepagesz", hugepagesz_setup);
4413 
4414 /*
4415  * default_hugepagesz command line input
4416  * Only one instance of default_hugepagesz allowed on command line.
4417  */
4418 static int __init default_hugepagesz_setup(char *s)
4419 {
4420 	unsigned long size;
4421 	int i;
4422 
4423 	if (!hugepages_supported()) {
4424 		pr_warn("HugeTLB: hugepages unsupported, ignoring default_hugepagesz=%s cmdline\n",
4425 			s);
4426 		return 0;
4427 	}
4428 
4429 	parsed_valid_hugepagesz = false;
4430 	if (parsed_default_hugepagesz) {
4431 		pr_err("HugeTLB: default_hugepagesz previously specified, ignoring %s\n", s);
4432 		return -EINVAL;
4433 	}
4434 
4435 	size = (unsigned long)memparse(s, NULL);
4436 
4437 	if (!arch_hugetlb_valid_size(size)) {
4438 		pr_err("HugeTLB: unsupported default_hugepagesz=%s\n", s);
4439 		return -EINVAL;
4440 	}
4441 
4442 	hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
4443 	parsed_valid_hugepagesz = true;
4444 	parsed_default_hugepagesz = true;
4445 	default_hstate_idx = hstate_index(size_to_hstate(size));
4446 
4447 	/*
4448 	 * The number of default huge pages (for this size) could have been
4449 	 * specified as the first hugetlb parameter: hugepages=X.  If so,
4450 	 * then default_hstate_max_huge_pages is set.  If the default huge
4451 	 * page size is gigantic (> MAX_PAGE_ORDER), then the pages must be
4452 	 * allocated here from bootmem allocator.
4453 	 */
4454 	if (default_hstate_max_huge_pages) {
4455 		default_hstate.max_huge_pages = default_hstate_max_huge_pages;
4456 		/*
4457 		 * Since this is an early parameter, we can't check
4458 		 * NUMA node state yet, so loop through MAX_NUMNODES.
4459 		 */
4460 		for (i = 0; i < MAX_NUMNODES; i++) {
4461 			if (default_hugepages_in_node[i] != 0)
4462 				default_hstate.max_huge_pages_node[i] =
4463 					default_hugepages_in_node[i];
4464 		}
4465 		default_hstate_max_huge_pages = 0;
4466 	}
4467 
4468 	return 0;
4469 }
4470 hugetlb_early_param("default_hugepagesz", default_hugepagesz_setup);
4471 
4472 void __init hugetlb_bootmem_set_nodes(void)
4473 {
4474 	int i, nid;
4475 
4476 	if (!nodes_empty(hugetlb_bootmem_nodes))
4477 		return;
4478 
4479 	for_each_mem_pfn_range(i, MAX_NUMNODES, NULL, NULL, &nid)
4480 		node_set(nid, hugetlb_bootmem_nodes);
4481 }
4482 
4483 void __init hugetlb_bootmem_alloc(void)
4484 {
4485 	struct hstate *h;
4486 	int i;
4487 
4488 	hugetlb_bootmem_set_nodes();
4489 
4490 	for (i = 0; i < MAX_NUMNODES; i++)
4491 		INIT_LIST_HEAD(&huge_boot_pages[i]);
4492 
4493 	hugetlb_parse_params();
4494 
4495 	for_each_hstate(h) {
4496 		h->next_nid_to_alloc = first_online_node;
4497 
4498 		if (hstate_is_gigantic(h))
4499 			hugetlb_hstate_alloc_pages(h);
4500 	}
4501 }
4502 
4503 /*
4504  * hugepage_alloc_threads command line parsing.
4505  *
4506  * When set, use this specific number of threads for the boot
4507  * allocation of hugepages.
4508  */
4509 static int __init hugepage_alloc_threads_setup(char *s)
4510 {
4511 	unsigned long allocation_threads;
4512 
4513 	if (kstrtoul(s, 0, &allocation_threads) != 0)
4514 		return 1;
4515 
4516 	if (allocation_threads == 0)
4517 		return 1;
4518 
4519 	hugepage_allocation_threads = allocation_threads;
4520 
4521 	return 1;
4522 }
4523 __setup("hugepage_alloc_threads=", hugepage_alloc_threads_setup);
4524 
4525 static unsigned int allowed_mems_nr(struct hstate *h)
4526 {
4527 	int node;
4528 	unsigned int nr = 0;
4529 	nodemask_t *mbind_nodemask;
4530 	unsigned int *array = h->free_huge_pages_node;
4531 	gfp_t gfp_mask = htlb_alloc_mask(h);
4532 
4533 	mbind_nodemask = policy_mbind_nodemask(gfp_mask);
4534 	for_each_node_mask(node, cpuset_current_mems_allowed) {
4535 		if (!mbind_nodemask || node_isset(node, *mbind_nodemask))
4536 			nr += array[node];
4537 	}
4538 
4539 	return nr;
4540 }
4541 
4542 void hugetlb_report_meminfo(struct seq_file *m)
4543 {
4544 	struct hstate *h;
4545 	unsigned long total = 0;
4546 
4547 	if (!hugepages_supported())
4548 		return;
4549 
4550 	for_each_hstate(h) {
4551 		unsigned long count = h->nr_huge_pages;
4552 
4553 		total += huge_page_size(h) * count;
4554 
4555 		if (h == &default_hstate)
4556 			seq_printf(m,
4557 				   "HugePages_Total:   %5lu\n"
4558 				   "HugePages_Free:    %5lu\n"
4559 				   "HugePages_Rsvd:    %5lu\n"
4560 				   "HugePages_Surp:    %5lu\n"
4561 				   "Hugepagesize:   %8lu kB\n",
4562 				   count,
4563 				   h->free_huge_pages,
4564 				   h->resv_huge_pages,
4565 				   h->surplus_huge_pages,
4566 				   huge_page_size(h) / SZ_1K);
4567 	}
4568 
4569 	seq_printf(m, "Hugetlb:        %8lu kB\n", total / SZ_1K);
4570 }
4571 
4572 int hugetlb_report_node_meminfo(char *buf, int len, int nid)
4573 {
4574 	struct hstate *h = &default_hstate;
4575 
4576 	if (!hugepages_supported())
4577 		return 0;
4578 
4579 	return sysfs_emit_at(buf, len,
4580 			     "Node %d HugePages_Total: %5u\n"
4581 			     "Node %d HugePages_Free:  %5u\n"
4582 			     "Node %d HugePages_Surp:  %5u\n",
4583 			     nid, h->nr_huge_pages_node[nid],
4584 			     nid, h->free_huge_pages_node[nid],
4585 			     nid, h->surplus_huge_pages_node[nid]);
4586 }
4587 
4588 void hugetlb_show_meminfo_node(int nid)
4589 {
4590 	struct hstate *h;
4591 
4592 	if (!hugepages_supported())
4593 		return;
4594 
4595 	for_each_hstate(h)
4596 		printk("Node %d hugepages_total=%u hugepages_free=%u hugepages_surp=%u hugepages_size=%lukB\n",
4597 			nid,
4598 			h->nr_huge_pages_node[nid],
4599 			h->free_huge_pages_node[nid],
4600 			h->surplus_huge_pages_node[nid],
4601 			huge_page_size(h) / SZ_1K);
4602 }
4603 
4604 void hugetlb_report_usage(struct seq_file *m, struct mm_struct *mm)
4605 {
4606 	seq_printf(m, "HugetlbPages:\t%8lu kB\n",
4607 		   K(atomic_long_read(&mm->hugetlb_usage)));
4608 }
4609 
4610 /* Return the number pages of memory we physically have, in PAGE_SIZE units. */
4611 unsigned long hugetlb_total_pages(void)
4612 {
4613 	struct hstate *h;
4614 	unsigned long nr_total_pages = 0;
4615 
4616 	for_each_hstate(h)
4617 		nr_total_pages += h->nr_huge_pages * pages_per_huge_page(h);
4618 	return nr_total_pages;
4619 }
4620 
4621 static int hugetlb_acct_memory(struct hstate *h, long delta)
4622 {
4623 	int ret = -ENOMEM;
4624 
4625 	if (!delta)
4626 		return 0;
4627 
4628 	spin_lock_irq(&hugetlb_lock);
4629 	/*
4630 	 * When cpuset is configured, it breaks the strict hugetlb page
4631 	 * reservation as the accounting is done on a global variable. Such
4632 	 * reservation is completely rubbish in the presence of cpuset because
4633 	 * the reservation is not checked against page availability for the
4634 	 * current cpuset. Application can still potentially OOM'ed by kernel
4635 	 * with lack of free htlb page in cpuset that the task is in.
4636 	 * Attempt to enforce strict accounting with cpuset is almost
4637 	 * impossible (or too ugly) because cpuset is too fluid that
4638 	 * task or memory node can be dynamically moved between cpusets.
4639 	 *
4640 	 * The change of semantics for shared hugetlb mapping with cpuset is
4641 	 * undesirable. However, in order to preserve some of the semantics,
4642 	 * we fall back to check against current free page availability as
4643 	 * a best attempt and hopefully to minimize the impact of changing
4644 	 * semantics that cpuset has.
4645 	 *
4646 	 * Apart from cpuset, we also have memory policy mechanism that
4647 	 * also determines from which node the kernel will allocate memory
4648 	 * in a NUMA system. So similar to cpuset, we also should consider
4649 	 * the memory policy of the current task. Similar to the description
4650 	 * above.
4651 	 */
4652 	if (delta > 0) {
4653 		if (gather_surplus_pages(h, delta) < 0)
4654 			goto out;
4655 
4656 		if (delta > allowed_mems_nr(h)) {
4657 			return_unused_surplus_pages(h, delta);
4658 			goto out;
4659 		}
4660 	}
4661 
4662 	ret = 0;
4663 	if (delta < 0)
4664 		return_unused_surplus_pages(h, (unsigned long) -delta);
4665 
4666 out:
4667 	spin_unlock_irq(&hugetlb_lock);
4668 	return ret;
4669 }
4670 
4671 static void hugetlb_vm_op_open(struct vm_area_struct *vma)
4672 {
4673 	struct resv_map *resv = vma_resv_map(vma);
4674 
4675 	/*
4676 	 * HPAGE_RESV_OWNER indicates a private mapping.
4677 	 * This new VMA should share its siblings reservation map if present.
4678 	 * The VMA will only ever have a valid reservation map pointer where
4679 	 * it is being copied for another still existing VMA.  As that VMA
4680 	 * has a reference to the reservation map it cannot disappear until
4681 	 * after this open call completes.  It is therefore safe to take a
4682 	 * new reference here without additional locking.
4683 	 */
4684 	if (resv && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
4685 		resv_map_dup_hugetlb_cgroup_uncharge_info(resv);
4686 		kref_get(&resv->refs);
4687 	}
4688 
4689 	/*
4690 	 * vma_lock structure for sharable mappings is vma specific.
4691 	 * Clear old pointer (if copied via vm_area_dup) and allocate
4692 	 * new structure.  Before clearing, make sure vma_lock is not
4693 	 * for this vma.
4694 	 */
4695 	if (vma->vm_flags & VM_MAYSHARE) {
4696 		struct hugetlb_vma_lock *vma_lock = vma->vm_private_data;
4697 
4698 		if (vma_lock) {
4699 			if (vma_lock->vma != vma) {
4700 				vma->vm_private_data = NULL;
4701 				hugetlb_vma_lock_alloc(vma);
4702 			} else {
4703 				pr_warn("HugeTLB: vma_lock already exists in %s.\n", __func__);
4704 			}
4705 		} else {
4706 			hugetlb_vma_lock_alloc(vma);
4707 		}
4708 	}
4709 }
4710 
4711 static void hugetlb_vm_op_close(struct vm_area_struct *vma)
4712 {
4713 	struct hstate *h = hstate_vma(vma);
4714 	struct resv_map *resv;
4715 	struct hugepage_subpool *spool = subpool_vma(vma);
4716 	unsigned long reserve, start, end;
4717 	long gbl_reserve;
4718 
4719 	hugetlb_vma_lock_free(vma);
4720 
4721 	resv = vma_resv_map(vma);
4722 	if (!resv || !is_vma_resv_set(vma, HPAGE_RESV_OWNER))
4723 		return;
4724 
4725 	start = vma_hugecache_offset(h, vma, vma->vm_start);
4726 	end = vma_hugecache_offset(h, vma, vma->vm_end);
4727 
4728 	reserve = (end - start) - region_count(resv, start, end);
4729 	hugetlb_cgroup_uncharge_counter(resv, start, end);
4730 	if (reserve) {
4731 		/*
4732 		 * Decrement reserve counts.  The global reserve count may be
4733 		 * adjusted if the subpool has a minimum size.
4734 		 */
4735 		gbl_reserve = hugepage_subpool_put_pages(spool, reserve);
4736 		hugetlb_acct_memory(h, -gbl_reserve);
4737 	}
4738 
4739 	kref_put(&resv->refs, resv_map_release);
4740 }
4741 
4742 static int hugetlb_vm_op_split(struct vm_area_struct *vma, unsigned long addr)
4743 {
4744 	if (addr & ~(huge_page_mask(hstate_vma(vma))))
4745 		return -EINVAL;
4746 	return 0;
4747 }
4748 
4749 void hugetlb_split(struct vm_area_struct *vma, unsigned long addr)
4750 {
4751 	/*
4752 	 * PMD sharing is only possible for PUD_SIZE-aligned address ranges
4753 	 * in HugeTLB VMAs. If we will lose PUD_SIZE alignment due to this
4754 	 * split, unshare PMDs in the PUD_SIZE interval surrounding addr now.
4755 	 * This function is called in the middle of a VMA split operation, with
4756 	 * MM, VMA and rmap all write-locked to prevent concurrent page table
4757 	 * walks (except hardware and gup_fast()).
4758 	 */
4759 	vma_assert_write_locked(vma);
4760 	i_mmap_assert_write_locked(vma->vm_file->f_mapping);
4761 
4762 	if (addr & ~PUD_MASK) {
4763 		unsigned long floor = addr & PUD_MASK;
4764 		unsigned long ceil = floor + PUD_SIZE;
4765 
4766 		if (floor >= vma->vm_start && ceil <= vma->vm_end) {
4767 			/*
4768 			 * Locking:
4769 			 * Use take_locks=false here.
4770 			 * The file rmap lock is already held.
4771 			 * The hugetlb VMA lock can't be taken when we already
4772 			 * hold the file rmap lock, and we don't need it because
4773 			 * its purpose is to synchronize against concurrent page
4774 			 * table walks, which are not possible thanks to the
4775 			 * locks held by our caller.
4776 			 */
4777 			hugetlb_unshare_pmds(vma, floor, ceil, /* take_locks = */ false);
4778 		}
4779 	}
4780 }
4781 
4782 static unsigned long hugetlb_vm_op_pagesize(struct vm_area_struct *vma)
4783 {
4784 	return huge_page_size(hstate_vma(vma));
4785 }
4786 
4787 /*
4788  * We cannot handle pagefaults against hugetlb pages at all.  They cause
4789  * handle_mm_fault() to try to instantiate regular-sized pages in the
4790  * hugepage VMA.  do_page_fault() is supposed to trap this, so BUG is we get
4791  * this far.
4792  */
4793 static vm_fault_t hugetlb_vm_op_fault(struct vm_fault *vmf)
4794 {
4795 	BUG();
4796 	return 0;
4797 }
4798 
4799 #ifdef CONFIG_USERFAULTFD
4800 static bool hugetlb_can_userfault(struct vm_area_struct *vma,
4801 				  vm_flags_t vm_flags)
4802 {
4803 	return true;
4804 }
4805 
4806 static const struct vm_uffd_ops hugetlb_uffd_ops = {
4807 	.can_userfault = hugetlb_can_userfault,
4808 };
4809 #endif
4810 
4811 /*
4812  * When a new function is introduced to vm_operations_struct and added
4813  * to hugetlb_vm_ops, please consider adding the function to shm_vm_ops.
4814  * This is because under System V memory model, mappings created via
4815  * shmget/shmat with "huge page" specified are backed by hugetlbfs files,
4816  * their original vm_ops are overwritten with shm_vm_ops.
4817  */
4818 const struct vm_operations_struct hugetlb_vm_ops = {
4819 	.fault = hugetlb_vm_op_fault,
4820 	.open = hugetlb_vm_op_open,
4821 	.close = hugetlb_vm_op_close,
4822 	.may_split = hugetlb_vm_op_split,
4823 	.pagesize = hugetlb_vm_op_pagesize,
4824 #ifdef CONFIG_USERFAULTFD
4825 	.uffd_ops = &hugetlb_uffd_ops,
4826 #endif
4827 };
4828 
4829 static pte_t make_huge_pte(struct vm_area_struct *vma, struct folio *folio,
4830 		bool try_mkwrite)
4831 {
4832 	pte_t entry = folio_mk_pte(folio, vma->vm_page_prot);
4833 	unsigned int shift = huge_page_shift(hstate_vma(vma));
4834 
4835 	if (try_mkwrite && (vma->vm_flags & VM_WRITE)) {
4836 		entry = pte_mkwrite_novma(pte_mkdirty(entry));
4837 	} else {
4838 		entry = pte_wrprotect(entry);
4839 	}
4840 	entry = pte_mkyoung(entry);
4841 	entry = arch_make_huge_pte(entry, shift, vma->vm_flags);
4842 
4843 	return entry;
4844 }
4845 
4846 static void set_huge_ptep_writable(struct vm_area_struct *vma,
4847 				   unsigned long address, pte_t *ptep)
4848 {
4849 	pte_t entry;
4850 
4851 	entry = huge_pte_mkwrite(huge_pte_mkdirty(huge_ptep_get(vma->vm_mm, address, ptep)));
4852 	if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1))
4853 		update_mmu_cache(vma, address, ptep);
4854 }
4855 
4856 static void set_huge_ptep_maybe_writable(struct vm_area_struct *vma,
4857 					 unsigned long address, pte_t *ptep)
4858 {
4859 	if (vma->vm_flags & VM_WRITE)
4860 		set_huge_ptep_writable(vma, address, ptep);
4861 }
4862 
4863 static void
4864 hugetlb_install_folio(struct vm_area_struct *vma, pte_t *ptep, unsigned long addr,
4865 		      struct folio *new_folio, pte_t old, unsigned long sz)
4866 {
4867 	pte_t newpte = make_huge_pte(vma, new_folio, true);
4868 
4869 	__folio_mark_uptodate(new_folio);
4870 	hugetlb_add_new_anon_rmap(new_folio, vma, addr);
4871 	if (userfaultfd_protected(vma) && huge_pte_uffd(old)) {
4872 		newpte = huge_pte_mkuffd(newpte);
4873 		/* Restore PAGE_NONE so the RWP marker keeps trapping. */
4874 		if (userfaultfd_rwp(vma)) {
4875 			unsigned int shift = huge_page_shift(hstate_vma(vma));
4876 
4877 			newpte = huge_pte_modify(newpte, PAGE_NONE);
4878 			newpte = arch_make_huge_pte(newpte, shift, vma->vm_flags);
4879 		}
4880 	}
4881 	set_huge_pte_at(vma->vm_mm, addr, ptep, newpte, sz);
4882 	hugetlb_count_add(pages_per_huge_page(hstate_vma(vma)), vma->vm_mm);
4883 	folio_set_hugetlb_migratable(new_folio);
4884 }
4885 
4886 int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src,
4887 			    struct vm_area_struct *dst_vma,
4888 			    struct vm_area_struct *src_vma)
4889 {
4890 	pte_t *src_pte, *dst_pte, entry;
4891 	struct folio *pte_folio;
4892 	unsigned long addr;
4893 	bool cow = vma_is_cow_mapping(src_vma);
4894 	struct hstate *h = hstate_vma(src_vma);
4895 	unsigned long sz = huge_page_size(h);
4896 	unsigned long npages = pages_per_huge_page(h);
4897 	struct mmu_notifier_range range;
4898 	unsigned long last_addr_mask;
4899 	softleaf_t softleaf;
4900 	int ret = 0;
4901 
4902 	if (cow) {
4903 		mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, src,
4904 					src_vma->vm_start,
4905 					src_vma->vm_end);
4906 		mmu_notifier_invalidate_range_start(&range);
4907 		vma_assert_write_locked(src_vma);
4908 		raw_write_seqcount_begin(&src->write_protect_seq);
4909 	} else {
4910 		/*
4911 		 * For shared mappings the vma lock must be held before
4912 		 * calling hugetlb_walk() in the src vma. Otherwise, the
4913 		 * returned ptep could go away if part of a shared pmd and
4914 		 * another thread calls huge_pmd_unshare.
4915 		 */
4916 		hugetlb_vma_lock_read(src_vma);
4917 	}
4918 
4919 	last_addr_mask = hugetlb_mask_last_page(h);
4920 	for (addr = src_vma->vm_start; addr < src_vma->vm_end; addr += sz) {
4921 		spinlock_t *src_ptl, *dst_ptl;
4922 		src_pte = hugetlb_walk(src_vma, addr, sz);
4923 		if (!src_pte) {
4924 			addr |= last_addr_mask;
4925 			continue;
4926 		}
4927 		dst_pte = huge_pte_alloc(dst, dst_vma, addr, sz);
4928 		if (!dst_pte) {
4929 			ret = -ENOMEM;
4930 			break;
4931 		}
4932 
4933 #ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING
4934 		/* If the pagetables are shared, there is nothing to do */
4935 		if (ptdesc_pmd_is_shared(virt_to_ptdesc(dst_pte))) {
4936 			addr |= last_addr_mask;
4937 			continue;
4938 		}
4939 #endif
4940 
4941 		dst_ptl = huge_pte_lock(h, dst, dst_pte);
4942 		src_ptl = huge_pte_lockptr(h, src, src_pte);
4943 		spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
4944 		entry = huge_ptep_get(src_vma->vm_mm, addr, src_pte);
4945 again:
4946 		if (huge_pte_none(entry)) {
4947 			/* Skip if src entry none. */
4948 			goto next;
4949 		}
4950 
4951 		softleaf = softleaf_from_pte(entry);
4952 		if (unlikely(softleaf_is_hwpoison(softleaf))) {
4953 			/*
4954 			 * A hwpoison entry never carries the uffd-wp bit: it is
4955 			 * installed fresh by make_hwpoison_entry() and
4956 			 * hugetlb_change_protection() leaves it untouched, so
4957 			 * there is nothing to clear for the child.
4958 			 */
4959 			set_huge_pte_at(dst, addr, dst_pte, entry, sz);
4960 		} else if (unlikely(softleaf_is_migration(softleaf))) {
4961 			bool uffd = pte_swp_uffd(entry);
4962 
4963 			if (!softleaf_is_migration_read(softleaf) && cow) {
4964 				/*
4965 				 * COW mappings require pages in both
4966 				 * parent and child to be set to read.
4967 				 */
4968 				softleaf = make_readable_migration_entry(
4969 							swp_offset(softleaf));
4970 				entry = swp_entry_to_pte(softleaf);
4971 				if (userfaultfd_protected(src_vma) && uffd)
4972 					entry = pte_swp_mkuffd(entry);
4973 				set_huge_pte_at(src, addr, src_pte, entry, sz);
4974 			}
4975 			if (!userfaultfd_protected(dst_vma))
4976 				entry = pte_swp_clear_uffd(entry);
4977 			set_huge_pte_at(dst, addr, dst_pte, entry, sz);
4978 		} else if (unlikely(pte_is_marker(entry))) {
4979 			const pte_marker marker = copy_pte_marker(softleaf, dst_vma);
4980 
4981 			if (marker)
4982 				set_huge_pte_at(dst, addr, dst_pte,
4983 						make_pte_marker(marker), sz);
4984 		} else {
4985 			entry = huge_ptep_get(src_vma->vm_mm, addr, src_pte);
4986 			pte_folio = page_folio(pte_page(entry));
4987 			folio_get(pte_folio);
4988 
4989 			/*
4990 			 * Failing to duplicate the anon rmap is a rare case
4991 			 * where we see pinned hugetlb pages while they're
4992 			 * prone to COW. We need to do the COW earlier during
4993 			 * fork.
4994 			 *
4995 			 * When pre-allocating the page or copying data, we
4996 			 * need to be without the pgtable locks since we could
4997 			 * sleep during the process.
4998 			 */
4999 			if (!folio_test_anon(pte_folio)) {
5000 				hugetlb_add_file_rmap(pte_folio);
5001 			} else if (hugetlb_try_dup_anon_rmap(pte_folio, src_vma)) {
5002 				pte_t src_pte_old = entry;
5003 				struct folio *new_folio;
5004 
5005 				spin_unlock(src_ptl);
5006 				spin_unlock(dst_ptl);
5007 				/* Do not use reserve as it's private owned */
5008 				new_folio = alloc_hugetlb_folio(dst_vma, addr, false);
5009 				if (IS_ERR(new_folio)) {
5010 					folio_put(pte_folio);
5011 					ret = PTR_ERR(new_folio);
5012 					break;
5013 				}
5014 				ret = copy_user_large_folio(new_folio, pte_folio,
5015 							    addr, dst_vma);
5016 				folio_put(pte_folio);
5017 				if (ret) {
5018 					restore_reserve_on_error(h, dst_vma, addr, new_folio);
5019 					folio_put(new_folio);
5020 					break;
5021 				}
5022 
5023 				/* Install the new hugetlb folio if src pte stable */
5024 				dst_ptl = huge_pte_lock(h, dst, dst_pte);
5025 				src_ptl = huge_pte_lockptr(h, src, src_pte);
5026 				spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
5027 				entry = huge_ptep_get(src_vma->vm_mm, addr, src_pte);
5028 				if (!pte_same(src_pte_old, entry)) {
5029 					restore_reserve_on_error(h, dst_vma, addr,
5030 								new_folio);
5031 					folio_put(new_folio);
5032 					/* huge_ptep of dst_pte won't change as in child */
5033 					goto again;
5034 				}
5035 				hugetlb_install_folio(dst_vma, dst_pte, addr,
5036 						      new_folio, src_pte_old, sz);
5037 				goto next;
5038 			}
5039 
5040 			/* See __copy_present_ptes(): restore accessible protection. */
5041 			if (!userfaultfd_protected(dst_vma)) {
5042 				if (userfaultfd_rwp(src_vma) && huge_pte_uffd(entry)) {
5043 					entry = huge_pte_modify(entry, dst_vma->vm_page_prot);
5044 					entry = arch_make_huge_pte(entry, huge_page_shift(h),
5045 								   dst_vma->vm_flags);
5046 				}
5047 				entry = huge_pte_clear_uffd(entry);
5048 			}
5049 
5050 			if (cow) {
5051 				/*
5052 				 * No need to notify as we are downgrading page
5053 				 * table protection not changing it to point
5054 				 * to a new page.
5055 				 *
5056 				 * See Documentation/mm/mmu_notifier.rst
5057 				 */
5058 				huge_ptep_set_wrprotect(src, addr, src_pte);
5059 				entry = huge_pte_wrprotect(entry);
5060 			}
5061 
5062 			set_huge_pte_at(dst, addr, dst_pte, entry, sz);
5063 			hugetlb_count_add(npages, dst);
5064 		}
5065 
5066 next:
5067 		spin_unlock(src_ptl);
5068 		spin_unlock(dst_ptl);
5069 	}
5070 
5071 	if (cow) {
5072 		raw_write_seqcount_end(&src->write_protect_seq);
5073 		mmu_notifier_invalidate_range_end(&range);
5074 	} else {
5075 		hugetlb_vma_unlock_read(src_vma);
5076 	}
5077 
5078 	return ret;
5079 }
5080 
5081 static void move_huge_pte(struct vm_area_struct *vma, unsigned long old_addr,
5082 			  unsigned long new_addr, pte_t *src_pte, pte_t *dst_pte,
5083 			  unsigned long sz)
5084 {
5085 	bool need_clear_uffd_wp = vma_has_uffd_without_event_remap(vma);
5086 	struct hstate *h = hstate_vma(vma);
5087 	struct mm_struct *mm = vma->vm_mm;
5088 	spinlock_t *src_ptl, *dst_ptl;
5089 	pte_t pte;
5090 
5091 	dst_ptl = huge_pte_lock(h, mm, dst_pte);
5092 	src_ptl = huge_pte_lockptr(h, mm, src_pte);
5093 
5094 	/*
5095 	 * We don't have to worry about the ordering of src and dst ptlocks
5096 	 * because exclusive mmap_lock (or the i_mmap_lock) prevents deadlock.
5097 	 */
5098 	if (src_ptl != dst_ptl)
5099 		spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
5100 
5101 	pte = huge_ptep_get_and_clear(mm, old_addr, src_pte, sz);
5102 
5103 	if (need_clear_uffd_wp && pte_is_uffd_wp_marker(pte)) {
5104 		huge_pte_clear(mm, new_addr, dst_pte, sz);
5105 	} else {
5106 		if (need_clear_uffd_wp) {
5107 			if (pte_present(pte)) {
5108 				/*
5109 				 * See __copy_present_ptes(): normalise the RWP
5110 				 * marker so the destination starts accessible
5111 				 * instead of taking a numa-hinting fault on
5112 				 * first access. Only the marker (protnone + uffd)
5113 				 * needs it; leave other present PTEs untouched.
5114 				 */
5115 				if (userfaultfd_rwp(vma) && huge_pte_uffd(pte)) {
5116 					pte = huge_pte_modify(pte, vma->vm_page_prot);
5117 					pte = arch_make_huge_pte(pte, huge_page_shift(h),
5118 								 vma->vm_flags);
5119 				}
5120 				pte = huge_pte_clear_uffd(pte);
5121 			} else {
5122 				pte = pte_swp_clear_uffd(pte);
5123 			}
5124 		}
5125 		set_huge_pte_at(mm, new_addr, dst_pte, pte, sz);
5126 	}
5127 
5128 	if (src_ptl != dst_ptl)
5129 		spin_unlock(src_ptl);
5130 	spin_unlock(dst_ptl);
5131 }
5132 
5133 int move_hugetlb_page_tables(struct vm_area_struct *vma,
5134 			     struct vm_area_struct *new_vma,
5135 			     unsigned long old_addr, unsigned long new_addr,
5136 			     unsigned long len)
5137 {
5138 	struct hstate *h = hstate_vma(vma);
5139 	struct address_space *mapping = vma->vm_file->f_mapping;
5140 	unsigned long sz = huge_page_size(h);
5141 	struct mm_struct *mm = vma->vm_mm;
5142 	unsigned long old_end = old_addr + len;
5143 	unsigned long last_addr_mask;
5144 	pte_t *src_pte, *dst_pte;
5145 	struct mmu_notifier_range range;
5146 	struct mmu_gather tlb;
5147 
5148 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, old_addr,
5149 				old_end);
5150 	adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
5151 	/*
5152 	 * In case of shared PMDs, we should cover the maximum possible
5153 	 * range.
5154 	 */
5155 	flush_cache_range(vma, range.start, range.end);
5156 	tlb_gather_mmu_vma(&tlb, vma);
5157 
5158 	mmu_notifier_invalidate_range_start(&range);
5159 	last_addr_mask = hugetlb_mask_last_page(h);
5160 	/* Prevent race with file truncation */
5161 	hugetlb_vma_lock_write(vma);
5162 	i_mmap_lock_write(mapping);
5163 	for (; old_addr < old_end; old_addr += sz, new_addr += sz) {
5164 		src_pte = hugetlb_walk(vma, old_addr, sz);
5165 		if (!src_pte) {
5166 			old_addr |= last_addr_mask;
5167 			new_addr |= last_addr_mask;
5168 			continue;
5169 		}
5170 		if (huge_pte_none(huge_ptep_get(mm, old_addr, src_pte)))
5171 			continue;
5172 
5173 		if (huge_pmd_unshare(&tlb, vma, old_addr, src_pte)) {
5174 			old_addr |= last_addr_mask;
5175 			new_addr |= last_addr_mask;
5176 			continue;
5177 		}
5178 
5179 		dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz);
5180 		if (!dst_pte)
5181 			break;
5182 
5183 		move_huge_pte(vma, old_addr, new_addr, src_pte, dst_pte, sz);
5184 		tlb_remove_huge_tlb_entry(h, &tlb, src_pte, old_addr);
5185 	}
5186 
5187 	tlb_flush_mmu_tlbonly(&tlb);
5188 	huge_pmd_unshare_flush(&tlb, vma);
5189 
5190 	mmu_notifier_invalidate_range_end(&range);
5191 	i_mmap_unlock_write(mapping);
5192 	hugetlb_vma_unlock_write(vma);
5193 	tlb_finish_mmu(&tlb);
5194 
5195 	return len + old_addr - old_end;
5196 }
5197 
5198 void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
5199 			    unsigned long start, unsigned long end,
5200 			    struct folio *folio, zap_flags_t zap_flags)
5201 {
5202 	struct mm_struct *mm = vma->vm_mm;
5203 	const bool folio_provided = !!folio;
5204 	unsigned long address;
5205 	pte_t *ptep;
5206 	pte_t pte;
5207 	spinlock_t *ptl;
5208 	struct hstate *h = hstate_vma(vma);
5209 	unsigned long sz = huge_page_size(h);
5210 	bool adjust_reservation;
5211 	unsigned long last_addr_mask;
5212 
5213 	i_mmap_assert_write_locked(vma->vm_file->f_mapping);
5214 	WARN_ON(!is_vm_hugetlb_page(vma));
5215 	BUG_ON(start & ~huge_page_mask(h));
5216 	BUG_ON(end & ~huge_page_mask(h));
5217 
5218 	/*
5219 	 * This is a hugetlb vma, all the pte entries should point
5220 	 * to huge page.
5221 	 */
5222 	tlb_change_page_size(tlb, sz);
5223 	tlb_start_vma(tlb, vma);
5224 
5225 	last_addr_mask = hugetlb_mask_last_page(h);
5226 	address = start;
5227 	for (; address < end; address += sz) {
5228 		ptep = hugetlb_walk(vma, address, sz);
5229 		if (!ptep) {
5230 			address |= last_addr_mask;
5231 			continue;
5232 		}
5233 
5234 		ptl = huge_pte_lock(h, mm, ptep);
5235 		if (huge_pmd_unshare(tlb, vma, address, ptep)) {
5236 			spin_unlock(ptl);
5237 			address |= last_addr_mask;
5238 			continue;
5239 		}
5240 
5241 		pte = huge_ptep_get(mm, address, ptep);
5242 		if (huge_pte_none(pte)) {
5243 			spin_unlock(ptl);
5244 			continue;
5245 		}
5246 
5247 		/*
5248 		 * Migrating hugepage or HWPoisoned hugepage is already
5249 		 * unmapped and its refcount is dropped, so just clear pte here.
5250 		 */
5251 		if (unlikely(!pte_present(pte))) {
5252 			/*
5253 			 * If the pte was wr-protected by uffd-wp in any of the
5254 			 * swap forms, meanwhile the caller does not want to
5255 			 * drop the uffd-wp bit in this zap, then replace the
5256 			 * pte with a marker.
5257 			 */
5258 			if (pte_swp_uffd_any(pte) &&
5259 			    !(zap_flags & ZAP_FLAG_DROP_MARKER))
5260 				set_huge_pte_at(mm, address, ptep,
5261 						make_pte_marker(PTE_MARKER_UFFD_WP),
5262 						sz);
5263 			else
5264 				huge_pte_clear(mm, address, ptep, sz);
5265 			spin_unlock(ptl);
5266 			continue;
5267 		}
5268 
5269 		/*
5270 		 * If a folio is supplied, it is because a specific
5271 		 * folio is being unmapped, not a range. Ensure the folio we
5272 		 * are about to unmap is the actual folio of interest.
5273 		 */
5274 		if (folio_provided) {
5275 			if (folio != page_folio(pte_page(pte))) {
5276 				spin_unlock(ptl);
5277 				continue;
5278 			}
5279 			/*
5280 			 * Mark the VMA as having unmapped its page so that
5281 			 * future faults in this VMA will fail rather than
5282 			 * looking like data was lost
5283 			 */
5284 			set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED);
5285 		} else {
5286 			folio = page_folio(pte_page(pte));
5287 		}
5288 
5289 		pte = huge_ptep_get_and_clear(mm, address, ptep, sz);
5290 		tlb_remove_huge_tlb_entry(h, tlb, ptep, address);
5291 		if (huge_pte_dirty(pte))
5292 			folio_mark_dirty(folio);
5293 		/* Leave a uffd-wp pte marker if needed */
5294 		if (huge_pte_uffd(pte) &&
5295 		    !(zap_flags & ZAP_FLAG_DROP_MARKER))
5296 			set_huge_pte_at(mm, address, ptep,
5297 					make_pte_marker(PTE_MARKER_UFFD_WP),
5298 					sz);
5299 		hugetlb_count_sub(pages_per_huge_page(h), mm);
5300 		hugetlb_remove_rmap(folio);
5301 		spin_unlock(ptl);
5302 
5303 		/*
5304 		 * Restore the reservation for anonymous page, otherwise the
5305 		 * backing page could be stolen by someone. Restore only on the
5306 		 * last unmap, otherwise the owner could empty its resv map
5307 		 * while the folio is still mapped by a child. Note that holding
5308 		 * i_mmap_lock_write is needed to check the number of mappings.
5309 		 * If there we are freeing a surplus, do not set the restore
5310 		 * reservation bit.
5311 		 */
5312 		adjust_reservation = false;
5313 
5314 		spin_lock_irq(&hugetlb_lock);
5315 		if (!h->surplus_huge_pages && __vma_private_lock(vma) &&
5316 		    !folio_mapped(folio) && folio_test_anon(folio)) {
5317 			folio_set_hugetlb_restore_reserve(folio);
5318 			/* Reservation to be adjusted after the spin lock */
5319 			adjust_reservation = true;
5320 		}
5321 		spin_unlock_irq(&hugetlb_lock);
5322 
5323 		/*
5324 		 * Adjust the reservation for the region that will have the
5325 		 * reserve restored. Keep in mind that vma_needs_reservation() changes
5326 		 * resv->adds_in_progress if it succeeds. If this is not done,
5327 		 * do_exit() will not see it, and will keep the reservation
5328 		 * forever.
5329 		 */
5330 		if (adjust_reservation) {
5331 			int rc = vma_needs_reservation(h, vma, address);
5332 
5333 			if (rc < 0)
5334 				/* Pressumably allocate_file_region_entries failed
5335 				 * to allocate a file_region struct. Clear
5336 				 * hugetlb_restore_reserve so that global reserve
5337 				 * count will not be incremented by free_huge_folio.
5338 				 * Act as if we consumed the reservation.
5339 				 */
5340 				folio_clear_hugetlb_restore_reserve(folio);
5341 			else if (rc)
5342 				vma_add_reservation(h, vma, address);
5343 		}
5344 
5345 		tlb_remove_page_size(tlb, folio_page(folio, 0),
5346 				     folio_size(folio));
5347 		/*
5348 		 * If we were instructed to unmap a specific folio, we're done.
5349 		 */
5350 		if (folio_provided)
5351 			break;
5352 	}
5353 	tlb_end_vma(tlb, vma);
5354 
5355 	huge_pmd_unshare_flush(tlb, vma);
5356 }
5357 
5358 void __hugetlb_zap_begin(struct vm_area_struct *vma,
5359 			 unsigned long *start, unsigned long *end)
5360 {
5361 	if (!vma->vm_file)	/* hugetlbfs_file_mmap error */
5362 		return;
5363 
5364 	adjust_range_if_pmd_sharing_possible(vma, start, end);
5365 	hugetlb_vma_lock_write(vma);
5366 	if (vma->vm_file)
5367 		i_mmap_lock_write(vma->vm_file->f_mapping);
5368 }
5369 
5370 void __hugetlb_zap_end(struct vm_area_struct *vma,
5371 		       struct zap_details *details)
5372 {
5373 	zap_flags_t zap_flags = details ? details->zap_flags : 0;
5374 
5375 	if (!vma->vm_file)	/* hugetlbfs_file_mmap error */
5376 		return;
5377 
5378 	if (zap_flags & ZAP_FLAG_UNMAP) {	/* final unmap */
5379 		/*
5380 		 * Unlock and free the vma lock before releasing i_mmap_rwsem.
5381 		 * When the vma_lock is freed, this makes the vma ineligible
5382 		 * for pmd sharing.  And, i_mmap_rwsem is required to set up
5383 		 * pmd sharing.  This is important as page tables for this
5384 		 * unmapped range will be asynchrously deleted.  If the page
5385 		 * tables are shared, there will be issues when accessed by
5386 		 * someone else.
5387 		 */
5388 		__hugetlb_vma_unlock_write_free(vma);
5389 	} else {
5390 		hugetlb_vma_unlock_write(vma);
5391 	}
5392 
5393 	if (vma->vm_file)
5394 		i_mmap_unlock_write(vma->vm_file->f_mapping);
5395 }
5396 
5397 void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
5398 			  unsigned long end, struct folio *folio,
5399 			  zap_flags_t zap_flags)
5400 {
5401 	struct mmu_notifier_range range;
5402 	struct mmu_gather tlb;
5403 
5404 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
5405 				start, end);
5406 	adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
5407 	mmu_notifier_invalidate_range_start(&range);
5408 	tlb_gather_mmu(&tlb, vma->vm_mm);
5409 
5410 	__unmap_hugepage_range(&tlb, vma, start, end,
5411 			       folio, zap_flags);
5412 
5413 	mmu_notifier_invalidate_range_end(&range);
5414 	tlb_finish_mmu(&tlb);
5415 }
5416 
5417 /*
5418  * This is called when the original mapper is failing to COW a MAP_PRIVATE
5419  * mapping it owns the reserve page for. The intention is to unmap the page
5420  * from other VMAs and let the children be SIGKILLed if they are faulting the
5421  * same region.
5422  */
5423 static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,
5424 			      struct folio *folio, unsigned long address)
5425 {
5426 	struct hstate *h = hstate_vma(vma);
5427 	struct vm_area_struct *iter_vma;
5428 	struct address_space *mapping;
5429 	pgoff_t pgoff;
5430 
5431 	/*
5432 	 * vm_pgoff is in PAGE_SIZE units, hence the different calculation
5433 	 * from page cache lookup which is in HPAGE_SIZE units.
5434 	 */
5435 	address = address & huge_page_mask(h);
5436 	pgoff = linear_page_index(vma, address);
5437 	mapping = vma->vm_file->f_mapping;
5438 
5439 	/*
5440 	 * Take the mapping lock for the duration of the table walk. As
5441 	 * this mapping should be shared between all the VMAs,
5442 	 * __unmap_hugepage_range() is called as the lock is already held
5443 	 */
5444 	i_mmap_lock_write(mapping);
5445 	mapping_rmap_tree_foreach(iter_vma, mapping, pgoff, pgoff) {
5446 		/* Do not unmap the current VMA */
5447 		if (iter_vma == vma)
5448 			continue;
5449 
5450 		/*
5451 		 * Shared VMAs have their own reserves and do not affect
5452 		 * MAP_PRIVATE accounting but it is possible that a shared
5453 		 * VMA is using the same page so check and skip such VMAs.
5454 		 */
5455 		if (iter_vma->vm_flags & VM_MAYSHARE)
5456 			continue;
5457 
5458 		/*
5459 		 * Unmap the page from other VMAs without their own reserves.
5460 		 * They get marked to be SIGKILLed if they fault in these
5461 		 * areas. This is because a future no-page fault on this VMA
5462 		 * could insert a zeroed page instead of the data existing
5463 		 * from the time of fork. This would look like data corruption
5464 		 */
5465 		if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER))
5466 			unmap_hugepage_range(iter_vma, address,
5467 					     address + huge_page_size(h),
5468 					     folio, 0);
5469 	}
5470 	i_mmap_unlock_write(mapping);
5471 }
5472 
5473 /*
5474  * hugetlb_wp() should be called with page lock of the original hugepage held.
5475  * Called with hugetlb_fault_mutex_table held and pte_page locked so we
5476  * cannot race with other handlers or page migration.
5477  * Keep the pte_same checks anyway to make transition from the mutex easier.
5478  */
5479 static vm_fault_t hugetlb_wp(struct vm_fault *vmf)
5480 {
5481 	struct vm_area_struct *vma = vmf->vma;
5482 	struct mm_struct *mm = vma->vm_mm;
5483 	const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
5484 	pte_t pte = huge_ptep_get(mm, vmf->address, vmf->pte);
5485 	struct hstate *h = hstate_vma(vma);
5486 	struct folio *old_folio;
5487 	struct folio *new_folio;
5488 	bool cow_from_owner = 0;
5489 	vm_fault_t ret = 0;
5490 	struct mmu_notifier_range range;
5491 
5492 	/*
5493 	 * Never handle CoW for uffd-wp protected pages.  It should be only
5494 	 * handled when the uffd-wp protection is removed.
5495 	 *
5496 	 * Note that only the CoW optimization path (in hugetlb_no_page())
5497 	 * can trigger this, because hugetlb_fault() will always resolve
5498 	 * uffd-wp bit first.
5499 	 */
5500 	if (!unshare && huge_pte_uffd(pte))
5501 		return 0;
5502 
5503 	/* Let's take out MAP_SHARED mappings first. */
5504 	if (vma->vm_flags & VM_MAYSHARE) {
5505 		set_huge_ptep_writable(vma, vmf->address, vmf->pte);
5506 		return 0;
5507 	}
5508 
5509 	old_folio = page_folio(pte_page(pte));
5510 
5511 	delayacct_wpcopy_start();
5512 
5513 retry_avoidcopy:
5514 	/*
5515 	 * If no-one else is actually using this page, we're the exclusive
5516 	 * owner and can reuse this page.
5517 	 *
5518 	 * Note that we don't rely on the (safer) folio refcount here, because
5519 	 * copying the hugetlb folio when there are unexpected (temporary)
5520 	 * folio references could harm simple fork()+exit() users when
5521 	 * we run out of free hugetlb folios: we would have to kill processes
5522 	 * in scenarios that used to work. As a side effect, there can still
5523 	 * be leaks between processes, for example, with FOLL_GET users.
5524 	 */
5525 	if (folio_mapcount(old_folio) == 1 && folio_test_anon(old_folio)) {
5526 		if (!PageAnonExclusive(&old_folio->page)) {
5527 			folio_move_anon_rmap(old_folio, vma);
5528 			SetPageAnonExclusive(&old_folio->page);
5529 		}
5530 		if (likely(!unshare))
5531 			set_huge_ptep_maybe_writable(vma, vmf->address,
5532 						     vmf->pte);
5533 
5534 		delayacct_wpcopy_end();
5535 		return 0;
5536 	}
5537 	VM_BUG_ON_PAGE(folio_test_anon(old_folio) &&
5538 		       PageAnonExclusive(&old_folio->page), &old_folio->page);
5539 
5540 	/*
5541 	 * If the process that created a MAP_PRIVATE mapping is about to perform
5542 	 * a COW due to a shared page count, attempt to satisfy the allocation
5543 	 * without using the existing reserves.
5544 	 * In order to determine where this is a COW on a MAP_PRIVATE mapping it
5545 	 * is enough to check whether the old_folio is anonymous. This means that
5546 	 * the reserve for this address was consumed. If reserves were used, a
5547 	 * partial faulted mapping at the fime of fork() could consume its reserves
5548 	 * on COW instead of the full address range.
5549 	 */
5550 	if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) &&
5551 	    folio_test_anon(old_folio))
5552 		cow_from_owner = true;
5553 
5554 	folio_get(old_folio);
5555 
5556 	/*
5557 	 * Drop page table lock as buddy allocator may be called. It will
5558 	 * be acquired again before returning to the caller, as expected.
5559 	 */
5560 	spin_unlock(vmf->ptl);
5561 	new_folio = alloc_hugetlb_folio(vma, vmf->address, cow_from_owner);
5562 
5563 	if (IS_ERR(new_folio)) {
5564 		/*
5565 		 * If a process owning a MAP_PRIVATE mapping fails to COW,
5566 		 * it is due to references held by a child and an insufficient
5567 		 * huge page pool. To guarantee the original mappers
5568 		 * reliability, unmap the page from child processes. The child
5569 		 * may get SIGKILLed if it later faults.
5570 		 */
5571 		if (cow_from_owner) {
5572 			struct address_space *mapping = vma->vm_file->f_mapping;
5573 			pgoff_t idx;
5574 			u32 hash;
5575 
5576 			folio_put(old_folio);
5577 			/*
5578 			 * Drop hugetlb_fault_mutex and vma_lock before
5579 			 * unmapping.  unmapping needs to hold vma_lock
5580 			 * in write mode.  Dropping vma_lock in read mode
5581 			 * here is OK as COW mappings do not interact with
5582 			 * PMD sharing.
5583 			 *
5584 			 * Reacquire both after unmap operation.
5585 			 */
5586 			idx = vma_hugecache_offset(h, vma, vmf->address);
5587 			hash = hugetlb_fault_mutex_hash(mapping, idx);
5588 			hugetlb_vma_unlock_read(vma);
5589 			mutex_unlock(&hugetlb_fault_mutex_table[hash]);
5590 
5591 			unmap_ref_private(mm, vma, old_folio, vmf->address);
5592 
5593 			mutex_lock(&hugetlb_fault_mutex_table[hash]);
5594 			hugetlb_vma_lock_read(vma);
5595 			spin_lock(vmf->ptl);
5596 			vmf->pte = hugetlb_walk(vma, vmf->address,
5597 					huge_page_size(h));
5598 			if (likely(vmf->pte &&
5599 				   pte_same(huge_ptep_get(mm, vmf->address, vmf->pte), pte)))
5600 				goto retry_avoidcopy;
5601 			/*
5602 			 * race occurs while re-acquiring page table
5603 			 * lock, and our job is done.
5604 			 */
5605 			delayacct_wpcopy_end();
5606 			return 0;
5607 		}
5608 
5609 		ret = vmf_error(PTR_ERR(new_folio));
5610 		goto out_release_old;
5611 	}
5612 
5613 	/*
5614 	 * When the original hugepage is shared one, it does not have
5615 	 * anon_vma prepared.
5616 	 */
5617 	ret = __vmf_anon_prepare(vmf);
5618 	if (unlikely(ret))
5619 		goto out_release_all;
5620 
5621 	if (copy_user_large_folio(new_folio, old_folio, vmf->real_address, vma)) {
5622 		ret = VM_FAULT_HWPOISON_LARGE | VM_FAULT_SET_HINDEX(hstate_index(h));
5623 		goto out_release_all;
5624 	}
5625 	__folio_mark_uptodate(new_folio);
5626 
5627 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm, vmf->address,
5628 				vmf->address + huge_page_size(h));
5629 	mmu_notifier_invalidate_range_start(&range);
5630 
5631 	/*
5632 	 * Retake the page table lock to check for racing updates
5633 	 * before the page tables are altered
5634 	 */
5635 	spin_lock(vmf->ptl);
5636 	vmf->pte = hugetlb_walk(vma, vmf->address, huge_page_size(h));
5637 	if (likely(vmf->pte && pte_same(huge_ptep_get(mm, vmf->address, vmf->pte), pte))) {
5638 		pte_t newpte = make_huge_pte(vma, new_folio, !unshare);
5639 
5640 		/* Break COW or unshare */
5641 		huge_ptep_clear_flush(vma, vmf->address, vmf->pte);
5642 		hugetlb_remove_rmap(old_folio);
5643 		hugetlb_add_new_anon_rmap(new_folio, vma, vmf->address);
5644 		if (huge_pte_uffd(pte))
5645 			newpte = huge_pte_mkuffd(newpte);
5646 		set_huge_pte_at(mm, vmf->address, vmf->pte, newpte,
5647 				huge_page_size(h));
5648 		folio_set_hugetlb_migratable(new_folio);
5649 		/* Make the old page be freed below */
5650 		new_folio = old_folio;
5651 	}
5652 	spin_unlock(vmf->ptl);
5653 	mmu_notifier_invalidate_range_end(&range);
5654 out_release_all:
5655 	/*
5656 	 * No restore in case of successful pagetable update (Break COW or
5657 	 * unshare)
5658 	 */
5659 	if (new_folio != old_folio)
5660 		restore_reserve_on_error(h, vma, vmf->address, new_folio);
5661 	folio_put(new_folio);
5662 out_release_old:
5663 	folio_put(old_folio);
5664 
5665 	spin_lock(vmf->ptl); /* Caller expects lock to be held */
5666 
5667 	delayacct_wpcopy_end();
5668 	return ret;
5669 }
5670 
5671 /*
5672  * Return whether there is a pagecache page to back given address within VMA.
5673  */
5674 bool hugetlbfs_pagecache_present(struct hstate *h,
5675 				 struct vm_area_struct *vma, unsigned long address)
5676 {
5677 	struct address_space *mapping = vma->vm_file->f_mapping;
5678 	pgoff_t idx = linear_page_index(vma, address);
5679 	struct folio *folio;
5680 
5681 	folio = filemap_get_folio(mapping, idx);
5682 	if (IS_ERR(folio))
5683 		return false;
5684 	folio_put(folio);
5685 	return true;
5686 }
5687 
5688 int hugetlb_add_to_page_cache(struct folio *folio, struct address_space *mapping,
5689 			   pgoff_t idx)
5690 {
5691 	struct inode *inode = mapping->host;
5692 	struct hstate *h = hstate_inode(inode);
5693 	int err;
5694 
5695 	idx <<= huge_page_order(h);
5696 	__folio_set_locked(folio);
5697 	err = __filemap_add_folio(mapping, folio, idx, GFP_KERNEL, NULL);
5698 
5699 	if (unlikely(err)) {
5700 		__folio_clear_locked(folio);
5701 		return err;
5702 	}
5703 	folio_clear_hugetlb_restore_reserve(folio);
5704 
5705 	/*
5706 	 * mark folio dirty so that it will not be removed from cache/file
5707 	 * by non-hugetlbfs specific code paths.
5708 	 */
5709 	folio_mark_dirty(folio);
5710 
5711 	spin_lock(&inode->i_lock);
5712 	inode->i_blocks += blocks_per_huge_page(h);
5713 	spin_unlock(&inode->i_lock);
5714 	return 0;
5715 }
5716 
5717 static inline vm_fault_t hugetlb_handle_userfault(struct vm_fault *vmf,
5718 						  struct address_space *mapping,
5719 						  unsigned long reason)
5720 {
5721 	u32 hash;
5722 
5723 	/*
5724 	 * vma_lock and hugetlb_fault_mutex must be dropped before handling
5725 	 * userfault. Also mmap_lock could be dropped due to handling
5726 	 * userfault, any vma operation should be careful from here.
5727 	 */
5728 	hugetlb_vma_unlock_read(vmf->vma);
5729 	hash = hugetlb_fault_mutex_hash(mapping, vmf->pgoff);
5730 	mutex_unlock(&hugetlb_fault_mutex_table[hash]);
5731 	return handle_userfault(vmf, reason);
5732 }
5733 
5734 /*
5735  * Recheck pte with pgtable lock.  Returns true if pte didn't change, or
5736  * false if pte changed or is changing.
5737  */
5738 static bool hugetlb_pte_stable(struct hstate *h, struct mm_struct *mm, unsigned long addr,
5739 			       pte_t *ptep, pte_t old_pte)
5740 {
5741 	spinlock_t *ptl;
5742 	bool same;
5743 
5744 	ptl = huge_pte_lock(h, mm, ptep);
5745 	same = pte_same(huge_ptep_get(mm, addr, ptep), old_pte);
5746 	spin_unlock(ptl);
5747 
5748 	return same;
5749 }
5750 
5751 static vm_fault_t hugetlb_no_page(struct address_space *mapping,
5752 			struct vm_fault *vmf)
5753 {
5754 	u32 hash = hugetlb_fault_mutex_hash(mapping, vmf->pgoff);
5755 	bool new_folio, new_anon_folio = false;
5756 	struct vm_area_struct *vma = vmf->vma;
5757 	struct mm_struct *mm = vma->vm_mm;
5758 	struct hstate *h = hstate_vma(vma);
5759 	vm_fault_t ret = VM_FAULT_SIGBUS;
5760 	bool folio_locked = true;
5761 	struct folio *folio;
5762 	unsigned long size;
5763 	pte_t new_pte;
5764 
5765 	/*
5766 	 * Currently, we are forced to kill the process in the event the
5767 	 * original mapper has unmapped pages from the child due to a failed
5768 	 * COW/unsharing. Warn that such a situation has occurred as it may not
5769 	 * be obvious.
5770 	 */
5771 	if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) {
5772 		pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n",
5773 			   current->pid);
5774 		goto out;
5775 	}
5776 
5777 	/*
5778 	 * Use page lock to guard against racing truncation
5779 	 * before we get page_table_lock.
5780 	 */
5781 	new_folio = false;
5782 	folio = filemap_lock_hugetlb_folio(h, mapping, vmf->pgoff);
5783 	if (IS_ERR(folio)) {
5784 		size = i_size_read(mapping->host) >> huge_page_shift(h);
5785 		if (vmf->pgoff >= size)
5786 			goto out;
5787 		/* Check for page in userfault range */
5788 		if (userfaultfd_missing(vma)) {
5789 			/*
5790 			 * Since hugetlb_no_page() was examining pte
5791 			 * without pgtable lock, we need to re-test under
5792 			 * lock because the pte may not be stable and could
5793 			 * have changed from under us.  Try to detect
5794 			 * either changed or during-changing ptes and retry
5795 			 * properly when needed.
5796 			 *
5797 			 * Note that userfaultfd is actually fine with
5798 			 * false positives (e.g. caused by pte changed),
5799 			 * but not wrong logical events (e.g. caused by
5800 			 * reading a pte during changing).  The latter can
5801 			 * confuse the userspace, so the strictness is very
5802 			 * much preferred.  E.g., MISSING event should
5803 			 * never happen on the page after UFFDIO_COPY has
5804 			 * correctly installed the page and returned.
5805 			 */
5806 			if (!hugetlb_pte_stable(h, mm, vmf->address, vmf->pte, vmf->orig_pte)) {
5807 				ret = 0;
5808 				goto out;
5809 			}
5810 
5811 			return hugetlb_handle_userfault(vmf, mapping,
5812 							VM_UFFD_MISSING);
5813 		}
5814 
5815 		if (!(vma->vm_flags & VM_MAYSHARE)) {
5816 			ret = __vmf_anon_prepare(vmf);
5817 			if (unlikely(ret))
5818 				goto out;
5819 		}
5820 
5821 		folio = alloc_hugetlb_folio(vma, vmf->address, false);
5822 		if (IS_ERR(folio)) {
5823 			/*
5824 			 * Returning error will result in faulting task being
5825 			 * sent SIGBUS.  The hugetlb fault mutex prevents two
5826 			 * tasks from racing to fault in the same page which
5827 			 * could result in false unable to allocate errors.
5828 			 * Page migration does not take the fault mutex, but
5829 			 * does a clear then write of pte's under page table
5830 			 * lock.  Page fault code could race with migration,
5831 			 * notice the clear pte and try to allocate a page
5832 			 * here.  Before returning error, get ptl and make
5833 			 * sure there really is no pte entry.
5834 			 */
5835 			if (hugetlb_pte_stable(h, mm, vmf->address, vmf->pte, vmf->orig_pte))
5836 				ret = vmf_error(PTR_ERR(folio));
5837 			else
5838 				ret = 0;
5839 			goto out;
5840 		}
5841 		folio_zero_user(folio, vmf->real_address);
5842 		__folio_mark_uptodate(folio);
5843 		new_folio = true;
5844 
5845 		if (vma->vm_flags & VM_MAYSHARE) {
5846 			int err = hugetlb_add_to_page_cache(folio, mapping,
5847 							vmf->pgoff);
5848 			if (err) {
5849 				/*
5850 				 * err can't be -EEXIST which implies someone
5851 				 * else consumed the reservation since hugetlb
5852 				 * fault mutex is held when add a hugetlb page
5853 				 * to the page cache. So it's safe to call
5854 				 * restore_reserve_on_error() here.
5855 				 */
5856 				restore_reserve_on_error(h, vma, vmf->address,
5857 							folio);
5858 				folio_put(folio);
5859 				ret = VM_FAULT_SIGBUS;
5860 				goto out;
5861 			}
5862 		} else {
5863 			new_anon_folio = true;
5864 			folio_lock(folio);
5865 		}
5866 	} else {
5867 		/*
5868 		 * If memory error occurs between mmap() and fault, some process
5869 		 * don't have hwpoisoned swap entry for errored virtual address.
5870 		 * So we need to block hugepage fault by PG_hwpoison bit check.
5871 		 */
5872 		if (unlikely(folio_test_hwpoison(folio))) {
5873 			ret = VM_FAULT_HWPOISON_LARGE |
5874 				VM_FAULT_SET_HINDEX(hstate_index(h));
5875 			goto backout_unlocked;
5876 		}
5877 
5878 		/* Check for page in userfault range. */
5879 		if (userfaultfd_minor(vma)) {
5880 			folio_unlock(folio);
5881 			folio_put(folio);
5882 			/* See comment in userfaultfd_missing() block above */
5883 			if (!hugetlb_pte_stable(h, mm, vmf->address, vmf->pte, vmf->orig_pte)) {
5884 				ret = 0;
5885 				goto out;
5886 			}
5887 			return hugetlb_handle_userfault(vmf, mapping,
5888 							VM_UFFD_MINOR);
5889 		}
5890 	}
5891 
5892 	/*
5893 	 * If we are going to COW a private mapping later, we examine the
5894 	 * pending reservations for this page now. This will ensure that
5895 	 * any allocations necessary to record that reservation occur outside
5896 	 * the spinlock.
5897 	 */
5898 	if ((vmf->flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
5899 		if (vma_needs_reservation(h, vma, vmf->address) < 0) {
5900 			ret = VM_FAULT_OOM;
5901 			goto backout_unlocked;
5902 		}
5903 		/* Just decrements count, does not deallocate */
5904 		vma_end_reservation(h, vma, vmf->address);
5905 	}
5906 
5907 	vmf->ptl = huge_pte_lock(h, mm, vmf->pte);
5908 	ret = 0;
5909 	/* If pte changed from under us, retry */
5910 	if (!pte_same(huge_ptep_get(mm, vmf->address, vmf->pte), vmf->orig_pte))
5911 		goto backout;
5912 
5913 	if (new_anon_folio)
5914 		hugetlb_add_new_anon_rmap(folio, vma, vmf->address);
5915 	else
5916 		hugetlb_add_file_rmap(folio);
5917 	new_pte = make_huge_pte(vma, folio, vma->vm_flags & VM_SHARED);
5918 	/*
5919 	 * If this pte was previously wr-protected, keep it wr-protected even
5920 	 * if populated.
5921 	 */
5922 	if (unlikely(pte_is_uffd_wp_marker(vmf->orig_pte)))
5923 		new_pte = huge_pte_mkuffd(new_pte);
5924 	set_huge_pte_at(mm, vmf->address, vmf->pte, new_pte, huge_page_size(h));
5925 
5926 	hugetlb_count_add(pages_per_huge_page(h), mm);
5927 	if ((vmf->flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
5928 		/*
5929 		 * No need to keep file folios locked. See comment in
5930 		 * hugetlb_fault().
5931 		 */
5932 		if (!new_anon_folio) {
5933 			folio_locked = false;
5934 			folio_unlock(folio);
5935 		}
5936 		/* Optimization, do the COW without a second fault */
5937 		ret = hugetlb_wp(vmf);
5938 	}
5939 
5940 	spin_unlock(vmf->ptl);
5941 
5942 	/*
5943 	 * Only set hugetlb_migratable in newly allocated pages.  Existing pages
5944 	 * found in the pagecache may not have hugetlb_migratable if they have
5945 	 * been isolated for migration.
5946 	 */
5947 	if (new_folio)
5948 		folio_set_hugetlb_migratable(folio);
5949 
5950 	if (folio_locked)
5951 		folio_unlock(folio);
5952 out:
5953 	hugetlb_vma_unlock_read(vma);
5954 
5955 	/*
5956 	 * We must check to release the per-VMA lock. __vmf_anon_prepare() is
5957 	 * the only way ret can be set to VM_FAULT_RETRY.
5958 	 */
5959 	if (unlikely(ret & VM_FAULT_RETRY))
5960 		vma_end_read(vma);
5961 
5962 	mutex_unlock(&hugetlb_fault_mutex_table[hash]);
5963 	return ret;
5964 
5965 backout:
5966 	spin_unlock(vmf->ptl);
5967 backout_unlocked:
5968 	/* We only need to restore reservations for private mappings */
5969 	if (new_anon_folio)
5970 		restore_reserve_on_error(h, vma, vmf->address, folio);
5971 
5972 	folio_unlock(folio);
5973 	folio_put(folio);
5974 	goto out;
5975 }
5976 
5977 #ifdef CONFIG_SMP
5978 u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
5979 {
5980 	unsigned long key[2];
5981 	u32 hash;
5982 
5983 	key[0] = (unsigned long) mapping;
5984 	key[1] = idx;
5985 
5986 	hash = jhash2((u32 *)&key, sizeof(key)/(sizeof(u32)), 0);
5987 
5988 	return hash & (num_fault_mutexes - 1);
5989 }
5990 #else
5991 /*
5992  * For uniprocessor systems we always use a single mutex, so just
5993  * return 0 and avoid the hashing overhead.
5994  */
5995 u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
5996 {
5997 	return 0;
5998 }
5999 #endif
6000 
6001 vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,
6002 			unsigned long address, unsigned int flags)
6003 {
6004 	vm_fault_t ret;
6005 	u32 hash;
6006 	struct folio *folio = NULL;
6007 	struct hstate *h = hstate_vma(vma);
6008 	struct address_space *mapping;
6009 	bool need_wait_lock = false;
6010 	struct vm_fault vmf = {
6011 		.vma = vma,
6012 		.address = address & huge_page_mask(h),
6013 		.real_address = address,
6014 		.flags = flags,
6015 		.pgoff = vma_hugecache_offset(h, vma,
6016 				address & huge_page_mask(h)),
6017 		/* TODO: Track hugetlb faults using vm_fault */
6018 
6019 		/*
6020 		 * Some fields may not be initialized, be careful as it may
6021 		 * be hard to debug if called functions make assumptions
6022 		 */
6023 	};
6024 
6025 	/*
6026 	 * Serialize hugepage allocation and instantiation, so that we don't
6027 	 * get spurious allocation failures if two CPUs race to instantiate
6028 	 * the same page in the page cache.
6029 	 */
6030 	mapping = vma->vm_file->f_mapping;
6031 	hash = hugetlb_fault_mutex_hash(mapping, vmf.pgoff);
6032 	mutex_lock(&hugetlb_fault_mutex_table[hash]);
6033 
6034 	/*
6035 	 * Acquire vma lock before calling huge_pte_alloc and hold
6036 	 * until finished with vmf.pte.  This prevents huge_pmd_unshare from
6037 	 * being called elsewhere and making the vmf.pte no longer valid.
6038 	 */
6039 	hugetlb_vma_lock_read(vma);
6040 	vmf.pte = huge_pte_alloc(mm, vma, vmf.address, huge_page_size(h));
6041 	if (!vmf.pte) {
6042 		hugetlb_vma_unlock_read(vma);
6043 		mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6044 		return VM_FAULT_OOM;
6045 	}
6046 
6047 	vmf.orig_pte = huge_ptep_get(mm, vmf.address, vmf.pte);
6048 	if (huge_pte_none(vmf.orig_pte))
6049 		/*
6050 		 * hugetlb_no_page will drop vma lock and hugetlb fault
6051 		 * mutex internally, which make us return immediately.
6052 		 */
6053 		return hugetlb_no_page(mapping, &vmf);
6054 
6055 	if (pte_is_marker(vmf.orig_pte)) {
6056 		const pte_marker marker =
6057 			softleaf_to_marker(softleaf_from_pte(vmf.orig_pte));
6058 
6059 		if (marker & PTE_MARKER_POISONED) {
6060 			ret = VM_FAULT_HWPOISON_LARGE |
6061 				VM_FAULT_SET_HINDEX(hstate_index(h));
6062 			goto out_mutex;
6063 		} else if (WARN_ON_ONCE(marker & PTE_MARKER_GUARD)) {
6064 			/* This isn't supported in hugetlb. */
6065 			ret = VM_FAULT_SIGSEGV;
6066 			goto out_mutex;
6067 		}
6068 
6069 		return hugetlb_no_page(mapping, &vmf);
6070 	}
6071 
6072 	ret = 0;
6073 
6074 	/* Not present, either a migration or a hwpoisoned entry */
6075 	if (!pte_present(vmf.orig_pte) && !huge_pte_none(vmf.orig_pte)) {
6076 		const softleaf_t softleaf = softleaf_from_pte(vmf.orig_pte);
6077 
6078 		if (softleaf_is_migration(softleaf)) {
6079 			/*
6080 			 * Release the hugetlb fault lock now, but retain
6081 			 * the vma lock, because it is needed to guard the
6082 			 * huge_pte_lockptr() later in
6083 			 * migration_entry_wait_huge(). The vma lock will
6084 			 * be released there.
6085 			 */
6086 			mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6087 			migration_entry_wait_huge(vma, vmf.address, vmf.pte);
6088 			return 0;
6089 		}
6090 		if (softleaf_is_hwpoison(softleaf)) {
6091 			ret = VM_FAULT_HWPOISON_LARGE |
6092 			    VM_FAULT_SET_HINDEX(hstate_index(h));
6093 		}
6094 
6095 		goto out_mutex;
6096 	}
6097 
6098 	/*
6099 	 * Protnone hugetlb PTEs with the uffd bit are used by
6100 	 * userfaultfd RWP for access tracking. Plain PROT_NONE (without the
6101 	 * marker) is not an RWP fault and is not expected on hugetlb (no
6102 	 * NUMA hinting), so let normal hugetlb fault handling proceed.
6103 	 */
6104 	if (pte_protnone(vmf.orig_pte) && vma_is_accessible(vma) &&
6105 	    userfaultfd_rwp(vma) && huge_pte_uffd(vmf.orig_pte)) {
6106 		spinlock_t *ptl;
6107 		pte_t pte;
6108 
6109 		/* Sync: drop hugetlb locks before blocking in handle_userfault() */
6110 		if (!userfaultfd_rwp_async(vma))
6111 			return hugetlb_handle_userfault(&vmf, mapping, VM_UFFD_RWP);
6112 
6113 		ptl = huge_pte_lock(h, mm, vmf.pte);
6114 		pte = huge_ptep_get(mm, vmf.address, vmf.pte);
6115 		if (pte_protnone(pte) && huge_pte_uffd(pte)) {
6116 			unsigned int shift = huge_page_shift(h);
6117 
6118 			pte = huge_pte_modify(pte, vma->vm_page_prot);
6119 			pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
6120 			/* huge_pte_modify() preserves _PAGE_UFFD; drop it on resolution */
6121 			pte = huge_pte_clear_uffd(pte);
6122 			pte = pte_mkyoung(pte);
6123 			/*
6124 			 * Unlike do_uffd_rwp(), do not upgrade to writable
6125 			 * here. Hugetlb lacks a can_change_huge_pte_writable()
6126 			 * equivalent, so a write access will take a separate
6127 			 * COW fault — acceptable for the rare private hugetlb
6128 			 * case.
6129 			 */
6130 			set_huge_pte_at(mm, vmf.address, vmf.pte, pte,
6131 					huge_page_size(h));
6132 			update_mmu_cache(vma, vmf.address, vmf.pte);
6133 		}
6134 		spin_unlock(ptl);
6135 		ret = 0;
6136 		goto out_mutex;
6137 	}
6138 
6139 	/*
6140 	 * If we are going to COW/unshare the mapping later, we examine the
6141 	 * pending reservations for this page now. This will ensure that any
6142 	 * allocations necessary to record that reservation occur outside the
6143 	 * spinlock.
6144 	 */
6145 	if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) &&
6146 	    !(vma->vm_flags & VM_MAYSHARE) && !huge_pte_write(vmf.orig_pte)) {
6147 		if (vma_needs_reservation(h, vma, vmf.address) < 0) {
6148 			ret = VM_FAULT_OOM;
6149 			goto out_mutex;
6150 		}
6151 		/* Just decrements count, does not deallocate */
6152 		vma_end_reservation(h, vma, vmf.address);
6153 	}
6154 
6155 	vmf.ptl = huge_pte_lock(h, mm, vmf.pte);
6156 
6157 	/* Check for a racing update before calling hugetlb_wp() */
6158 	if (unlikely(!pte_same(vmf.orig_pte, huge_ptep_get(mm, vmf.address, vmf.pte))))
6159 		goto out_ptl;
6160 
6161 	/* Handle userfault-wp first, before trying to lock more pages */
6162 	if (userfaultfd_wp(vma) && huge_pte_uffd(huge_ptep_get(mm, vmf.address, vmf.pte)) &&
6163 	    (flags & FAULT_FLAG_WRITE) && !huge_pte_write(vmf.orig_pte)) {
6164 		if (!userfaultfd_wp_async(vma)) {
6165 			spin_unlock(vmf.ptl);
6166 			hugetlb_vma_unlock_read(vma);
6167 			mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6168 			return handle_userfault(&vmf, VM_UFFD_WP);
6169 		}
6170 
6171 		vmf.orig_pte = huge_pte_clear_uffd(vmf.orig_pte);
6172 		set_huge_pte_at(mm, vmf.address, vmf.pte, vmf.orig_pte,
6173 				huge_page_size(hstate_vma(vma)));
6174 		/* Fallthrough to CoW */
6175 	}
6176 
6177 	if (flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) {
6178 		if (!huge_pte_write(vmf.orig_pte)) {
6179 			/*
6180 			 * Anonymous folios need to be lock since hugetlb_wp()
6181 			 * checks whether we can re-use the folio exclusively
6182 			 * for us in case we are the only user of it.
6183 			 */
6184 			folio = page_folio(pte_page(vmf.orig_pte));
6185 			if (folio_test_anon(folio) && !folio_trylock(folio)) {
6186 				need_wait_lock = true;
6187 				goto out_ptl;
6188 			}
6189 			folio_get(folio);
6190 			ret = hugetlb_wp(&vmf);
6191 			if (folio_test_anon(folio))
6192 				folio_unlock(folio);
6193 			folio_put(folio);
6194 			goto out_ptl;
6195 		} else if (likely(flags & FAULT_FLAG_WRITE)) {
6196 			vmf.orig_pte = huge_pte_mkdirty(vmf.orig_pte);
6197 		}
6198 	}
6199 	vmf.orig_pte = pte_mkyoung(vmf.orig_pte);
6200 	if (huge_ptep_set_access_flags(vma, vmf.address, vmf.pte, vmf.orig_pte,
6201 						flags & FAULT_FLAG_WRITE))
6202 		update_mmu_cache(vma, vmf.address, vmf.pte);
6203 out_ptl:
6204 	spin_unlock(vmf.ptl);
6205 out_mutex:
6206 	hugetlb_vma_unlock_read(vma);
6207 
6208 	/*
6209 	 * We must check to release the per-VMA lock. __vmf_anon_prepare() in
6210 	 * hugetlb_wp() is the only way ret can be set to VM_FAULT_RETRY.
6211 	 */
6212 	if (unlikely(ret & VM_FAULT_RETRY))
6213 		vma_end_read(vma);
6214 
6215 	mutex_unlock(&hugetlb_fault_mutex_table[hash]);
6216 	/*
6217 	 * hugetlb_wp drops all the locks, but the folio lock, before trying to
6218 	 * unmap the folio from other processes. During that window, if another
6219 	 * process mapping that folio faults in, it will take the mutex and then
6220 	 * it will wait on folio_lock, causing an ABBA deadlock.
6221 	 * Use trylock instead and bail out if we fail.
6222 	 *
6223 	 * Ideally, we should hold a refcount on the folio we wait for, but we do
6224 	 * not want to use the folio after it becomes unlocked, but rather just
6225 	 * wait for it to become unlocked, so hopefully next fault successes on
6226 	 * the trylock.
6227 	 */
6228 	if (need_wait_lock)
6229 		folio_wait_locked(folio);
6230 	return ret;
6231 }
6232 
6233 #ifdef CONFIG_USERFAULTFD
6234 /*
6235  * Can probably be eliminated, but still used by hugetlb_mfill_atomic_pte().
6236  */
6237 static struct folio *alloc_hugetlb_folio_vma(struct hstate *h,
6238 		struct vm_area_struct *vma, unsigned long address)
6239 {
6240 	struct mempolicy *mpol;
6241 	nodemask_t *nodemask;
6242 	struct folio *folio;
6243 	gfp_t gfp_mask;
6244 	int node;
6245 
6246 	gfp_mask = htlb_alloc_mask(h);
6247 	node = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
6248 	/*
6249 	 * This is used to allocate a temporary hugetlb to hold the copied
6250 	 * content, which will then be copied again to the final hugetlb
6251 	 * consuming a reservation. Set the alloc_fallback to false to indicate
6252 	 * that breaking the per-node hugetlb pool is not allowed in this case.
6253 	 */
6254 	folio = alloc_hugetlb_folio_nodemask(h, node, nodemask, gfp_mask, false);
6255 	mpol_cond_put(mpol);
6256 
6257 	return folio;
6258 }
6259 
6260 /*
6261  * Used by userfaultfd UFFDIO_* ioctls. Based on userfaultfd's mfill_atomic_pte
6262  * with modifications for hugetlb pages.
6263  */
6264 int hugetlb_mfill_atomic_pte(pte_t *dst_pte,
6265 			     struct vm_area_struct *dst_vma,
6266 			     unsigned long dst_addr,
6267 			     unsigned long src_addr,
6268 			     uffd_flags_t flags,
6269 			     struct folio **foliop)
6270 {
6271 	struct mm_struct *dst_mm = dst_vma->vm_mm;
6272 	bool is_continue = uffd_flags_mode_is(flags, MFILL_ATOMIC_CONTINUE);
6273 	bool wp_enabled = (flags & MFILL_ATOMIC_WP);
6274 	struct hstate *h = hstate_vma(dst_vma);
6275 	struct address_space *mapping = dst_vma->vm_file->f_mapping;
6276 	pgoff_t idx = vma_hugecache_offset(h, dst_vma, dst_addr);
6277 	unsigned long size = huge_page_size(h);
6278 	int vm_shared = dst_vma->vm_flags & VM_SHARED;
6279 	pte_t _dst_pte;
6280 	spinlock_t *ptl;
6281 	int ret = -ENOMEM;
6282 	struct folio *folio;
6283 	bool folio_in_pagecache = false;
6284 	pte_t dst_ptep;
6285 
6286 	if (uffd_flags_mode_is(flags, MFILL_ATOMIC_POISON)) {
6287 		ptl = huge_pte_lock(h, dst_mm, dst_pte);
6288 
6289 		/* Don't overwrite any existing PTEs (even markers) */
6290 		if (!huge_pte_none(huge_ptep_get(dst_mm, dst_addr, dst_pte))) {
6291 			spin_unlock(ptl);
6292 			return -EEXIST;
6293 		}
6294 
6295 		_dst_pte = make_pte_marker(PTE_MARKER_POISONED);
6296 		set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte, size);
6297 
6298 		/* No need to invalidate - it was non-present before */
6299 		update_mmu_cache(dst_vma, dst_addr, dst_pte);
6300 
6301 		spin_unlock(ptl);
6302 		return 0;
6303 	}
6304 
6305 	if (is_continue) {
6306 		ret = -EFAULT;
6307 		folio = filemap_lock_hugetlb_folio(h, mapping, idx);
6308 		if (IS_ERR(folio))
6309 			goto out;
6310 		folio_in_pagecache = true;
6311 	} else if (!*foliop) {
6312 		/* If a folio already exists, then it's UFFDIO_COPY for
6313 		 * a non-missing case. Return -EEXIST.
6314 		 */
6315 		if (vm_shared &&
6316 		    hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
6317 			ret = -EEXIST;
6318 			goto out;
6319 		}
6320 
6321 		folio = alloc_hugetlb_folio(dst_vma, dst_addr, false);
6322 		if (IS_ERR(folio)) {
6323 			pte_t *actual_pte = hugetlb_walk(dst_vma, dst_addr, PMD_SIZE);
6324 			if (actual_pte) {
6325 				ret = -EEXIST;
6326 				goto out;
6327 			}
6328 			ret = -ENOMEM;
6329 			goto out;
6330 		}
6331 
6332 		ret = copy_folio_from_user(folio, (const void __user *) src_addr,
6333 					   false);
6334 
6335 		/* fallback to copy_from_user outside mmap_lock */
6336 		if (unlikely(ret)) {
6337 			ret = -ENOENT;
6338 			/* Free the allocated folio which may have
6339 			 * consumed a reservation.
6340 			 */
6341 			restore_reserve_on_error(h, dst_vma, dst_addr, folio);
6342 			folio_put(folio);
6343 
6344 			/* Allocate a temporary folio to hold the copied
6345 			 * contents.
6346 			 */
6347 			folio = alloc_hugetlb_folio_vma(h, dst_vma, dst_addr);
6348 			if (!folio) {
6349 				ret = -ENOMEM;
6350 				goto out;
6351 			}
6352 			*foliop = folio;
6353 			/* Set the outparam foliop and return to the caller to
6354 			 * copy the contents outside the lock. Don't free the
6355 			 * folio.
6356 			 */
6357 			goto out;
6358 		}
6359 	} else {
6360 		if (vm_shared &&
6361 		    hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
6362 			folio_put(*foliop);
6363 			ret = -EEXIST;
6364 			*foliop = NULL;
6365 			goto out;
6366 		}
6367 
6368 		folio = alloc_hugetlb_folio(dst_vma, dst_addr, false);
6369 		if (IS_ERR(folio)) {
6370 			folio_put(*foliop);
6371 			ret = -ENOMEM;
6372 			*foliop = NULL;
6373 			goto out;
6374 		}
6375 		ret = copy_user_large_folio(folio, *foliop, dst_addr, dst_vma);
6376 		folio_put(*foliop);
6377 		*foliop = NULL;
6378 		if (ret) {
6379 			restore_reserve_on_error(h, dst_vma, dst_addr, folio);
6380 			folio_put(folio);
6381 			goto out;
6382 		}
6383 	}
6384 
6385 	/*
6386 	 * If we just allocated a new page, we need a memory barrier to ensure
6387 	 * that preceding stores to the page become visible before the
6388 	 * set_pte_at() write. The memory barrier inside __folio_mark_uptodate
6389 	 * is what we need.
6390 	 *
6391 	 * In the case where we have not allocated a new page (is_continue),
6392 	 * the page must already be uptodate. UFFDIO_CONTINUE already includes
6393 	 * an earlier smp_wmb() to ensure that prior stores will be visible
6394 	 * before the set_pte_at() write.
6395 	 */
6396 	if (!is_continue)
6397 		__folio_mark_uptodate(folio);
6398 	else
6399 		WARN_ON_ONCE(!folio_test_uptodate(folio));
6400 
6401 	/* Add shared, newly allocated pages to the page cache. */
6402 	if (vm_shared && !is_continue) {
6403 		ret = -EFAULT;
6404 		if (idx >= (i_size_read(mapping->host) >> huge_page_shift(h)))
6405 			goto out_release_nounlock;
6406 
6407 		/*
6408 		 * Serialization between remove_inode_hugepages() and
6409 		 * hugetlb_add_to_page_cache() below happens through the
6410 		 * hugetlb_fault_mutex_table that here must be hold by
6411 		 * the caller.
6412 		 */
6413 		ret = hugetlb_add_to_page_cache(folio, mapping, idx);
6414 		if (ret)
6415 			goto out_release_nounlock;
6416 		folio_in_pagecache = true;
6417 	}
6418 
6419 	ptl = huge_pte_lock(h, dst_mm, dst_pte);
6420 
6421 	ret = -EIO;
6422 	if (folio_test_hwpoison(folio))
6423 		goto out_release_unlock;
6424 
6425 	ret = -EEXIST;
6426 
6427 	dst_ptep = huge_ptep_get(dst_mm, dst_addr, dst_pte);
6428 	/*
6429 	 * See comment about UFFD marker overwriting in
6430 	 * mfill_atomic_install_pte().
6431 	 */
6432 	if (!huge_pte_none(dst_ptep) && !pte_is_uffd_marker(dst_ptep))
6433 		goto out_release_unlock;
6434 
6435 	if (folio_in_pagecache)
6436 		hugetlb_add_file_rmap(folio);
6437 	else
6438 		hugetlb_add_new_anon_rmap(folio, dst_vma, dst_addr);
6439 
6440 	/*
6441 	 * For either: (1) CONTINUE on a non-shared VMA, or (2) UFFDIO_COPY
6442 	 * with wp flag set, don't set pte write bit.
6443 	 */
6444 	_dst_pte = make_huge_pte(dst_vma, folio,
6445 				 !wp_enabled && !(is_continue && !vm_shared));
6446 	/*
6447 	 * Always mark UFFDIO_COPY page dirty; note that this may not be
6448 	 * extremely important for hugetlbfs for now since swapping is not
6449 	 * supported, but we should still be clear in that this page cannot be
6450 	 * thrown away at will, even if write bit not set.
6451 	 */
6452 	_dst_pte = huge_pte_mkdirty(_dst_pte);
6453 	_dst_pte = pte_mkyoung(_dst_pte);
6454 
6455 	if (wp_enabled)
6456 		_dst_pte = huge_pte_mkuffd(_dst_pte);
6457 
6458 	set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte, size);
6459 
6460 	hugetlb_count_add(pages_per_huge_page(h), dst_mm);
6461 
6462 	/* No need to invalidate - it was non-present before */
6463 	update_mmu_cache(dst_vma, dst_addr, dst_pte);
6464 
6465 	spin_unlock(ptl);
6466 	if (!is_continue)
6467 		folio_set_hugetlb_migratable(folio);
6468 	if (vm_shared || is_continue)
6469 		folio_unlock(folio);
6470 	ret = 0;
6471 out:
6472 	return ret;
6473 out_release_unlock:
6474 	spin_unlock(ptl);
6475 	if (vm_shared || is_continue)
6476 		folio_unlock(folio);
6477 out_release_nounlock:
6478 	if (!folio_in_pagecache)
6479 		restore_reserve_on_error(h, dst_vma, dst_addr, folio);
6480 	folio_put(folio);
6481 	goto out;
6482 }
6483 #endif /* CONFIG_USERFAULTFD */
6484 
6485 long hugetlb_change_protection(struct vm_area_struct *vma,
6486 		unsigned long address, unsigned long end,
6487 		pgprot_t newprot, unsigned long cp_flags)
6488 {
6489 	struct mm_struct *mm = vma->vm_mm;
6490 	unsigned long start = address;
6491 	pte_t *ptep;
6492 	pte_t pte;
6493 	struct hstate *h = hstate_vma(vma);
6494 	long pages = 0, psize = huge_page_size(h);
6495 	struct mmu_notifier_range range;
6496 	unsigned long last_addr_mask;
6497 	bool uffd_wp = cp_flags & MM_CP_UFFD_WP;
6498 	bool uffd_wp_resolve = cp_flags & MM_CP_UFFD_WP_RESOLVE;
6499 	bool uffd_rwp = cp_flags & MM_CP_UFFD_RWP;
6500 	bool uffd_rwp_resolve = cp_flags & MM_CP_UFFD_RWP_RESOLVE;
6501 	struct mmu_gather tlb;
6502 
6503 	/*
6504 	 * In the case of shared PMDs, the area to flush could be beyond
6505 	 * start/end.  Set range.start/range.end to cover the maximum possible
6506 	 * range if PMD sharing is possible.
6507 	 */
6508 	mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_VMA,
6509 				0, mm, start, end);
6510 	adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
6511 
6512 	BUG_ON(address >= end);
6513 	flush_cache_range(vma, range.start, range.end);
6514 	tlb_gather_mmu_vma(&tlb, vma);
6515 
6516 	mmu_notifier_invalidate_range_start(&range);
6517 	hugetlb_vma_lock_write(vma);
6518 	i_mmap_lock_write(vma->vm_file->f_mapping);
6519 	last_addr_mask = hugetlb_mask_last_page(h);
6520 	for (; address < end; address += psize) {
6521 		softleaf_t entry;
6522 		spinlock_t *ptl;
6523 
6524 		ptep = hugetlb_walk(vma, address, psize);
6525 		if (!ptep) {
6526 			/*
6527 			 * uffd_wp installs a pte marker on the unpopulated
6528 			 * entry; uffd_rwp does not install markers so the
6529 			 * allocation is unnecessary for it.
6530 			 */
6531 			if (!uffd_wp) {
6532 				address |= last_addr_mask;
6533 				continue;
6534 			}
6535 			/*
6536 			 * Userfaultfd wr-protect requires pgtable
6537 			 * pre-allocations to install pte markers.
6538 			 */
6539 			ptep = huge_pte_alloc(mm, vma, address, psize);
6540 			if (!ptep) {
6541 				pages = -ENOMEM;
6542 				break;
6543 			}
6544 		}
6545 		ptl = huge_pte_lock(h, mm, ptep);
6546 		if (huge_pmd_unshare(&tlb, vma, address, ptep)) {
6547 			/*
6548 			 * When uffd-wp is enabled on the vma, unshare
6549 			 * shouldn't happen at all.  Warn about it if it
6550 			 * happened due to some reason.
6551 			 */
6552 			WARN_ON_ONCE(uffd_wp || uffd_wp_resolve ||
6553 				     uffd_rwp || uffd_rwp_resolve);
6554 			pages++;
6555 			spin_unlock(ptl);
6556 			address |= last_addr_mask;
6557 			continue;
6558 		}
6559 		pte = huge_ptep_get(mm, address, ptep);
6560 		if (huge_pte_none(pte)) {
6561 			if (unlikely(uffd_wp))
6562 				/* Safe to modify directly (none->non-present). */
6563 				set_huge_pte_at(mm, address, ptep,
6564 						make_pte_marker(PTE_MARKER_UFFD_WP),
6565 						psize);
6566 			goto next;
6567 		}
6568 
6569 		entry = softleaf_from_pte(pte);
6570 		if (unlikely(softleaf_is_hwpoison(entry))) {
6571 			/* Nothing to do. */
6572 		} else if (unlikely(softleaf_is_migration(entry))) {
6573 			struct folio *folio = softleaf_to_folio(entry);
6574 			pte_t newpte = pte;
6575 
6576 			if (softleaf_is_migration_write(entry)) {
6577 				if (folio_test_anon(folio))
6578 					entry = make_readable_exclusive_migration_entry(
6579 								swp_offset(entry));
6580 				else
6581 					entry = make_readable_migration_entry(
6582 								swp_offset(entry));
6583 				newpte = swp_entry_to_pte(entry);
6584 				pages++;
6585 			}
6586 
6587 			if (uffd_wp || uffd_rwp)
6588 				newpte = pte_swp_mkuffd(newpte);
6589 			else if (uffd_wp_resolve || uffd_rwp_resolve)
6590 				newpte = pte_swp_clear_uffd(newpte);
6591 			if (!pte_same(pte, newpte))
6592 				set_huge_pte_at(mm, address, ptep, newpte, psize);
6593 		} else if (unlikely(pte_is_marker(pte))) {
6594 			/*
6595 			 * Do nothing on a poison marker; page is
6596 			 * corrupted, permissions do not apply. Here
6597 			 * pte_marker_uffd_wp()==true implies !poison
6598 			 * because they're mutual exclusive.
6599 			 */
6600 			if (pte_is_uffd_wp_marker(pte) &&
6601 			    (uffd_wp_resolve || uffd_rwp_resolve))
6602 				/* Safe to modify directly (non-present->none). */
6603 				huge_pte_clear(mm, address, ptep, psize);
6604 		} else {
6605 			pte_t old_pte;
6606 			unsigned int shift = huge_page_shift(hstate_vma(vma));
6607 
6608 			/* Already protnone with uffd bit set? Nothing to do. */
6609 			if (uffd_rwp && pte_protnone(pte) && huge_pte_uffd(pte))
6610 				goto next;
6611 
6612 			old_pte = huge_ptep_modify_prot_start(vma, address, ptep);
6613 			pte = huge_pte_modify(old_pte, newprot);
6614 			pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
6615 			if (uffd_wp || uffd_rwp)
6616 				pte = huge_pte_mkuffd(pte);
6617 			else if (uffd_wp_resolve || uffd_rwp_resolve)
6618 				pte = huge_pte_clear_uffd(pte);
6619 
6620 			/* Preserve RWP protection across mprotect() */
6621 			if (userfaultfd_rwp(vma) && huge_pte_uffd(pte)) {
6622 				pte = huge_pte_modify(pte, PAGE_NONE);
6623 				pte = arch_make_huge_pte(pte, shift, vma->vm_flags);
6624 			}
6625 
6626 			huge_ptep_modify_prot_commit(vma, address, ptep, old_pte, pte);
6627 			pages++;
6628 			tlb_remove_huge_tlb_entry(h, &tlb, ptep, address);
6629 		}
6630 
6631 next:
6632 		spin_unlock(ptl);
6633 		cond_resched();
6634 	}
6635 
6636 	tlb_flush_mmu_tlbonly(&tlb);
6637 	huge_pmd_unshare_flush(&tlb, vma);
6638 	/*
6639 	 * No need to call mmu_notifier_arch_invalidate_secondary_tlbs() we are
6640 	 * downgrading page table protection not changing it to point to a new
6641 	 * page.
6642 	 *
6643 	 * See Documentation/mm/mmu_notifier.rst
6644 	 */
6645 	i_mmap_unlock_write(vma->vm_file->f_mapping);
6646 	hugetlb_vma_unlock_write(vma);
6647 	mmu_notifier_invalidate_range_end(&range);
6648 	tlb_finish_mmu(&tlb);
6649 
6650 	return pages > 0 ? (pages << h->order) : pages;
6651 }
6652 
6653 /*
6654  * Update the reservation map for the range [from, to].
6655  *
6656  * Returns the number of entries that would be added to the reservation map
6657  * associated with the range [from, to].  This number is greater or equal to
6658  * zero. -EINVAL or -ENOMEM is returned in case of any errors.
6659  */
6660 
6661 long hugetlb_reserve_pages(struct inode *inode,
6662 		long from, long to,
6663 		struct vm_area_struct *vma,
6664 		vma_flags_t vma_flags)
6665 {
6666 	long chg = -1, add = -1, spool_resv, gbl_resv;
6667 	struct hstate *h = hstate_inode(inode);
6668 	struct hugepage_subpool *spool = subpool_inode(inode);
6669 	struct resv_map *resv_map;
6670 	struct hugetlb_cgroup *h_cg = NULL;
6671 	long gbl_reserve, regions_needed = 0;
6672 	int err;
6673 
6674 	/* This should never happen */
6675 	if (from > to) {
6676 		VM_WARN(1, "%s called with a negative range\n", __func__);
6677 		return -EINVAL;
6678 	}
6679 
6680 	/*
6681 	 * vma specific semaphore used for pmd sharing and fault/truncation
6682 	 * synchronization
6683 	 */
6684 	hugetlb_vma_lock_alloc(vma);
6685 
6686 	/*
6687 	 * Only apply hugepage reservation if asked. At fault time, an
6688 	 * attempt will be made for VM_NORESERVE to allocate a page
6689 	 * without using reserves
6690 	 */
6691 	if (vma_flags_test(&vma_flags, VMA_NORESERVE_BIT))
6692 		return 0;
6693 
6694 	/*
6695 	 * Shared mappings base their reservation on the number of pages that
6696 	 * are already allocated on behalf of the file. Private mappings need
6697 	 * to reserve the full area even if read-only as mprotect() may be
6698 	 * called to make the mapping read-write. Assume !vma is a shm mapping
6699 	 */
6700 	if (!vma || vma_test(vma, VMA_MAYSHARE_BIT)) {
6701 		/*
6702 		 * resv_map can not be NULL as hugetlb_reserve_pages is only
6703 		 * called for inodes for which resv_maps were created (see
6704 		 * hugetlbfs_get_inode).
6705 		 */
6706 		resv_map = inode_resv_map(inode);
6707 
6708 		chg = region_chg(resv_map, from, to, &regions_needed);
6709 	} else {
6710 		/* Private mapping. */
6711 		resv_map = resv_map_alloc();
6712 		if (!resv_map) {
6713 			err = -ENOMEM;
6714 			goto out_err;
6715 		}
6716 
6717 		chg = to - from;
6718 
6719 		set_vma_resv_map(vma, resv_map);
6720 		set_vma_resv_flags(vma, HPAGE_RESV_OWNER);
6721 	}
6722 
6723 	if (chg < 0) {
6724 		/* region_chg() above can return -ENOMEM */
6725 		err = (chg == -ENOMEM) ? -ENOMEM : -EINVAL;
6726 		goto out_err;
6727 	}
6728 
6729 	err = hugetlb_cgroup_charge_cgroup_rsvd(hstate_index(h),
6730 				chg * pages_per_huge_page(h), &h_cg);
6731 	if (err < 0)
6732 		goto out_err;
6733 
6734 	if (vma && !vma_test(vma, VMA_MAYSHARE_BIT) && h_cg) {
6735 		/* For private mappings, the hugetlb_cgroup uncharge info hangs
6736 		 * of the resv_map.
6737 		 */
6738 		resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, h_cg, h);
6739 	}
6740 
6741 	/*
6742 	 * There must be enough pages in the subpool for the mapping. If
6743 	 * the subpool has a minimum size, there may be some global
6744 	 * reservations already in place (gbl_reserve).
6745 	 */
6746 	gbl_reserve = hugepage_subpool_get_pages(spool, chg);
6747 	if (gbl_reserve < 0) {
6748 		err = gbl_reserve;
6749 		goto out_uncharge_cgroup;
6750 	}
6751 
6752 	/*
6753 	 * Check enough hugepages are available for the reservation.
6754 	 * Hand the pages back to the subpool if there are not
6755 	 */
6756 	err = hugetlb_acct_memory(h, gbl_reserve);
6757 	if (err < 0)
6758 		goto out_put_pages;
6759 
6760 	/*
6761 	 * Account for the reservations made. Shared mappings record regions
6762 	 * that have reservations as they are shared by multiple VMAs.
6763 	 * When the last VMA disappears, the region map says how much
6764 	 * the reservation was and the page cache tells how much of
6765 	 * the reservation was consumed. Private mappings are per-VMA and
6766 	 * only the consumed reservations are tracked. When the VMA
6767 	 * disappears, the original reservation is the VMA size and the
6768 	 * consumed reservations are stored in the map. Hence, nothing
6769 	 * else has to be done for private mappings here
6770 	 */
6771 	if (!vma || vma_test(vma, VMA_MAYSHARE_BIT)) {
6772 		add = region_add(resv_map, from, to, regions_needed, h, h_cg);
6773 
6774 		if (unlikely(add < 0)) {
6775 			hugetlb_acct_memory(h, -gbl_reserve);
6776 			err = add;
6777 			goto out_put_pages;
6778 		} else if (unlikely(chg > add)) {
6779 			/*
6780 			 * pages in this range were added to the reserve
6781 			 * map between region_chg and region_add.  This
6782 			 * indicates a race with alloc_hugetlb_folio.  Adjust
6783 			 * the subpool and reserve counts modified above
6784 			 * based on the difference.
6785 			 */
6786 			long rsv_adjust;
6787 
6788 			/*
6789 			 * hugetlb_cgroup_uncharge_cgroup_rsvd() will put the
6790 			 * reference to h_cg->css. See comment below for detail.
6791 			 */
6792 			hugetlb_cgroup_uncharge_cgroup_rsvd(
6793 				hstate_index(h),
6794 				(chg - add) * pages_per_huge_page(h), h_cg);
6795 
6796 			rsv_adjust = hugepage_subpool_put_pages(spool,
6797 								chg - add);
6798 			hugetlb_acct_memory(h, -rsv_adjust);
6799 		} else if (h_cg) {
6800 			/*
6801 			 * The file_regions will hold their own reference to
6802 			 * h_cg->css. So we should release the reference held
6803 			 * via hugetlb_cgroup_charge_cgroup_rsvd() when we are
6804 			 * done.
6805 			 */
6806 			hugetlb_cgroup_put_rsvd_cgroup(h_cg);
6807 		}
6808 	}
6809 	return chg;
6810 
6811 out_put_pages:
6812 	spool_resv = chg - gbl_reserve;
6813 	if (spool_resv) {
6814 		/* put sub pool's reservation back, chg - gbl_reserve */
6815 		gbl_resv = hugepage_subpool_put_pages(spool, spool_resv);
6816 		/*
6817 		 * subpool's reserved pages can not be put back due to race,
6818 		 * return to hstate.
6819 		 */
6820 		hugetlb_acct_memory(h, -gbl_resv);
6821 	}
6822 	/* Restore used_hpages for pages that failed global reservation */
6823 	if (gbl_reserve && spool) {
6824 		unsigned long flags;
6825 
6826 		spin_lock_irqsave(&spool->lock, flags);
6827 		if (spool->max_hpages != -1)
6828 			spool->used_hpages -= gbl_reserve;
6829 		unlock_or_release_subpool(spool, flags);
6830 	}
6831 out_uncharge_cgroup:
6832 	hugetlb_cgroup_uncharge_cgroup_rsvd(hstate_index(h),
6833 					    chg * pages_per_huge_page(h), h_cg);
6834 out_err:
6835 	hugetlb_vma_lock_free(vma);
6836 	if (!vma || vma_test(vma, VMA_MAYSHARE_BIT))
6837 		/* Only call region_abort if the region_chg succeeded but the
6838 		 * region_add failed or didn't run.
6839 		 */
6840 		if (chg >= 0 && add < 0)
6841 			region_abort(resv_map, from, to, regions_needed);
6842 	if (vma && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
6843 		kref_put(&resv_map->refs, resv_map_release);
6844 		set_vma_resv_map(vma, NULL);
6845 	}
6846 	return err;
6847 }
6848 
6849 long hugetlb_unreserve_pages(struct inode *inode, long start, long end,
6850 								long freed)
6851 {
6852 	struct hstate *h = hstate_inode(inode);
6853 	struct resv_map *resv_map = inode_resv_map(inode);
6854 	long chg = 0;
6855 	struct hugepage_subpool *spool = subpool_inode(inode);
6856 	long gbl_reserve;
6857 
6858 	/*
6859 	 * Since this routine can be called in the evict inode path for all
6860 	 * hugetlbfs inodes, resv_map could be NULL.
6861 	 */
6862 	if (resv_map) {
6863 		chg = region_del(resv_map, start, end);
6864 		/*
6865 		 * region_del() can fail in the rare case where a region
6866 		 * must be split and another region descriptor can not be
6867 		 * allocated.  If end == LONG_MAX, it will not fail.
6868 		 */
6869 		if (chg < 0)
6870 			return chg;
6871 	}
6872 
6873 	spin_lock(&inode->i_lock);
6874 	inode->i_blocks -= (blocks_per_huge_page(h) * freed);
6875 	spin_unlock(&inode->i_lock);
6876 
6877 	/*
6878 	 * If the subpool has a minimum size, the number of global
6879 	 * reservations to be released may be adjusted.
6880 	 *
6881 	 * Note that !resv_map implies freed == 0. So (chg - freed)
6882 	 * won't go negative.
6883 	 */
6884 	gbl_reserve = hugepage_subpool_put_pages(spool, (chg - freed));
6885 	hugetlb_acct_memory(h, -gbl_reserve);
6886 
6887 	return 0;
6888 }
6889 
6890 #ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING
6891 static unsigned long page_table_shareable(struct vm_area_struct *svma,
6892 				struct vm_area_struct *vma,
6893 				unsigned long addr, pgoff_t idx)
6894 {
6895 	unsigned long saddr = ((idx - vma_start_pgoff(svma)) << PAGE_SHIFT) +
6896 				svma->vm_start;
6897 	unsigned long sbase = saddr & PUD_MASK;
6898 	unsigned long s_end = sbase + PUD_SIZE;
6899 
6900 	/* Allow segments to share if only one is marked locked */
6901 	vm_flags_t vm_flags = vma->vm_flags & ~VM_LOCKED_MASK;
6902 	vm_flags_t svm_flags = svma->vm_flags & ~VM_LOCKED_MASK;
6903 
6904 	/*
6905 	 * match the virtual addresses, permission and the alignment of the
6906 	 * page table page.
6907 	 *
6908 	 * Also, vma_lock (vm_private_data) is required for sharing.
6909 	 */
6910 	if (pmd_index(addr) != pmd_index(saddr) ||
6911 	    vm_flags != svm_flags ||
6912 	    !range_in_vma(svma, sbase, s_end) ||
6913 	    !svma->vm_private_data)
6914 		return 0;
6915 
6916 	return saddr;
6917 }
6918 
6919 bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
6920 {
6921 	unsigned long start = addr & PUD_MASK;
6922 	unsigned long end = start + PUD_SIZE;
6923 
6924 #ifdef CONFIG_USERFAULTFD
6925 	if (uffd_disable_huge_pmd_share(vma))
6926 		return false;
6927 #endif
6928 	/*
6929 	 * check on proper vm_flags and page table alignment
6930 	 */
6931 	if (!(vma->vm_flags & VM_MAYSHARE))
6932 		return false;
6933 	if (!vma->vm_private_data)	/* vma lock required for sharing */
6934 		return false;
6935 	if (!range_in_vma(vma, start, end))
6936 		return false;
6937 	return true;
6938 }
6939 
6940 /*
6941  * Determine if start,end range within vma could be mapped by shared pmd.
6942  * If yes, adjust start and end to cover range associated with possible
6943  * shared pmd mappings.
6944  */
6945 void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
6946 				unsigned long *start, unsigned long *end)
6947 {
6948 	unsigned long v_start = ALIGN(vma->vm_start, PUD_SIZE),
6949 		v_end = ALIGN_DOWN(vma->vm_end, PUD_SIZE);
6950 
6951 	/*
6952 	 * vma needs to span at least one aligned PUD size, and the range
6953 	 * must be at least partially within in.
6954 	 */
6955 	if (!(vma->vm_flags & VM_MAYSHARE) || !(v_end > v_start) ||
6956 		(*end <= v_start) || (*start >= v_end))
6957 		return;
6958 
6959 	/* Extend the range to be PUD aligned for a worst case scenario */
6960 	if (*start > v_start)
6961 		*start = ALIGN_DOWN(*start, PUD_SIZE);
6962 
6963 	if (*end < v_end)
6964 		*end = ALIGN(*end, PUD_SIZE);
6965 }
6966 
6967 /*
6968  * Search for a shareable pmd page for hugetlb. In any case calls pmd_alloc()
6969  * and returns the corresponding pte. While this is not necessary for the
6970  * !shared pmd case because we can allocate the pmd later as well, it makes the
6971  * code much cleaner. pmd allocation is essential for the shared case because
6972  * pud has to be populated inside the same i_mmap_rwsem section - otherwise
6973  * racing tasks could either miss the sharing (see huge_pte_offset) or select a
6974  * bad pmd for sharing.
6975  */
6976 pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
6977 		      unsigned long addr, pud_t *pud)
6978 {
6979 	struct address_space *mapping = vma->vm_file->f_mapping;
6980 	const pgoff_t idx = linear_page_index(vma, addr);
6981 	struct vm_area_struct *svma;
6982 	unsigned long saddr;
6983 	pte_t *spte = NULL;
6984 	pte_t *pte;
6985 
6986 	i_mmap_lock_read(mapping);
6987 	mapping_rmap_tree_foreach(svma, mapping, idx, idx) {
6988 		if (svma == vma)
6989 			continue;
6990 
6991 		saddr = page_table_shareable(svma, vma, addr, idx);
6992 		if (saddr) {
6993 			spte = hugetlb_walk(svma, saddr,
6994 					    vma_mmu_pagesize(svma));
6995 			if (spte) {
6996 				ptdesc_pmd_pts_inc(virt_to_ptdesc(spte));
6997 				break;
6998 			}
6999 		}
7000 	}
7001 
7002 	if (!spte)
7003 		goto out;
7004 
7005 	spin_lock(&mm->page_table_lock);
7006 	if (pud_none(*pud)) {
7007 		pud_populate(mm, pud,
7008 				(pmd_t *)((unsigned long)spte & PAGE_MASK));
7009 		mm_inc_nr_pmds(mm);
7010 	} else {
7011 		ptdesc_pmd_pts_dec(virt_to_ptdesc(spte));
7012 	}
7013 	spin_unlock(&mm->page_table_lock);
7014 out:
7015 	pte = (pte_t *)pmd_alloc(mm, pud, addr);
7016 	i_mmap_unlock_read(mapping);
7017 	return pte;
7018 }
7019 
7020 static int __huge_pmd_unshare(struct mmu_gather *tlb,
7021 		struct vm_area_struct *vma, unsigned long addr, pte_t *ptep,
7022 		bool check_locks)
7023 {
7024 	unsigned long sz = huge_page_size(hstate_vma(vma));
7025 	struct mm_struct *mm = vma->vm_mm;
7026 	pgd_t *pgd = pgd_offset(mm, addr);
7027 	p4d_t *p4d = p4d_offset(pgd, addr);
7028 	pud_t *pud = pud_offset(p4d, addr);
7029 
7030 	if (sz != PMD_SIZE)
7031 		return 0;
7032 	if (!ptdesc_pmd_is_shared(virt_to_ptdesc(ptep)))
7033 		return 0;
7034 	i_mmap_assert_write_locked(vma->vm_file->f_mapping);
7035 	if (check_locks)
7036 		hugetlb_vma_assert_locked(vma);
7037 	pud_clear(pud);
7038 
7039 	tlb_unshare_pmd_ptdesc(tlb, virt_to_ptdesc(ptep), addr);
7040 
7041 	mm_dec_nr_pmds(mm);
7042 	return 1;
7043 }
7044 
7045 /**
7046  * huge_pmd_unshare - Unmap a pmd table if it is shared by multiple users
7047  * @tlb: the current mmu_gather.
7048  * @vma: the vma covering the pmd table.
7049  * @addr: the address we are trying to unshare.
7050  * @ptep: pointer into the (pmd) page table.
7051  *
7052  * Called with the page table lock held, the i_mmap_rwsem held in write mode
7053  * and the hugetlb vma lock held in write mode.
7054  *
7055  * Note: The caller must call huge_pmd_unshare_flush() before dropping the
7056  * i_mmap_rwsem.
7057  *
7058  * Returns: 1 if it was a shared PMD table and it got unmapped, or 0 if it
7059  *	    was not a shared PMD table.
7060  */
7061 int huge_pmd_unshare(struct mmu_gather *tlb, struct vm_area_struct *vma,
7062 		unsigned long addr, pte_t *ptep)
7063 {
7064 	return __huge_pmd_unshare(tlb, vma, addr, ptep, /*check_locks=*/true);
7065 }
7066 
7067 /*
7068  * huge_pmd_unshare_flush - Complete a sequence of huge_pmd_unshare() calls
7069  * @tlb: the current mmu_gather.
7070  * @vma: the vma covering the pmd table.
7071  *
7072  * Perform necessary TLB flushes or IPI broadcasts to synchronize PMD table
7073  * unsharing with concurrent page table walkers.
7074  *
7075  * This function must be called after a sequence of huge_pmd_unshare()
7076  * calls while still holding the i_mmap_rwsem.
7077  */
7078 void huge_pmd_unshare_flush(struct mmu_gather *tlb, struct vm_area_struct *vma)
7079 {
7080 	/*
7081 	 * We must synchronize page table unsharing such that nobody will
7082 	 * try reusing a previously-shared page table while it might still
7083 	 * be in use by previous sharers (TLB, GUP_fast).
7084 	 */
7085 	i_mmap_assert_write_locked(vma->vm_file->f_mapping);
7086 
7087 	tlb_flush_unshared_tables(tlb);
7088 }
7089 
7090 #else /* !CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING */
7091 
7092 pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
7093 		      unsigned long addr, pud_t *pud)
7094 {
7095 	return NULL;
7096 }
7097 
7098 static int __huge_pmd_unshare(struct mmu_gather *tlb,
7099 		struct vm_area_struct *vma, unsigned long addr, pte_t *ptep,
7100 		bool check_locks)
7101 {
7102 	return 0;
7103 }
7104 
7105 int huge_pmd_unshare(struct mmu_gather *tlb, struct vm_area_struct *vma,
7106 		unsigned long addr, pte_t *ptep)
7107 {
7108 	return 0;
7109 }
7110 
7111 void huge_pmd_unshare_flush(struct mmu_gather *tlb, struct vm_area_struct *vma)
7112 {
7113 }
7114 
7115 void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
7116 				unsigned long *start, unsigned long *end)
7117 {
7118 }
7119 
7120 bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
7121 {
7122 	return false;
7123 }
7124 #endif /* CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING */
7125 
7126 #ifdef CONFIG_ARCH_WANT_GENERAL_HUGETLB
7127 pte_t *huge_pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma,
7128 			unsigned long addr, unsigned long sz)
7129 {
7130 	pgd_t *pgd;
7131 	p4d_t *p4d;
7132 	pud_t *pud;
7133 	pte_t *pte = NULL;
7134 
7135 	pgd = pgd_offset(mm, addr);
7136 	p4d = p4d_alloc(mm, pgd, addr);
7137 	if (!p4d)
7138 		return NULL;
7139 	pud = pud_alloc(mm, p4d, addr);
7140 	if (pud) {
7141 		if (sz == PUD_SIZE) {
7142 			pte = (pte_t *)pud;
7143 		} else {
7144 			BUG_ON(sz != PMD_SIZE);
7145 			if (want_pmd_share(vma, addr) && pud_none(*pud))
7146 				pte = huge_pmd_share(mm, vma, addr, pud);
7147 			else
7148 				pte = (pte_t *)pmd_alloc(mm, pud, addr);
7149 		}
7150 	}
7151 
7152 	if (pte) {
7153 		pte_t pteval = ptep_get_lockless(pte);
7154 
7155 		BUG_ON(pte_present(pteval) && !pte_huge(pteval));
7156 	}
7157 
7158 	return pte;
7159 }
7160 
7161 /*
7162  * huge_pte_offset() - Walk the page table to resolve the hugepage
7163  * entry at address @addr
7164  *
7165  * Return: Pointer to page table entry (PUD or PMD) for
7166  * address @addr, or NULL if a !p*d_present() entry is encountered and the
7167  * size @sz doesn't match the hugepage size at this level of the page
7168  * table.
7169  */
7170 pte_t *huge_pte_offset(struct mm_struct *mm,
7171 		       unsigned long addr, unsigned long sz)
7172 {
7173 	pgd_t *pgd;
7174 	p4d_t *p4d;
7175 	pud_t *pud;
7176 	pmd_t *pmd;
7177 
7178 	pgd = pgd_offset(mm, addr);
7179 	if (!pgd_present(*pgd))
7180 		return NULL;
7181 	p4d = p4d_offset(pgd, addr);
7182 	if (!p4d_present(*p4d))
7183 		return NULL;
7184 
7185 	pud = pud_offset(p4d, addr);
7186 	if (sz == PUD_SIZE)
7187 		/* must be pud huge, non-present or none */
7188 		return (pte_t *)pud;
7189 	if (!pud_present(*pud))
7190 		return NULL;
7191 	/* must have a valid entry and size to go further */
7192 
7193 	pmd = pmd_offset(pud, addr);
7194 	/* must be pmd huge, non-present or none */
7195 	return (pte_t *)pmd;
7196 }
7197 
7198 /*
7199  * Return a mask that can be used to update an address to the last huge
7200  * page in a page table page mapping size.  Used to skip non-present
7201  * page table entries when linearly scanning address ranges.  Architectures
7202  * with unique huge page to page table relationships can define their own
7203  * version of this routine.
7204  */
7205 unsigned long hugetlb_mask_last_page(struct hstate *h)
7206 {
7207 	unsigned long hp_size = huge_page_size(h);
7208 
7209 	if (hp_size == PUD_SIZE)
7210 		return P4D_SIZE - PUD_SIZE;
7211 	else if (hp_size == PMD_SIZE)
7212 		return PUD_SIZE - PMD_SIZE;
7213 	else
7214 		return 0UL;
7215 }
7216 
7217 #else
7218 
7219 /* See description above.  Architectures can provide their own version. */
7220 __weak unsigned long hugetlb_mask_last_page(struct hstate *h)
7221 {
7222 #ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING
7223 	if (huge_page_size(h) == PMD_SIZE)
7224 		return PUD_SIZE - PMD_SIZE;
7225 #endif
7226 	return 0UL;
7227 }
7228 
7229 #endif /* CONFIG_ARCH_WANT_GENERAL_HUGETLB */
7230 
7231 /**
7232  * folio_isolate_hugetlb - try to isolate an allocated hugetlb folio
7233  * @folio: the folio to isolate
7234  * @list: the list to add the folio to on success
7235  *
7236  * Isolate an allocated (refcount > 0) hugetlb folio, marking it as
7237  * isolated/non-migratable, and moving it from the active list to the
7238  * given list.
7239  *
7240  * Isolation will fail if @folio is not an allocated hugetlb folio, or if
7241  * it is already isolated/non-migratable.
7242  *
7243  * On success, an additional folio reference is taken that must be dropped
7244  * using folio_putback_hugetlb() to undo the isolation.
7245  *
7246  * Return: True if isolation worked, otherwise False.
7247  */
7248 bool folio_isolate_hugetlb(struct folio *folio, struct list_head *list)
7249 {
7250 	bool ret = true;
7251 
7252 	spin_lock_irq(&hugetlb_lock);
7253 	if (!folio_test_hugetlb(folio) ||
7254 	    !folio_test_hugetlb_migratable(folio) ||
7255 	    !folio_try_get(folio)) {
7256 		ret = false;
7257 		goto unlock;
7258 	}
7259 	folio_clear_hugetlb_migratable(folio);
7260 	list_move_tail(&folio->lru, list);
7261 unlock:
7262 	spin_unlock_irq(&hugetlb_lock);
7263 	return ret;
7264 }
7265 
7266 int get_hwpoison_hugetlb_folio(struct folio *folio, bool *hugetlb, bool unpoison)
7267 {
7268 	int ret = 0;
7269 
7270 	*hugetlb = false;
7271 	spin_lock_irq(&hugetlb_lock);
7272 	if (folio_test_hugetlb(folio)) {
7273 		*hugetlb = true;
7274 		if (folio_test_hugetlb_freed(folio))
7275 			ret = 0;
7276 		else if (folio_test_hugetlb_migratable(folio) || unpoison)
7277 			ret = folio_try_get(folio);
7278 		else
7279 			ret = -EBUSY;
7280 	}
7281 	spin_unlock_irq(&hugetlb_lock);
7282 	return ret;
7283 }
7284 
7285 /**
7286  * folio_putback_hugetlb - unisolate a hugetlb folio
7287  * @folio: the isolated hugetlb folio
7288  *
7289  * Putback/un-isolate the hugetlb folio that was previous isolated using
7290  * folio_isolate_hugetlb(): marking it non-isolated/migratable and putting it
7291  * back onto the active list.
7292  *
7293  * Will drop the additional folio reference obtained through
7294  * folio_isolate_hugetlb().
7295  */
7296 void folio_putback_hugetlb(struct folio *folio)
7297 {
7298 	spin_lock_irq(&hugetlb_lock);
7299 	folio_set_hugetlb_migratable(folio);
7300 	list_move_tail(&folio->lru, &(folio_hstate(folio))->hugepage_activelist);
7301 	spin_unlock_irq(&hugetlb_lock);
7302 	folio_put(folio);
7303 }
7304 
7305 void move_hugetlb_state(struct folio *old_folio, struct folio *new_folio,
7306 			enum migrate_reason reason)
7307 {
7308 	struct hstate *h = folio_hstate(old_folio);
7309 
7310 	hugetlb_cgroup_migrate(old_folio, new_folio);
7311 	folio_set_owner_migrate_reason(new_folio, reason);
7312 
7313 	/*
7314 	 * transfer temporary state of the new hugetlb folio. This is
7315 	 * reverse to other transitions because the newpage is going to
7316 	 * be final while the old one will be freed so it takes over
7317 	 * the temporary status.
7318 	 *
7319 	 * Also note that we have to transfer the per-node surplus state
7320 	 * here as well otherwise the global surplus count will not match
7321 	 * the per-node's.
7322 	 */
7323 	if (folio_test_hugetlb_temporary(new_folio)) {
7324 		int old_nid = folio_nid(old_folio);
7325 		int new_nid = folio_nid(new_folio);
7326 
7327 		folio_set_hugetlb_temporary(old_folio);
7328 		folio_clear_hugetlb_temporary(new_folio);
7329 
7330 
7331 		/*
7332 		 * There is no need to transfer the per-node surplus state
7333 		 * when we do not cross the node.
7334 		 */
7335 		if (new_nid != old_nid) {
7336 			spin_lock_irq(&hugetlb_lock);
7337 			if (h->surplus_huge_pages_node[old_nid]) {
7338 				h->surplus_huge_pages_node[old_nid]--;
7339 				h->surplus_huge_pages_node[new_nid]++;
7340 			}
7341 			spin_unlock_irq(&hugetlb_lock);
7342 		}
7343 	}
7344 
7345 	/*
7346 	 * Our old folio is isolated and has "migratable" cleared until it
7347 	 * is putback. As migration succeeded, set the new folio "migratable"
7348 	 * and add it to the active list.
7349 	 */
7350 	spin_lock_irq(&hugetlb_lock);
7351 	folio_set_hugetlb_migratable(new_folio);
7352 	list_move_tail(&new_folio->lru, &(folio_hstate(new_folio))->hugepage_activelist);
7353 	spin_unlock_irq(&hugetlb_lock);
7354 }
7355 
7356 /*
7357  * If @take_locks is false, the caller must ensure that no concurrent page table
7358  * access can happen (except for gup_fast() and hardware page walks).
7359  * If @take_locks is true, we take the hugetlb VMA lock (to lock out things like
7360  * concurrent page fault handling) and the file rmap lock.
7361  */
7362 static void hugetlb_unshare_pmds(struct vm_area_struct *vma,
7363 				   unsigned long start,
7364 				   unsigned long end,
7365 				   bool take_locks)
7366 {
7367 	struct hstate *h = hstate_vma(vma);
7368 	unsigned long sz = huge_page_size(h);
7369 	struct mm_struct *mm = vma->vm_mm;
7370 	struct mmu_notifier_range range;
7371 	struct mmu_gather tlb;
7372 	unsigned long address;
7373 	spinlock_t *ptl;
7374 	pte_t *ptep;
7375 
7376 	if (!(vma->vm_flags & VM_MAYSHARE))
7377 		return;
7378 
7379 	if (start >= end)
7380 		return;
7381 
7382 	flush_cache_range(vma, start, end);
7383 	tlb_gather_mmu_vma(&tlb, vma);
7384 
7385 	/*
7386 	 * No need to call adjust_range_if_pmd_sharing_possible(), because
7387 	 * we have already done the PUD_SIZE alignment.
7388 	 */
7389 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
7390 				start, end);
7391 	mmu_notifier_invalidate_range_start(&range);
7392 	if (take_locks) {
7393 		hugetlb_vma_lock_write(vma);
7394 		i_mmap_lock_write(vma->vm_file->f_mapping);
7395 	} else {
7396 		i_mmap_assert_write_locked(vma->vm_file->f_mapping);
7397 	}
7398 	for (address = start; address < end; address += PUD_SIZE) {
7399 		ptep = hugetlb_walk(vma, address, sz);
7400 		if (!ptep)
7401 			continue;
7402 		ptl = huge_pte_lock(h, mm, ptep);
7403 		__huge_pmd_unshare(&tlb, vma, address, ptep, take_locks);
7404 		spin_unlock(ptl);
7405 	}
7406 	huge_pmd_unshare_flush(&tlb, vma);
7407 	if (take_locks) {
7408 		i_mmap_unlock_write(vma->vm_file->f_mapping);
7409 		hugetlb_vma_unlock_write(vma);
7410 	}
7411 	/*
7412 	 * No need to call mmu_notifier_arch_invalidate_secondary_tlbs(), see
7413 	 * Documentation/mm/mmu_notifier.rst.
7414 	 */
7415 	mmu_notifier_invalidate_range_end(&range);
7416 	tlb_finish_mmu(&tlb);
7417 }
7418 
7419 /*
7420  * This function will unconditionally remove all the shared pmd pgtable entries
7421  * within the specific vma for a hugetlbfs memory range.
7422  */
7423 void hugetlb_unshare_all_pmds(struct vm_area_struct *vma)
7424 {
7425 	hugetlb_unshare_pmds(vma, ALIGN(vma->vm_start, PUD_SIZE),
7426 			ALIGN_DOWN(vma->vm_end, PUD_SIZE),
7427 			/* take_locks = */ true);
7428 }
7429 
7430 /*
7431  * For hugetlb, mremap() is an odd edge case - while the VMA copying is
7432  * performed, we permit both the old and new VMAs to reference the same
7433  * reservation.
7434  *
7435  * We fix this up after the operation succeeds, or if a newly allocated VMA
7436  * is closed as a result of a failure to allocate memory.
7437  */
7438 void fixup_hugetlb_reservations(struct vm_area_struct *vma)
7439 {
7440 	if (is_vm_hugetlb_page(vma))
7441 		clear_vma_resv_huge_pages(vma);
7442 }
7443