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