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