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