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