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