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