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