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
34 #include <asm/page.h>
35 #include <asm/pgalloc.h>
36 #include <asm/tlb.h>
37
38 #include <linux/io.h>
39 #include <linux/hugetlb.h>
40 #include <linux/hugetlb_cgroup.h>
41 #include <linux/node.h>
42 #include <linux/page_owner.h>
43 #include "internal.h"
44
45 int hugetlb_max_hstate __read_mostly;
46 unsigned int default_hstate_idx;
47 struct hstate hstates[HUGE_MAX_HSTATE];
48
49 #ifdef CONFIG_CMA
50 static struct cma *hugetlb_cma[MAX_NUMNODES];
51 #endif
52 static unsigned long hugetlb_cma_size __initdata;
53
54 /*
55 * Minimum page order among possible hugepage sizes, set to a proper value
56 * at boot time.
57 */
58 static unsigned int minimum_order __read_mostly = UINT_MAX;
59
60 __initdata LIST_HEAD(huge_boot_pages);
61
62 /* for command line parsing */
63 static struct hstate * __initdata parsed_hstate;
64 static unsigned long __initdata default_hstate_max_huge_pages;
65 static bool __initdata parsed_valid_hugepagesz = true;
66 static bool __initdata parsed_default_hugepagesz;
67
68 /*
69 * Protects updates to hugepage_freelists, hugepage_activelist, nr_huge_pages,
70 * free_huge_pages, and surplus_huge_pages.
71 */
72 DEFINE_SPINLOCK(hugetlb_lock);
73
74 /*
75 * Serializes faults on the same logical page. This is used to
76 * prevent spurious OOMs when the hugepage pool is fully utilized.
77 */
78 static int num_fault_mutexes;
79 struct mutex *hugetlb_fault_mutex_table ____cacheline_aligned_in_smp;
80
81 static void hugetlb_unshare_pmds(struct vm_area_struct *vma,
82 unsigned long start, unsigned long end);
83
PageHugeFreed(struct page * head)84 static inline bool PageHugeFreed(struct page *head)
85 {
86 return page_private(head + 4) == -1UL;
87 }
88
SetPageHugeFreed(struct page * head)89 static inline void SetPageHugeFreed(struct page *head)
90 {
91 set_page_private(head + 4, -1UL);
92 }
93
ClearPageHugeFreed(struct page * head)94 static inline void ClearPageHugeFreed(struct page *head)
95 {
96 set_page_private(head + 4, 0);
97 }
98
99 /* Forward declaration */
100 static int hugetlb_acct_memory(struct hstate *h, long delta);
101
unlock_or_release_subpool(struct hugepage_subpool * spool)102 static inline void unlock_or_release_subpool(struct hugepage_subpool *spool)
103 {
104 bool free = (spool->count == 0) && (spool->used_hpages == 0);
105
106 spin_unlock(&spool->lock);
107
108 /* If no pages are used, and no other handles to the subpool
109 * remain, give up any reservations based on minimum size and
110 * free the subpool */
111 if (free) {
112 if (spool->min_hpages != -1)
113 hugetlb_acct_memory(spool->hstate,
114 -spool->min_hpages);
115 kfree(spool);
116 }
117 }
118
hugepage_new_subpool(struct hstate * h,long max_hpages,long min_hpages)119 struct hugepage_subpool *hugepage_new_subpool(struct hstate *h, long max_hpages,
120 long min_hpages)
121 {
122 struct hugepage_subpool *spool;
123
124 spool = kzalloc(sizeof(*spool), GFP_KERNEL);
125 if (!spool)
126 return NULL;
127
128 spin_lock_init(&spool->lock);
129 spool->count = 1;
130 spool->max_hpages = max_hpages;
131 spool->hstate = h;
132 spool->min_hpages = min_hpages;
133
134 if (min_hpages != -1 && hugetlb_acct_memory(h, min_hpages)) {
135 kfree(spool);
136 return NULL;
137 }
138 spool->rsv_hpages = min_hpages;
139
140 return spool;
141 }
142
hugepage_put_subpool(struct hugepage_subpool * spool)143 void hugepage_put_subpool(struct hugepage_subpool *spool)
144 {
145 spin_lock(&spool->lock);
146 BUG_ON(!spool->count);
147 spool->count--;
148 unlock_or_release_subpool(spool);
149 }
150
151 /*
152 * Subpool accounting for allocating and reserving pages.
153 * Return -ENOMEM if there are not enough resources to satisfy the
154 * request. Otherwise, return the number of pages by which the
155 * global pools must be adjusted (upward). The returned value may
156 * only be different than the passed value (delta) in the case where
157 * a subpool minimum size must be maintained.
158 */
hugepage_subpool_get_pages(struct hugepage_subpool * spool,long delta)159 static long hugepage_subpool_get_pages(struct hugepage_subpool *spool,
160 long delta)
161 {
162 long ret = delta;
163
164 if (!spool)
165 return ret;
166
167 spin_lock(&spool->lock);
168
169 if (spool->max_hpages != -1) { /* maximum size accounting */
170 if ((spool->used_hpages + delta) <= spool->max_hpages)
171 spool->used_hpages += delta;
172 else {
173 ret = -ENOMEM;
174 goto unlock_ret;
175 }
176 }
177
178 /* minimum size accounting */
179 if (spool->min_hpages != -1 && spool->rsv_hpages) {
180 if (delta > spool->rsv_hpages) {
181 /*
182 * Asking for more reserves than those already taken on
183 * behalf of subpool. Return difference.
184 */
185 ret = delta - spool->rsv_hpages;
186 spool->rsv_hpages = 0;
187 } else {
188 ret = 0; /* reserves already accounted for */
189 spool->rsv_hpages -= delta;
190 }
191 }
192
193 unlock_ret:
194 spin_unlock(&spool->lock);
195 return ret;
196 }
197
198 /*
199 * Subpool accounting for freeing and unreserving pages.
200 * Return the number of global page reservations that must be dropped.
201 * The return value may only be different than the passed value (delta)
202 * in the case where a subpool minimum size must be maintained.
203 */
hugepage_subpool_put_pages(struct hugepage_subpool * spool,long delta)204 static long hugepage_subpool_put_pages(struct hugepage_subpool *spool,
205 long delta)
206 {
207 long ret = delta;
208
209 if (!spool)
210 return delta;
211
212 spin_lock(&spool->lock);
213
214 if (spool->max_hpages != -1) /* maximum size accounting */
215 spool->used_hpages -= delta;
216
217 /* minimum size accounting */
218 if (spool->min_hpages != -1 && spool->used_hpages < spool->min_hpages) {
219 if (spool->rsv_hpages + delta <= spool->min_hpages)
220 ret = 0;
221 else
222 ret = spool->rsv_hpages + delta - spool->min_hpages;
223
224 spool->rsv_hpages += delta;
225 if (spool->rsv_hpages > spool->min_hpages)
226 spool->rsv_hpages = spool->min_hpages;
227 }
228
229 /*
230 * If hugetlbfs_put_super couldn't free spool due to an outstanding
231 * quota reference, free it now.
232 */
233 unlock_or_release_subpool(spool);
234
235 return ret;
236 }
237
subpool_inode(struct inode * inode)238 static inline struct hugepage_subpool *subpool_inode(struct inode *inode)
239 {
240 return HUGETLBFS_SB(inode->i_sb)->spool;
241 }
242
subpool_vma(struct vm_area_struct * vma)243 static inline struct hugepage_subpool *subpool_vma(struct vm_area_struct *vma)
244 {
245 return subpool_inode(file_inode(vma->vm_file));
246 }
247
248 /* Helper that removes a struct file_region from the resv_map cache and returns
249 * it for use.
250 */
251 static struct file_region *
get_file_region_entry_from_cache(struct resv_map * resv,long from,long to)252 get_file_region_entry_from_cache(struct resv_map *resv, long from, long to)
253 {
254 struct file_region *nrg = NULL;
255
256 VM_BUG_ON(resv->region_cache_count <= 0);
257
258 resv->region_cache_count--;
259 nrg = list_first_entry(&resv->region_cache, struct file_region, link);
260 list_del(&nrg->link);
261
262 nrg->from = from;
263 nrg->to = to;
264
265 return nrg;
266 }
267
copy_hugetlb_cgroup_uncharge_info(struct file_region * nrg,struct file_region * rg)268 static void copy_hugetlb_cgroup_uncharge_info(struct file_region *nrg,
269 struct file_region *rg)
270 {
271 #ifdef CONFIG_CGROUP_HUGETLB
272 nrg->reservation_counter = rg->reservation_counter;
273 nrg->css = rg->css;
274 if (rg->css)
275 css_get(rg->css);
276 #endif
277 }
278
279 /* 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)280 static void record_hugetlb_cgroup_uncharge_info(struct hugetlb_cgroup *h_cg,
281 struct hstate *h,
282 struct resv_map *resv,
283 struct file_region *nrg)
284 {
285 #ifdef CONFIG_CGROUP_HUGETLB
286 if (h_cg) {
287 nrg->reservation_counter =
288 &h_cg->rsvd_hugepage[hstate_index(h)];
289 nrg->css = &h_cg->css;
290 /*
291 * The caller will hold exactly one h_cg->css reference for the
292 * whole contiguous reservation region. But this area might be
293 * scattered when there are already some file_regions reside in
294 * it. As a result, many file_regions may share only one css
295 * reference. In order to ensure that one file_region must hold
296 * exactly one h_cg->css reference, we should do css_get for
297 * each file_region and leave the reference held by caller
298 * untouched.
299 */
300 css_get(&h_cg->css);
301 if (!resv->pages_per_hpage)
302 resv->pages_per_hpage = pages_per_huge_page(h);
303 /* pages_per_hpage should be the same for all entries in
304 * a resv_map.
305 */
306 VM_BUG_ON(resv->pages_per_hpage != pages_per_huge_page(h));
307 } else {
308 nrg->reservation_counter = NULL;
309 nrg->css = NULL;
310 }
311 #endif
312 }
313
put_uncharge_info(struct file_region * rg)314 static void put_uncharge_info(struct file_region *rg)
315 {
316 #ifdef CONFIG_CGROUP_HUGETLB
317 if (rg->css)
318 css_put(rg->css);
319 #endif
320 }
321
has_same_uncharge_info(struct file_region * rg,struct file_region * org)322 static bool has_same_uncharge_info(struct file_region *rg,
323 struct file_region *org)
324 {
325 #ifdef CONFIG_CGROUP_HUGETLB
326 return rg && org &&
327 rg->reservation_counter == org->reservation_counter &&
328 rg->css == org->css;
329
330 #else
331 return true;
332 #endif
333 }
334
coalesce_file_region(struct resv_map * resv,struct file_region * rg)335 static void coalesce_file_region(struct resv_map *resv, struct file_region *rg)
336 {
337 struct file_region *nrg = NULL, *prg = NULL;
338
339 prg = list_prev_entry(rg, link);
340 if (&prg->link != &resv->regions && prg->to == rg->from &&
341 has_same_uncharge_info(prg, rg)) {
342 prg->to = rg->to;
343
344 list_del(&rg->link);
345 put_uncharge_info(rg);
346 kfree(rg);
347
348 rg = prg;
349 }
350
351 nrg = list_next_entry(rg, link);
352 if (&nrg->link != &resv->regions && nrg->from == rg->to &&
353 has_same_uncharge_info(nrg, rg)) {
354 nrg->from = rg->from;
355
356 list_del(&rg->link);
357 put_uncharge_info(rg);
358 kfree(rg);
359 }
360 }
361
362 /*
363 * Must be called with resv->lock held.
364 *
365 * Calling this with regions_needed != NULL will count the number of pages
366 * to be added but will not modify the linked list. And regions_needed will
367 * indicate the number of file_regions needed in the cache to carry out to add
368 * the regions for this range.
369 */
add_reservation_in_range(struct resv_map * resv,long f,long t,struct hugetlb_cgroup * h_cg,struct hstate * h,long * regions_needed)370 static long add_reservation_in_range(struct resv_map *resv, long f, long t,
371 struct hugetlb_cgroup *h_cg,
372 struct hstate *h, long *regions_needed)
373 {
374 long add = 0;
375 struct list_head *head = &resv->regions;
376 long last_accounted_offset = f;
377 struct file_region *rg = NULL, *trg = NULL, *nrg = NULL;
378
379 if (regions_needed)
380 *regions_needed = 0;
381
382 /* In this loop, we essentially handle an entry for the range
383 * [last_accounted_offset, rg->from), at every iteration, with some
384 * bounds checking.
385 */
386 list_for_each_entry_safe(rg, trg, head, link) {
387 /* Skip irrelevant regions that start before our range. */
388 if (rg->from < f) {
389 /* If this region ends after the last accounted offset,
390 * then we need to update last_accounted_offset.
391 */
392 if (rg->to > last_accounted_offset)
393 last_accounted_offset = rg->to;
394 continue;
395 }
396
397 /* When we find a region that starts beyond our range, we've
398 * finished.
399 */
400 if (rg->from > t)
401 break;
402
403 /* Add an entry for last_accounted_offset -> rg->from, and
404 * update last_accounted_offset.
405 */
406 if (rg->from > last_accounted_offset) {
407 add += rg->from - last_accounted_offset;
408 if (!regions_needed) {
409 nrg = get_file_region_entry_from_cache(
410 resv, last_accounted_offset, rg->from);
411 record_hugetlb_cgroup_uncharge_info(h_cg, h,
412 resv, nrg);
413 list_add(&nrg->link, rg->link.prev);
414 coalesce_file_region(resv, nrg);
415 } else
416 *regions_needed += 1;
417 }
418
419 last_accounted_offset = rg->to;
420 }
421
422 /* Handle the case where our range extends beyond
423 * last_accounted_offset.
424 */
425 if (last_accounted_offset < t) {
426 add += t - last_accounted_offset;
427 if (!regions_needed) {
428 nrg = get_file_region_entry_from_cache(
429 resv, last_accounted_offset, t);
430 record_hugetlb_cgroup_uncharge_info(h_cg, h, resv, nrg);
431 list_add(&nrg->link, rg->link.prev);
432 coalesce_file_region(resv, nrg);
433 } else
434 *regions_needed += 1;
435 }
436
437 VM_BUG_ON(add < 0);
438 return add;
439 }
440
441 /* Must be called with resv->lock acquired. Will drop lock to allocate entries.
442 */
allocate_file_region_entries(struct resv_map * resv,int regions_needed)443 static int allocate_file_region_entries(struct resv_map *resv,
444 int regions_needed)
445 __must_hold(&resv->lock)
446 {
447 struct list_head allocated_regions;
448 int to_allocate = 0, i = 0;
449 struct file_region *trg = NULL, *rg = NULL;
450
451 VM_BUG_ON(regions_needed < 0);
452
453 INIT_LIST_HEAD(&allocated_regions);
454
455 /*
456 * Check for sufficient descriptors in the cache to accommodate
457 * the number of in progress add operations plus regions_needed.
458 *
459 * This is a while loop because when we drop the lock, some other call
460 * to region_add or region_del may have consumed some region_entries,
461 * so we keep looping here until we finally have enough entries for
462 * (adds_in_progress + regions_needed).
463 */
464 while (resv->region_cache_count <
465 (resv->adds_in_progress + regions_needed)) {
466 to_allocate = resv->adds_in_progress + regions_needed -
467 resv->region_cache_count;
468
469 /* At this point, we should have enough entries in the cache
470 * for all the existings adds_in_progress. We should only be
471 * needing to allocate for regions_needed.
472 */
473 VM_BUG_ON(resv->region_cache_count < resv->adds_in_progress);
474
475 spin_unlock(&resv->lock);
476 for (i = 0; i < to_allocate; i++) {
477 trg = kmalloc(sizeof(*trg), GFP_KERNEL);
478 if (!trg)
479 goto out_of_memory;
480 list_add(&trg->link, &allocated_regions);
481 }
482
483 spin_lock(&resv->lock);
484
485 list_splice(&allocated_regions, &resv->region_cache);
486 resv->region_cache_count += to_allocate;
487 }
488
489 return 0;
490
491 out_of_memory:
492 list_for_each_entry_safe(rg, trg, &allocated_regions, link) {
493 list_del(&rg->link);
494 kfree(rg);
495 }
496 return -ENOMEM;
497 }
498
499 /*
500 * Add the huge page range represented by [f, t) to the reserve
501 * map. Regions will be taken from the cache to fill in this range.
502 * Sufficient regions should exist in the cache due to the previous
503 * call to region_chg with the same range, but in some cases the cache will not
504 * have sufficient entries due to races with other code doing region_add or
505 * region_del. The extra needed entries will be allocated.
506 *
507 * regions_needed is the out value provided by a previous call to region_chg.
508 *
509 * Return the number of new huge pages added to the map. This number is greater
510 * than or equal to zero. If file_region entries needed to be allocated for
511 * this operation and we were not able to allocate, it returns -ENOMEM.
512 * region_add of regions of length 1 never allocate file_regions and cannot
513 * fail; region_chg will always allocate at least 1 entry and a region_add for
514 * 1 page will only require at most 1 entry.
515 */
region_add(struct resv_map * resv,long f,long t,long in_regions_needed,struct hstate * h,struct hugetlb_cgroup * h_cg)516 static long region_add(struct resv_map *resv, long f, long t,
517 long in_regions_needed, struct hstate *h,
518 struct hugetlb_cgroup *h_cg)
519 {
520 long add = 0, actual_regions_needed = 0;
521
522 spin_lock(&resv->lock);
523 retry:
524
525 /* Count how many regions are actually needed to execute this add. */
526 add_reservation_in_range(resv, f, t, NULL, NULL,
527 &actual_regions_needed);
528
529 /*
530 * Check for sufficient descriptors in the cache to accommodate
531 * this add operation. Note that actual_regions_needed may be greater
532 * than in_regions_needed, as the resv_map may have been modified since
533 * the region_chg call. In this case, we need to make sure that we
534 * allocate extra entries, such that we have enough for all the
535 * existing adds_in_progress, plus the excess needed for this
536 * operation.
537 */
538 if (actual_regions_needed > in_regions_needed &&
539 resv->region_cache_count <
540 resv->adds_in_progress +
541 (actual_regions_needed - in_regions_needed)) {
542 /* region_add operation of range 1 should never need to
543 * allocate file_region entries.
544 */
545 VM_BUG_ON(t - f <= 1);
546
547 if (allocate_file_region_entries(
548 resv, actual_regions_needed - in_regions_needed)) {
549 return -ENOMEM;
550 }
551
552 goto retry;
553 }
554
555 add = add_reservation_in_range(resv, f, t, h_cg, h, NULL);
556
557 resv->adds_in_progress -= in_regions_needed;
558
559 spin_unlock(&resv->lock);
560 VM_BUG_ON(add < 0);
561 return add;
562 }
563
564 /*
565 * Examine the existing reserve map and determine how many
566 * huge pages in the specified range [f, t) are NOT currently
567 * represented. This routine is called before a subsequent
568 * call to region_add that will actually modify the reserve
569 * map to add the specified range [f, t). region_chg does
570 * not change the number of huge pages represented by the
571 * map. A number of new file_region structures is added to the cache as a
572 * placeholder, for the subsequent region_add call to use. At least 1
573 * file_region structure is added.
574 *
575 * out_regions_needed is the number of regions added to the
576 * resv->adds_in_progress. This value needs to be provided to a follow up call
577 * to region_add or region_abort for proper accounting.
578 *
579 * Returns the number of huge pages that need to be added to the existing
580 * reservation map for the range [f, t). This number is greater or equal to
581 * zero. -ENOMEM is returned if a new file_region structure or cache entry
582 * is needed and can not be allocated.
583 */
region_chg(struct resv_map * resv,long f,long t,long * out_regions_needed)584 static long region_chg(struct resv_map *resv, long f, long t,
585 long *out_regions_needed)
586 {
587 long chg = 0;
588
589 spin_lock(&resv->lock);
590
591 /* Count how many hugepages in this range are NOT represented. */
592 chg = add_reservation_in_range(resv, f, t, NULL, NULL,
593 out_regions_needed);
594
595 if (*out_regions_needed == 0)
596 *out_regions_needed = 1;
597
598 if (allocate_file_region_entries(resv, *out_regions_needed))
599 return -ENOMEM;
600
601 resv->adds_in_progress += *out_regions_needed;
602
603 spin_unlock(&resv->lock);
604 return chg;
605 }
606
607 /*
608 * Abort the in progress add operation. The adds_in_progress field
609 * of the resv_map keeps track of the operations in progress between
610 * calls to region_chg and region_add. Operations are sometimes
611 * aborted after the call to region_chg. In such cases, region_abort
612 * is called to decrement the adds_in_progress counter. regions_needed
613 * is the value returned by the region_chg call, it is used to decrement
614 * the adds_in_progress counter.
615 *
616 * NOTE: The range arguments [f, t) are not needed or used in this
617 * routine. They are kept to make reading the calling code easier as
618 * arguments will match the associated region_chg call.
619 */
region_abort(struct resv_map * resv,long f,long t,long regions_needed)620 static void region_abort(struct resv_map *resv, long f, long t,
621 long regions_needed)
622 {
623 spin_lock(&resv->lock);
624 VM_BUG_ON(!resv->region_cache_count);
625 resv->adds_in_progress -= regions_needed;
626 spin_unlock(&resv->lock);
627 }
628
629 /*
630 * Delete the specified range [f, t) from the reserve map. If the
631 * t parameter is LONG_MAX, this indicates that ALL regions after f
632 * should be deleted. Locate the regions which intersect [f, t)
633 * and either trim, delete or split the existing regions.
634 *
635 * Returns the number of huge pages deleted from the reserve map.
636 * In the normal case, the return value is zero or more. In the
637 * case where a region must be split, a new region descriptor must
638 * be allocated. If the allocation fails, -ENOMEM will be returned.
639 * NOTE: If the parameter t == LONG_MAX, then we will never split
640 * a region and possibly return -ENOMEM. Callers specifying
641 * t == LONG_MAX do not need to check for -ENOMEM error.
642 */
region_del(struct resv_map * resv,long f,long t)643 static long region_del(struct resv_map *resv, long f, long t)
644 {
645 struct list_head *head = &resv->regions;
646 struct file_region *rg, *trg;
647 struct file_region *nrg = NULL;
648 long del = 0;
649
650 retry:
651 spin_lock(&resv->lock);
652 list_for_each_entry_safe(rg, trg, head, link) {
653 /*
654 * Skip regions before the range to be deleted. file_region
655 * ranges are normally of the form [from, to). However, there
656 * may be a "placeholder" entry in the map which is of the form
657 * (from, to) with from == to. Check for placeholder entries
658 * at the beginning of the range to be deleted.
659 */
660 if (rg->to <= f && (rg->to != rg->from || rg->to != f))
661 continue;
662
663 if (rg->from >= t)
664 break;
665
666 if (f > rg->from && t < rg->to) { /* Must split region */
667 /*
668 * Check for an entry in the cache before dropping
669 * lock and attempting allocation.
670 */
671 if (!nrg &&
672 resv->region_cache_count > resv->adds_in_progress) {
673 nrg = list_first_entry(&resv->region_cache,
674 struct file_region,
675 link);
676 list_del(&nrg->link);
677 resv->region_cache_count--;
678 }
679
680 if (!nrg) {
681 spin_unlock(&resv->lock);
682 nrg = kmalloc(sizeof(*nrg), GFP_KERNEL);
683 if (!nrg)
684 return -ENOMEM;
685 goto retry;
686 }
687
688 del += t - f;
689 hugetlb_cgroup_uncharge_file_region(
690 resv, rg, t - f, false);
691
692 /* New entry for end of split region */
693 nrg->from = t;
694 nrg->to = rg->to;
695
696 copy_hugetlb_cgroup_uncharge_info(nrg, rg);
697
698 INIT_LIST_HEAD(&nrg->link);
699
700 /* Original entry is trimmed */
701 rg->to = f;
702
703 list_add(&nrg->link, &rg->link);
704 nrg = NULL;
705 break;
706 }
707
708 if (f <= rg->from && t >= rg->to) { /* Remove entire region */
709 del += rg->to - rg->from;
710 hugetlb_cgroup_uncharge_file_region(resv, rg,
711 rg->to - rg->from, true);
712 list_del(&rg->link);
713 kfree(rg);
714 continue;
715 }
716
717 if (f <= rg->from) { /* Trim beginning of region */
718 hugetlb_cgroup_uncharge_file_region(resv, rg,
719 t - rg->from, false);
720
721 del += t - rg->from;
722 rg->from = t;
723 } else { /* Trim end of region */
724 hugetlb_cgroup_uncharge_file_region(resv, rg,
725 rg->to - f, false);
726
727 del += rg->to - f;
728 rg->to = f;
729 }
730 }
731
732 spin_unlock(&resv->lock);
733 kfree(nrg);
734 return del;
735 }
736
737 /*
738 * A rare out of memory error was encountered which prevented removal of
739 * the reserve map region for a page. The huge page itself was free'ed
740 * and removed from the page cache. This routine will adjust the subpool
741 * usage count, and the global reserve count if needed. By incrementing
742 * these counts, the reserve map entry which could not be deleted will
743 * appear as a "reserved" entry instead of simply dangling with incorrect
744 * counts.
745 */
hugetlb_fix_reserve_counts(struct inode * inode)746 void hugetlb_fix_reserve_counts(struct inode *inode)
747 {
748 struct hugepage_subpool *spool = subpool_inode(inode);
749 long rsv_adjust;
750 bool reserved = false;
751
752 rsv_adjust = hugepage_subpool_get_pages(spool, 1);
753 if (rsv_adjust > 0) {
754 struct hstate *h = hstate_inode(inode);
755
756 if (!hugetlb_acct_memory(h, 1))
757 reserved = true;
758 } else if (!rsv_adjust) {
759 reserved = true;
760 }
761
762 if (!reserved)
763 pr_warn("hugetlb: Huge Page Reserved count may go negative.\n");
764 }
765
766 /*
767 * Count and return the number of huge pages in the reserve map
768 * that intersect with the range [f, t).
769 */
region_count(struct resv_map * resv,long f,long t)770 static long region_count(struct resv_map *resv, long f, long t)
771 {
772 struct list_head *head = &resv->regions;
773 struct file_region *rg;
774 long chg = 0;
775
776 spin_lock(&resv->lock);
777 /* Locate each segment we overlap with, and count that overlap. */
778 list_for_each_entry(rg, head, link) {
779 long seg_from;
780 long seg_to;
781
782 if (rg->to <= f)
783 continue;
784 if (rg->from >= t)
785 break;
786
787 seg_from = max(rg->from, f);
788 seg_to = min(rg->to, t);
789
790 chg += seg_to - seg_from;
791 }
792 spin_unlock(&resv->lock);
793
794 return chg;
795 }
796
797 /*
798 * Convert the address within this vma to the page offset within
799 * the mapping, in pagecache page units; huge pages here.
800 */
vma_hugecache_offset(struct hstate * h,struct vm_area_struct * vma,unsigned long address)801 static pgoff_t vma_hugecache_offset(struct hstate *h,
802 struct vm_area_struct *vma, unsigned long address)
803 {
804 return ((address - vma->vm_start) >> huge_page_shift(h)) +
805 (vma->vm_pgoff >> huge_page_order(h));
806 }
807
linear_hugepage_index(struct vm_area_struct * vma,unsigned long address)808 pgoff_t linear_hugepage_index(struct vm_area_struct *vma,
809 unsigned long address)
810 {
811 return vma_hugecache_offset(hstate_vma(vma), vma, address);
812 }
813 EXPORT_SYMBOL_GPL(linear_hugepage_index);
814
815 /*
816 * Return the size of the pages allocated when backing a VMA. In the majority
817 * cases this will be same size as used by the page table entries.
818 */
vma_kernel_pagesize(struct vm_area_struct * vma)819 unsigned long vma_kernel_pagesize(struct vm_area_struct *vma)
820 {
821 if (vma->vm_ops && vma->vm_ops->pagesize)
822 return vma->vm_ops->pagesize(vma);
823 return PAGE_SIZE;
824 }
825 EXPORT_SYMBOL_GPL(vma_kernel_pagesize);
826
827 /*
828 * Return the page size being used by the MMU to back a VMA. In the majority
829 * of cases, the page size used by the kernel matches the MMU size. On
830 * architectures where it differs, an architecture-specific 'strong'
831 * version of this symbol is required.
832 */
vma_mmu_pagesize(struct vm_area_struct * vma)833 __weak unsigned long vma_mmu_pagesize(struct vm_area_struct *vma)
834 {
835 return vma_kernel_pagesize(vma);
836 }
837
838 /*
839 * Flags for MAP_PRIVATE reservations. These are stored in the bottom
840 * bits of the reservation map pointer, which are always clear due to
841 * alignment.
842 */
843 #define HPAGE_RESV_OWNER (1UL << 0)
844 #define HPAGE_RESV_UNMAPPED (1UL << 1)
845 #define HPAGE_RESV_MASK (HPAGE_RESV_OWNER | HPAGE_RESV_UNMAPPED)
846
847 /*
848 * These helpers are used to track how many pages are reserved for
849 * faults in a MAP_PRIVATE mapping. Only the process that called mmap()
850 * is guaranteed to have their future faults succeed.
851 *
852 * With the exception of reset_vma_resv_huge_pages() which is called at fork(),
853 * the reserve counters are updated with the hugetlb_lock held. It is safe
854 * to reset the VMA at fork() time as it is not in use yet and there is no
855 * chance of the global counters getting corrupted as a result of the values.
856 *
857 * The private mapping reservation is represented in a subtly different
858 * manner to a shared mapping. A shared mapping has a region map associated
859 * with the underlying file, this region map represents the backing file
860 * pages which have ever had a reservation assigned which this persists even
861 * after the page is instantiated. A private mapping has a region map
862 * associated with the original mmap which is attached to all VMAs which
863 * reference it, this region map represents those offsets which have consumed
864 * reservation ie. where pages have been instantiated.
865 */
get_vma_private_data(struct vm_area_struct * vma)866 static unsigned long get_vma_private_data(struct vm_area_struct *vma)
867 {
868 return (unsigned long)vma->vm_private_data;
869 }
870
set_vma_private_data(struct vm_area_struct * vma,unsigned long value)871 static void set_vma_private_data(struct vm_area_struct *vma,
872 unsigned long value)
873 {
874 vma->vm_private_data = (void *)value;
875 }
876
877 static void
resv_map_set_hugetlb_cgroup_uncharge_info(struct resv_map * resv_map,struct hugetlb_cgroup * h_cg,struct hstate * h)878 resv_map_set_hugetlb_cgroup_uncharge_info(struct resv_map *resv_map,
879 struct hugetlb_cgroup *h_cg,
880 struct hstate *h)
881 {
882 #ifdef CONFIG_CGROUP_HUGETLB
883 if (!h_cg || !h) {
884 resv_map->reservation_counter = NULL;
885 resv_map->pages_per_hpage = 0;
886 resv_map->css = NULL;
887 } else {
888 resv_map->reservation_counter =
889 &h_cg->rsvd_hugepage[hstate_index(h)];
890 resv_map->pages_per_hpage = pages_per_huge_page(h);
891 resv_map->css = &h_cg->css;
892 }
893 #endif
894 }
895
resv_map_alloc(void)896 struct resv_map *resv_map_alloc(void)
897 {
898 struct resv_map *resv_map = kmalloc(sizeof(*resv_map), GFP_KERNEL);
899 struct file_region *rg = kmalloc(sizeof(*rg), GFP_KERNEL);
900
901 if (!resv_map || !rg) {
902 kfree(resv_map);
903 kfree(rg);
904 return NULL;
905 }
906
907 kref_init(&resv_map->refs);
908 spin_lock_init(&resv_map->lock);
909 INIT_LIST_HEAD(&resv_map->regions);
910
911 resv_map->adds_in_progress = 0;
912 /*
913 * Initialize these to 0. On shared mappings, 0's here indicate these
914 * fields don't do cgroup accounting. On private mappings, these will be
915 * re-initialized to the proper values, to indicate that hugetlb cgroup
916 * reservations are to be un-charged from here.
917 */
918 resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, NULL, NULL);
919
920 INIT_LIST_HEAD(&resv_map->region_cache);
921 list_add(&rg->link, &resv_map->region_cache);
922 resv_map->region_cache_count = 1;
923
924 return resv_map;
925 }
926
resv_map_release(struct kref * ref)927 void resv_map_release(struct kref *ref)
928 {
929 struct resv_map *resv_map = container_of(ref, struct resv_map, refs);
930 struct list_head *head = &resv_map->region_cache;
931 struct file_region *rg, *trg;
932
933 /* Clear out any active regions before we release the map. */
934 region_del(resv_map, 0, LONG_MAX);
935
936 /* ... and any entries left in the cache */
937 list_for_each_entry_safe(rg, trg, head, link) {
938 list_del(&rg->link);
939 kfree(rg);
940 }
941
942 VM_BUG_ON(resv_map->adds_in_progress);
943
944 kfree(resv_map);
945 }
946
inode_resv_map(struct inode * inode)947 static inline struct resv_map *inode_resv_map(struct inode *inode)
948 {
949 /*
950 * At inode evict time, i_mapping may not point to the original
951 * address space within the inode. This original address space
952 * contains the pointer to the resv_map. So, always use the
953 * address space embedded within the inode.
954 * The VERY common case is inode->mapping == &inode->i_data but,
955 * this may not be true for device special inodes.
956 */
957 return (struct resv_map *)(&inode->i_data)->private_data;
958 }
959
vma_resv_map(struct vm_area_struct * vma)960 static struct resv_map *vma_resv_map(struct vm_area_struct *vma)
961 {
962 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
963 if (vma->vm_flags & VM_MAYSHARE) {
964 struct address_space *mapping = vma->vm_file->f_mapping;
965 struct inode *inode = mapping->host;
966
967 return inode_resv_map(inode);
968
969 } else {
970 return (struct resv_map *)(get_vma_private_data(vma) &
971 ~HPAGE_RESV_MASK);
972 }
973 }
974
set_vma_resv_map(struct vm_area_struct * vma,struct resv_map * map)975 static void set_vma_resv_map(struct vm_area_struct *vma, struct resv_map *map)
976 {
977 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
978 VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
979
980 set_vma_private_data(vma, (get_vma_private_data(vma) &
981 HPAGE_RESV_MASK) | (unsigned long)map);
982 }
983
set_vma_resv_flags(struct vm_area_struct * vma,unsigned long flags)984 static void set_vma_resv_flags(struct vm_area_struct *vma, unsigned long flags)
985 {
986 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
987 VM_BUG_ON_VMA(vma->vm_flags & VM_MAYSHARE, vma);
988
989 set_vma_private_data(vma, get_vma_private_data(vma) | flags);
990 }
991
is_vma_resv_set(struct vm_area_struct * vma,unsigned long flag)992 static int is_vma_resv_set(struct vm_area_struct *vma, unsigned long flag)
993 {
994 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
995
996 return (get_vma_private_data(vma) & flag) != 0;
997 }
998
999 /* Reset counters to 0 and clear all HPAGE_RESV_* flags */
reset_vma_resv_huge_pages(struct vm_area_struct * vma)1000 void reset_vma_resv_huge_pages(struct vm_area_struct *vma)
1001 {
1002 VM_BUG_ON_VMA(!is_vm_hugetlb_page(vma), vma);
1003 if (!(vma->vm_flags & VM_MAYSHARE))
1004 vma->vm_private_data = (void *)0;
1005 }
1006
1007 /* Returns true if the VMA has associated reserve pages */
vma_has_reserves(struct vm_area_struct * vma,long chg)1008 static bool vma_has_reserves(struct vm_area_struct *vma, long chg)
1009 {
1010 if (vma->vm_flags & VM_NORESERVE) {
1011 /*
1012 * This address is already reserved by other process(chg == 0),
1013 * so, we should decrement reserved count. Without decrementing,
1014 * reserve count remains after releasing inode, because this
1015 * allocated page will go into page cache and is regarded as
1016 * coming from reserved pool in releasing step. Currently, we
1017 * don't have any other solution to deal with this situation
1018 * properly, so add work-around here.
1019 */
1020 if (vma->vm_flags & VM_MAYSHARE && chg == 0)
1021 return true;
1022 else
1023 return false;
1024 }
1025
1026 /* Shared mappings always use reserves */
1027 if (vma->vm_flags & VM_MAYSHARE) {
1028 /*
1029 * We know VM_NORESERVE is not set. Therefore, there SHOULD
1030 * be a region map for all pages. The only situation where
1031 * there is no region map is if a hole was punched via
1032 * fallocate. In this case, there really are no reserves to
1033 * use. This situation is indicated if chg != 0.
1034 */
1035 if (chg)
1036 return false;
1037 else
1038 return true;
1039 }
1040
1041 /*
1042 * Only the process that called mmap() has reserves for
1043 * private mappings.
1044 */
1045 if (is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
1046 /*
1047 * Like the shared case above, a hole punch or truncate
1048 * could have been performed on the private mapping.
1049 * Examine the value of chg to determine if reserves
1050 * actually exist or were previously consumed.
1051 * Very Subtle - The value of chg comes from a previous
1052 * call to vma_needs_reserves(). The reserve map for
1053 * private mappings has different (opposite) semantics
1054 * than that of shared mappings. vma_needs_reserves()
1055 * has already taken this difference in semantics into
1056 * account. Therefore, the meaning of chg is the same
1057 * as in the shared case above. Code could easily be
1058 * combined, but keeping it separate draws attention to
1059 * subtle differences.
1060 */
1061 if (chg)
1062 return false;
1063 else
1064 return true;
1065 }
1066
1067 return false;
1068 }
1069
enqueue_huge_page(struct hstate * h,struct page * page)1070 static void enqueue_huge_page(struct hstate *h, struct page *page)
1071 {
1072 int nid = page_to_nid(page);
1073 list_move(&page->lru, &h->hugepage_freelists[nid]);
1074 h->free_huge_pages++;
1075 h->free_huge_pages_node[nid]++;
1076 SetPageHugeFreed(page);
1077 }
1078
dequeue_huge_page_node_exact(struct hstate * h,int nid)1079 static struct page *dequeue_huge_page_node_exact(struct hstate *h, int nid)
1080 {
1081 struct page *page;
1082 bool nocma = !!(current->flags & PF_MEMALLOC_NOCMA);
1083
1084 list_for_each_entry(page, &h->hugepage_freelists[nid], lru) {
1085 if (nocma && is_migrate_cma_page(page))
1086 continue;
1087
1088 if (PageHWPoison(page))
1089 continue;
1090
1091 list_move(&page->lru, &h->hugepage_activelist);
1092 set_page_refcounted(page);
1093 ClearPageHugeFreed(page);
1094 h->free_huge_pages--;
1095 h->free_huge_pages_node[nid]--;
1096 return page;
1097 }
1098
1099 return NULL;
1100 }
1101
dequeue_huge_page_nodemask(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nmask)1102 static struct page *dequeue_huge_page_nodemask(struct hstate *h, gfp_t gfp_mask, int nid,
1103 nodemask_t *nmask)
1104 {
1105 unsigned int cpuset_mems_cookie;
1106 struct zonelist *zonelist;
1107 struct zone *zone;
1108 struct zoneref *z;
1109 int node = NUMA_NO_NODE;
1110
1111 zonelist = node_zonelist(nid, gfp_mask);
1112
1113 retry_cpuset:
1114 cpuset_mems_cookie = read_mems_allowed_begin();
1115 for_each_zone_zonelist_nodemask(zone, z, zonelist, gfp_zone(gfp_mask), nmask) {
1116 struct page *page;
1117
1118 if (!cpuset_zone_allowed(zone, gfp_mask))
1119 continue;
1120 /*
1121 * no need to ask again on the same node. Pool is node rather than
1122 * zone aware
1123 */
1124 if (zone_to_nid(zone) == node)
1125 continue;
1126 node = zone_to_nid(zone);
1127
1128 page = dequeue_huge_page_node_exact(h, node);
1129 if (page)
1130 return page;
1131 }
1132 if (unlikely(read_mems_allowed_retry(cpuset_mems_cookie)))
1133 goto retry_cpuset;
1134
1135 return NULL;
1136 }
1137
dequeue_huge_page_vma(struct hstate * h,struct vm_area_struct * vma,unsigned long address,int avoid_reserve,long chg)1138 static struct page *dequeue_huge_page_vma(struct hstate *h,
1139 struct vm_area_struct *vma,
1140 unsigned long address, int avoid_reserve,
1141 long chg)
1142 {
1143 struct page *page;
1144 struct mempolicy *mpol;
1145 gfp_t gfp_mask;
1146 nodemask_t *nodemask;
1147 int nid;
1148
1149 /*
1150 * A child process with MAP_PRIVATE mappings created by their parent
1151 * have no page reserves. This check ensures that reservations are
1152 * not "stolen". The child may still get SIGKILLed
1153 */
1154 if (!vma_has_reserves(vma, chg) &&
1155 h->free_huge_pages - h->resv_huge_pages == 0)
1156 goto err;
1157
1158 /* If reserves cannot be used, ensure enough pages are in the pool */
1159 if (avoid_reserve && h->free_huge_pages - h->resv_huge_pages == 0)
1160 goto err;
1161
1162 gfp_mask = htlb_alloc_mask(h);
1163 nid = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
1164 page = dequeue_huge_page_nodemask(h, gfp_mask, nid, nodemask);
1165 if (page && !avoid_reserve && vma_has_reserves(vma, chg)) {
1166 SetPagePrivate(page);
1167 h->resv_huge_pages--;
1168 }
1169
1170 mpol_cond_put(mpol);
1171 return page;
1172
1173 err:
1174 return NULL;
1175 }
1176
1177 /*
1178 * common helper functions for hstate_next_node_to_{alloc|free}.
1179 * We may have allocated or freed a huge page based on a different
1180 * nodes_allowed previously, so h->next_node_to_{alloc|free} might
1181 * be outside of *nodes_allowed. Ensure that we use an allowed
1182 * node for alloc or free.
1183 */
next_node_allowed(int nid,nodemask_t * nodes_allowed)1184 static int next_node_allowed(int nid, nodemask_t *nodes_allowed)
1185 {
1186 nid = next_node_in(nid, *nodes_allowed);
1187 VM_BUG_ON(nid >= MAX_NUMNODES);
1188
1189 return nid;
1190 }
1191
get_valid_node_allowed(int nid,nodemask_t * nodes_allowed)1192 static int get_valid_node_allowed(int nid, nodemask_t *nodes_allowed)
1193 {
1194 if (!node_isset(nid, *nodes_allowed))
1195 nid = next_node_allowed(nid, nodes_allowed);
1196 return nid;
1197 }
1198
1199 /*
1200 * returns the previously saved node ["this node"] from which to
1201 * allocate a persistent huge page for the pool and advance the
1202 * next node from which to allocate, handling wrap at end of node
1203 * mask.
1204 */
hstate_next_node_to_alloc(struct hstate * h,nodemask_t * nodes_allowed)1205 static int hstate_next_node_to_alloc(struct hstate *h,
1206 nodemask_t *nodes_allowed)
1207 {
1208 int nid;
1209
1210 VM_BUG_ON(!nodes_allowed);
1211
1212 nid = get_valid_node_allowed(h->next_nid_to_alloc, nodes_allowed);
1213 h->next_nid_to_alloc = next_node_allowed(nid, nodes_allowed);
1214
1215 return nid;
1216 }
1217
1218 /*
1219 * helper for free_pool_huge_page() - return the previously saved
1220 * node ["this node"] from which to free a huge page. Advance the
1221 * next node id whether or not we find a free huge page to free so
1222 * that the next attempt to free addresses the next node.
1223 */
hstate_next_node_to_free(struct hstate * h,nodemask_t * nodes_allowed)1224 static int hstate_next_node_to_free(struct hstate *h, nodemask_t *nodes_allowed)
1225 {
1226 int nid;
1227
1228 VM_BUG_ON(!nodes_allowed);
1229
1230 nid = get_valid_node_allowed(h->next_nid_to_free, nodes_allowed);
1231 h->next_nid_to_free = next_node_allowed(nid, nodes_allowed);
1232
1233 return nid;
1234 }
1235
1236 #define for_each_node_mask_to_alloc(hs, nr_nodes, node, mask) \
1237 for (nr_nodes = nodes_weight(*mask); \
1238 nr_nodes > 0 && \
1239 ((node = hstate_next_node_to_alloc(hs, mask)) || 1); \
1240 nr_nodes--)
1241
1242 #define for_each_node_mask_to_free(hs, nr_nodes, node, mask) \
1243 for (nr_nodes = nodes_weight(*mask); \
1244 nr_nodes > 0 && \
1245 ((node = hstate_next_node_to_free(hs, mask)) || 1); \
1246 nr_nodes--)
1247
1248 #ifdef CONFIG_ARCH_HAS_GIGANTIC_PAGE
destroy_compound_gigantic_page(struct page * page,unsigned int order)1249 static void destroy_compound_gigantic_page(struct page *page,
1250 unsigned int order)
1251 {
1252 int i;
1253 int nr_pages = 1 << order;
1254 struct page *p = page + 1;
1255
1256 atomic_set(compound_mapcount_ptr(page), 0);
1257 atomic_set(compound_pincount_ptr(page), 0);
1258
1259 for (i = 1; i < nr_pages; i++, p = mem_map_next(p, page, i)) {
1260 clear_compound_head(p);
1261 set_page_refcounted(p);
1262 }
1263
1264 set_compound_order(page, 0);
1265 page[1].compound_nr = 0;
1266 __ClearPageHead(page);
1267 }
1268
free_gigantic_page(struct page * page,unsigned int order)1269 static void free_gigantic_page(struct page *page, unsigned int order)
1270 {
1271 /*
1272 * If the page isn't allocated using the cma allocator,
1273 * cma_release() returns false.
1274 */
1275 #ifdef CONFIG_CMA
1276 if (cma_release(hugetlb_cma[page_to_nid(page)], page, 1 << order))
1277 return;
1278 #endif
1279
1280 free_contig_range(page_to_pfn(page), 1 << order);
1281 }
1282
1283 #ifdef CONFIG_CONTIG_ALLOC
alloc_gigantic_page(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nodemask)1284 static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
1285 int nid, nodemask_t *nodemask)
1286 {
1287 unsigned long nr_pages = 1UL << huge_page_order(h);
1288 if (nid == NUMA_NO_NODE)
1289 nid = numa_mem_id();
1290
1291 #ifdef CONFIG_CMA
1292 {
1293 struct page *page;
1294 int node;
1295
1296 if (hugetlb_cma[nid]) {
1297 page = cma_alloc(hugetlb_cma[nid], nr_pages,
1298 huge_page_order(h),
1299 GFP_KERNEL | __GFP_NOWARN);
1300 if (page)
1301 return page;
1302 }
1303
1304 if (!(gfp_mask & __GFP_THISNODE)) {
1305 for_each_node_mask(node, *nodemask) {
1306 if (node == nid || !hugetlb_cma[node])
1307 continue;
1308
1309 page = cma_alloc(hugetlb_cma[node], nr_pages,
1310 huge_page_order(h),
1311 GFP_KERNEL | __GFP_NOWARN);
1312 if (page)
1313 return page;
1314 }
1315 }
1316 }
1317 #endif
1318
1319 return alloc_contig_pages(nr_pages, gfp_mask, nid, nodemask);
1320 }
1321
1322 #else /* !CONFIG_CONTIG_ALLOC */
alloc_gigantic_page(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nodemask)1323 static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
1324 int nid, nodemask_t *nodemask)
1325 {
1326 return NULL;
1327 }
1328 #endif /* CONFIG_CONTIG_ALLOC */
1329
1330 #else /* !CONFIG_ARCH_HAS_GIGANTIC_PAGE */
alloc_gigantic_page(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nodemask)1331 static struct page *alloc_gigantic_page(struct hstate *h, gfp_t gfp_mask,
1332 int nid, nodemask_t *nodemask)
1333 {
1334 return NULL;
1335 }
free_gigantic_page(struct page * page,unsigned int order)1336 static inline void free_gigantic_page(struct page *page, unsigned int order) { }
destroy_compound_gigantic_page(struct page * page,unsigned int order)1337 static inline void destroy_compound_gigantic_page(struct page *page,
1338 unsigned int order) { }
1339 #endif
1340
update_and_free_page(struct hstate * h,struct page * page)1341 static void update_and_free_page(struct hstate *h, struct page *page)
1342 {
1343 int i;
1344 struct page *subpage = page;
1345
1346 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
1347 return;
1348
1349 h->nr_huge_pages--;
1350 h->nr_huge_pages_node[page_to_nid(page)]--;
1351 for (i = 0; i < pages_per_huge_page(h);
1352 i++, subpage = mem_map_next(subpage, page, i)) {
1353 subpage->flags &= ~(1 << PG_locked | 1 << PG_error |
1354 1 << PG_referenced | 1 << PG_dirty |
1355 1 << PG_active | 1 << PG_private |
1356 1 << PG_writeback);
1357 }
1358 VM_BUG_ON_PAGE(hugetlb_cgroup_from_page(page), page);
1359 VM_BUG_ON_PAGE(hugetlb_cgroup_from_page_rsvd(page), page);
1360 set_compound_page_dtor(page, NULL_COMPOUND_DTOR);
1361 set_page_refcounted(page);
1362 if (hstate_is_gigantic(h)) {
1363 /*
1364 * Temporarily drop the hugetlb_lock, because
1365 * we might block in free_gigantic_page().
1366 */
1367 spin_unlock(&hugetlb_lock);
1368 destroy_compound_gigantic_page(page, huge_page_order(h));
1369 free_gigantic_page(page, huge_page_order(h));
1370 spin_lock(&hugetlb_lock);
1371 } else {
1372 __free_pages(page, huge_page_order(h));
1373 }
1374 }
1375
size_to_hstate(unsigned long size)1376 struct hstate *size_to_hstate(unsigned long size)
1377 {
1378 struct hstate *h;
1379
1380 for_each_hstate(h) {
1381 if (huge_page_size(h) == size)
1382 return h;
1383 }
1384 return NULL;
1385 }
1386
1387 /*
1388 * Test to determine whether the hugepage is "active/in-use" (i.e. being linked
1389 * to hstate->hugepage_activelist.)
1390 *
1391 * This function can be called for tail pages, but never returns true for them.
1392 */
page_huge_active(struct page * page)1393 bool page_huge_active(struct page *page)
1394 {
1395 return PageHeadHuge(page) && PagePrivate(&page[1]);
1396 }
1397
1398 /* never called for tail page */
set_page_huge_active(struct page * page)1399 void set_page_huge_active(struct page *page)
1400 {
1401 VM_BUG_ON_PAGE(!PageHeadHuge(page), page);
1402 SetPagePrivate(&page[1]);
1403 }
1404
clear_page_huge_active(struct page * page)1405 static void clear_page_huge_active(struct page *page)
1406 {
1407 VM_BUG_ON_PAGE(!PageHeadHuge(page), page);
1408 ClearPagePrivate(&page[1]);
1409 }
1410
1411 /*
1412 * Internal hugetlb specific page flag. Do not use outside of the hugetlb
1413 * code
1414 */
PageHugeTemporary(struct page * page)1415 static inline bool PageHugeTemporary(struct page *page)
1416 {
1417 if (!PageHuge(page))
1418 return false;
1419
1420 return (unsigned long)page[2].mapping == -1U;
1421 }
1422
SetPageHugeTemporary(struct page * page)1423 static inline void SetPageHugeTemporary(struct page *page)
1424 {
1425 page[2].mapping = (void *)-1U;
1426 }
1427
ClearPageHugeTemporary(struct page * page)1428 static inline void ClearPageHugeTemporary(struct page *page)
1429 {
1430 page[2].mapping = NULL;
1431 }
1432
__free_huge_page(struct page * page)1433 static void __free_huge_page(struct page *page)
1434 {
1435 /*
1436 * Can't pass hstate in here because it is called from the
1437 * compound page destructor.
1438 */
1439 struct hstate *h = page_hstate(page);
1440 int nid = page_to_nid(page);
1441 struct hugepage_subpool *spool =
1442 (struct hugepage_subpool *)page_private(page);
1443 bool restore_reserve;
1444
1445 VM_BUG_ON_PAGE(page_count(page), page);
1446 VM_BUG_ON_PAGE(page_mapcount(page), page);
1447
1448 set_page_private(page, 0);
1449 page->mapping = NULL;
1450 restore_reserve = PagePrivate(page);
1451 ClearPagePrivate(page);
1452
1453 /*
1454 * If PagePrivate() was set on page, page allocation consumed a
1455 * reservation. If the page was associated with a subpool, there
1456 * would have been a page reserved in the subpool before allocation
1457 * via hugepage_subpool_get_pages(). Since we are 'restoring' the
1458 * reservtion, do not call hugepage_subpool_put_pages() as this will
1459 * remove the reserved page from the subpool.
1460 */
1461 if (!restore_reserve) {
1462 /*
1463 * A return code of zero implies that the subpool will be
1464 * under its minimum size if the reservation is not restored
1465 * after page is free. Therefore, force restore_reserve
1466 * operation.
1467 */
1468 if (hugepage_subpool_put_pages(spool, 1) == 0)
1469 restore_reserve = true;
1470 }
1471
1472 spin_lock(&hugetlb_lock);
1473 clear_page_huge_active(page);
1474 hugetlb_cgroup_uncharge_page(hstate_index(h),
1475 pages_per_huge_page(h), page);
1476 hugetlb_cgroup_uncharge_page_rsvd(hstate_index(h),
1477 pages_per_huge_page(h), page);
1478 if (restore_reserve)
1479 h->resv_huge_pages++;
1480
1481 if (PageHugeTemporary(page)) {
1482 list_del(&page->lru);
1483 ClearPageHugeTemporary(page);
1484 update_and_free_page(h, page);
1485 } else if (h->surplus_huge_pages_node[nid]) {
1486 /* remove the page from active list */
1487 list_del(&page->lru);
1488 update_and_free_page(h, page);
1489 h->surplus_huge_pages--;
1490 h->surplus_huge_pages_node[nid]--;
1491 } else {
1492 arch_clear_hugepage_flags(page);
1493 enqueue_huge_page(h, page);
1494 }
1495 spin_unlock(&hugetlb_lock);
1496 }
1497
1498 /*
1499 * As free_huge_page() can be called from a non-task context, we have
1500 * to defer the actual freeing in a workqueue to prevent potential
1501 * hugetlb_lock deadlock.
1502 *
1503 * free_hpage_workfn() locklessly retrieves the linked list of pages to
1504 * be freed and frees them one-by-one. As the page->mapping pointer is
1505 * going to be cleared in __free_huge_page() anyway, it is reused as the
1506 * llist_node structure of a lockless linked list of huge pages to be freed.
1507 */
1508 static LLIST_HEAD(hpage_freelist);
1509
free_hpage_workfn(struct work_struct * work)1510 static void free_hpage_workfn(struct work_struct *work)
1511 {
1512 struct llist_node *node;
1513 struct page *page;
1514
1515 node = llist_del_all(&hpage_freelist);
1516
1517 while (node) {
1518 page = container_of((struct address_space **)node,
1519 struct page, mapping);
1520 node = node->next;
1521 __free_huge_page(page);
1522 }
1523 }
1524 static DECLARE_WORK(free_hpage_work, free_hpage_workfn);
1525
free_huge_page(struct page * page)1526 void free_huge_page(struct page *page)
1527 {
1528 /*
1529 * Defer freeing if in non-task context to avoid hugetlb_lock deadlock.
1530 */
1531 if (!in_task()) {
1532 /*
1533 * Only call schedule_work() if hpage_freelist is previously
1534 * empty. Otherwise, schedule_work() had been called but the
1535 * workfn hasn't retrieved the list yet.
1536 */
1537 if (llist_add((struct llist_node *)&page->mapping,
1538 &hpage_freelist))
1539 schedule_work(&free_hpage_work);
1540 return;
1541 }
1542
1543 __free_huge_page(page);
1544 }
1545
prep_new_huge_page(struct hstate * h,struct page * page,int nid)1546 static void prep_new_huge_page(struct hstate *h, struct page *page, int nid)
1547 {
1548 INIT_LIST_HEAD(&page->lru);
1549 set_compound_page_dtor(page, HUGETLB_PAGE_DTOR);
1550 set_hugetlb_cgroup(page, NULL);
1551 set_hugetlb_cgroup_rsvd(page, NULL);
1552 spin_lock(&hugetlb_lock);
1553 h->nr_huge_pages++;
1554 h->nr_huge_pages_node[nid]++;
1555 ClearPageHugeFreed(page);
1556 spin_unlock(&hugetlb_lock);
1557 }
1558
prep_compound_gigantic_page(struct page * page,unsigned int order)1559 static void prep_compound_gigantic_page(struct page *page, unsigned int order)
1560 {
1561 int i;
1562 int nr_pages = 1 << order;
1563 struct page *p = page + 1;
1564
1565 /* we rely on prep_new_huge_page to set the destructor */
1566 set_compound_order(page, order);
1567 __ClearPageReserved(page);
1568 __SetPageHead(page);
1569 for (i = 1; i < nr_pages; i++, p = mem_map_next(p, page, i)) {
1570 /*
1571 * For gigantic hugepages allocated through bootmem at
1572 * boot, it's safer to be consistent with the not-gigantic
1573 * hugepages and clear the PG_reserved bit from all tail pages
1574 * too. Otherwise drivers using get_user_pages() to access tail
1575 * pages may get the reference counting wrong if they see
1576 * PG_reserved set on a tail page (despite the head page not
1577 * having PG_reserved set). Enforcing this consistency between
1578 * head and tail pages allows drivers to optimize away a check
1579 * on the head page when they need know if put_page() is needed
1580 * after get_user_pages().
1581 */
1582 __ClearPageReserved(p);
1583 set_page_count(p, 0);
1584 set_compound_head(p, page);
1585 }
1586 atomic_set(compound_mapcount_ptr(page), -1);
1587 atomic_set(compound_pincount_ptr(page), 0);
1588 }
1589
1590 /*
1591 * PageHuge() only returns true for hugetlbfs pages, but not for normal or
1592 * transparent huge pages. See the PageTransHuge() documentation for more
1593 * details.
1594 */
PageHuge(struct page * page)1595 int PageHuge(struct page *page)
1596 {
1597 if (!PageCompound(page))
1598 return 0;
1599
1600 page = compound_head(page);
1601 return page[1].compound_dtor == HUGETLB_PAGE_DTOR;
1602 }
1603 EXPORT_SYMBOL_GPL(PageHuge);
1604
1605 /*
1606 * PageHeadHuge() only returns true for hugetlbfs head page, but not for
1607 * normal or transparent huge pages.
1608 */
PageHeadHuge(struct page * page_head)1609 int PageHeadHuge(struct page *page_head)
1610 {
1611 if (!PageHead(page_head))
1612 return 0;
1613
1614 return page_head[1].compound_dtor == HUGETLB_PAGE_DTOR;
1615 }
1616
1617 /*
1618 * Find and lock address space (mapping) in write mode.
1619 *
1620 * Upon entry, the page is locked which means that page_mapping() is
1621 * stable. Due to locking order, we can only trylock_write. If we can
1622 * not get the lock, simply return NULL to caller.
1623 */
hugetlb_page_mapping_lock_write(struct page * hpage)1624 struct address_space *hugetlb_page_mapping_lock_write(struct page *hpage)
1625 {
1626 struct address_space *mapping = page_mapping(hpage);
1627
1628 if (!mapping)
1629 return mapping;
1630
1631 if (i_mmap_trylock_write(mapping))
1632 return mapping;
1633
1634 return NULL;
1635 }
1636
hugetlb_basepage_index(struct page * page)1637 pgoff_t hugetlb_basepage_index(struct page *page)
1638 {
1639 struct page *page_head = compound_head(page);
1640 pgoff_t index = page_index(page_head);
1641 unsigned long compound_idx;
1642
1643 if (compound_order(page_head) >= MAX_ORDER)
1644 compound_idx = page_to_pfn(page) - page_to_pfn(page_head);
1645 else
1646 compound_idx = page - page_head;
1647
1648 return (index << compound_order(page_head)) + compound_idx;
1649 }
1650
alloc_buddy_huge_page(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nmask,nodemask_t * node_alloc_noretry)1651 static struct page *alloc_buddy_huge_page(struct hstate *h,
1652 gfp_t gfp_mask, int nid, nodemask_t *nmask,
1653 nodemask_t *node_alloc_noretry)
1654 {
1655 int order = huge_page_order(h);
1656 struct page *page;
1657 bool alloc_try_hard = true;
1658
1659 /*
1660 * By default we always try hard to allocate the page with
1661 * __GFP_RETRY_MAYFAIL flag. However, if we are allocating pages in
1662 * a loop (to adjust global huge page counts) and previous allocation
1663 * failed, do not continue to try hard on the same node. Use the
1664 * node_alloc_noretry bitmap to manage this state information.
1665 */
1666 if (node_alloc_noretry && node_isset(nid, *node_alloc_noretry))
1667 alloc_try_hard = false;
1668 gfp_mask |= __GFP_COMP|__GFP_NOWARN;
1669 if (alloc_try_hard)
1670 gfp_mask |= __GFP_RETRY_MAYFAIL;
1671 if (nid == NUMA_NO_NODE)
1672 nid = numa_mem_id();
1673 page = __alloc_pages_nodemask(gfp_mask, order, nid, nmask);
1674 if (page)
1675 __count_vm_event(HTLB_BUDDY_PGALLOC);
1676 else
1677 __count_vm_event(HTLB_BUDDY_PGALLOC_FAIL);
1678
1679 /*
1680 * If we did not specify __GFP_RETRY_MAYFAIL, but still got a page this
1681 * indicates an overall state change. Clear bit so that we resume
1682 * normal 'try hard' allocations.
1683 */
1684 if (node_alloc_noretry && page && !alloc_try_hard)
1685 node_clear(nid, *node_alloc_noretry);
1686
1687 /*
1688 * If we tried hard to get a page but failed, set bit so that
1689 * subsequent attempts will not try as hard until there is an
1690 * overall state change.
1691 */
1692 if (node_alloc_noretry && !page && alloc_try_hard)
1693 node_set(nid, *node_alloc_noretry);
1694
1695 return page;
1696 }
1697
1698 /*
1699 * Common helper to allocate a fresh hugetlb page. All specific allocators
1700 * should use this function to get new hugetlb pages
1701 */
alloc_fresh_huge_page(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nmask,nodemask_t * node_alloc_noretry)1702 static struct page *alloc_fresh_huge_page(struct hstate *h,
1703 gfp_t gfp_mask, int nid, nodemask_t *nmask,
1704 nodemask_t *node_alloc_noretry)
1705 {
1706 struct page *page;
1707
1708 if (hstate_is_gigantic(h))
1709 page = alloc_gigantic_page(h, gfp_mask, nid, nmask);
1710 else
1711 page = alloc_buddy_huge_page(h, gfp_mask,
1712 nid, nmask, node_alloc_noretry);
1713 if (!page)
1714 return NULL;
1715
1716 if (hstate_is_gigantic(h))
1717 prep_compound_gigantic_page(page, huge_page_order(h));
1718 prep_new_huge_page(h, page, page_to_nid(page));
1719
1720 return page;
1721 }
1722
1723 /*
1724 * Allocates a fresh page to the hugetlb allocator pool in the node interleaved
1725 * manner.
1726 */
alloc_pool_huge_page(struct hstate * h,nodemask_t * nodes_allowed,nodemask_t * node_alloc_noretry)1727 static int alloc_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed,
1728 nodemask_t *node_alloc_noretry)
1729 {
1730 struct page *page;
1731 int nr_nodes, node;
1732 gfp_t gfp_mask = htlb_alloc_mask(h) | __GFP_THISNODE;
1733
1734 for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
1735 page = alloc_fresh_huge_page(h, gfp_mask, node, nodes_allowed,
1736 node_alloc_noretry);
1737 if (page)
1738 break;
1739 }
1740
1741 if (!page)
1742 return 0;
1743
1744 put_page(page); /* free it into the hugepage allocator */
1745
1746 return 1;
1747 }
1748
1749 /*
1750 * Free huge page from pool from next node to free.
1751 * Attempt to keep persistent huge pages more or less
1752 * balanced over allowed nodes.
1753 * Called with hugetlb_lock locked.
1754 */
free_pool_huge_page(struct hstate * h,nodemask_t * nodes_allowed,bool acct_surplus)1755 static int free_pool_huge_page(struct hstate *h, nodemask_t *nodes_allowed,
1756 bool acct_surplus)
1757 {
1758 int nr_nodes, node;
1759 int ret = 0;
1760
1761 for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
1762 /*
1763 * If we're returning unused surplus pages, only examine
1764 * nodes with surplus pages.
1765 */
1766 if ((!acct_surplus || h->surplus_huge_pages_node[node]) &&
1767 !list_empty(&h->hugepage_freelists[node])) {
1768 struct page *page =
1769 list_entry(h->hugepage_freelists[node].next,
1770 struct page, lru);
1771 list_del(&page->lru);
1772 h->free_huge_pages--;
1773 h->free_huge_pages_node[node]--;
1774 if (acct_surplus) {
1775 h->surplus_huge_pages--;
1776 h->surplus_huge_pages_node[node]--;
1777 }
1778 update_and_free_page(h, page);
1779 ret = 1;
1780 break;
1781 }
1782 }
1783
1784 return ret;
1785 }
1786
1787 /*
1788 * Dissolve a given free hugepage into free buddy pages. This function does
1789 * nothing for in-use hugepages and non-hugepages.
1790 * This function returns values like below:
1791 *
1792 * -EBUSY: failed to dissolved free hugepages or the hugepage is in-use
1793 * (allocated or reserved.)
1794 * 0: successfully dissolved free hugepages or the page is not a
1795 * hugepage (considered as already dissolved)
1796 */
dissolve_free_huge_page(struct page * page)1797 int dissolve_free_huge_page(struct page *page)
1798 {
1799 int rc = -EBUSY;
1800
1801 retry:
1802 /* Not to disrupt normal path by vainly holding hugetlb_lock */
1803 if (!PageHuge(page))
1804 return 0;
1805
1806 spin_lock(&hugetlb_lock);
1807 if (!PageHuge(page)) {
1808 rc = 0;
1809 goto out;
1810 }
1811
1812 if (!page_count(page)) {
1813 struct page *head = compound_head(page);
1814 struct hstate *h = page_hstate(head);
1815 int nid = page_to_nid(head);
1816 if (h->free_huge_pages - h->resv_huge_pages == 0)
1817 goto out;
1818
1819 /*
1820 * We should make sure that the page is already on the free list
1821 * when it is dissolved.
1822 */
1823 if (unlikely(!PageHugeFreed(head))) {
1824 spin_unlock(&hugetlb_lock);
1825 cond_resched();
1826
1827 /*
1828 * Theoretically, we should return -EBUSY when we
1829 * encounter this race. In fact, we have a chance
1830 * to successfully dissolve the page if we do a
1831 * retry. Because the race window is quite small.
1832 * If we seize this opportunity, it is an optimization
1833 * for increasing the success rate of dissolving page.
1834 */
1835 goto retry;
1836 }
1837
1838 /*
1839 * Move PageHWPoison flag from head page to the raw error page,
1840 * which makes any subpages rather than the error page reusable.
1841 */
1842 if (PageHWPoison(head) && page != head) {
1843 SetPageHWPoison(page);
1844 ClearPageHWPoison(head);
1845 }
1846 list_del(&head->lru);
1847 h->free_huge_pages--;
1848 h->free_huge_pages_node[nid]--;
1849 h->max_huge_pages--;
1850 update_and_free_page(h, head);
1851 rc = 0;
1852 }
1853 out:
1854 spin_unlock(&hugetlb_lock);
1855 return rc;
1856 }
1857
1858 /*
1859 * Dissolve free hugepages in a given pfn range. Used by memory hotplug to
1860 * make specified memory blocks removable from the system.
1861 * Note that this will dissolve a free gigantic hugepage completely, if any
1862 * part of it lies within the given range.
1863 * Also note that if dissolve_free_huge_page() returns with an error, all
1864 * free hugepages that were dissolved before that error are lost.
1865 */
dissolve_free_huge_pages(unsigned long start_pfn,unsigned long end_pfn)1866 int dissolve_free_huge_pages(unsigned long start_pfn, unsigned long end_pfn)
1867 {
1868 unsigned long pfn;
1869 struct page *page;
1870 int rc = 0;
1871
1872 if (!hugepages_supported())
1873 return rc;
1874
1875 for (pfn = start_pfn; pfn < end_pfn; pfn += 1 << minimum_order) {
1876 page = pfn_to_page(pfn);
1877 rc = dissolve_free_huge_page(page);
1878 if (rc)
1879 break;
1880 }
1881
1882 return rc;
1883 }
1884
1885 /*
1886 * Allocates a fresh surplus page from the page allocator.
1887 */
alloc_surplus_huge_page(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nmask)1888 static struct page *alloc_surplus_huge_page(struct hstate *h, gfp_t gfp_mask,
1889 int nid, nodemask_t *nmask)
1890 {
1891 struct page *page = NULL;
1892
1893 if (hstate_is_gigantic(h))
1894 return NULL;
1895
1896 spin_lock(&hugetlb_lock);
1897 if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages)
1898 goto out_unlock;
1899 spin_unlock(&hugetlb_lock);
1900
1901 page = alloc_fresh_huge_page(h, gfp_mask, nid, nmask, NULL);
1902 if (!page)
1903 return NULL;
1904
1905 spin_lock(&hugetlb_lock);
1906 /*
1907 * We could have raced with the pool size change.
1908 * Double check that and simply deallocate the new page
1909 * if we would end up overcommiting the surpluses. Abuse
1910 * temporary page to workaround the nasty free_huge_page
1911 * codeflow
1912 */
1913 if (h->surplus_huge_pages >= h->nr_overcommit_huge_pages) {
1914 SetPageHugeTemporary(page);
1915 spin_unlock(&hugetlb_lock);
1916 put_page(page);
1917 return NULL;
1918 } else {
1919 h->surplus_huge_pages++;
1920 h->surplus_huge_pages_node[page_to_nid(page)]++;
1921 }
1922
1923 out_unlock:
1924 spin_unlock(&hugetlb_lock);
1925
1926 return page;
1927 }
1928
alloc_migrate_huge_page(struct hstate * h,gfp_t gfp_mask,int nid,nodemask_t * nmask)1929 static struct page *alloc_migrate_huge_page(struct hstate *h, gfp_t gfp_mask,
1930 int nid, nodemask_t *nmask)
1931 {
1932 struct page *page;
1933
1934 if (hstate_is_gigantic(h))
1935 return NULL;
1936
1937 page = alloc_fresh_huge_page(h, gfp_mask, nid, nmask, NULL);
1938 if (!page)
1939 return NULL;
1940
1941 /*
1942 * We do not account these pages as surplus because they are only
1943 * temporary and will be released properly on the last reference
1944 */
1945 SetPageHugeTemporary(page);
1946
1947 return page;
1948 }
1949
1950 /*
1951 * Use the VMA's mpolicy to allocate a huge page from the buddy.
1952 */
1953 static
alloc_buddy_huge_page_with_mpol(struct hstate * h,struct vm_area_struct * vma,unsigned long addr)1954 struct page *alloc_buddy_huge_page_with_mpol(struct hstate *h,
1955 struct vm_area_struct *vma, unsigned long addr)
1956 {
1957 struct page *page;
1958 struct mempolicy *mpol;
1959 gfp_t gfp_mask = htlb_alloc_mask(h);
1960 int nid;
1961 nodemask_t *nodemask;
1962
1963 nid = huge_node(vma, addr, gfp_mask, &mpol, &nodemask);
1964 page = alloc_surplus_huge_page(h, gfp_mask, nid, nodemask);
1965 mpol_cond_put(mpol);
1966
1967 return page;
1968 }
1969
1970 /* page migration callback function */
alloc_huge_page_nodemask(struct hstate * h,int preferred_nid,nodemask_t * nmask,gfp_t gfp_mask)1971 struct page *alloc_huge_page_nodemask(struct hstate *h, int preferred_nid,
1972 nodemask_t *nmask, gfp_t gfp_mask)
1973 {
1974 spin_lock(&hugetlb_lock);
1975 if (h->free_huge_pages - h->resv_huge_pages > 0) {
1976 struct page *page;
1977
1978 page = dequeue_huge_page_nodemask(h, gfp_mask, preferred_nid, nmask);
1979 if (page) {
1980 spin_unlock(&hugetlb_lock);
1981 return page;
1982 }
1983 }
1984 spin_unlock(&hugetlb_lock);
1985
1986 return alloc_migrate_huge_page(h, gfp_mask, preferred_nid, nmask);
1987 }
1988
1989 /* mempolicy aware migration callback */
alloc_huge_page_vma(struct hstate * h,struct vm_area_struct * vma,unsigned long address)1990 struct page *alloc_huge_page_vma(struct hstate *h, struct vm_area_struct *vma,
1991 unsigned long address)
1992 {
1993 struct mempolicy *mpol;
1994 nodemask_t *nodemask;
1995 struct page *page;
1996 gfp_t gfp_mask;
1997 int node;
1998
1999 gfp_mask = htlb_alloc_mask(h);
2000 node = huge_node(vma, address, gfp_mask, &mpol, &nodemask);
2001 page = alloc_huge_page_nodemask(h, node, nodemask, gfp_mask);
2002 mpol_cond_put(mpol);
2003
2004 return page;
2005 }
2006
2007 /*
2008 * Increase the hugetlb pool such that it can accommodate a reservation
2009 * of size 'delta'.
2010 */
gather_surplus_pages(struct hstate * h,int delta)2011 static int gather_surplus_pages(struct hstate *h, int delta)
2012 __must_hold(&hugetlb_lock)
2013 {
2014 struct list_head surplus_list;
2015 struct page *page, *tmp;
2016 int ret, i;
2017 int needed, allocated;
2018 bool alloc_ok = true;
2019
2020 needed = (h->resv_huge_pages + delta) - h->free_huge_pages;
2021 if (needed <= 0) {
2022 h->resv_huge_pages += delta;
2023 return 0;
2024 }
2025
2026 allocated = 0;
2027 INIT_LIST_HEAD(&surplus_list);
2028
2029 ret = -ENOMEM;
2030 retry:
2031 spin_unlock(&hugetlb_lock);
2032 for (i = 0; i < needed; i++) {
2033 page = alloc_surplus_huge_page(h, htlb_alloc_mask(h),
2034 NUMA_NO_NODE, NULL);
2035 if (!page) {
2036 alloc_ok = false;
2037 break;
2038 }
2039 list_add(&page->lru, &surplus_list);
2040 cond_resched();
2041 }
2042 allocated += i;
2043
2044 /*
2045 * After retaking hugetlb_lock, we need to recalculate 'needed'
2046 * because either resv_huge_pages or free_huge_pages may have changed.
2047 */
2048 spin_lock(&hugetlb_lock);
2049 needed = (h->resv_huge_pages + delta) -
2050 (h->free_huge_pages + allocated);
2051 if (needed > 0) {
2052 if (alloc_ok)
2053 goto retry;
2054 /*
2055 * We were not able to allocate enough pages to
2056 * satisfy the entire reservation so we free what
2057 * we've allocated so far.
2058 */
2059 goto free;
2060 }
2061 /*
2062 * The surplus_list now contains _at_least_ the number of extra pages
2063 * needed to accommodate the reservation. Add the appropriate number
2064 * of pages to the hugetlb pool and free the extras back to the buddy
2065 * allocator. Commit the entire reservation here to prevent another
2066 * process from stealing the pages as they are added to the pool but
2067 * before they are reserved.
2068 */
2069 needed += allocated;
2070 h->resv_huge_pages += delta;
2071 ret = 0;
2072
2073 /* Free the needed pages to the hugetlb pool */
2074 list_for_each_entry_safe(page, tmp, &surplus_list, lru) {
2075 if ((--needed) < 0)
2076 break;
2077 /*
2078 * This page is now managed by the hugetlb allocator and has
2079 * no users -- drop the buddy allocator's reference.
2080 */
2081 put_page_testzero(page);
2082 VM_BUG_ON_PAGE(page_count(page), page);
2083 enqueue_huge_page(h, page);
2084 }
2085 free:
2086 spin_unlock(&hugetlb_lock);
2087
2088 /* Free unnecessary surplus pages to the buddy allocator */
2089 list_for_each_entry_safe(page, tmp, &surplus_list, lru)
2090 put_page(page);
2091 spin_lock(&hugetlb_lock);
2092
2093 return ret;
2094 }
2095
2096 /*
2097 * This routine has two main purposes:
2098 * 1) Decrement the reservation count (resv_huge_pages) by the value passed
2099 * in unused_resv_pages. This corresponds to the prior adjustments made
2100 * to the associated reservation map.
2101 * 2) Free any unused surplus pages that may have been allocated to satisfy
2102 * the reservation. As many as unused_resv_pages may be freed.
2103 *
2104 * Called with hugetlb_lock held. However, the lock could be dropped (and
2105 * reacquired) during calls to cond_resched_lock. Whenever dropping the lock,
2106 * we must make sure nobody else can claim pages we are in the process of
2107 * freeing. Do this by ensuring resv_huge_page always is greater than the
2108 * number of huge pages we plan to free when dropping the lock.
2109 */
return_unused_surplus_pages(struct hstate * h,unsigned long unused_resv_pages)2110 static void return_unused_surplus_pages(struct hstate *h,
2111 unsigned long unused_resv_pages)
2112 {
2113 unsigned long nr_pages;
2114
2115 /* Cannot return gigantic pages currently */
2116 if (hstate_is_gigantic(h))
2117 goto out;
2118
2119 /*
2120 * Part (or even all) of the reservation could have been backed
2121 * by pre-allocated pages. Only free surplus pages.
2122 */
2123 nr_pages = min(unused_resv_pages, h->surplus_huge_pages);
2124
2125 /*
2126 * We want to release as many surplus pages as possible, spread
2127 * evenly across all nodes with memory. Iterate across these nodes
2128 * until we can no longer free unreserved surplus pages. This occurs
2129 * when the nodes with surplus pages have no free pages.
2130 * free_pool_huge_page() will balance the freed pages across the
2131 * on-line nodes with memory and will handle the hstate accounting.
2132 *
2133 * Note that we decrement resv_huge_pages as we free the pages. If
2134 * we drop the lock, resv_huge_pages will still be sufficiently large
2135 * to cover subsequent pages we may free.
2136 */
2137 while (nr_pages--) {
2138 h->resv_huge_pages--;
2139 unused_resv_pages--;
2140 if (!free_pool_huge_page(h, &node_states[N_MEMORY], 1))
2141 goto out;
2142 cond_resched_lock(&hugetlb_lock);
2143 }
2144
2145 out:
2146 /* Fully uncommit the reservation */
2147 h->resv_huge_pages -= unused_resv_pages;
2148 }
2149
2150
2151 /*
2152 * vma_needs_reservation, vma_commit_reservation and vma_end_reservation
2153 * are used by the huge page allocation routines to manage reservations.
2154 *
2155 * vma_needs_reservation is called to determine if the huge page at addr
2156 * within the vma has an associated reservation. If a reservation is
2157 * needed, the value 1 is returned. The caller is then responsible for
2158 * managing the global reservation and subpool usage counts. After
2159 * the huge page has been allocated, vma_commit_reservation is called
2160 * to add the page to the reservation map. If the page allocation fails,
2161 * the reservation must be ended instead of committed. vma_end_reservation
2162 * is called in such cases.
2163 *
2164 * In the normal case, vma_commit_reservation returns the same value
2165 * as the preceding vma_needs_reservation call. The only time this
2166 * is not the case is if a reserve map was changed between calls. It
2167 * is the responsibility of the caller to notice the difference and
2168 * take appropriate action.
2169 *
2170 * vma_add_reservation is used in error paths where a reservation must
2171 * be restored when a newly allocated huge page must be freed. It is
2172 * to be called after calling vma_needs_reservation to determine if a
2173 * reservation exists.
2174 */
2175 enum vma_resv_mode {
2176 VMA_NEEDS_RESV,
2177 VMA_COMMIT_RESV,
2178 VMA_END_RESV,
2179 VMA_ADD_RESV,
2180 };
__vma_reservation_common(struct hstate * h,struct vm_area_struct * vma,unsigned long addr,enum vma_resv_mode mode)2181 static long __vma_reservation_common(struct hstate *h,
2182 struct vm_area_struct *vma, unsigned long addr,
2183 enum vma_resv_mode mode)
2184 {
2185 struct resv_map *resv;
2186 pgoff_t idx;
2187 long ret;
2188 long dummy_out_regions_needed;
2189
2190 resv = vma_resv_map(vma);
2191 if (!resv)
2192 return 1;
2193
2194 idx = vma_hugecache_offset(h, vma, addr);
2195 switch (mode) {
2196 case VMA_NEEDS_RESV:
2197 ret = region_chg(resv, idx, idx + 1, &dummy_out_regions_needed);
2198 /* We assume that vma_reservation_* routines always operate on
2199 * 1 page, and that adding to resv map a 1 page entry can only
2200 * ever require 1 region.
2201 */
2202 VM_BUG_ON(dummy_out_regions_needed != 1);
2203 break;
2204 case VMA_COMMIT_RESV:
2205 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2206 /* region_add calls of range 1 should never fail. */
2207 VM_BUG_ON(ret < 0);
2208 break;
2209 case VMA_END_RESV:
2210 region_abort(resv, idx, idx + 1, 1);
2211 ret = 0;
2212 break;
2213 case VMA_ADD_RESV:
2214 if (vma->vm_flags & VM_MAYSHARE) {
2215 ret = region_add(resv, idx, idx + 1, 1, NULL, NULL);
2216 /* region_add calls of range 1 should never fail. */
2217 VM_BUG_ON(ret < 0);
2218 } else {
2219 region_abort(resv, idx, idx + 1, 1);
2220 ret = region_del(resv, idx, idx + 1);
2221 }
2222 break;
2223 default:
2224 BUG();
2225 }
2226
2227 if (vma->vm_flags & VM_MAYSHARE)
2228 return ret;
2229 else if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) && ret >= 0) {
2230 /*
2231 * In most cases, reserves always exist for private mappings.
2232 * However, a file associated with mapping could have been
2233 * hole punched or truncated after reserves were consumed.
2234 * As subsequent fault on such a range will not use reserves.
2235 * Subtle - The reserve map for private mappings has the
2236 * opposite meaning than that of shared mappings. If NO
2237 * entry is in the reserve map, it means a reservation exists.
2238 * If an entry exists in the reserve map, it means the
2239 * reservation has already been consumed. As a result, the
2240 * return value of this routine is the opposite of the
2241 * value returned from reserve map manipulation routines above.
2242 */
2243 if (ret)
2244 return 0;
2245 else
2246 return 1;
2247 }
2248 else
2249 return ret < 0 ? ret : 0;
2250 }
2251
vma_needs_reservation(struct hstate * h,struct vm_area_struct * vma,unsigned long addr)2252 static long vma_needs_reservation(struct hstate *h,
2253 struct vm_area_struct *vma, unsigned long addr)
2254 {
2255 return __vma_reservation_common(h, vma, addr, VMA_NEEDS_RESV);
2256 }
2257
vma_commit_reservation(struct hstate * h,struct vm_area_struct * vma,unsigned long addr)2258 static long vma_commit_reservation(struct hstate *h,
2259 struct vm_area_struct *vma, unsigned long addr)
2260 {
2261 return __vma_reservation_common(h, vma, addr, VMA_COMMIT_RESV);
2262 }
2263
vma_end_reservation(struct hstate * h,struct vm_area_struct * vma,unsigned long addr)2264 static void vma_end_reservation(struct hstate *h,
2265 struct vm_area_struct *vma, unsigned long addr)
2266 {
2267 (void)__vma_reservation_common(h, vma, addr, VMA_END_RESV);
2268 }
2269
vma_add_reservation(struct hstate * h,struct vm_area_struct * vma,unsigned long addr)2270 static long vma_add_reservation(struct hstate *h,
2271 struct vm_area_struct *vma, unsigned long addr)
2272 {
2273 return __vma_reservation_common(h, vma, addr, VMA_ADD_RESV);
2274 }
2275
2276 /*
2277 * This routine is called to restore a reservation on error paths. In the
2278 * specific error paths, a huge page was allocated (via alloc_huge_page)
2279 * and is about to be freed. If a reservation for the page existed,
2280 * alloc_huge_page would have consumed the reservation and set PagePrivate
2281 * in the newly allocated page. When the page is freed via free_huge_page,
2282 * the global reservation count will be incremented if PagePrivate is set.
2283 * However, free_huge_page can not adjust the reserve map. Adjust the
2284 * reserve map here to be consistent with global reserve count adjustments
2285 * to be made by free_huge_page.
2286 */
restore_reserve_on_error(struct hstate * h,struct vm_area_struct * vma,unsigned long address,struct page * page)2287 static void restore_reserve_on_error(struct hstate *h,
2288 struct vm_area_struct *vma, unsigned long address,
2289 struct page *page)
2290 {
2291 if (unlikely(PagePrivate(page))) {
2292 long rc = vma_needs_reservation(h, vma, address);
2293
2294 if (unlikely(rc < 0)) {
2295 /*
2296 * Rare out of memory condition in reserve map
2297 * manipulation. Clear PagePrivate so that
2298 * global reserve count will not be incremented
2299 * by free_huge_page. This will make it appear
2300 * as though the reservation for this page was
2301 * consumed. This may prevent the task from
2302 * faulting in the page at a later time. This
2303 * is better than inconsistent global huge page
2304 * accounting of reserve counts.
2305 */
2306 ClearPagePrivate(page);
2307 } else if (rc) {
2308 rc = vma_add_reservation(h, vma, address);
2309 if (unlikely(rc < 0))
2310 /*
2311 * See above comment about rare out of
2312 * memory condition.
2313 */
2314 ClearPagePrivate(page);
2315 } else
2316 vma_end_reservation(h, vma, address);
2317 }
2318 }
2319
alloc_huge_page(struct vm_area_struct * vma,unsigned long addr,int avoid_reserve)2320 struct page *alloc_huge_page(struct vm_area_struct *vma,
2321 unsigned long addr, int avoid_reserve)
2322 {
2323 struct hugepage_subpool *spool = subpool_vma(vma);
2324 struct hstate *h = hstate_vma(vma);
2325 struct page *page;
2326 long map_chg, map_commit;
2327 long gbl_chg;
2328 int ret, idx;
2329 struct hugetlb_cgroup *h_cg;
2330 bool deferred_reserve;
2331
2332 idx = hstate_index(h);
2333 /*
2334 * Examine the region/reserve map to determine if the process
2335 * has a reservation for the page to be allocated. A return
2336 * code of zero indicates a reservation exists (no change).
2337 */
2338 map_chg = gbl_chg = vma_needs_reservation(h, vma, addr);
2339 if (map_chg < 0)
2340 return ERR_PTR(-ENOMEM);
2341
2342 /*
2343 * Processes that did not create the mapping will have no
2344 * reserves as indicated by the region/reserve map. Check
2345 * that the allocation will not exceed the subpool limit.
2346 * Allocations for MAP_NORESERVE mappings also need to be
2347 * checked against any subpool limit.
2348 */
2349 if (map_chg || avoid_reserve) {
2350 gbl_chg = hugepage_subpool_get_pages(spool, 1);
2351 if (gbl_chg < 0) {
2352 vma_end_reservation(h, vma, addr);
2353 return ERR_PTR(-ENOSPC);
2354 }
2355
2356 /*
2357 * Even though there was no reservation in the region/reserve
2358 * map, there could be reservations associated with the
2359 * subpool that can be used. This would be indicated if the
2360 * return value of hugepage_subpool_get_pages() is zero.
2361 * However, if avoid_reserve is specified we still avoid even
2362 * the subpool reservations.
2363 */
2364 if (avoid_reserve)
2365 gbl_chg = 1;
2366 }
2367
2368 /* If this allocation is not consuming a reservation, charge it now.
2369 */
2370 deferred_reserve = map_chg || avoid_reserve || !vma_resv_map(vma);
2371 if (deferred_reserve) {
2372 ret = hugetlb_cgroup_charge_cgroup_rsvd(
2373 idx, pages_per_huge_page(h), &h_cg);
2374 if (ret)
2375 goto out_subpool_put;
2376 }
2377
2378 ret = hugetlb_cgroup_charge_cgroup(idx, pages_per_huge_page(h), &h_cg);
2379 if (ret)
2380 goto out_uncharge_cgroup_reservation;
2381
2382 spin_lock(&hugetlb_lock);
2383 /*
2384 * glb_chg is passed to indicate whether or not a page must be taken
2385 * from the global free pool (global change). gbl_chg == 0 indicates
2386 * a reservation exists for the allocation.
2387 */
2388 page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve, gbl_chg);
2389 if (!page) {
2390 spin_unlock(&hugetlb_lock);
2391 page = alloc_buddy_huge_page_with_mpol(h, vma, addr);
2392 if (!page)
2393 goto out_uncharge_cgroup;
2394 spin_lock(&hugetlb_lock);
2395 if (!avoid_reserve && vma_has_reserves(vma, gbl_chg)) {
2396 SetPagePrivate(page);
2397 h->resv_huge_pages--;
2398 }
2399 list_add(&page->lru, &h->hugepage_activelist);
2400 /* Fall through */
2401 }
2402 hugetlb_cgroup_commit_charge(idx, pages_per_huge_page(h), h_cg, page);
2403 /* If allocation is not consuming a reservation, also store the
2404 * hugetlb_cgroup pointer on the page.
2405 */
2406 if (deferred_reserve) {
2407 hugetlb_cgroup_commit_charge_rsvd(idx, pages_per_huge_page(h),
2408 h_cg, page);
2409 }
2410
2411 spin_unlock(&hugetlb_lock);
2412
2413 set_page_private(page, (unsigned long)spool);
2414
2415 map_commit = vma_commit_reservation(h, vma, addr);
2416 if (unlikely(map_chg > map_commit)) {
2417 /*
2418 * The page was added to the reservation map between
2419 * vma_needs_reservation and vma_commit_reservation.
2420 * This indicates a race with hugetlb_reserve_pages.
2421 * Adjust for the subpool count incremented above AND
2422 * in hugetlb_reserve_pages for the same page. Also,
2423 * the reservation count added in hugetlb_reserve_pages
2424 * no longer applies.
2425 */
2426 long rsv_adjust;
2427
2428 rsv_adjust = hugepage_subpool_put_pages(spool, 1);
2429 hugetlb_acct_memory(h, -rsv_adjust);
2430 if (deferred_reserve)
2431 hugetlb_cgroup_uncharge_page_rsvd(hstate_index(h),
2432 pages_per_huge_page(h), page);
2433 }
2434 return page;
2435
2436 out_uncharge_cgroup:
2437 hugetlb_cgroup_uncharge_cgroup(idx, pages_per_huge_page(h), h_cg);
2438 out_uncharge_cgroup_reservation:
2439 if (deferred_reserve)
2440 hugetlb_cgroup_uncharge_cgroup_rsvd(idx, pages_per_huge_page(h),
2441 h_cg);
2442 out_subpool_put:
2443 if (map_chg || avoid_reserve)
2444 hugepage_subpool_put_pages(spool, 1);
2445 vma_end_reservation(h, vma, addr);
2446 return ERR_PTR(-ENOSPC);
2447 }
2448
2449 int alloc_bootmem_huge_page(struct hstate *h)
2450 __attribute__ ((weak, alias("__alloc_bootmem_huge_page")));
__alloc_bootmem_huge_page(struct hstate * h)2451 int __alloc_bootmem_huge_page(struct hstate *h)
2452 {
2453 struct huge_bootmem_page *m;
2454 int nr_nodes, node;
2455
2456 for_each_node_mask_to_alloc(h, nr_nodes, node, &node_states[N_MEMORY]) {
2457 void *addr;
2458
2459 addr = memblock_alloc_try_nid_raw(
2460 huge_page_size(h), huge_page_size(h),
2461 0, MEMBLOCK_ALLOC_ACCESSIBLE, node);
2462 if (addr) {
2463 /*
2464 * Use the beginning of the huge page to store the
2465 * huge_bootmem_page struct (until gather_bootmem
2466 * puts them into the mem_map).
2467 */
2468 m = addr;
2469 goto found;
2470 }
2471 }
2472 return 0;
2473
2474 found:
2475 BUG_ON(!IS_ALIGNED(virt_to_phys(m), huge_page_size(h)));
2476 /* Put them into a private list first because mem_map is not up yet */
2477 INIT_LIST_HEAD(&m->list);
2478 list_add(&m->list, &huge_boot_pages);
2479 m->hstate = h;
2480 return 1;
2481 }
2482
2483 /*
2484 * Put bootmem huge pages into the standard lists after mem_map is up.
2485 * Note: This only applies to gigantic (order > MAX_ORDER) pages.
2486 */
gather_bootmem_prealloc(void)2487 static void __init gather_bootmem_prealloc(void)
2488 {
2489 struct huge_bootmem_page *m;
2490
2491 list_for_each_entry(m, &huge_boot_pages, list) {
2492 struct page *page = virt_to_page(m);
2493 struct hstate *h = m->hstate;
2494
2495 VM_BUG_ON(!hstate_is_gigantic(h));
2496 WARN_ON(page_count(page) != 1);
2497 prep_compound_gigantic_page(page, huge_page_order(h));
2498 WARN_ON(PageReserved(page));
2499 prep_new_huge_page(h, page, page_to_nid(page));
2500 put_page(page); /* free it into the hugepage allocator */
2501
2502 /*
2503 * We need to restore the 'stolen' pages to totalram_pages
2504 * in order to fix confusing memory reports from free(1) and
2505 * other side-effects, like CommitLimit going negative.
2506 */
2507 adjust_managed_page_count(page, pages_per_huge_page(h));
2508 cond_resched();
2509 }
2510 }
2511
hugetlb_hstate_alloc_pages(struct hstate * h)2512 static void __init hugetlb_hstate_alloc_pages(struct hstate *h)
2513 {
2514 unsigned long i;
2515 nodemask_t *node_alloc_noretry;
2516
2517 if (!hstate_is_gigantic(h)) {
2518 /*
2519 * Bit mask controlling how hard we retry per-node allocations.
2520 * Ignore errors as lower level routines can deal with
2521 * node_alloc_noretry == NULL. If this kmalloc fails at boot
2522 * time, we are likely in bigger trouble.
2523 */
2524 node_alloc_noretry = kmalloc(sizeof(*node_alloc_noretry),
2525 GFP_KERNEL);
2526 } else {
2527 /* allocations done at boot time */
2528 node_alloc_noretry = NULL;
2529 }
2530
2531 /* bit mask controlling how hard we retry per-node allocations */
2532 if (node_alloc_noretry)
2533 nodes_clear(*node_alloc_noretry);
2534
2535 for (i = 0; i < h->max_huge_pages; ++i) {
2536 if (hstate_is_gigantic(h)) {
2537 if (hugetlb_cma_size) {
2538 pr_warn_once("HugeTLB: hugetlb_cma is enabled, skip boot time allocation\n");
2539 goto free;
2540 }
2541 if (!alloc_bootmem_huge_page(h))
2542 break;
2543 } else if (!alloc_pool_huge_page(h,
2544 &node_states[N_MEMORY],
2545 node_alloc_noretry))
2546 break;
2547 cond_resched();
2548 }
2549 if (i < h->max_huge_pages) {
2550 char buf[32];
2551
2552 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
2553 pr_warn("HugeTLB: allocating %lu of page size %s failed. Only allocated %lu hugepages.\n",
2554 h->max_huge_pages, buf, i);
2555 h->max_huge_pages = i;
2556 }
2557 free:
2558 kfree(node_alloc_noretry);
2559 }
2560
hugetlb_init_hstates(void)2561 static void __init hugetlb_init_hstates(void)
2562 {
2563 struct hstate *h;
2564
2565 for_each_hstate(h) {
2566 if (minimum_order > huge_page_order(h))
2567 minimum_order = huge_page_order(h);
2568
2569 /* oversize hugepages were init'ed in early boot */
2570 if (!hstate_is_gigantic(h))
2571 hugetlb_hstate_alloc_pages(h);
2572 }
2573 VM_BUG_ON(minimum_order == UINT_MAX);
2574 }
2575
report_hugepages(void)2576 static void __init report_hugepages(void)
2577 {
2578 struct hstate *h;
2579
2580 for_each_hstate(h) {
2581 char buf[32];
2582
2583 string_get_size(huge_page_size(h), 1, STRING_UNITS_2, buf, 32);
2584 pr_info("HugeTLB registered %s page size, pre-allocated %ld pages\n",
2585 buf, h->free_huge_pages);
2586 }
2587 }
2588
2589 #ifdef CONFIG_HIGHMEM
try_to_free_low(struct hstate * h,unsigned long count,nodemask_t * nodes_allowed)2590 static void try_to_free_low(struct hstate *h, unsigned long count,
2591 nodemask_t *nodes_allowed)
2592 {
2593 int i;
2594
2595 if (hstate_is_gigantic(h))
2596 return;
2597
2598 for_each_node_mask(i, *nodes_allowed) {
2599 struct page *page, *next;
2600 struct list_head *freel = &h->hugepage_freelists[i];
2601 list_for_each_entry_safe(page, next, freel, lru) {
2602 if (count >= h->nr_huge_pages)
2603 return;
2604 if (PageHighMem(page))
2605 continue;
2606 list_del(&page->lru);
2607 update_and_free_page(h, page);
2608 h->free_huge_pages--;
2609 h->free_huge_pages_node[page_to_nid(page)]--;
2610 }
2611 }
2612 }
2613 #else
try_to_free_low(struct hstate * h,unsigned long count,nodemask_t * nodes_allowed)2614 static inline void try_to_free_low(struct hstate *h, unsigned long count,
2615 nodemask_t *nodes_allowed)
2616 {
2617 }
2618 #endif
2619
2620 /*
2621 * Increment or decrement surplus_huge_pages. Keep node-specific counters
2622 * balanced by operating on them in a round-robin fashion.
2623 * Returns 1 if an adjustment was made.
2624 */
adjust_pool_surplus(struct hstate * h,nodemask_t * nodes_allowed,int delta)2625 static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed,
2626 int delta)
2627 {
2628 int nr_nodes, node;
2629
2630 VM_BUG_ON(delta != -1 && delta != 1);
2631
2632 if (delta < 0) {
2633 for_each_node_mask_to_alloc(h, nr_nodes, node, nodes_allowed) {
2634 if (h->surplus_huge_pages_node[node])
2635 goto found;
2636 }
2637 } else {
2638 for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
2639 if (h->surplus_huge_pages_node[node] <
2640 h->nr_huge_pages_node[node])
2641 goto found;
2642 }
2643 }
2644 return 0;
2645
2646 found:
2647 h->surplus_huge_pages += delta;
2648 h->surplus_huge_pages_node[node] += delta;
2649 return 1;
2650 }
2651
2652 #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)2653 static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,
2654 nodemask_t *nodes_allowed)
2655 {
2656 unsigned long min_count, ret;
2657 NODEMASK_ALLOC(nodemask_t, node_alloc_noretry, GFP_KERNEL);
2658
2659 /*
2660 * Bit mask controlling how hard we retry per-node allocations.
2661 * If we can not allocate the bit mask, do not attempt to allocate
2662 * the requested huge pages.
2663 */
2664 if (node_alloc_noretry)
2665 nodes_clear(*node_alloc_noretry);
2666 else
2667 return -ENOMEM;
2668
2669 spin_lock(&hugetlb_lock);
2670
2671 /*
2672 * Check for a node specific request.
2673 * Changing node specific huge page count may require a corresponding
2674 * change to the global count. In any case, the passed node mask
2675 * (nodes_allowed) will restrict alloc/free to the specified node.
2676 */
2677 if (nid != NUMA_NO_NODE) {
2678 unsigned long old_count = count;
2679
2680 count += h->nr_huge_pages - h->nr_huge_pages_node[nid];
2681 /*
2682 * User may have specified a large count value which caused the
2683 * above calculation to overflow. In this case, they wanted
2684 * to allocate as many huge pages as possible. Set count to
2685 * largest possible value to align with their intention.
2686 */
2687 if (count < old_count)
2688 count = ULONG_MAX;
2689 }
2690
2691 /*
2692 * Gigantic pages runtime allocation depend on the capability for large
2693 * page range allocation.
2694 * If the system does not provide this feature, return an error when
2695 * the user tries to allocate gigantic pages but let the user free the
2696 * boottime allocated gigantic pages.
2697 */
2698 if (hstate_is_gigantic(h) && !IS_ENABLED(CONFIG_CONTIG_ALLOC)) {
2699 if (count > persistent_huge_pages(h)) {
2700 spin_unlock(&hugetlb_lock);
2701 NODEMASK_FREE(node_alloc_noretry);
2702 return -EINVAL;
2703 }
2704 /* Fall through to decrease pool */
2705 }
2706
2707 /*
2708 * Increase the pool size
2709 * First take pages out of surplus state. Then make up the
2710 * remaining difference by allocating fresh huge pages.
2711 *
2712 * We might race with alloc_surplus_huge_page() here and be unable
2713 * to convert a surplus huge page to a normal huge page. That is
2714 * not critical, though, it just means the overall size of the
2715 * pool might be one hugepage larger than it needs to be, but
2716 * within all the constraints specified by the sysctls.
2717 */
2718 while (h->surplus_huge_pages && count > persistent_huge_pages(h)) {
2719 if (!adjust_pool_surplus(h, nodes_allowed, -1))
2720 break;
2721 }
2722
2723 while (count > persistent_huge_pages(h)) {
2724 /*
2725 * If this allocation races such that we no longer need the
2726 * page, free_huge_page will handle it by freeing the page
2727 * and reducing the surplus.
2728 */
2729 spin_unlock(&hugetlb_lock);
2730
2731 /* yield cpu to avoid soft lockup */
2732 cond_resched();
2733
2734 ret = alloc_pool_huge_page(h, nodes_allowed,
2735 node_alloc_noretry);
2736 spin_lock(&hugetlb_lock);
2737 if (!ret)
2738 goto out;
2739
2740 /* Bail for signals. Probably ctrl-c from user */
2741 if (signal_pending(current))
2742 goto out;
2743 }
2744
2745 /*
2746 * Decrease the pool size
2747 * First return free pages to the buddy allocator (being careful
2748 * to keep enough around to satisfy reservations). Then place
2749 * pages into surplus state as needed so the pool will shrink
2750 * to the desired size as pages become free.
2751 *
2752 * By placing pages into the surplus state independent of the
2753 * overcommit value, we are allowing the surplus pool size to
2754 * exceed overcommit. There are few sane options here. Since
2755 * alloc_surplus_huge_page() is checking the global counter,
2756 * though, we'll note that we're not allowed to exceed surplus
2757 * and won't grow the pool anywhere else. Not until one of the
2758 * sysctls are changed, or the surplus pages go out of use.
2759 */
2760 min_count = h->resv_huge_pages + h->nr_huge_pages - h->free_huge_pages;
2761 min_count = max(count, min_count);
2762 try_to_free_low(h, min_count, nodes_allowed);
2763 while (min_count < persistent_huge_pages(h)) {
2764 if (!free_pool_huge_page(h, nodes_allowed, 0))
2765 break;
2766 cond_resched_lock(&hugetlb_lock);
2767 }
2768 while (count < persistent_huge_pages(h)) {
2769 if (!adjust_pool_surplus(h, nodes_allowed, 1))
2770 break;
2771 }
2772 out:
2773 h->max_huge_pages = persistent_huge_pages(h);
2774 spin_unlock(&hugetlb_lock);
2775
2776 NODEMASK_FREE(node_alloc_noretry);
2777
2778 return 0;
2779 }
2780
2781 #define HSTATE_ATTR_RO(_name) \
2782 static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
2783
2784 #define HSTATE_ATTR(_name) \
2785 static struct kobj_attribute _name##_attr = \
2786 __ATTR(_name, 0644, _name##_show, _name##_store)
2787
2788 static struct kobject *hugepages_kobj;
2789 static struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
2790
2791 static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp);
2792
kobj_to_hstate(struct kobject * kobj,int * nidp)2793 static struct hstate *kobj_to_hstate(struct kobject *kobj, int *nidp)
2794 {
2795 int i;
2796
2797 for (i = 0; i < HUGE_MAX_HSTATE; i++)
2798 if (hstate_kobjs[i] == kobj) {
2799 if (nidp)
2800 *nidp = NUMA_NO_NODE;
2801 return &hstates[i];
2802 }
2803
2804 return kobj_to_node_hstate(kobj, nidp);
2805 }
2806
nr_hugepages_show_common(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2807 static ssize_t nr_hugepages_show_common(struct kobject *kobj,
2808 struct kobj_attribute *attr, char *buf)
2809 {
2810 struct hstate *h;
2811 unsigned long nr_huge_pages;
2812 int nid;
2813
2814 h = kobj_to_hstate(kobj, &nid);
2815 if (nid == NUMA_NO_NODE)
2816 nr_huge_pages = h->nr_huge_pages;
2817 else
2818 nr_huge_pages = h->nr_huge_pages_node[nid];
2819
2820 return sprintf(buf, "%lu\n", nr_huge_pages);
2821 }
2822
__nr_hugepages_store_common(bool obey_mempolicy,struct hstate * h,int nid,unsigned long count,size_t len)2823 static ssize_t __nr_hugepages_store_common(bool obey_mempolicy,
2824 struct hstate *h, int nid,
2825 unsigned long count, size_t len)
2826 {
2827 int err;
2828 nodemask_t nodes_allowed, *n_mask;
2829
2830 if (hstate_is_gigantic(h) && !gigantic_page_runtime_supported())
2831 return -EINVAL;
2832
2833 if (nid == NUMA_NO_NODE) {
2834 /*
2835 * global hstate attribute
2836 */
2837 if (!(obey_mempolicy &&
2838 init_nodemask_of_mempolicy(&nodes_allowed)))
2839 n_mask = &node_states[N_MEMORY];
2840 else
2841 n_mask = &nodes_allowed;
2842 } else {
2843 /*
2844 * Node specific request. count adjustment happens in
2845 * set_max_huge_pages() after acquiring hugetlb_lock.
2846 */
2847 init_nodemask_of_node(&nodes_allowed, nid);
2848 n_mask = &nodes_allowed;
2849 }
2850
2851 err = set_max_huge_pages(h, count, nid, n_mask);
2852
2853 return err ? err : len;
2854 }
2855
nr_hugepages_store_common(bool obey_mempolicy,struct kobject * kobj,const char * buf,size_t len)2856 static ssize_t nr_hugepages_store_common(bool obey_mempolicy,
2857 struct kobject *kobj, const char *buf,
2858 size_t len)
2859 {
2860 struct hstate *h;
2861 unsigned long count;
2862 int nid;
2863 int err;
2864
2865 err = kstrtoul(buf, 10, &count);
2866 if (err)
2867 return err;
2868
2869 h = kobj_to_hstate(kobj, &nid);
2870 return __nr_hugepages_store_common(obey_mempolicy, h, nid, count, len);
2871 }
2872
nr_hugepages_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2873 static ssize_t nr_hugepages_show(struct kobject *kobj,
2874 struct kobj_attribute *attr, char *buf)
2875 {
2876 return nr_hugepages_show_common(kobj, attr, buf);
2877 }
2878
nr_hugepages_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t len)2879 static ssize_t nr_hugepages_store(struct kobject *kobj,
2880 struct kobj_attribute *attr, const char *buf, size_t len)
2881 {
2882 return nr_hugepages_store_common(false, kobj, buf, len);
2883 }
2884 HSTATE_ATTR(nr_hugepages);
2885
2886 #ifdef CONFIG_NUMA
2887
2888 /*
2889 * hstate attribute for optionally mempolicy-based constraint on persistent
2890 * huge page alloc/free.
2891 */
nr_hugepages_mempolicy_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2892 static ssize_t nr_hugepages_mempolicy_show(struct kobject *kobj,
2893 struct kobj_attribute *attr, char *buf)
2894 {
2895 return nr_hugepages_show_common(kobj, attr, buf);
2896 }
2897
nr_hugepages_mempolicy_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t len)2898 static ssize_t nr_hugepages_mempolicy_store(struct kobject *kobj,
2899 struct kobj_attribute *attr, const char *buf, size_t len)
2900 {
2901 return nr_hugepages_store_common(true, kobj, buf, len);
2902 }
2903 HSTATE_ATTR(nr_hugepages_mempolicy);
2904 #endif
2905
2906
nr_overcommit_hugepages_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2907 static ssize_t nr_overcommit_hugepages_show(struct kobject *kobj,
2908 struct kobj_attribute *attr, char *buf)
2909 {
2910 struct hstate *h = kobj_to_hstate(kobj, NULL);
2911 return sprintf(buf, "%lu\n", h->nr_overcommit_huge_pages);
2912 }
2913
nr_overcommit_hugepages_store(struct kobject * kobj,struct kobj_attribute * attr,const char * buf,size_t count)2914 static ssize_t nr_overcommit_hugepages_store(struct kobject *kobj,
2915 struct kobj_attribute *attr, const char *buf, size_t count)
2916 {
2917 int err;
2918 unsigned long input;
2919 struct hstate *h = kobj_to_hstate(kobj, NULL);
2920
2921 if (hstate_is_gigantic(h))
2922 return -EINVAL;
2923
2924 err = kstrtoul(buf, 10, &input);
2925 if (err)
2926 return err;
2927
2928 spin_lock(&hugetlb_lock);
2929 h->nr_overcommit_huge_pages = input;
2930 spin_unlock(&hugetlb_lock);
2931
2932 return count;
2933 }
2934 HSTATE_ATTR(nr_overcommit_hugepages);
2935
free_hugepages_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2936 static ssize_t free_hugepages_show(struct kobject *kobj,
2937 struct kobj_attribute *attr, char *buf)
2938 {
2939 struct hstate *h;
2940 unsigned long free_huge_pages;
2941 int nid;
2942
2943 h = kobj_to_hstate(kobj, &nid);
2944 if (nid == NUMA_NO_NODE)
2945 free_huge_pages = h->free_huge_pages;
2946 else
2947 free_huge_pages = h->free_huge_pages_node[nid];
2948
2949 return sprintf(buf, "%lu\n", free_huge_pages);
2950 }
2951 HSTATE_ATTR_RO(free_hugepages);
2952
resv_hugepages_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2953 static ssize_t resv_hugepages_show(struct kobject *kobj,
2954 struct kobj_attribute *attr, char *buf)
2955 {
2956 struct hstate *h = kobj_to_hstate(kobj, NULL);
2957 return sprintf(buf, "%lu\n", h->resv_huge_pages);
2958 }
2959 HSTATE_ATTR_RO(resv_hugepages);
2960
surplus_hugepages_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)2961 static ssize_t surplus_hugepages_show(struct kobject *kobj,
2962 struct kobj_attribute *attr, char *buf)
2963 {
2964 struct hstate *h;
2965 unsigned long surplus_huge_pages;
2966 int nid;
2967
2968 h = kobj_to_hstate(kobj, &nid);
2969 if (nid == NUMA_NO_NODE)
2970 surplus_huge_pages = h->surplus_huge_pages;
2971 else
2972 surplus_huge_pages = h->surplus_huge_pages_node[nid];
2973
2974 return sprintf(buf, "%lu\n", surplus_huge_pages);
2975 }
2976 HSTATE_ATTR_RO(surplus_hugepages);
2977
2978 static struct attribute *hstate_attrs[] = {
2979 &nr_hugepages_attr.attr,
2980 &nr_overcommit_hugepages_attr.attr,
2981 &free_hugepages_attr.attr,
2982 &resv_hugepages_attr.attr,
2983 &surplus_hugepages_attr.attr,
2984 #ifdef CONFIG_NUMA
2985 &nr_hugepages_mempolicy_attr.attr,
2986 #endif
2987 NULL,
2988 };
2989
2990 static const struct attribute_group hstate_attr_group = {
2991 .attrs = hstate_attrs,
2992 };
2993
hugetlb_sysfs_add_hstate(struct hstate * h,struct kobject * parent,struct kobject ** hstate_kobjs,const struct attribute_group * hstate_attr_group)2994 static int hugetlb_sysfs_add_hstate(struct hstate *h, struct kobject *parent,
2995 struct kobject **hstate_kobjs,
2996 const struct attribute_group *hstate_attr_group)
2997 {
2998 int retval;
2999 int hi = hstate_index(h);
3000
3001 hstate_kobjs[hi] = kobject_create_and_add(h->name, parent);
3002 if (!hstate_kobjs[hi])
3003 return -ENOMEM;
3004
3005 retval = sysfs_create_group(hstate_kobjs[hi], hstate_attr_group);
3006 if (retval) {
3007 kobject_put(hstate_kobjs[hi]);
3008 hstate_kobjs[hi] = NULL;
3009 }
3010
3011 return retval;
3012 }
3013
hugetlb_sysfs_init(void)3014 static void __init hugetlb_sysfs_init(void)
3015 {
3016 struct hstate *h;
3017 int err;
3018
3019 hugepages_kobj = kobject_create_and_add("hugepages", mm_kobj);
3020 if (!hugepages_kobj)
3021 return;
3022
3023 for_each_hstate(h) {
3024 err = hugetlb_sysfs_add_hstate(h, hugepages_kobj,
3025 hstate_kobjs, &hstate_attr_group);
3026 if (err)
3027 pr_err("HugeTLB: Unable to add hstate %s", h->name);
3028 }
3029 }
3030
3031 #ifdef CONFIG_NUMA
3032
3033 /*
3034 * node_hstate/s - associate per node hstate attributes, via their kobjects,
3035 * with node devices in node_devices[] using a parallel array. The array
3036 * index of a node device or _hstate == node id.
3037 * This is here to avoid any static dependency of the node device driver, in
3038 * the base kernel, on the hugetlb module.
3039 */
3040 struct node_hstate {
3041 struct kobject *hugepages_kobj;
3042 struct kobject *hstate_kobjs[HUGE_MAX_HSTATE];
3043 };
3044 static struct node_hstate node_hstates[MAX_NUMNODES];
3045
3046 /*
3047 * A subset of global hstate attributes for node devices
3048 */
3049 static struct attribute *per_node_hstate_attrs[] = {
3050 &nr_hugepages_attr.attr,
3051 &free_hugepages_attr.attr,
3052 &surplus_hugepages_attr.attr,
3053 NULL,
3054 };
3055
3056 static const struct attribute_group per_node_hstate_attr_group = {
3057 .attrs = per_node_hstate_attrs,
3058 };
3059
3060 /*
3061 * kobj_to_node_hstate - lookup global hstate for node device hstate attr kobj.
3062 * Returns node id via non-NULL nidp.
3063 */
kobj_to_node_hstate(struct kobject * kobj,int * nidp)3064 static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
3065 {
3066 int nid;
3067
3068 for (nid = 0; nid < nr_node_ids; nid++) {
3069 struct node_hstate *nhs = &node_hstates[nid];
3070 int i;
3071 for (i = 0; i < HUGE_MAX_HSTATE; i++)
3072 if (nhs->hstate_kobjs[i] == kobj) {
3073 if (nidp)
3074 *nidp = nid;
3075 return &hstates[i];
3076 }
3077 }
3078
3079 BUG();
3080 return NULL;
3081 }
3082
3083 /*
3084 * Unregister hstate attributes from a single node device.
3085 * No-op if no hstate attributes attached.
3086 */
hugetlb_unregister_node(struct node * node)3087 static void hugetlb_unregister_node(struct node *node)
3088 {
3089 struct hstate *h;
3090 struct node_hstate *nhs = &node_hstates[node->dev.id];
3091
3092 if (!nhs->hugepages_kobj)
3093 return; /* no hstate attributes */
3094
3095 for_each_hstate(h) {
3096 int idx = hstate_index(h);
3097 if (nhs->hstate_kobjs[idx]) {
3098 kobject_put(nhs->hstate_kobjs[idx]);
3099 nhs->hstate_kobjs[idx] = NULL;
3100 }
3101 }
3102
3103 kobject_put(nhs->hugepages_kobj);
3104 nhs->hugepages_kobj = NULL;
3105 }
3106
3107
3108 /*
3109 * Register hstate attributes for a single node device.
3110 * No-op if attributes already registered.
3111 */
hugetlb_register_node(struct node * node)3112 static void hugetlb_register_node(struct node *node)
3113 {
3114 struct hstate *h;
3115 struct node_hstate *nhs = &node_hstates[node->dev.id];
3116 int err;
3117
3118 if (nhs->hugepages_kobj)
3119 return; /* already allocated */
3120
3121 nhs->hugepages_kobj = kobject_create_and_add("hugepages",
3122 &node->dev.kobj);
3123 if (!nhs->hugepages_kobj)
3124 return;
3125
3126 for_each_hstate(h) {
3127 err = hugetlb_sysfs_add_hstate(h, nhs->hugepages_kobj,
3128 nhs->hstate_kobjs,
3129 &per_node_hstate_attr_group);
3130 if (err) {
3131 pr_err("HugeTLB: Unable to add hstate %s for node %d\n",
3132 h->name, node->dev.id);
3133 hugetlb_unregister_node(node);
3134 break;
3135 }
3136 }
3137 }
3138
3139 /*
3140 * hugetlb init time: register hstate attributes for all registered node
3141 * devices of nodes that have memory. All on-line nodes should have
3142 * registered their associated device by this time.
3143 */
hugetlb_register_all_nodes(void)3144 static void __init hugetlb_register_all_nodes(void)
3145 {
3146 int nid;
3147
3148 for_each_node_state(nid, N_MEMORY) {
3149 struct node *node = node_devices[nid];
3150 if (node->dev.id == nid)
3151 hugetlb_register_node(node);
3152 }
3153
3154 /*
3155 * Let the node device driver know we're here so it can
3156 * [un]register hstate attributes on node hotplug.
3157 */
3158 register_hugetlbfs_with_node(hugetlb_register_node,
3159 hugetlb_unregister_node);
3160 }
3161 #else /* !CONFIG_NUMA */
3162
kobj_to_node_hstate(struct kobject * kobj,int * nidp)3163 static struct hstate *kobj_to_node_hstate(struct kobject *kobj, int *nidp)
3164 {
3165 BUG();
3166 if (nidp)
3167 *nidp = -1;
3168 return NULL;
3169 }
3170
hugetlb_register_all_nodes(void)3171 static void hugetlb_register_all_nodes(void) { }
3172
3173 #endif
3174
hugetlb_init(void)3175 static int __init hugetlb_init(void)
3176 {
3177 int i;
3178
3179 if (!hugepages_supported()) {
3180 if (hugetlb_max_hstate || default_hstate_max_huge_pages)
3181 pr_warn("HugeTLB: huge pages not supported, ignoring associated command-line parameters\n");
3182 return 0;
3183 }
3184
3185 /*
3186 * Make sure HPAGE_SIZE (HUGETLB_PAGE_ORDER) hstate exists. Some
3187 * architectures depend on setup being done here.
3188 */
3189 hugetlb_add_hstate(HUGETLB_PAGE_ORDER);
3190 if (!parsed_default_hugepagesz) {
3191 /*
3192 * If we did not parse a default huge page size, set
3193 * default_hstate_idx to HPAGE_SIZE hstate. And, if the
3194 * number of huge pages for this default size was implicitly
3195 * specified, set that here as well.
3196 * Note that the implicit setting will overwrite an explicit
3197 * setting. A warning will be printed in this case.
3198 */
3199 default_hstate_idx = hstate_index(size_to_hstate(HPAGE_SIZE));
3200 if (default_hstate_max_huge_pages) {
3201 if (default_hstate.max_huge_pages) {
3202 char buf[32];
3203
3204 string_get_size(huge_page_size(&default_hstate),
3205 1, STRING_UNITS_2, buf, 32);
3206 pr_warn("HugeTLB: Ignoring hugepages=%lu associated with %s page size\n",
3207 default_hstate.max_huge_pages, buf);
3208 pr_warn("HugeTLB: Using hugepages=%lu for number of default huge pages\n",
3209 default_hstate_max_huge_pages);
3210 }
3211 default_hstate.max_huge_pages =
3212 default_hstate_max_huge_pages;
3213 }
3214 }
3215
3216 hugetlb_cma_check();
3217 hugetlb_init_hstates();
3218 gather_bootmem_prealloc();
3219 report_hugepages();
3220
3221 hugetlb_sysfs_init();
3222 hugetlb_register_all_nodes();
3223 hugetlb_cgroup_file_init();
3224
3225 #ifdef CONFIG_SMP
3226 num_fault_mutexes = roundup_pow_of_two(8 * num_possible_cpus());
3227 #else
3228 num_fault_mutexes = 1;
3229 #endif
3230 hugetlb_fault_mutex_table =
3231 kmalloc_array(num_fault_mutexes, sizeof(struct mutex),
3232 GFP_KERNEL);
3233 BUG_ON(!hugetlb_fault_mutex_table);
3234
3235 for (i = 0; i < num_fault_mutexes; i++)
3236 mutex_init(&hugetlb_fault_mutex_table[i]);
3237 return 0;
3238 }
3239 subsys_initcall(hugetlb_init);
3240
3241 /* Overwritten by architectures with more huge page sizes */
__init(weak)3242 bool __init __attribute((weak)) arch_hugetlb_valid_size(unsigned long size)
3243 {
3244 return size == HPAGE_SIZE;
3245 }
3246
hugetlb_add_hstate(unsigned int order)3247 void __init hugetlb_add_hstate(unsigned int order)
3248 {
3249 struct hstate *h;
3250 unsigned long i;
3251
3252 if (size_to_hstate(PAGE_SIZE << order)) {
3253 return;
3254 }
3255 BUG_ON(hugetlb_max_hstate >= HUGE_MAX_HSTATE);
3256 BUG_ON(order == 0);
3257 h = &hstates[hugetlb_max_hstate++];
3258 h->order = order;
3259 h->mask = ~((1ULL << (order + PAGE_SHIFT)) - 1);
3260 h->nr_huge_pages = 0;
3261 h->free_huge_pages = 0;
3262 for (i = 0; i < MAX_NUMNODES; ++i)
3263 INIT_LIST_HEAD(&h->hugepage_freelists[i]);
3264 INIT_LIST_HEAD(&h->hugepage_activelist);
3265 h->next_nid_to_alloc = first_memory_node;
3266 h->next_nid_to_free = first_memory_node;
3267 snprintf(h->name, HSTATE_NAME_LEN, "hugepages-%lukB",
3268 huge_page_size(h)/1024);
3269
3270 parsed_hstate = h;
3271 }
3272
3273 /*
3274 * hugepages command line processing
3275 * hugepages normally follows a valid hugepagsz or default_hugepagsz
3276 * specification. If not, ignore the hugepages value. hugepages can also
3277 * be the first huge page command line option in which case it implicitly
3278 * specifies the number of huge pages for the default size.
3279 */
hugepages_setup(char * s)3280 static int __init hugepages_setup(char *s)
3281 {
3282 unsigned long *mhp;
3283 static unsigned long *last_mhp;
3284
3285 if (!parsed_valid_hugepagesz) {
3286 pr_warn("HugeTLB: hugepages=%s does not follow a valid hugepagesz, ignoring\n", s);
3287 parsed_valid_hugepagesz = true;
3288 return 0;
3289 }
3290
3291 /*
3292 * !hugetlb_max_hstate means we haven't parsed a hugepagesz= parameter
3293 * yet, so this hugepages= parameter goes to the "default hstate".
3294 * Otherwise, it goes with the previously parsed hugepagesz or
3295 * default_hugepagesz.
3296 */
3297 else if (!hugetlb_max_hstate)
3298 mhp = &default_hstate_max_huge_pages;
3299 else
3300 mhp = &parsed_hstate->max_huge_pages;
3301
3302 if (mhp == last_mhp) {
3303 pr_warn("HugeTLB: hugepages= specified twice without interleaving hugepagesz=, ignoring hugepages=%s\n", s);
3304 return 0;
3305 }
3306
3307 if (sscanf(s, "%lu", mhp) <= 0)
3308 *mhp = 0;
3309
3310 /*
3311 * Global state is always initialized later in hugetlb_init.
3312 * But we need to allocate >= MAX_ORDER hstates here early to still
3313 * use the bootmem allocator.
3314 */
3315 if (hugetlb_max_hstate && parsed_hstate->order >= MAX_ORDER)
3316 hugetlb_hstate_alloc_pages(parsed_hstate);
3317
3318 last_mhp = mhp;
3319
3320 return 1;
3321 }
3322 __setup("hugepages=", hugepages_setup);
3323
3324 /*
3325 * hugepagesz command line processing
3326 * A specific huge page size can only be specified once with hugepagesz.
3327 * hugepagesz is followed by hugepages on the command line. The global
3328 * variable 'parsed_valid_hugepagesz' is used to determine if prior
3329 * hugepagesz argument was valid.
3330 */
hugepagesz_setup(char * s)3331 static int __init hugepagesz_setup(char *s)
3332 {
3333 unsigned long size;
3334 struct hstate *h;
3335
3336 parsed_valid_hugepagesz = false;
3337 size = (unsigned long)memparse(s, NULL);
3338
3339 if (!arch_hugetlb_valid_size(size)) {
3340 pr_err("HugeTLB: unsupported hugepagesz=%s\n", s);
3341 return 0;
3342 }
3343
3344 h = size_to_hstate(size);
3345 if (h) {
3346 /*
3347 * hstate for this size already exists. This is normally
3348 * an error, but is allowed if the existing hstate is the
3349 * default hstate. More specifically, it is only allowed if
3350 * the number of huge pages for the default hstate was not
3351 * previously specified.
3352 */
3353 if (!parsed_default_hugepagesz || h != &default_hstate ||
3354 default_hstate.max_huge_pages) {
3355 pr_warn("HugeTLB: hugepagesz=%s specified twice, ignoring\n", s);
3356 return 0;
3357 }
3358
3359 /*
3360 * No need to call hugetlb_add_hstate() as hstate already
3361 * exists. But, do set parsed_hstate so that a following
3362 * hugepages= parameter will be applied to this hstate.
3363 */
3364 parsed_hstate = h;
3365 parsed_valid_hugepagesz = true;
3366 return 1;
3367 }
3368
3369 hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
3370 parsed_valid_hugepagesz = true;
3371 return 1;
3372 }
3373 __setup("hugepagesz=", hugepagesz_setup);
3374
3375 /*
3376 * default_hugepagesz command line input
3377 * Only one instance of default_hugepagesz allowed on command line.
3378 */
default_hugepagesz_setup(char * s)3379 static int __init default_hugepagesz_setup(char *s)
3380 {
3381 unsigned long size;
3382
3383 parsed_valid_hugepagesz = false;
3384 if (parsed_default_hugepagesz) {
3385 pr_err("HugeTLB: default_hugepagesz previously specified, ignoring %s\n", s);
3386 return 0;
3387 }
3388
3389 size = (unsigned long)memparse(s, NULL);
3390
3391 if (!arch_hugetlb_valid_size(size)) {
3392 pr_err("HugeTLB: unsupported default_hugepagesz=%s\n", s);
3393 return 0;
3394 }
3395
3396 hugetlb_add_hstate(ilog2(size) - PAGE_SHIFT);
3397 parsed_valid_hugepagesz = true;
3398 parsed_default_hugepagesz = true;
3399 default_hstate_idx = hstate_index(size_to_hstate(size));
3400
3401 /*
3402 * The number of default huge pages (for this size) could have been
3403 * specified as the first hugetlb parameter: hugepages=X. If so,
3404 * then default_hstate_max_huge_pages is set. If the default huge
3405 * page size is gigantic (>= MAX_ORDER), then the pages must be
3406 * allocated here from bootmem allocator.
3407 */
3408 if (default_hstate_max_huge_pages) {
3409 default_hstate.max_huge_pages = default_hstate_max_huge_pages;
3410 if (hstate_is_gigantic(&default_hstate))
3411 hugetlb_hstate_alloc_pages(&default_hstate);
3412 default_hstate_max_huge_pages = 0;
3413 }
3414
3415 return 1;
3416 }
3417 __setup("default_hugepagesz=", default_hugepagesz_setup);
3418
allowed_mems_nr(struct hstate * h)3419 static unsigned int allowed_mems_nr(struct hstate *h)
3420 {
3421 int node;
3422 unsigned int nr = 0;
3423 nodemask_t *mpol_allowed;
3424 unsigned int *array = h->free_huge_pages_node;
3425 gfp_t gfp_mask = htlb_alloc_mask(h);
3426
3427 mpol_allowed = policy_nodemask_current(gfp_mask);
3428
3429 for_each_node_mask(node, cpuset_current_mems_allowed) {
3430 if (!mpol_allowed ||
3431 (mpol_allowed && node_isset(node, *mpol_allowed)))
3432 nr += array[node];
3433 }
3434
3435 return nr;
3436 }
3437
3438 #ifdef CONFIG_SYSCTL
proc_hugetlb_doulongvec_minmax(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos,unsigned long * out)3439 static int proc_hugetlb_doulongvec_minmax(struct ctl_table *table, int write,
3440 void *buffer, size_t *length,
3441 loff_t *ppos, unsigned long *out)
3442 {
3443 struct ctl_table dup_table;
3444
3445 /*
3446 * In order to avoid races with __do_proc_doulongvec_minmax(), we
3447 * can duplicate the @table and alter the duplicate of it.
3448 */
3449 dup_table = *table;
3450 dup_table.data = out;
3451
3452 return proc_doulongvec_minmax(&dup_table, write, buffer, length, ppos);
3453 }
3454
hugetlb_sysctl_handler_common(bool obey_mempolicy,struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)3455 static int hugetlb_sysctl_handler_common(bool obey_mempolicy,
3456 struct ctl_table *table, int write,
3457 void *buffer, size_t *length, loff_t *ppos)
3458 {
3459 struct hstate *h = &default_hstate;
3460 unsigned long tmp = h->max_huge_pages;
3461 int ret;
3462
3463 if (!hugepages_supported())
3464 return -EOPNOTSUPP;
3465
3466 ret = proc_hugetlb_doulongvec_minmax(table, write, buffer, length, ppos,
3467 &tmp);
3468 if (ret)
3469 goto out;
3470
3471 if (write)
3472 ret = __nr_hugepages_store_common(obey_mempolicy, h,
3473 NUMA_NO_NODE, tmp, *length);
3474 out:
3475 return ret;
3476 }
3477
hugetlb_sysctl_handler(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)3478 int hugetlb_sysctl_handler(struct ctl_table *table, int write,
3479 void *buffer, size_t *length, loff_t *ppos)
3480 {
3481
3482 return hugetlb_sysctl_handler_common(false, table, write,
3483 buffer, length, ppos);
3484 }
3485
3486 #ifdef CONFIG_NUMA
hugetlb_mempolicy_sysctl_handler(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)3487 int hugetlb_mempolicy_sysctl_handler(struct ctl_table *table, int write,
3488 void *buffer, size_t *length, loff_t *ppos)
3489 {
3490 return hugetlb_sysctl_handler_common(true, table, write,
3491 buffer, length, ppos);
3492 }
3493 #endif /* CONFIG_NUMA */
3494
hugetlb_overcommit_handler(struct ctl_table * table,int write,void * buffer,size_t * length,loff_t * ppos)3495 int hugetlb_overcommit_handler(struct ctl_table *table, int write,
3496 void *buffer, size_t *length, loff_t *ppos)
3497 {
3498 struct hstate *h = &default_hstate;
3499 unsigned long tmp;
3500 int ret;
3501
3502 if (!hugepages_supported())
3503 return -EOPNOTSUPP;
3504
3505 tmp = h->nr_overcommit_huge_pages;
3506
3507 if (write && hstate_is_gigantic(h))
3508 return -EINVAL;
3509
3510 ret = proc_hugetlb_doulongvec_minmax(table, write, buffer, length, ppos,
3511 &tmp);
3512 if (ret)
3513 goto out;
3514
3515 if (write) {
3516 spin_lock(&hugetlb_lock);
3517 h->nr_overcommit_huge_pages = tmp;
3518 spin_unlock(&hugetlb_lock);
3519 }
3520 out:
3521 return ret;
3522 }
3523
3524 #endif /* CONFIG_SYSCTL */
3525
hugetlb_report_meminfo(struct seq_file * m)3526 void hugetlb_report_meminfo(struct seq_file *m)
3527 {
3528 struct hstate *h;
3529 unsigned long total = 0;
3530
3531 if (!hugepages_supported())
3532 return;
3533
3534 for_each_hstate(h) {
3535 unsigned long count = h->nr_huge_pages;
3536
3537 total += (PAGE_SIZE << huge_page_order(h)) * count;
3538
3539 if (h == &default_hstate)
3540 seq_printf(m,
3541 "HugePages_Total: %5lu\n"
3542 "HugePages_Free: %5lu\n"
3543 "HugePages_Rsvd: %5lu\n"
3544 "HugePages_Surp: %5lu\n"
3545 "Hugepagesize: %8lu kB\n",
3546 count,
3547 h->free_huge_pages,
3548 h->resv_huge_pages,
3549 h->surplus_huge_pages,
3550 (PAGE_SIZE << huge_page_order(h)) / 1024);
3551 }
3552
3553 seq_printf(m, "Hugetlb: %8lu kB\n", total / 1024);
3554 }
3555
hugetlb_report_node_meminfo(char * buf,int len,int nid)3556 int hugetlb_report_node_meminfo(char *buf, int len, int nid)
3557 {
3558 struct hstate *h = &default_hstate;
3559
3560 if (!hugepages_supported())
3561 return 0;
3562
3563 return sysfs_emit_at(buf, len,
3564 "Node %d HugePages_Total: %5u\n"
3565 "Node %d HugePages_Free: %5u\n"
3566 "Node %d HugePages_Surp: %5u\n",
3567 nid, h->nr_huge_pages_node[nid],
3568 nid, h->free_huge_pages_node[nid],
3569 nid, h->surplus_huge_pages_node[nid]);
3570 }
3571
hugetlb_show_meminfo(void)3572 void hugetlb_show_meminfo(void)
3573 {
3574 struct hstate *h;
3575 int nid;
3576
3577 if (!hugepages_supported())
3578 return;
3579
3580 for_each_node_state(nid, N_MEMORY)
3581 for_each_hstate(h)
3582 pr_info("Node %d hugepages_total=%u hugepages_free=%u hugepages_surp=%u hugepages_size=%lukB\n",
3583 nid,
3584 h->nr_huge_pages_node[nid],
3585 h->free_huge_pages_node[nid],
3586 h->surplus_huge_pages_node[nid],
3587 1UL << (huge_page_order(h) + PAGE_SHIFT - 10));
3588 }
3589
hugetlb_report_usage(struct seq_file * m,struct mm_struct * mm)3590 void hugetlb_report_usage(struct seq_file *m, struct mm_struct *mm)
3591 {
3592 seq_printf(m, "HugetlbPages:\t%8lu kB\n",
3593 atomic_long_read(&mm->hugetlb_usage) << (PAGE_SHIFT - 10));
3594 }
3595
3596 /* Return the number pages of memory we physically have, in PAGE_SIZE units. */
hugetlb_total_pages(void)3597 unsigned long hugetlb_total_pages(void)
3598 {
3599 struct hstate *h;
3600 unsigned long nr_total_pages = 0;
3601
3602 for_each_hstate(h)
3603 nr_total_pages += h->nr_huge_pages * pages_per_huge_page(h);
3604 return nr_total_pages;
3605 }
3606
hugetlb_acct_memory(struct hstate * h,long delta)3607 static int hugetlb_acct_memory(struct hstate *h, long delta)
3608 {
3609 int ret = -ENOMEM;
3610
3611 spin_lock(&hugetlb_lock);
3612 /*
3613 * When cpuset is configured, it breaks the strict hugetlb page
3614 * reservation as the accounting is done on a global variable. Such
3615 * reservation is completely rubbish in the presence of cpuset because
3616 * the reservation is not checked against page availability for the
3617 * current cpuset. Application can still potentially OOM'ed by kernel
3618 * with lack of free htlb page in cpuset that the task is in.
3619 * Attempt to enforce strict accounting with cpuset is almost
3620 * impossible (or too ugly) because cpuset is too fluid that
3621 * task or memory node can be dynamically moved between cpusets.
3622 *
3623 * The change of semantics for shared hugetlb mapping with cpuset is
3624 * undesirable. However, in order to preserve some of the semantics,
3625 * we fall back to check against current free page availability as
3626 * a best attempt and hopefully to minimize the impact of changing
3627 * semantics that cpuset has.
3628 *
3629 * Apart from cpuset, we also have memory policy mechanism that
3630 * also determines from which node the kernel will allocate memory
3631 * in a NUMA system. So similar to cpuset, we also should consider
3632 * the memory policy of the current task. Similar to the description
3633 * above.
3634 */
3635 if (delta > 0) {
3636 if (gather_surplus_pages(h, delta) < 0)
3637 goto out;
3638
3639 if (delta > allowed_mems_nr(h)) {
3640 return_unused_surplus_pages(h, delta);
3641 goto out;
3642 }
3643 }
3644
3645 ret = 0;
3646 if (delta < 0)
3647 return_unused_surplus_pages(h, (unsigned long) -delta);
3648
3649 out:
3650 spin_unlock(&hugetlb_lock);
3651 return ret;
3652 }
3653
hugetlb_vm_op_open(struct vm_area_struct * vma)3654 static void hugetlb_vm_op_open(struct vm_area_struct *vma)
3655 {
3656 struct resv_map *resv = vma_resv_map(vma);
3657
3658 /*
3659 * This new VMA should share its siblings reservation map if present.
3660 * The VMA will only ever have a valid reservation map pointer where
3661 * it is being copied for another still existing VMA. As that VMA
3662 * has a reference to the reservation map it cannot disappear until
3663 * after this open call completes. It is therefore safe to take a
3664 * new reference here without additional locking.
3665 */
3666 if (resv && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
3667 resv_map_dup_hugetlb_cgroup_uncharge_info(resv);
3668 kref_get(&resv->refs);
3669 }
3670 }
3671
hugetlb_vm_op_close(struct vm_area_struct * vma)3672 static void hugetlb_vm_op_close(struct vm_area_struct *vma)
3673 {
3674 struct hstate *h = hstate_vma(vma);
3675 struct resv_map *resv = vma_resv_map(vma);
3676 struct hugepage_subpool *spool = subpool_vma(vma);
3677 unsigned long reserve, start, end;
3678 long gbl_reserve;
3679
3680 if (!resv || !is_vma_resv_set(vma, HPAGE_RESV_OWNER))
3681 return;
3682
3683 start = vma_hugecache_offset(h, vma, vma->vm_start);
3684 end = vma_hugecache_offset(h, vma, vma->vm_end);
3685
3686 reserve = (end - start) - region_count(resv, start, end);
3687 hugetlb_cgroup_uncharge_counter(resv, start, end);
3688 if (reserve) {
3689 /*
3690 * Decrement reserve counts. The global reserve count may be
3691 * adjusted if the subpool has a minimum size.
3692 */
3693 gbl_reserve = hugepage_subpool_put_pages(spool, reserve);
3694 hugetlb_acct_memory(h, -gbl_reserve);
3695 }
3696
3697 kref_put(&resv->refs, resv_map_release);
3698 }
3699
hugetlb_vm_op_split(struct vm_area_struct * vma,unsigned long addr)3700 static int hugetlb_vm_op_split(struct vm_area_struct *vma, unsigned long addr)
3701 {
3702 if (addr & ~(huge_page_mask(hstate_vma(vma))))
3703 return -EINVAL;
3704
3705 /*
3706 * PMD sharing is only possible for PUD_SIZE-aligned address ranges
3707 * in HugeTLB VMAs. If we will lose PUD_SIZE alignment due to this
3708 * split, unshare PMDs in the PUD_SIZE interval surrounding addr now.
3709 */
3710 if (addr & ~PUD_MASK) {
3711 /*
3712 * hugetlb_vm_op_split is called right before we attempt to
3713 * split the VMA. We will need to unshare PMDs in the old and
3714 * new VMAs, so let's unshare before we split.
3715 */
3716 unsigned long floor = addr & PUD_MASK;
3717 unsigned long ceil = floor + PUD_SIZE;
3718
3719 if (floor >= vma->vm_start && ceil <= vma->vm_end)
3720 hugetlb_unshare_pmds(vma, floor, ceil);
3721 }
3722
3723 return 0;
3724 }
3725
hugetlb_vm_op_pagesize(struct vm_area_struct * vma)3726 static unsigned long hugetlb_vm_op_pagesize(struct vm_area_struct *vma)
3727 {
3728 struct hstate *hstate = hstate_vma(vma);
3729
3730 return 1UL << huge_page_shift(hstate);
3731 }
3732
3733 /*
3734 * We cannot handle pagefaults against hugetlb pages at all. They cause
3735 * handle_mm_fault() to try to instantiate regular-sized pages in the
3736 * hugegpage VMA. do_page_fault() is supposed to trap this, so BUG is we get
3737 * this far.
3738 */
hugetlb_vm_op_fault(struct vm_fault * vmf)3739 static vm_fault_t hugetlb_vm_op_fault(struct vm_fault *vmf)
3740 {
3741 BUG();
3742 return 0;
3743 }
3744
3745 /*
3746 * When a new function is introduced to vm_operations_struct and added
3747 * to hugetlb_vm_ops, please consider adding the function to shm_vm_ops.
3748 * This is because under System V memory model, mappings created via
3749 * shmget/shmat with "huge page" specified are backed by hugetlbfs files,
3750 * their original vm_ops are overwritten with shm_vm_ops.
3751 */
3752 const struct vm_operations_struct hugetlb_vm_ops = {
3753 .fault = hugetlb_vm_op_fault,
3754 .open = hugetlb_vm_op_open,
3755 .close = hugetlb_vm_op_close,
3756 .split = hugetlb_vm_op_split,
3757 .pagesize = hugetlb_vm_op_pagesize,
3758 };
3759
make_huge_pte(struct vm_area_struct * vma,struct page * page,int writable)3760 static pte_t make_huge_pte(struct vm_area_struct *vma, struct page *page,
3761 int writable)
3762 {
3763 pte_t entry;
3764
3765 if (writable) {
3766 entry = huge_pte_mkwrite(huge_pte_mkdirty(mk_huge_pte(page,
3767 vma->vm_page_prot)));
3768 } else {
3769 entry = huge_pte_wrprotect(mk_huge_pte(page,
3770 vma->vm_page_prot));
3771 }
3772 entry = pte_mkyoung(entry);
3773 entry = pte_mkhuge(entry);
3774 entry = arch_make_huge_pte(entry, vma, page, writable);
3775
3776 return entry;
3777 }
3778
set_huge_ptep_writable(struct vm_area_struct * vma,unsigned long address,pte_t * ptep)3779 static void set_huge_ptep_writable(struct vm_area_struct *vma,
3780 unsigned long address, pte_t *ptep)
3781 {
3782 pte_t entry;
3783
3784 entry = huge_pte_mkwrite(huge_pte_mkdirty(huge_ptep_get(ptep)));
3785 if (huge_ptep_set_access_flags(vma, address, ptep, entry, 1))
3786 update_mmu_cache(vma, address, ptep);
3787 }
3788
is_hugetlb_entry_migration(pte_t pte)3789 bool is_hugetlb_entry_migration(pte_t pte)
3790 {
3791 swp_entry_t swp;
3792
3793 if (huge_pte_none(pte) || pte_present(pte))
3794 return false;
3795 swp = pte_to_swp_entry(pte);
3796 if (is_migration_entry(swp))
3797 return true;
3798 else
3799 return false;
3800 }
3801
is_hugetlb_entry_hwpoisoned(pte_t pte)3802 static bool is_hugetlb_entry_hwpoisoned(pte_t pte)
3803 {
3804 swp_entry_t swp;
3805
3806 if (huge_pte_none(pte) || pte_present(pte))
3807 return false;
3808 swp = pte_to_swp_entry(pte);
3809 if (is_hwpoison_entry(swp))
3810 return true;
3811 else
3812 return false;
3813 }
3814
copy_hugetlb_page_range(struct mm_struct * dst,struct mm_struct * src,struct vm_area_struct * vma)3815 int copy_hugetlb_page_range(struct mm_struct *dst, struct mm_struct *src,
3816 struct vm_area_struct *vma)
3817 {
3818 pte_t *src_pte, *dst_pte, entry, dst_entry;
3819 struct page *ptepage;
3820 unsigned long addr;
3821 int cow;
3822 struct hstate *h = hstate_vma(vma);
3823 unsigned long sz = huge_page_size(h);
3824 struct address_space *mapping = vma->vm_file->f_mapping;
3825 struct mmu_notifier_range range;
3826 int ret = 0;
3827
3828 cow = (vma->vm_flags & (VM_SHARED | VM_MAYWRITE)) == VM_MAYWRITE;
3829
3830 if (cow) {
3831 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, src,
3832 vma->vm_start,
3833 vma->vm_end);
3834 mmu_notifier_invalidate_range_start(&range);
3835 } else {
3836 /*
3837 * For shared mappings i_mmap_rwsem must be held to call
3838 * huge_pte_alloc, otherwise the returned ptep could go
3839 * away if part of a shared pmd and another thread calls
3840 * huge_pmd_unshare.
3841 */
3842 i_mmap_lock_read(mapping);
3843 }
3844
3845 for (addr = vma->vm_start; addr < vma->vm_end; addr += sz) {
3846 spinlock_t *src_ptl, *dst_ptl;
3847 src_pte = huge_pte_offset(src, addr, sz);
3848 if (!src_pte)
3849 continue;
3850 dst_pte = huge_pte_alloc(dst, vma, addr, sz);
3851 if (!dst_pte) {
3852 ret = -ENOMEM;
3853 break;
3854 }
3855
3856 /*
3857 * If the pagetables are shared don't copy or take references.
3858 * dst_pte == src_pte is the common case of src/dest sharing.
3859 *
3860 * However, src could have 'unshared' and dst shares with
3861 * another vma. If dst_pte !none, this implies sharing.
3862 * Check here before taking page table lock, and once again
3863 * after taking the lock below.
3864 */
3865 dst_entry = huge_ptep_get(dst_pte);
3866 if ((dst_pte == src_pte) || !huge_pte_none(dst_entry))
3867 continue;
3868
3869 dst_ptl = huge_pte_lock(h, dst, dst_pte);
3870 src_ptl = huge_pte_lockptr(h, src, src_pte);
3871 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
3872 entry = huge_ptep_get(src_pte);
3873 dst_entry = huge_ptep_get(dst_pte);
3874 if (huge_pte_none(entry) || !huge_pte_none(dst_entry)) {
3875 /*
3876 * Skip if src entry none. Also, skip in the
3877 * unlikely case dst entry !none as this implies
3878 * sharing with another vma.
3879 */
3880 ;
3881 } else if (unlikely(is_hugetlb_entry_migration(entry) ||
3882 is_hugetlb_entry_hwpoisoned(entry))) {
3883 swp_entry_t swp_entry = pte_to_swp_entry(entry);
3884
3885 if (is_write_migration_entry(swp_entry) && cow) {
3886 /*
3887 * COW mappings require pages in both
3888 * parent and child to be set to read.
3889 */
3890 make_migration_entry_read(&swp_entry);
3891 entry = swp_entry_to_pte(swp_entry);
3892 set_huge_swap_pte_at(src, addr, src_pte,
3893 entry, sz);
3894 }
3895 set_huge_swap_pte_at(dst, addr, dst_pte, entry, sz);
3896 } else {
3897 if (cow) {
3898 /*
3899 * No need to notify as we are downgrading page
3900 * table protection not changing it to point
3901 * to a new page.
3902 *
3903 * See Documentation/vm/mmu_notifier.rst
3904 */
3905 huge_ptep_set_wrprotect(src, addr, src_pte);
3906 }
3907 entry = huge_ptep_get(src_pte);
3908 ptepage = pte_page(entry);
3909 get_page(ptepage);
3910 page_dup_rmap(ptepage, true);
3911 set_huge_pte_at(dst, addr, dst_pte, entry);
3912 hugetlb_count_add(pages_per_huge_page(h), dst);
3913 }
3914 spin_unlock(src_ptl);
3915 spin_unlock(dst_ptl);
3916 }
3917
3918 if (cow)
3919 mmu_notifier_invalidate_range_end(&range);
3920 else
3921 i_mmap_unlock_read(mapping);
3922
3923 return ret;
3924 }
3925
__unmap_hugepage_range(struct mmu_gather * tlb,struct vm_area_struct * vma,unsigned long start,unsigned long end,struct page * ref_page)3926 void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
3927 unsigned long start, unsigned long end,
3928 struct page *ref_page)
3929 {
3930 struct mm_struct *mm = vma->vm_mm;
3931 unsigned long address;
3932 pte_t *ptep;
3933 pte_t pte;
3934 spinlock_t *ptl;
3935 struct page *page;
3936 struct hstate *h = hstate_vma(vma);
3937 unsigned long sz = huge_page_size(h);
3938 struct mmu_notifier_range range;
3939 bool force_flush = false;
3940
3941 WARN_ON(!is_vm_hugetlb_page(vma));
3942 BUG_ON(start & ~huge_page_mask(h));
3943 BUG_ON(end & ~huge_page_mask(h));
3944
3945 /*
3946 * This is a hugetlb vma, all the pte entries should point
3947 * to huge page.
3948 */
3949 tlb_change_page_size(tlb, sz);
3950 tlb_start_vma(tlb, vma);
3951
3952 /*
3953 * If sharing possible, alert mmu notifiers of worst case.
3954 */
3955 mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, mm, start,
3956 end);
3957 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
3958 mmu_notifier_invalidate_range_start(&range);
3959 address = start;
3960 for (; address < end; address += sz) {
3961 ptep = huge_pte_offset(mm, address, sz);
3962 if (!ptep)
3963 continue;
3964
3965 ptl = huge_pte_lock(h, mm, ptep);
3966 if (huge_pmd_unshare(mm, vma, &address, ptep)) {
3967 spin_unlock(ptl);
3968 tlb_flush_pmd_range(tlb, address & PUD_MASK, PUD_SIZE);
3969 force_flush = true;
3970 continue;
3971 }
3972
3973 pte = huge_ptep_get(ptep);
3974 if (huge_pte_none(pte)) {
3975 spin_unlock(ptl);
3976 continue;
3977 }
3978
3979 /*
3980 * Migrating hugepage or HWPoisoned hugepage is already
3981 * unmapped and its refcount is dropped, so just clear pte here.
3982 */
3983 if (unlikely(!pte_present(pte))) {
3984 huge_pte_clear(mm, address, ptep, sz);
3985 spin_unlock(ptl);
3986 continue;
3987 }
3988
3989 page = pte_page(pte);
3990 /*
3991 * If a reference page is supplied, it is because a specific
3992 * page is being unmapped, not a range. Ensure the page we
3993 * are about to unmap is the actual page of interest.
3994 */
3995 if (ref_page) {
3996 if (page != ref_page) {
3997 spin_unlock(ptl);
3998 continue;
3999 }
4000 /*
4001 * Mark the VMA as having unmapped its page so that
4002 * future faults in this VMA will fail rather than
4003 * looking like data was lost
4004 */
4005 set_vma_resv_flags(vma, HPAGE_RESV_UNMAPPED);
4006 }
4007
4008 pte = huge_ptep_get_and_clear(mm, address, ptep);
4009 tlb_remove_huge_tlb_entry(h, tlb, ptep, address);
4010 if (huge_pte_dirty(pte))
4011 set_page_dirty(page);
4012
4013 hugetlb_count_sub(pages_per_huge_page(h), mm);
4014 page_remove_rmap(page, true);
4015
4016 spin_unlock(ptl);
4017 tlb_remove_page_size(tlb, page, huge_page_size(h));
4018 /*
4019 * Bail out after unmapping reference page if supplied
4020 */
4021 if (ref_page)
4022 break;
4023 }
4024 mmu_notifier_invalidate_range_end(&range);
4025 tlb_end_vma(tlb, vma);
4026
4027 /*
4028 * If we unshared PMDs, the TLB flush was not recorded in mmu_gather. We
4029 * could defer the flush until now, since by holding i_mmap_rwsem we
4030 * guaranteed that the last refernece would not be dropped. But we must
4031 * do the flushing before we return, as otherwise i_mmap_rwsem will be
4032 * dropped and the last reference to the shared PMDs page might be
4033 * dropped as well.
4034 *
4035 * In theory we could defer the freeing of the PMD pages as well, but
4036 * huge_pmd_unshare() relies on the exact page_count for the PMD page to
4037 * detect sharing, so we cannot defer the release of the page either.
4038 * Instead, do flush now.
4039 */
4040 if (force_flush)
4041 tlb_flush_mmu_tlbonly(tlb);
4042 }
4043
__unmap_hugepage_range_final(struct mmu_gather * tlb,struct vm_area_struct * vma,unsigned long start,unsigned long end,struct page * ref_page)4044 void __unmap_hugepage_range_final(struct mmu_gather *tlb,
4045 struct vm_area_struct *vma, unsigned long start,
4046 unsigned long end, struct page *ref_page)
4047 {
4048 __unmap_hugepage_range(tlb, vma, start, end, ref_page);
4049
4050 /*
4051 * Clear this flag so that x86's huge_pmd_share page_table_shareable
4052 * test will fail on a vma being torn down, and not grab a page table
4053 * on its way out. We're lucky that the flag has such an appropriate
4054 * name, and can in fact be safely cleared here. We could clear it
4055 * before the __unmap_hugepage_range above, but all that's necessary
4056 * is to clear it before releasing the i_mmap_rwsem. This works
4057 * because in the context this is called, the VMA is about to be
4058 * destroyed and the i_mmap_rwsem is held.
4059 */
4060 vma->vm_flags &= ~VM_MAYSHARE;
4061 }
4062
unmap_hugepage_range(struct vm_area_struct * vma,unsigned long start,unsigned long end,struct page * ref_page)4063 void unmap_hugepage_range(struct vm_area_struct *vma, unsigned long start,
4064 unsigned long end, struct page *ref_page)
4065 {
4066 struct mm_struct *mm;
4067 struct mmu_gather tlb;
4068 unsigned long tlb_start = start;
4069 unsigned long tlb_end = end;
4070
4071 /*
4072 * If shared PMDs were possibly used within this vma range, adjust
4073 * start/end for worst case tlb flushing.
4074 * Note that we can not be sure if PMDs are shared until we try to
4075 * unmap pages. However, we want to make sure TLB flushing covers
4076 * the largest possible range.
4077 */
4078 adjust_range_if_pmd_sharing_possible(vma, &tlb_start, &tlb_end);
4079
4080 mm = vma->vm_mm;
4081
4082 tlb_gather_mmu(&tlb, mm, tlb_start, tlb_end);
4083 __unmap_hugepage_range(&tlb, vma, start, end, ref_page);
4084 tlb_finish_mmu(&tlb, tlb_start, tlb_end);
4085 }
4086
4087 /*
4088 * This is called when the original mapper is failing to COW a MAP_PRIVATE
4089 * mappping it owns the reserve page for. The intention is to unmap the page
4090 * from other VMAs and let the children be SIGKILLed if they are faulting the
4091 * same region.
4092 */
unmap_ref_private(struct mm_struct * mm,struct vm_area_struct * vma,struct page * page,unsigned long address)4093 static void unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma,
4094 struct page *page, unsigned long address)
4095 {
4096 struct hstate *h = hstate_vma(vma);
4097 struct vm_area_struct *iter_vma;
4098 struct address_space *mapping;
4099 pgoff_t pgoff;
4100
4101 /*
4102 * vm_pgoff is in PAGE_SIZE units, hence the different calculation
4103 * from page cache lookup which is in HPAGE_SIZE units.
4104 */
4105 address = address & huge_page_mask(h);
4106 pgoff = ((address - vma->vm_start) >> PAGE_SHIFT) +
4107 vma->vm_pgoff;
4108 mapping = vma->vm_file->f_mapping;
4109
4110 /*
4111 * Take the mapping lock for the duration of the table walk. As
4112 * this mapping should be shared between all the VMAs,
4113 * __unmap_hugepage_range() is called as the lock is already held
4114 */
4115 i_mmap_lock_write(mapping);
4116 vma_interval_tree_foreach(iter_vma, &mapping->i_mmap, pgoff, pgoff) {
4117 /* Do not unmap the current VMA */
4118 if (iter_vma == vma)
4119 continue;
4120
4121 /*
4122 * Shared VMAs have their own reserves and do not affect
4123 * MAP_PRIVATE accounting but it is possible that a shared
4124 * VMA is using the same page so check and skip such VMAs.
4125 */
4126 if (iter_vma->vm_flags & VM_MAYSHARE)
4127 continue;
4128
4129 /*
4130 * Unmap the page from other VMAs without their own reserves.
4131 * They get marked to be SIGKILLed if they fault in these
4132 * areas. This is because a future no-page fault on this VMA
4133 * could insert a zeroed page instead of the data existing
4134 * from the time of fork. This would look like data corruption
4135 */
4136 if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER))
4137 unmap_hugepage_range(iter_vma, address,
4138 address + huge_page_size(h), page);
4139 }
4140 i_mmap_unlock_write(mapping);
4141 }
4142
4143 /*
4144 * Hugetlb_cow() should be called with page lock of the original hugepage held.
4145 * Called with hugetlb_instantiation_mutex held and pte_page locked so we
4146 * cannot race with other handlers or page migration.
4147 * Keep the pte_same checks anyway to make transition from the mutex easier.
4148 */
hugetlb_cow(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long address,pte_t * ptep,struct page * pagecache_page,spinlock_t * ptl)4149 static vm_fault_t hugetlb_cow(struct mm_struct *mm, struct vm_area_struct *vma,
4150 unsigned long address, pte_t *ptep,
4151 struct page *pagecache_page, spinlock_t *ptl)
4152 {
4153 pte_t pte;
4154 struct hstate *h = hstate_vma(vma);
4155 struct page *old_page, *new_page;
4156 int outside_reserve = 0;
4157 vm_fault_t ret = 0;
4158 unsigned long haddr = address & huge_page_mask(h);
4159 struct mmu_notifier_range range;
4160
4161 pte = huge_ptep_get(ptep);
4162 old_page = pte_page(pte);
4163
4164 retry_avoidcopy:
4165 /* If no-one else is actually using this page, avoid the copy
4166 * and just make the page writable */
4167 if (page_mapcount(old_page) == 1 && PageAnon(old_page)) {
4168 page_move_anon_rmap(old_page, vma);
4169 set_huge_ptep_writable(vma, haddr, ptep);
4170 return 0;
4171 }
4172
4173 /*
4174 * If the process that created a MAP_PRIVATE mapping is about to
4175 * perform a COW due to a shared page count, attempt to satisfy
4176 * the allocation without using the existing reserves. The pagecache
4177 * page is used to determine if the reserve at this address was
4178 * consumed or not. If reserves were used, a partial faulted mapping
4179 * at the time of fork() could consume its reserves on COW instead
4180 * of the full address range.
4181 */
4182 if (is_vma_resv_set(vma, HPAGE_RESV_OWNER) &&
4183 old_page != pagecache_page)
4184 outside_reserve = 1;
4185
4186 get_page(old_page);
4187
4188 /*
4189 * Drop page table lock as buddy allocator may be called. It will
4190 * be acquired again before returning to the caller, as expected.
4191 */
4192 spin_unlock(ptl);
4193 new_page = alloc_huge_page(vma, haddr, outside_reserve);
4194
4195 if (IS_ERR(new_page)) {
4196 /*
4197 * If a process owning a MAP_PRIVATE mapping fails to COW,
4198 * it is due to references held by a child and an insufficient
4199 * huge page pool. To guarantee the original mappers
4200 * reliability, unmap the page from child processes. The child
4201 * may get SIGKILLed if it later faults.
4202 */
4203 if (outside_reserve) {
4204 struct address_space *mapping = vma->vm_file->f_mapping;
4205 pgoff_t idx;
4206 u32 hash;
4207
4208 put_page(old_page);
4209 BUG_ON(huge_pte_none(pte));
4210 /*
4211 * Drop hugetlb_fault_mutex and i_mmap_rwsem before
4212 * unmapping. unmapping needs to hold i_mmap_rwsem
4213 * in write mode. Dropping i_mmap_rwsem in read mode
4214 * here is OK as COW mappings do not interact with
4215 * PMD sharing.
4216 *
4217 * Reacquire both after unmap operation.
4218 */
4219 idx = vma_hugecache_offset(h, vma, haddr);
4220 hash = hugetlb_fault_mutex_hash(mapping, idx);
4221 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
4222 i_mmap_unlock_read(mapping);
4223
4224 unmap_ref_private(mm, vma, old_page, haddr);
4225
4226 i_mmap_lock_read(mapping);
4227 mutex_lock(&hugetlb_fault_mutex_table[hash]);
4228 spin_lock(ptl);
4229 ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
4230 if (likely(ptep &&
4231 pte_same(huge_ptep_get(ptep), pte)))
4232 goto retry_avoidcopy;
4233 /*
4234 * race occurs while re-acquiring page table
4235 * lock, and our job is done.
4236 */
4237 return 0;
4238 }
4239
4240 ret = vmf_error(PTR_ERR(new_page));
4241 goto out_release_old;
4242 }
4243
4244 /*
4245 * When the original hugepage is shared one, it does not have
4246 * anon_vma prepared.
4247 */
4248 if (unlikely(anon_vma_prepare(vma))) {
4249 ret = VM_FAULT_OOM;
4250 goto out_release_all;
4251 }
4252
4253 copy_user_huge_page(new_page, old_page, address, vma,
4254 pages_per_huge_page(h));
4255 __SetPageUptodate(new_page);
4256
4257 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm, haddr,
4258 haddr + huge_page_size(h));
4259 mmu_notifier_invalidate_range_start(&range);
4260
4261 /*
4262 * Retake the page table lock to check for racing updates
4263 * before the page tables are altered
4264 */
4265 spin_lock(ptl);
4266 ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
4267 if (likely(ptep && pte_same(huge_ptep_get(ptep), pte))) {
4268 ClearPagePrivate(new_page);
4269
4270 /* Break COW */
4271 huge_ptep_clear_flush(vma, haddr, ptep);
4272 mmu_notifier_invalidate_range(mm, range.start, range.end);
4273 set_huge_pte_at(mm, haddr, ptep,
4274 make_huge_pte(vma, new_page, 1));
4275 page_remove_rmap(old_page, true);
4276 hugepage_add_new_anon_rmap(new_page, vma, haddr);
4277 set_page_huge_active(new_page);
4278 /* Make the old page be freed below */
4279 new_page = old_page;
4280 }
4281 spin_unlock(ptl);
4282 mmu_notifier_invalidate_range_end(&range);
4283 out_release_all:
4284 restore_reserve_on_error(h, vma, haddr, new_page);
4285 put_page(new_page);
4286 out_release_old:
4287 put_page(old_page);
4288
4289 spin_lock(ptl); /* Caller expects lock to be held */
4290 return ret;
4291 }
4292
4293 /* Return the pagecache page at a given address within a VMA */
hugetlbfs_pagecache_page(struct hstate * h,struct vm_area_struct * vma,unsigned long address)4294 static struct page *hugetlbfs_pagecache_page(struct hstate *h,
4295 struct vm_area_struct *vma, unsigned long address)
4296 {
4297 struct address_space *mapping;
4298 pgoff_t idx;
4299
4300 mapping = vma->vm_file->f_mapping;
4301 idx = vma_hugecache_offset(h, vma, address);
4302
4303 return find_lock_page(mapping, idx);
4304 }
4305
4306 /*
4307 * Return whether there is a pagecache page to back given address within VMA.
4308 * Caller follow_hugetlb_page() holds page_table_lock so we cannot lock_page.
4309 */
hugetlbfs_pagecache_present(struct hstate * h,struct vm_area_struct * vma,unsigned long address)4310 static bool hugetlbfs_pagecache_present(struct hstate *h,
4311 struct vm_area_struct *vma, unsigned long address)
4312 {
4313 struct address_space *mapping;
4314 pgoff_t idx;
4315 struct page *page;
4316
4317 mapping = vma->vm_file->f_mapping;
4318 idx = vma_hugecache_offset(h, vma, address);
4319
4320 page = find_get_page(mapping, idx);
4321 if (page)
4322 put_page(page);
4323 return page != NULL;
4324 }
4325
huge_add_to_page_cache(struct page * page,struct address_space * mapping,pgoff_t idx)4326 int huge_add_to_page_cache(struct page *page, struct address_space *mapping,
4327 pgoff_t idx)
4328 {
4329 struct inode *inode = mapping->host;
4330 struct hstate *h = hstate_inode(inode);
4331 int err = add_to_page_cache(page, mapping, idx, GFP_KERNEL);
4332
4333 if (err)
4334 return err;
4335 ClearPagePrivate(page);
4336
4337 /*
4338 * set page dirty so that it will not be removed from cache/file
4339 * by non-hugetlbfs specific code paths.
4340 */
4341 set_page_dirty(page);
4342
4343 spin_lock(&inode->i_lock);
4344 inode->i_blocks += blocks_per_huge_page(h);
4345 spin_unlock(&inode->i_lock);
4346 return 0;
4347 }
4348
hugetlb_handle_userfault(struct vm_area_struct * vma,struct address_space * mapping,pgoff_t idx,unsigned int flags,unsigned long haddr,unsigned long reason)4349 static inline vm_fault_t hugetlb_handle_userfault(struct vm_area_struct *vma,
4350 struct address_space *mapping,
4351 pgoff_t idx,
4352 unsigned int flags,
4353 unsigned long haddr,
4354 unsigned long reason)
4355 {
4356 u32 hash = hugetlb_fault_mutex_hash(mapping, idx);
4357 struct vm_fault vmf = {
4358 .vma = vma,
4359 .address = haddr,
4360 .flags = flags,
4361 /*
4362 * Hard to debug if it ends up being
4363 * used by a callee that assumes
4364 * something about the other
4365 * uninitialized fields... same as in
4366 * memory.c
4367 */
4368 };
4369
4370 /*
4371 * vma_lock and hugetlb_fault_mutex must be dropped
4372 * before handling userfault. Also mmap_lock will
4373 * be dropped during handling userfault, any vma
4374 * operation should be careful from here.
4375 */
4376 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
4377 i_mmap_unlock_read(mapping);
4378 return handle_userfault(&vmf, VM_UFFD_MISSING);
4379 }
4380
hugetlb_no_page(struct mm_struct * mm,struct vm_area_struct * vma,struct address_space * mapping,pgoff_t idx,unsigned long address,pte_t * ptep,unsigned int flags)4381 static vm_fault_t hugetlb_no_page(struct mm_struct *mm,
4382 struct vm_area_struct *vma,
4383 struct address_space *mapping, pgoff_t idx,
4384 unsigned long address, pte_t *ptep, unsigned int flags)
4385 {
4386 struct hstate *h = hstate_vma(vma);
4387 vm_fault_t ret = VM_FAULT_SIGBUS;
4388 int anon_rmap = 0;
4389 unsigned long size;
4390 struct page *page;
4391 pte_t new_pte;
4392 spinlock_t *ptl;
4393 unsigned long haddr = address & huge_page_mask(h);
4394 bool new_page = false;
4395 u32 hash = hugetlb_fault_mutex_hash(mapping, idx);
4396
4397 /*
4398 * Currently, we are forced to kill the process in the event the
4399 * original mapper has unmapped pages from the child due to a failed
4400 * COW. Warn that such a situation has occurred as it may not be obvious
4401 */
4402 if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) {
4403 pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n",
4404 current->pid);
4405 goto out;
4406 }
4407
4408 /*
4409 * We can not race with truncation due to holding i_mmap_rwsem.
4410 * i_size is modified when holding i_mmap_rwsem, so check here
4411 * once for faults beyond end of file.
4412 */
4413 size = i_size_read(mapping->host) >> huge_page_shift(h);
4414 if (idx >= size)
4415 goto out;
4416
4417 retry:
4418 page = find_lock_page(mapping, idx);
4419 if (!page) {
4420 /* Check for page in userfault range */
4421 if (userfaultfd_missing(vma)) {
4422 ret = hugetlb_handle_userfault(vma, mapping, idx,
4423 flags, haddr,
4424 VM_UFFD_MISSING);
4425 goto out;
4426 }
4427
4428 page = alloc_huge_page(vma, haddr, 0);
4429 if (IS_ERR(page)) {
4430 /*
4431 * Returning error will result in faulting task being
4432 * sent SIGBUS. The hugetlb fault mutex prevents two
4433 * tasks from racing to fault in the same page which
4434 * could result in false unable to allocate errors.
4435 * Page migration does not take the fault mutex, but
4436 * does a clear then write of pte's under page table
4437 * lock. Page fault code could race with migration,
4438 * notice the clear pte and try to allocate a page
4439 * here. Before returning error, get ptl and make
4440 * sure there really is no pte entry.
4441 */
4442 ptl = huge_pte_lock(h, mm, ptep);
4443 if (!huge_pte_none(huge_ptep_get(ptep))) {
4444 ret = 0;
4445 spin_unlock(ptl);
4446 goto out;
4447 }
4448 spin_unlock(ptl);
4449 ret = vmf_error(PTR_ERR(page));
4450 goto out;
4451 }
4452 clear_huge_page(page, address, pages_per_huge_page(h));
4453 __SetPageUptodate(page);
4454 new_page = true;
4455
4456 if (vma->vm_flags & VM_MAYSHARE) {
4457 int err = huge_add_to_page_cache(page, mapping, idx);
4458 if (err) {
4459 put_page(page);
4460 if (err == -EEXIST)
4461 goto retry;
4462 goto out;
4463 }
4464 } else {
4465 lock_page(page);
4466 if (unlikely(anon_vma_prepare(vma))) {
4467 ret = VM_FAULT_OOM;
4468 goto backout_unlocked;
4469 }
4470 anon_rmap = 1;
4471 }
4472 } else {
4473 /*
4474 * If memory error occurs between mmap() and fault, some process
4475 * don't have hwpoisoned swap entry for errored virtual address.
4476 * So we need to block hugepage fault by PG_hwpoison bit check.
4477 */
4478 if (unlikely(PageHWPoison(page))) {
4479 ret = VM_FAULT_HWPOISON_LARGE |
4480 VM_FAULT_SET_HINDEX(hstate_index(h));
4481 goto backout_unlocked;
4482 }
4483
4484 /* Check for page in userfault range. */
4485 if (userfaultfd_minor(vma)) {
4486 unlock_page(page);
4487 put_page(page);
4488 ret = hugetlb_handle_userfault(vma, mapping, idx,
4489 flags, haddr,
4490 VM_UFFD_MINOR);
4491 goto out;
4492 }
4493 }
4494
4495 /*
4496 * If we are going to COW a private mapping later, we examine the
4497 * pending reservations for this page now. This will ensure that
4498 * any allocations necessary to record that reservation occur outside
4499 * the spinlock.
4500 */
4501 if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
4502 if (vma_needs_reservation(h, vma, haddr) < 0) {
4503 ret = VM_FAULT_OOM;
4504 goto backout_unlocked;
4505 }
4506 /* Just decrements count, does not deallocate */
4507 vma_end_reservation(h, vma, haddr);
4508 }
4509
4510 ptl = huge_pte_lock(h, mm, ptep);
4511 ret = 0;
4512 if (!huge_pte_none(huge_ptep_get(ptep)))
4513 goto backout;
4514
4515 if (anon_rmap) {
4516 ClearPagePrivate(page);
4517 hugepage_add_new_anon_rmap(page, vma, haddr);
4518 } else
4519 page_dup_rmap(page, true);
4520 new_pte = make_huge_pte(vma, page, ((vma->vm_flags & VM_WRITE)
4521 && (vma->vm_flags & VM_SHARED)));
4522 set_huge_pte_at(mm, haddr, ptep, new_pte);
4523
4524 hugetlb_count_add(pages_per_huge_page(h), mm);
4525 if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
4526 /* Optimization, do the COW without a second fault */
4527 ret = hugetlb_cow(mm, vma, address, ptep, page, ptl);
4528 }
4529
4530 spin_unlock(ptl);
4531
4532 /*
4533 * Only make newly allocated pages active. Existing pages found
4534 * in the pagecache could be !page_huge_active() if they have been
4535 * isolated for migration.
4536 */
4537 if (new_page)
4538 set_page_huge_active(page);
4539
4540 unlock_page(page);
4541 out:
4542 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
4543 i_mmap_unlock_read(mapping);
4544 return ret;
4545
4546 backout:
4547 spin_unlock(ptl);
4548 backout_unlocked:
4549 unlock_page(page);
4550 restore_reserve_on_error(h, vma, haddr, page);
4551 put_page(page);
4552 goto out;
4553 }
4554
4555 #ifdef CONFIG_SMP
hugetlb_fault_mutex_hash(struct address_space * mapping,pgoff_t idx)4556 u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
4557 {
4558 unsigned long key[2];
4559 u32 hash;
4560
4561 key[0] = (unsigned long) mapping;
4562 key[1] = idx;
4563
4564 hash = jhash2((u32 *)&key, sizeof(key)/(sizeof(u32)), 0);
4565
4566 return hash & (num_fault_mutexes - 1);
4567 }
4568 #else
4569 /*
4570 * For uniprocesor systems we always use a single mutex, so just
4571 * return 0 and avoid the hashing overhead.
4572 */
hugetlb_fault_mutex_hash(struct address_space * mapping,pgoff_t idx)4573 u32 hugetlb_fault_mutex_hash(struct address_space *mapping, pgoff_t idx)
4574 {
4575 return 0;
4576 }
4577 #endif
4578
hugetlb_fault(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long address,unsigned int flags)4579 vm_fault_t hugetlb_fault(struct mm_struct *mm, struct vm_area_struct *vma,
4580 unsigned long address, unsigned int flags)
4581 {
4582 pte_t *ptep, entry;
4583 spinlock_t *ptl;
4584 vm_fault_t ret;
4585 u32 hash;
4586 pgoff_t idx;
4587 struct page *page = NULL;
4588 struct page *pagecache_page = NULL;
4589 struct hstate *h = hstate_vma(vma);
4590 struct address_space *mapping;
4591 int need_wait_lock = 0;
4592 unsigned long haddr = address & huge_page_mask(h);
4593
4594 ptep = huge_pte_offset(mm, haddr, huge_page_size(h));
4595 if (ptep) {
4596 /*
4597 * Since we hold no locks, ptep could be stale. That is
4598 * OK as we are only making decisions based on content and
4599 * not actually modifying content here.
4600 */
4601 entry = huge_ptep_get(ptep);
4602 if (unlikely(is_hugetlb_entry_migration(entry))) {
4603 migration_entry_wait_huge(vma, mm, ptep);
4604 return 0;
4605 } else if (unlikely(is_hugetlb_entry_hwpoisoned(entry)))
4606 return VM_FAULT_HWPOISON_LARGE |
4607 VM_FAULT_SET_HINDEX(hstate_index(h));
4608 }
4609
4610 /*
4611 * Acquire i_mmap_rwsem before calling huge_pte_alloc and hold
4612 * until finished with ptep. This serves two purposes:
4613 * 1) It prevents huge_pmd_unshare from being called elsewhere
4614 * and making the ptep no longer valid.
4615 * 2) It synchronizes us with i_size modifications during truncation.
4616 *
4617 * ptep could have already be assigned via huge_pte_offset. That
4618 * is OK, as huge_pte_alloc will return the same value unless
4619 * something has changed.
4620 */
4621 mapping = vma->vm_file->f_mapping;
4622 i_mmap_lock_read(mapping);
4623 ptep = huge_pte_alloc(mm, vma, haddr, huge_page_size(h));
4624 if (!ptep) {
4625 i_mmap_unlock_read(mapping);
4626 return VM_FAULT_OOM;
4627 }
4628
4629 /*
4630 * Serialize hugepage allocation and instantiation, so that we don't
4631 * get spurious allocation failures if two CPUs race to instantiate
4632 * the same page in the page cache.
4633 */
4634 idx = vma_hugecache_offset(h, vma, haddr);
4635 hash = hugetlb_fault_mutex_hash(mapping, idx);
4636 mutex_lock(&hugetlb_fault_mutex_table[hash]);
4637
4638 entry = huge_ptep_get(ptep);
4639 if (huge_pte_none(entry))
4640 /*
4641 * hugetlb_no_page will drop vma lock and hugetlb fault
4642 * mutex internally, which make us return immediately.
4643 */
4644 return hugetlb_no_page(mm, vma, mapping, idx, address, ptep, flags);
4645
4646 ret = 0;
4647
4648 /*
4649 * entry could be a migration/hwpoison entry at this point, so this
4650 * check prevents the kernel from going below assuming that we have
4651 * an active hugepage in pagecache. This goto expects the 2nd page
4652 * fault, and is_hugetlb_entry_(migration|hwpoisoned) check will
4653 * properly handle it.
4654 */
4655 if (!pte_present(entry))
4656 goto out_mutex;
4657
4658 /*
4659 * If we are going to COW the mapping later, we examine the pending
4660 * reservations for this page now. This will ensure that any
4661 * allocations necessary to record that reservation occur outside the
4662 * spinlock. For private mappings, we also lookup the pagecache
4663 * page now as it is used to determine if a reservation has been
4664 * consumed.
4665 */
4666 if ((flags & FAULT_FLAG_WRITE) && !huge_pte_write(entry)) {
4667 if (vma_needs_reservation(h, vma, haddr) < 0) {
4668 ret = VM_FAULT_OOM;
4669 goto out_mutex;
4670 }
4671 /* Just decrements count, does not deallocate */
4672 vma_end_reservation(h, vma, haddr);
4673
4674 if (!(vma->vm_flags & VM_MAYSHARE))
4675 pagecache_page = hugetlbfs_pagecache_page(h,
4676 vma, haddr);
4677 }
4678
4679 ptl = huge_pte_lock(h, mm, ptep);
4680
4681 /* Check for a racing update before calling hugetlb_cow */
4682 if (unlikely(!pte_same(entry, huge_ptep_get(ptep))))
4683 goto out_ptl;
4684
4685 /*
4686 * hugetlb_cow() requires page locks of pte_page(entry) and
4687 * pagecache_page, so here we need take the former one
4688 * when page != pagecache_page or !pagecache_page.
4689 */
4690 page = pte_page(entry);
4691 if (page != pagecache_page)
4692 if (!trylock_page(page)) {
4693 need_wait_lock = 1;
4694 goto out_ptl;
4695 }
4696
4697 get_page(page);
4698
4699 if (flags & FAULT_FLAG_WRITE) {
4700 if (!huge_pte_write(entry)) {
4701 ret = hugetlb_cow(mm, vma, address, ptep,
4702 pagecache_page, ptl);
4703 goto out_put_page;
4704 }
4705 entry = huge_pte_mkdirty(entry);
4706 }
4707 entry = pte_mkyoung(entry);
4708 if (huge_ptep_set_access_flags(vma, haddr, ptep, entry,
4709 flags & FAULT_FLAG_WRITE))
4710 update_mmu_cache(vma, haddr, ptep);
4711 out_put_page:
4712 if (page != pagecache_page)
4713 unlock_page(page);
4714 put_page(page);
4715 out_ptl:
4716 spin_unlock(ptl);
4717
4718 if (pagecache_page) {
4719 unlock_page(pagecache_page);
4720 put_page(pagecache_page);
4721 }
4722 out_mutex:
4723 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
4724 i_mmap_unlock_read(mapping);
4725 /*
4726 * Generally it's safe to hold refcount during waiting page lock. But
4727 * here we just wait to defer the next page fault to avoid busy loop and
4728 * the page is not used after unlocked before returning from the current
4729 * page fault. So we are safe from accessing freed page, even if we wait
4730 * here without taking refcount.
4731 */
4732 if (need_wait_lock)
4733 wait_on_page_locked(page);
4734 return ret;
4735 }
4736
4737 #ifdef CONFIG_USERFAULTFD
4738 /*
4739 * Used by userfaultfd UFFDIO_COPY. Based on mcopy_atomic_pte with
4740 * modifications for huge pages.
4741 */
hugetlb_mcopy_atomic_pte(struct mm_struct * dst_mm,pte_t * dst_pte,struct vm_area_struct * dst_vma,unsigned long dst_addr,unsigned long src_addr,enum mcopy_atomic_mode mode,struct page ** pagep)4742 int hugetlb_mcopy_atomic_pte(struct mm_struct *dst_mm,
4743 pte_t *dst_pte,
4744 struct vm_area_struct *dst_vma,
4745 unsigned long dst_addr,
4746 unsigned long src_addr,
4747 enum mcopy_atomic_mode mode,
4748 struct page **pagep)
4749 {
4750 bool is_continue = (mode == MCOPY_ATOMIC_CONTINUE);
4751 struct address_space *mapping;
4752 pgoff_t idx;
4753 unsigned long size;
4754 int vm_shared = dst_vma->vm_flags & VM_SHARED;
4755 struct hstate *h = hstate_vma(dst_vma);
4756 pte_t _dst_pte;
4757 spinlock_t *ptl;
4758 int ret;
4759 struct page *page;
4760 int writable;
4761
4762 mapping = dst_vma->vm_file->f_mapping;
4763 idx = vma_hugecache_offset(h, dst_vma, dst_addr);
4764
4765 if (is_continue) {
4766 ret = -EFAULT;
4767 page = find_lock_page(mapping, idx);
4768 if (!page)
4769 goto out;
4770 } else if (!*pagep) {
4771 /* If a page already exists, then it's UFFDIO_COPY for
4772 * a non-missing case. Return -EEXIST.
4773 */
4774 if (vm_shared &&
4775 hugetlbfs_pagecache_present(h, dst_vma, dst_addr)) {
4776 ret = -EEXIST;
4777 goto out;
4778 }
4779
4780 page = alloc_huge_page(dst_vma, dst_addr, 0);
4781 if (IS_ERR(page)) {
4782 ret = -ENOMEM;
4783 goto out;
4784 }
4785
4786 ret = copy_huge_page_from_user(page,
4787 (const void __user *) src_addr,
4788 pages_per_huge_page(h), false);
4789
4790 /* fallback to copy_from_user outside mmap_lock */
4791 if (unlikely(ret)) {
4792 ret = -ENOENT;
4793 *pagep = page;
4794 /* don't free the page */
4795 goto out;
4796 }
4797 } else {
4798 page = *pagep;
4799 *pagep = NULL;
4800 }
4801
4802 /*
4803 * The memory barrier inside __SetPageUptodate makes sure that
4804 * preceding stores to the page contents become visible before
4805 * the set_pte_at() write.
4806 */
4807 __SetPageUptodate(page);
4808
4809 /* Add shared, newly allocated pages to the page cache. */
4810 if (vm_shared && !is_continue) {
4811 size = i_size_read(mapping->host) >> huge_page_shift(h);
4812 ret = -EFAULT;
4813 if (idx >= size)
4814 goto out_release_nounlock;
4815
4816 /*
4817 * Serialization between remove_inode_hugepages() and
4818 * huge_add_to_page_cache() below happens through the
4819 * hugetlb_fault_mutex_table that here must be hold by
4820 * the caller.
4821 */
4822 ret = huge_add_to_page_cache(page, mapping, idx);
4823 if (ret)
4824 goto out_release_nounlock;
4825 }
4826
4827 ptl = huge_pte_lockptr(h, dst_mm, dst_pte);
4828 spin_lock(ptl);
4829
4830 /*
4831 * Recheck the i_size after holding PT lock to make sure not
4832 * to leave any page mapped (as page_mapped()) beyond the end
4833 * of the i_size (remove_inode_hugepages() is strict about
4834 * enforcing that). If we bail out here, we'll also leave a
4835 * page in the radix tree in the vm_shared case beyond the end
4836 * of the i_size, but remove_inode_hugepages() will take care
4837 * of it as soon as we drop the hugetlb_fault_mutex_table.
4838 */
4839 size = i_size_read(mapping->host) >> huge_page_shift(h);
4840 ret = -EFAULT;
4841 if (idx >= size)
4842 goto out_release_unlock;
4843
4844 ret = -EEXIST;
4845 if (!huge_pte_none(huge_ptep_get(dst_pte)))
4846 goto out_release_unlock;
4847
4848 if (vm_shared) {
4849 page_dup_rmap(page, true);
4850 } else {
4851 ClearPagePrivate(page);
4852 hugepage_add_new_anon_rmap(page, dst_vma, dst_addr);
4853 }
4854
4855 /* For CONTINUE on a non-shared VMA, don't set VM_WRITE for CoW. */
4856 if (is_continue && !vm_shared)
4857 writable = 0;
4858 else
4859 writable = dst_vma->vm_flags & VM_WRITE;
4860
4861 _dst_pte = make_huge_pte(dst_vma, page, writable);
4862 if (writable)
4863 _dst_pte = huge_pte_mkdirty(_dst_pte);
4864 _dst_pte = pte_mkyoung(_dst_pte);
4865
4866 set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
4867
4868 (void)huge_ptep_set_access_flags(dst_vma, dst_addr, dst_pte, _dst_pte,
4869 dst_vma->vm_flags & VM_WRITE);
4870 hugetlb_count_add(pages_per_huge_page(h), dst_mm);
4871
4872 /* No need to invalidate - it was non-present before */
4873 update_mmu_cache(dst_vma, dst_addr, dst_pte);
4874
4875 spin_unlock(ptl);
4876 if (!is_continue)
4877 set_page_huge_active(page);
4878 if (vm_shared || is_continue)
4879 unlock_page(page);
4880 ret = 0;
4881 out:
4882 return ret;
4883 out_release_unlock:
4884 spin_unlock(ptl);
4885 if (vm_shared || is_continue)
4886 unlock_page(page);
4887 out_release_nounlock:
4888 put_page(page);
4889 goto out;
4890 }
4891 #endif /* CONFIG_USERFAULTFD */
4892
follow_hugetlb_page(struct mm_struct * mm,struct vm_area_struct * vma,struct page ** pages,struct vm_area_struct ** vmas,unsigned long * position,unsigned long * nr_pages,long i,unsigned int flags,int * locked)4893 long follow_hugetlb_page(struct mm_struct *mm, struct vm_area_struct *vma,
4894 struct page **pages, struct vm_area_struct **vmas,
4895 unsigned long *position, unsigned long *nr_pages,
4896 long i, unsigned int flags, int *locked)
4897 {
4898 unsigned long pfn_offset;
4899 unsigned long vaddr = *position;
4900 unsigned long remainder = *nr_pages;
4901 struct hstate *h = hstate_vma(vma);
4902 int err = -EFAULT;
4903
4904 while (vaddr < vma->vm_end && remainder) {
4905 pte_t *pte;
4906 spinlock_t *ptl = NULL;
4907 int absent;
4908 struct page *page;
4909
4910 /*
4911 * If we have a pending SIGKILL, don't keep faulting pages and
4912 * potentially allocating memory.
4913 */
4914 if (fatal_signal_pending(current)) {
4915 remainder = 0;
4916 break;
4917 }
4918
4919 /*
4920 * Some archs (sparc64, sh*) have multiple pte_ts to
4921 * each hugepage. We have to make sure we get the
4922 * first, for the page indexing below to work.
4923 *
4924 * Note that page table lock is not held when pte is null.
4925 */
4926 pte = huge_pte_offset(mm, vaddr & huge_page_mask(h),
4927 huge_page_size(h));
4928 if (pte)
4929 ptl = huge_pte_lock(h, mm, pte);
4930 absent = !pte || huge_pte_none(huge_ptep_get(pte));
4931
4932 /*
4933 * When coredumping, it suits get_dump_page if we just return
4934 * an error where there's an empty slot with no huge pagecache
4935 * to back it. This way, we avoid allocating a hugepage, and
4936 * the sparse dumpfile avoids allocating disk blocks, but its
4937 * huge holes still show up with zeroes where they need to be.
4938 */
4939 if (absent && (flags & FOLL_DUMP) &&
4940 !hugetlbfs_pagecache_present(h, vma, vaddr)) {
4941 if (pte)
4942 spin_unlock(ptl);
4943 remainder = 0;
4944 break;
4945 }
4946
4947 /*
4948 * We need call hugetlb_fault for both hugepages under migration
4949 * (in which case hugetlb_fault waits for the migration,) and
4950 * hwpoisoned hugepages (in which case we need to prevent the
4951 * caller from accessing to them.) In order to do this, we use
4952 * here is_swap_pte instead of is_hugetlb_entry_migration and
4953 * is_hugetlb_entry_hwpoisoned. This is because it simply covers
4954 * both cases, and because we can't follow correct pages
4955 * directly from any kind of swap entries.
4956 */
4957 if (absent || is_swap_pte(huge_ptep_get(pte)) ||
4958 ((flags & FOLL_WRITE) &&
4959 !huge_pte_write(huge_ptep_get(pte)))) {
4960 vm_fault_t ret;
4961 unsigned int fault_flags = 0;
4962
4963 if (pte)
4964 spin_unlock(ptl);
4965 if (flags & FOLL_WRITE)
4966 fault_flags |= FAULT_FLAG_WRITE;
4967 if (locked)
4968 fault_flags |= FAULT_FLAG_ALLOW_RETRY |
4969 FAULT_FLAG_KILLABLE;
4970 if (flags & FOLL_NOWAIT)
4971 fault_flags |= FAULT_FLAG_ALLOW_RETRY |
4972 FAULT_FLAG_RETRY_NOWAIT;
4973 if (flags & FOLL_TRIED) {
4974 /*
4975 * Note: FAULT_FLAG_ALLOW_RETRY and
4976 * FAULT_FLAG_TRIED can co-exist
4977 */
4978 fault_flags |= FAULT_FLAG_TRIED;
4979 }
4980 ret = hugetlb_fault(mm, vma, vaddr, fault_flags);
4981 if (ret & VM_FAULT_ERROR) {
4982 err = vm_fault_to_errno(ret, flags);
4983 remainder = 0;
4984 break;
4985 }
4986 if (ret & VM_FAULT_RETRY) {
4987 if (locked &&
4988 !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
4989 *locked = 0;
4990 *nr_pages = 0;
4991 /*
4992 * VM_FAULT_RETRY must not return an
4993 * error, it will return zero
4994 * instead.
4995 *
4996 * No need to update "position" as the
4997 * caller will not check it after
4998 * *nr_pages is set to 0.
4999 */
5000 return i;
5001 }
5002 continue;
5003 }
5004
5005 pfn_offset = (vaddr & ~huge_page_mask(h)) >> PAGE_SHIFT;
5006 page = pte_page(huge_ptep_get(pte));
5007
5008 /*
5009 * If subpage information not requested, update counters
5010 * and skip the same_page loop below.
5011 */
5012 if (!pages && !vmas && !pfn_offset &&
5013 (vaddr + huge_page_size(h) < vma->vm_end) &&
5014 (remainder >= pages_per_huge_page(h))) {
5015 vaddr += huge_page_size(h);
5016 remainder -= pages_per_huge_page(h);
5017 i += pages_per_huge_page(h);
5018 spin_unlock(ptl);
5019 continue;
5020 }
5021
5022 same_page:
5023 if (pages) {
5024 pages[i] = mem_map_offset(page, pfn_offset);
5025 /*
5026 * try_grab_page() should always succeed here, because:
5027 * a) we hold the ptl lock, and b) we've just checked
5028 * that the huge page is present in the page tables. If
5029 * the huge page is present, then the tail pages must
5030 * also be present. The ptl prevents the head page and
5031 * tail pages from being rearranged in any way. So this
5032 * page must be available at this point, unless the page
5033 * refcount overflowed:
5034 */
5035 if (WARN_ON_ONCE(!try_grab_page(pages[i], flags))) {
5036 spin_unlock(ptl);
5037 remainder = 0;
5038 err = -ENOMEM;
5039 break;
5040 }
5041 }
5042
5043 if (vmas)
5044 vmas[i] = vma;
5045
5046 vaddr += PAGE_SIZE;
5047 ++pfn_offset;
5048 --remainder;
5049 ++i;
5050 if (vaddr < vma->vm_end && remainder &&
5051 pfn_offset < pages_per_huge_page(h)) {
5052 /*
5053 * We use pfn_offset to avoid touching the pageframes
5054 * of this compound page.
5055 */
5056 goto same_page;
5057 }
5058 spin_unlock(ptl);
5059 }
5060 *nr_pages = remainder;
5061 /*
5062 * setting position is actually required only if remainder is
5063 * not zero but it's faster not to add a "if (remainder)"
5064 * branch.
5065 */
5066 *position = vaddr;
5067
5068 return i ? i : err;
5069 }
5070
hugetlb_change_protection(struct vm_area_struct * vma,unsigned long address,unsigned long end,pgprot_t newprot)5071 unsigned long hugetlb_change_protection(struct vm_area_struct *vma,
5072 unsigned long address, unsigned long end, pgprot_t newprot)
5073 {
5074 struct mm_struct *mm = vma->vm_mm;
5075 unsigned long start = address;
5076 pte_t *ptep;
5077 pte_t pte;
5078 struct hstate *h = hstate_vma(vma);
5079 unsigned long pages = 0;
5080 bool shared_pmd = false;
5081 struct mmu_notifier_range range;
5082
5083 /*
5084 * In the case of shared PMDs, the area to flush could be beyond
5085 * start/end. Set range.start/range.end to cover the maximum possible
5086 * range if PMD sharing is possible.
5087 */
5088 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_VMA,
5089 0, vma, mm, start, end);
5090 adjust_range_if_pmd_sharing_possible(vma, &range.start, &range.end);
5091
5092 BUG_ON(address >= end);
5093 flush_cache_range(vma, range.start, range.end);
5094
5095 mmu_notifier_invalidate_range_start(&range);
5096 i_mmap_lock_write(vma->vm_file->f_mapping);
5097 for (; address < end; address += huge_page_size(h)) {
5098 spinlock_t *ptl;
5099 ptep = huge_pte_offset(mm, address, huge_page_size(h));
5100 if (!ptep)
5101 continue;
5102 ptl = huge_pte_lock(h, mm, ptep);
5103 if (huge_pmd_unshare(mm, vma, &address, ptep)) {
5104 pages++;
5105 spin_unlock(ptl);
5106 shared_pmd = true;
5107 continue;
5108 }
5109 pte = huge_ptep_get(ptep);
5110 if (unlikely(is_hugetlb_entry_hwpoisoned(pte))) {
5111 spin_unlock(ptl);
5112 continue;
5113 }
5114 if (unlikely(is_hugetlb_entry_migration(pte))) {
5115 swp_entry_t entry = pte_to_swp_entry(pte);
5116
5117 if (is_write_migration_entry(entry)) {
5118 pte_t newpte;
5119
5120 make_migration_entry_read(&entry);
5121 newpte = swp_entry_to_pte(entry);
5122 set_huge_swap_pte_at(mm, address, ptep,
5123 newpte, huge_page_size(h));
5124 pages++;
5125 }
5126 spin_unlock(ptl);
5127 continue;
5128 }
5129 if (!huge_pte_none(pte)) {
5130 pte_t old_pte;
5131
5132 old_pte = huge_ptep_modify_prot_start(vma, address, ptep);
5133 pte = pte_mkhuge(huge_pte_modify(old_pte, newprot));
5134 pte = arch_make_huge_pte(pte, vma, NULL, 0);
5135 huge_ptep_modify_prot_commit(vma, address, ptep, old_pte, pte);
5136 pages++;
5137 }
5138 spin_unlock(ptl);
5139 }
5140 /*
5141 * Must flush TLB before releasing i_mmap_rwsem: x86's huge_pmd_unshare
5142 * may have cleared our pud entry and done put_page on the page table:
5143 * once we release i_mmap_rwsem, another task can do the final put_page
5144 * and that page table be reused and filled with junk. If we actually
5145 * did unshare a page of pmds, flush the range corresponding to the pud.
5146 */
5147 if (shared_pmd)
5148 flush_hugetlb_tlb_range(vma, range.start, range.end);
5149 else
5150 flush_hugetlb_tlb_range(vma, start, end);
5151 /*
5152 * No need to call mmu_notifier_invalidate_range() we are downgrading
5153 * page table protection not changing it to point to a new page.
5154 *
5155 * See Documentation/vm/mmu_notifier.rst
5156 */
5157 i_mmap_unlock_write(vma->vm_file->f_mapping);
5158 mmu_notifier_invalidate_range_end(&range);
5159
5160 return pages << h->order;
5161 }
5162
5163 /* 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)5164 bool hugetlb_reserve_pages(struct inode *inode,
5165 long from, long to,
5166 struct vm_area_struct *vma,
5167 vm_flags_t vm_flags)
5168 {
5169 long chg, add = -1;
5170 struct hstate *h = hstate_inode(inode);
5171 struct hugepage_subpool *spool = subpool_inode(inode);
5172 struct resv_map *resv_map;
5173 struct hugetlb_cgroup *h_cg = NULL;
5174 long gbl_reserve, regions_needed = 0;
5175
5176 /* This should never happen */
5177 if (from > to) {
5178 VM_WARN(1, "%s called with a negative range\n", __func__);
5179 return false;
5180 }
5181
5182 /*
5183 * Only apply hugepage reservation if asked. At fault time, an
5184 * attempt will be made for VM_NORESERVE to allocate a page
5185 * without using reserves
5186 */
5187 if (vm_flags & VM_NORESERVE)
5188 return true;
5189
5190 /*
5191 * Shared mappings base their reservation on the number of pages that
5192 * are already allocated on behalf of the file. Private mappings need
5193 * to reserve the full area even if read-only as mprotect() may be
5194 * called to make the mapping read-write. Assume !vma is a shm mapping
5195 */
5196 if (!vma || vma->vm_flags & VM_MAYSHARE) {
5197 /*
5198 * resv_map can not be NULL as hugetlb_reserve_pages is only
5199 * called for inodes for which resv_maps were created (see
5200 * hugetlbfs_get_inode).
5201 */
5202 resv_map = inode_resv_map(inode);
5203
5204 chg = region_chg(resv_map, from, to, ®ions_needed);
5205
5206 } else {
5207 /* Private mapping. */
5208 resv_map = resv_map_alloc();
5209 if (!resv_map)
5210 return false;
5211
5212 chg = to - from;
5213
5214 set_vma_resv_map(vma, resv_map);
5215 set_vma_resv_flags(vma, HPAGE_RESV_OWNER);
5216 }
5217
5218 if (chg < 0)
5219 goto out_err;
5220
5221 if (hugetlb_cgroup_charge_cgroup_rsvd(hstate_index(h),
5222 chg * pages_per_huge_page(h), &h_cg) < 0)
5223 goto out_err;
5224
5225 if (vma && !(vma->vm_flags & VM_MAYSHARE) && h_cg) {
5226 /* For private mappings, the hugetlb_cgroup uncharge info hangs
5227 * of the resv_map.
5228 */
5229 resv_map_set_hugetlb_cgroup_uncharge_info(resv_map, h_cg, h);
5230 }
5231
5232 /*
5233 * There must be enough pages in the subpool for the mapping. If
5234 * the subpool has a minimum size, there may be some global
5235 * reservations already in place (gbl_reserve).
5236 */
5237 gbl_reserve = hugepage_subpool_get_pages(spool, chg);
5238 if (gbl_reserve < 0)
5239 goto out_uncharge_cgroup;
5240
5241 /*
5242 * Check enough hugepages are available for the reservation.
5243 * Hand the pages back to the subpool if there are not
5244 */
5245 if (hugetlb_acct_memory(h, gbl_reserve) < 0)
5246 goto out_put_pages;
5247
5248 /*
5249 * Account for the reservations made. Shared mappings record regions
5250 * that have reservations as they are shared by multiple VMAs.
5251 * When the last VMA disappears, the region map says how much
5252 * the reservation was and the page cache tells how much of
5253 * the reservation was consumed. Private mappings are per-VMA and
5254 * only the consumed reservations are tracked. When the VMA
5255 * disappears, the original reservation is the VMA size and the
5256 * consumed reservations are stored in the map. Hence, nothing
5257 * else has to be done for private mappings here
5258 */
5259 if (!vma || vma->vm_flags & VM_MAYSHARE) {
5260 add = region_add(resv_map, from, to, regions_needed, h, h_cg);
5261
5262 if (unlikely(add < 0)) {
5263 hugetlb_acct_memory(h, -gbl_reserve);
5264 goto out_put_pages;
5265 } else if (unlikely(chg > add)) {
5266 /*
5267 * pages in this range were added to the reserve
5268 * map between region_chg and region_add. This
5269 * indicates a race with alloc_huge_page. Adjust
5270 * the subpool and reserve counts modified above
5271 * based on the difference.
5272 */
5273 long rsv_adjust;
5274
5275 /*
5276 * hugetlb_cgroup_uncharge_cgroup_rsvd() will put the
5277 * reference to h_cg->css. See comment below for detail.
5278 */
5279 hugetlb_cgroup_uncharge_cgroup_rsvd(
5280 hstate_index(h),
5281 (chg - add) * pages_per_huge_page(h), h_cg);
5282
5283 rsv_adjust = hugepage_subpool_put_pages(spool,
5284 chg - add);
5285 hugetlb_acct_memory(h, -rsv_adjust);
5286 } else if (h_cg) {
5287 /*
5288 * The file_regions will hold their own reference to
5289 * h_cg->css. So we should release the reference held
5290 * via hugetlb_cgroup_charge_cgroup_rsvd() when we are
5291 * done.
5292 */
5293 hugetlb_cgroup_put_rsvd_cgroup(h_cg);
5294 }
5295 }
5296 return true;
5297
5298 out_put_pages:
5299 /* put back original number of pages, chg */
5300 (void)hugepage_subpool_put_pages(spool, chg);
5301 out_uncharge_cgroup:
5302 hugetlb_cgroup_uncharge_cgroup_rsvd(hstate_index(h),
5303 chg * pages_per_huge_page(h), h_cg);
5304 out_err:
5305 if (!vma || vma->vm_flags & VM_MAYSHARE)
5306 /* Only call region_abort if the region_chg succeeded but the
5307 * region_add failed or didn't run.
5308 */
5309 if (chg >= 0 && add < 0)
5310 region_abort(resv_map, from, to, regions_needed);
5311 if (vma && is_vma_resv_set(vma, HPAGE_RESV_OWNER))
5312 kref_put(&resv_map->refs, resv_map_release);
5313 return false;
5314 }
5315
hugetlb_unreserve_pages(struct inode * inode,long start,long end,long freed)5316 long hugetlb_unreserve_pages(struct inode *inode, long start, long end,
5317 long freed)
5318 {
5319 struct hstate *h = hstate_inode(inode);
5320 struct resv_map *resv_map = inode_resv_map(inode);
5321 long chg = 0;
5322 struct hugepage_subpool *spool = subpool_inode(inode);
5323 long gbl_reserve;
5324
5325 /*
5326 * Since this routine can be called in the evict inode path for all
5327 * hugetlbfs inodes, resv_map could be NULL.
5328 */
5329 if (resv_map) {
5330 chg = region_del(resv_map, start, end);
5331 /*
5332 * region_del() can fail in the rare case where a region
5333 * must be split and another region descriptor can not be
5334 * allocated. If end == LONG_MAX, it will not fail.
5335 */
5336 if (chg < 0)
5337 return chg;
5338 }
5339
5340 spin_lock(&inode->i_lock);
5341 inode->i_blocks -= (blocks_per_huge_page(h) * freed);
5342 spin_unlock(&inode->i_lock);
5343
5344 /*
5345 * If the subpool has a minimum size, the number of global
5346 * reservations to be released may be adjusted.
5347 */
5348 gbl_reserve = hugepage_subpool_put_pages(spool, (chg - freed));
5349 hugetlb_acct_memory(h, -gbl_reserve);
5350
5351 return 0;
5352 }
5353
5354 #ifdef CONFIG_ARCH_WANT_HUGE_PMD_SHARE
page_table_shareable(struct vm_area_struct * svma,struct vm_area_struct * vma,unsigned long addr,pgoff_t idx)5355 static unsigned long page_table_shareable(struct vm_area_struct *svma,
5356 struct vm_area_struct *vma,
5357 unsigned long addr, pgoff_t idx)
5358 {
5359 unsigned long saddr = ((idx - svma->vm_pgoff) << PAGE_SHIFT) +
5360 svma->vm_start;
5361 unsigned long sbase = saddr & PUD_MASK;
5362 unsigned long s_end = sbase + PUD_SIZE;
5363
5364 /* Allow segments to share if only one is marked locked */
5365 unsigned long vm_flags = vma->vm_flags & VM_LOCKED_CLEAR_MASK;
5366 unsigned long svm_flags = svma->vm_flags & VM_LOCKED_CLEAR_MASK;
5367
5368 /*
5369 * match the virtual addresses, permission and the alignment of the
5370 * page table page.
5371 */
5372 if (pmd_index(addr) != pmd_index(saddr) ||
5373 vm_flags != svm_flags ||
5374 sbase < svma->vm_start || svma->vm_end < s_end)
5375 return 0;
5376
5377 return saddr;
5378 }
5379
vma_shareable(struct vm_area_struct * vma,unsigned long addr)5380 static bool vma_shareable(struct vm_area_struct *vma, unsigned long addr)
5381 {
5382 unsigned long base = addr & PUD_MASK;
5383 unsigned long end = base + PUD_SIZE;
5384
5385 /*
5386 * check on proper vm_flags and page table alignment
5387 */
5388 if (vma->vm_flags & VM_MAYSHARE && range_in_vma(vma, base, end))
5389 return true;
5390 return false;
5391 }
5392
want_pmd_share(struct vm_area_struct * vma,unsigned long addr)5393 bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
5394 {
5395 #ifdef CONFIG_USERFAULTFD
5396 if (uffd_disable_huge_pmd_share(vma))
5397 return false;
5398 #endif
5399 return vma_shareable(vma, addr);
5400 }
5401
5402 /*
5403 * Determine if start,end range within vma could be mapped by shared pmd.
5404 * If yes, adjust start and end to cover range associated with possible
5405 * shared pmd mappings.
5406 */
adjust_range_if_pmd_sharing_possible(struct vm_area_struct * vma,unsigned long * start,unsigned long * end)5407 void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
5408 unsigned long *start, unsigned long *end)
5409 {
5410 unsigned long v_start = ALIGN(vma->vm_start, PUD_SIZE),
5411 v_end = ALIGN_DOWN(vma->vm_end, PUD_SIZE);
5412
5413 /*
5414 * vma need span at least one aligned PUD size and the start,end range
5415 * must at least partialy within it.
5416 */
5417 if (!(vma->vm_flags & VM_MAYSHARE) || !(v_end > v_start) ||
5418 (*end <= v_start) || (*start >= v_end))
5419 return;
5420
5421 /* Extend the range to be PUD aligned for a worst case scenario */
5422 if (*start > v_start)
5423 *start = ALIGN_DOWN(*start, PUD_SIZE);
5424
5425 if (*end < v_end)
5426 *end = ALIGN(*end, PUD_SIZE);
5427 }
5428
5429 /*
5430 * Search for a shareable pmd page for hugetlb. In any case calls pmd_alloc()
5431 * and returns the corresponding pte. While this is not necessary for the
5432 * !shared pmd case because we can allocate the pmd later as well, it makes the
5433 * code much cleaner.
5434 *
5435 * This routine must be called with i_mmap_rwsem held in at least read mode if
5436 * sharing is possible. For hugetlbfs, this prevents removal of any page
5437 * table entries associated with the address space. This is important as we
5438 * are setting up sharing based on existing page table entries (mappings).
5439 *
5440 * NOTE: This routine is only called from huge_pte_alloc. Some callers of
5441 * huge_pte_alloc know that sharing is not possible and do not take
5442 * i_mmap_rwsem as a performance optimization. This is handled by the
5443 * if !vma_shareable check at the beginning of the routine. i_mmap_rwsem is
5444 * only required for subsequent processing.
5445 */
huge_pmd_share(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long addr,pud_t * pud)5446 pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
5447 unsigned long addr, pud_t *pud)
5448 {
5449 struct address_space *mapping = vma->vm_file->f_mapping;
5450 pgoff_t idx = ((addr - vma->vm_start) >> PAGE_SHIFT) +
5451 vma->vm_pgoff;
5452 struct vm_area_struct *svma;
5453 unsigned long saddr;
5454 pte_t *spte = NULL;
5455 pte_t *pte;
5456 spinlock_t *ptl;
5457
5458 i_mmap_assert_locked(mapping);
5459 vma_interval_tree_foreach(svma, &mapping->i_mmap, idx, idx) {
5460 if (svma == vma)
5461 continue;
5462
5463 saddr = page_table_shareable(svma, vma, addr, idx);
5464 if (saddr) {
5465 spte = huge_pte_offset(svma->vm_mm, saddr,
5466 vma_mmu_pagesize(svma));
5467 if (spte) {
5468 get_page(virt_to_page(spte));
5469 break;
5470 }
5471 }
5472 }
5473
5474 if (!spte)
5475 goto out;
5476
5477 ptl = huge_pte_lock(hstate_vma(vma), mm, spte);
5478 if (pud_none(*pud)) {
5479 pud_populate(mm, pud,
5480 (pmd_t *)((unsigned long)spte & PAGE_MASK));
5481 mm_inc_nr_pmds(mm);
5482 } else {
5483 put_page(virt_to_page(spte));
5484 }
5485 spin_unlock(ptl);
5486 out:
5487 pte = (pte_t *)pmd_alloc(mm, pud, addr);
5488 return pte;
5489 }
5490
5491 /*
5492 * unmap huge page backed by shared pte.
5493 *
5494 * Hugetlb pte page is ref counted at the time of mapping. If pte is shared
5495 * indicated by page_count > 1, unmap is achieved by clearing pud and
5496 * decrementing the ref count. If count == 1, the pte page is not shared.
5497 *
5498 * Called with page table lock held and i_mmap_rwsem held in write mode.
5499 *
5500 * returns: 1 successfully unmapped a shared pte page
5501 * 0 the underlying pte page is not shared, or it is the last user
5502 */
huge_pmd_unshare(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long * addr,pte_t * ptep)5503 int huge_pmd_unshare(struct mm_struct *mm, struct vm_area_struct *vma,
5504 unsigned long *addr, pte_t *ptep)
5505 {
5506 pgd_t *pgd = pgd_offset(mm, *addr);
5507 p4d_t *p4d = p4d_offset(pgd, *addr);
5508 pud_t *pud = pud_offset(p4d, *addr);
5509
5510 i_mmap_assert_write_locked(vma->vm_file->f_mapping);
5511 BUG_ON(page_count(virt_to_page(ptep)) == 0);
5512 if (page_count(virt_to_page(ptep)) == 1)
5513 return 0;
5514
5515 pud_clear(pud);
5516 put_page(virt_to_page(ptep));
5517 mm_dec_nr_pmds(mm);
5518 /*
5519 * This update of passed address optimizes loops sequentially
5520 * processing addresses in increments of huge page size (PMD_SIZE
5521 * in this case). By clearing the pud, a PUD_SIZE area is unmapped.
5522 * Update address to the 'last page' in the cleared area so that
5523 * calling loop can move to first page past this area.
5524 */
5525 *addr |= PUD_SIZE - PMD_SIZE;
5526 return 1;
5527 }
5528
5529 #else /* !CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
huge_pmd_share(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long addr,pud_t * pud)5530 pte_t *huge_pmd_share(struct mm_struct *mm, struct vm_area_struct *vma,
5531 unsigned long addr, pud_t *pud)
5532 {
5533 return NULL;
5534 }
5535
huge_pmd_unshare(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long * addr,pte_t * ptep)5536 int huge_pmd_unshare(struct mm_struct *mm, struct vm_area_struct *vma,
5537 unsigned long *addr, pte_t *ptep)
5538 {
5539 return 0;
5540 }
5541
adjust_range_if_pmd_sharing_possible(struct vm_area_struct * vma,unsigned long * start,unsigned long * end)5542 void adjust_range_if_pmd_sharing_possible(struct vm_area_struct *vma,
5543 unsigned long *start, unsigned long *end)
5544 {
5545 }
5546
want_pmd_share(struct vm_area_struct * vma,unsigned long addr)5547 bool want_pmd_share(struct vm_area_struct *vma, unsigned long addr)
5548 {
5549 return false;
5550 }
5551 #endif /* CONFIG_ARCH_WANT_HUGE_PMD_SHARE */
5552
5553 #ifdef CONFIG_ARCH_WANT_GENERAL_HUGETLB
huge_pte_alloc(struct mm_struct * mm,struct vm_area_struct * vma,unsigned long addr,unsigned long sz)5554 pte_t *huge_pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma,
5555 unsigned long addr, unsigned long sz)
5556 {
5557 pgd_t *pgd;
5558 p4d_t *p4d;
5559 pud_t *pud;
5560 pte_t *pte = NULL;
5561
5562 pgd = pgd_offset(mm, addr);
5563 p4d = p4d_alloc(mm, pgd, addr);
5564 if (!p4d)
5565 return NULL;
5566 pud = pud_alloc(mm, p4d, addr);
5567 if (pud) {
5568 if (sz == PUD_SIZE) {
5569 pte = (pte_t *)pud;
5570 } else {
5571 BUG_ON(sz != PMD_SIZE);
5572 if (want_pmd_share(vma, addr) && pud_none(*pud))
5573 pte = huge_pmd_share(mm, vma, addr, pud);
5574 else
5575 pte = (pte_t *)pmd_alloc(mm, pud, addr);
5576 }
5577 }
5578 BUG_ON(pte && pte_present(*pte) && !pte_huge(*pte));
5579
5580 return pte;
5581 }
5582
5583 /*
5584 * huge_pte_offset() - Walk the page table to resolve the hugepage
5585 * entry at address @addr
5586 *
5587 * Return: Pointer to page table entry (PUD or PMD) for
5588 * address @addr, or NULL if a !p*d_present() entry is encountered and the
5589 * size @sz doesn't match the hugepage size at this level of the page
5590 * table.
5591 */
huge_pte_offset(struct mm_struct * mm,unsigned long addr,unsigned long sz)5592 pte_t *huge_pte_offset(struct mm_struct *mm,
5593 unsigned long addr, unsigned long sz)
5594 {
5595 pgd_t *pgd;
5596 p4d_t *p4d;
5597 pud_t *pud;
5598 pmd_t *pmd;
5599
5600 pgd = pgd_offset(mm, addr);
5601 if (!pgd_present(*pgd))
5602 return NULL;
5603 p4d = p4d_offset(pgd, addr);
5604 if (!p4d_present(*p4d))
5605 return NULL;
5606
5607 pud = pud_offset(p4d, addr);
5608 if (sz == PUD_SIZE)
5609 /* must be pud huge, non-present or none */
5610 return (pte_t *)pud;
5611 if (!pud_present(*pud))
5612 return NULL;
5613 /* must have a valid entry and size to go further */
5614
5615 pmd = pmd_offset(pud, addr);
5616 /* must be pmd huge, non-present or none */
5617 return (pte_t *)pmd;
5618 }
5619
5620 #endif /* CONFIG_ARCH_WANT_GENERAL_HUGETLB */
5621
5622 /*
5623 * These functions are overwritable if your architecture needs its own
5624 * behavior.
5625 */
5626 struct page * __weak
follow_huge_addr(struct mm_struct * mm,unsigned long address,int write)5627 follow_huge_addr(struct mm_struct *mm, unsigned long address,
5628 int write)
5629 {
5630 return ERR_PTR(-EINVAL);
5631 }
5632
5633 struct page * __weak
follow_huge_pd(struct vm_area_struct * vma,unsigned long address,hugepd_t hpd,int flags,int pdshift)5634 follow_huge_pd(struct vm_area_struct *vma,
5635 unsigned long address, hugepd_t hpd, int flags, int pdshift)
5636 {
5637 WARN(1, "hugepd follow called with no support for hugepage directory format\n");
5638 return NULL;
5639 }
5640
5641 struct page * __weak
follow_huge_pmd_pte(struct vm_area_struct * vma,unsigned long address,int flags)5642 follow_huge_pmd_pte(struct vm_area_struct *vma, unsigned long address, int flags)
5643 {
5644 struct hstate *h = hstate_vma(vma);
5645 struct mm_struct *mm = vma->vm_mm;
5646 struct page *page = NULL;
5647 spinlock_t *ptl;
5648 pte_t *ptep, pte;
5649
5650 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
5651 if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
5652 (FOLL_PIN | FOLL_GET)))
5653 return NULL;
5654
5655 retry:
5656 ptep = huge_pte_offset(mm, address, huge_page_size(h));
5657 if (!ptep)
5658 return NULL;
5659
5660 ptl = huge_pte_lock(h, mm, ptep);
5661 pte = huge_ptep_get(ptep);
5662 if (pte_present(pte)) {
5663 page = pte_page(pte) +
5664 ((address & ~huge_page_mask(h)) >> PAGE_SHIFT);
5665 /*
5666 * try_grab_page() should always succeed here, because: a) we
5667 * hold the pmd (ptl) lock, and b) we've just checked that the
5668 * huge pmd (head) page is present in the page tables. The ptl
5669 * prevents the head page and tail pages from being rearranged
5670 * in any way. So this page must be available at this point,
5671 * unless the page refcount overflowed:
5672 */
5673 if (WARN_ON_ONCE(!try_grab_page(page, flags))) {
5674 page = NULL;
5675 goto out;
5676 }
5677 } else {
5678 if (is_hugetlb_entry_migration(pte)) {
5679 spin_unlock(ptl);
5680 __migration_entry_wait(mm, ptep, ptl);
5681 goto retry;
5682 }
5683 /*
5684 * hwpoisoned entry is treated as no_page_table in
5685 * follow_page_mask().
5686 */
5687 }
5688 out:
5689 spin_unlock(ptl);
5690 return page;
5691 }
5692
5693 struct page * __weak
follow_huge_pud(struct mm_struct * mm,unsigned long address,pud_t * pud,int flags)5694 follow_huge_pud(struct mm_struct *mm, unsigned long address,
5695 pud_t *pud, int flags)
5696 {
5697 if (flags & (FOLL_GET | FOLL_PIN))
5698 return NULL;
5699
5700 return pte_page(*(pte_t *)pud) + ((address & ~PUD_MASK) >> PAGE_SHIFT);
5701 }
5702
5703 struct page * __weak
follow_huge_pgd(struct mm_struct * mm,unsigned long address,pgd_t * pgd,int flags)5704 follow_huge_pgd(struct mm_struct *mm, unsigned long address, pgd_t *pgd, int flags)
5705 {
5706 if (flags & (FOLL_GET | FOLL_PIN))
5707 return NULL;
5708
5709 return pte_page(*(pte_t *)pgd) + ((address & ~PGDIR_MASK) >> PAGE_SHIFT);
5710 }
5711
isolate_hugetlb(struct page * page,struct list_head * list)5712 int isolate_hugetlb(struct page *page, struct list_head *list)
5713 {
5714 int ret = 0;
5715
5716 spin_lock(&hugetlb_lock);
5717 if (!PageHeadHuge(page) || !page_huge_active(page) ||
5718 !get_page_unless_zero(page)) {
5719 ret = -EBUSY;
5720 goto unlock;
5721 }
5722 clear_page_huge_active(page);
5723 list_move_tail(&page->lru, list);
5724 unlock:
5725 spin_unlock(&hugetlb_lock);
5726 return ret;
5727 }
5728
putback_active_hugepage(struct page * page)5729 void putback_active_hugepage(struct page *page)
5730 {
5731 VM_BUG_ON_PAGE(!PageHead(page), page);
5732 spin_lock(&hugetlb_lock);
5733 set_page_huge_active(page);
5734 list_move_tail(&page->lru, &(page_hstate(page))->hugepage_activelist);
5735 spin_unlock(&hugetlb_lock);
5736 put_page(page);
5737 }
5738
move_hugetlb_state(struct page * oldpage,struct page * newpage,int reason)5739 void move_hugetlb_state(struct page *oldpage, struct page *newpage, int reason)
5740 {
5741 struct hstate *h = page_hstate(oldpage);
5742
5743 hugetlb_cgroup_migrate(oldpage, newpage);
5744 set_page_owner_migrate_reason(newpage, reason);
5745
5746 /*
5747 * transfer temporary state of the new huge page. This is
5748 * reverse to other transitions because the newpage is going to
5749 * be final while the old one will be freed so it takes over
5750 * the temporary status.
5751 *
5752 * Also note that we have to transfer the per-node surplus state
5753 * here as well otherwise the global surplus count will not match
5754 * the per-node's.
5755 */
5756 if (PageHugeTemporary(newpage)) {
5757 int old_nid = page_to_nid(oldpage);
5758 int new_nid = page_to_nid(newpage);
5759
5760 SetPageHugeTemporary(oldpage);
5761 ClearPageHugeTemporary(newpage);
5762
5763 spin_lock(&hugetlb_lock);
5764 if (h->surplus_huge_pages_node[old_nid]) {
5765 h->surplus_huge_pages_node[old_nid]--;
5766 h->surplus_huge_pages_node[new_nid]++;
5767 }
5768 spin_unlock(&hugetlb_lock);
5769 }
5770 }
5771
hugetlb_unshare_pmds(struct vm_area_struct * vma,unsigned long start,unsigned long end)5772 static void hugetlb_unshare_pmds(struct vm_area_struct *vma,
5773 unsigned long start,
5774 unsigned long end)
5775 {
5776 struct hstate *h = hstate_vma(vma);
5777 unsigned long sz = huge_page_size(h);
5778 struct mm_struct *mm = vma->vm_mm;
5779 struct mmu_notifier_range range;
5780 unsigned long address;
5781 spinlock_t *ptl;
5782 pte_t *ptep;
5783
5784 if (!(vma->vm_flags & VM_MAYSHARE))
5785 return;
5786
5787 if (start >= end)
5788 return;
5789
5790 flush_cache_range(vma, start, end);
5791 /*
5792 * No need to call adjust_range_if_pmd_sharing_possible(), because
5793 * we have already done the PUD_SIZE alignment.
5794 */
5795 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
5796 start, end);
5797 mmu_notifier_invalidate_range_start(&range);
5798 i_mmap_lock_write(vma->vm_file->f_mapping);
5799 for (address = start; address < end; address += PUD_SIZE) {
5800 unsigned long tmp = address;
5801
5802 ptep = huge_pte_offset(mm, address, sz);
5803 if (!ptep)
5804 continue;
5805 ptl = huge_pte_lock(h, mm, ptep);
5806 /* We don't want 'address' to be changed */
5807 huge_pmd_unshare(mm, vma, &tmp, ptep);
5808 spin_unlock(ptl);
5809 }
5810 flush_hugetlb_tlb_range(vma, start, end);
5811 i_mmap_unlock_write(vma->vm_file->f_mapping);
5812 /*
5813 * No need to call mmu_notifier_invalidate_range(), see
5814 * Documentation/vm/mmu_notifier.rst.
5815 */
5816 mmu_notifier_invalidate_range_end(&range);
5817 }
5818
5819 /*
5820 * This function will unconditionally remove all the shared pmd pgtable entries
5821 * within the specific vma for a hugetlbfs memory range.
5822 */
hugetlb_unshare_all_pmds(struct vm_area_struct * vma)5823 void hugetlb_unshare_all_pmds(struct vm_area_struct *vma)
5824 {
5825 hugetlb_unshare_pmds(vma, ALIGN(vma->vm_start, PUD_SIZE),
5826 ALIGN_DOWN(vma->vm_end, PUD_SIZE));
5827 }
5828
5829 #ifdef CONFIG_CMA
5830 static bool cma_reserve_called __initdata;
5831
cmdline_parse_hugetlb_cma(char * p)5832 static int __init cmdline_parse_hugetlb_cma(char *p)
5833 {
5834 hugetlb_cma_size = memparse(p, &p);
5835 return 0;
5836 }
5837
5838 early_param("hugetlb_cma", cmdline_parse_hugetlb_cma);
5839
hugetlb_cma_reserve(int order)5840 void __init hugetlb_cma_reserve(int order)
5841 {
5842 unsigned long size, reserved, per_node;
5843 int nid;
5844
5845 cma_reserve_called = true;
5846
5847 if (!hugetlb_cma_size)
5848 return;
5849
5850 if (hugetlb_cma_size < (PAGE_SIZE << order)) {
5851 pr_warn("hugetlb_cma: cma area should be at least %lu MiB\n",
5852 (PAGE_SIZE << order) / SZ_1M);
5853 return;
5854 }
5855
5856 /*
5857 * If 3 GB area is requested on a machine with 4 numa nodes,
5858 * let's allocate 1 GB on first three nodes and ignore the last one.
5859 */
5860 per_node = DIV_ROUND_UP(hugetlb_cma_size, nr_online_nodes);
5861 pr_info("hugetlb_cma: reserve %lu MiB, up to %lu MiB per node\n",
5862 hugetlb_cma_size / SZ_1M, per_node / SZ_1M);
5863
5864 reserved = 0;
5865 for_each_node_state(nid, N_ONLINE) {
5866 int res;
5867 char name[CMA_MAX_NAME];
5868
5869 size = min(per_node, hugetlb_cma_size - reserved);
5870 size = round_up(size, PAGE_SIZE << order);
5871
5872 snprintf(name, sizeof(name), "hugetlb%d", nid);
5873 res = cma_declare_contiguous_nid(0, size, 0, PAGE_SIZE << order,
5874 0, false, name,
5875 &hugetlb_cma[nid], nid);
5876 if (res) {
5877 pr_warn("hugetlb_cma: reservation failed: err %d, node %d",
5878 res, nid);
5879 continue;
5880 }
5881
5882 reserved += size;
5883 pr_info("hugetlb_cma: reserved %lu MiB on node %d\n",
5884 size / SZ_1M, nid);
5885
5886 if (reserved >= hugetlb_cma_size)
5887 break;
5888 }
5889 }
5890
hugetlb_cma_check(void)5891 void __init hugetlb_cma_check(void)
5892 {
5893 if (!hugetlb_cma_size || cma_reserve_called)
5894 return;
5895
5896 pr_warn("hugetlb_cma: the option isn't supported by current arch\n");
5897 }
5898
5899 #endif /* CONFIG_CMA */
5900