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