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