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