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