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