Merge "kfence: Use pt_regs to generate stack trace on faults" into tizen
[platform/kernel/linux-rpi.git] / mm / gup.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 #include <linux/kernel.h>
3 #include <linux/errno.h>
4 #include <linux/err.h>
5 #include <linux/spinlock.h>
6
7 #include <linux/mm.h>
8 #include <linux/memremap.h>
9 #include <linux/pagemap.h>
10 #include <linux/rmap.h>
11 #include <linux/swap.h>
12 #include <linux/swapops.h>
13
14 #include <linux/sched/signal.h>
15 #include <linux/rwsem.h>
16 #include <linux/hugetlb.h>
17 #include <linux/migrate.h>
18 #include <linux/mm_inline.h>
19 #include <linux/sched/mm.h>
20
21 #include <asm/mmu_context.h>
22 #include <asm/tlbflush.h>
23
24 #include "internal.h"
25
26 struct follow_page_context {
27         struct dev_pagemap *pgmap;
28         unsigned int page_mask;
29 };
30
31 static void hpage_pincount_add(struct page *page, int refs)
32 {
33         VM_BUG_ON_PAGE(!hpage_pincount_available(page), page);
34         VM_BUG_ON_PAGE(page != compound_head(page), page);
35
36         atomic_add(refs, compound_pincount_ptr(page));
37 }
38
39 static void hpage_pincount_sub(struct page *page, int refs)
40 {
41         VM_BUG_ON_PAGE(!hpage_pincount_available(page), page);
42         VM_BUG_ON_PAGE(page != compound_head(page), page);
43
44         atomic_sub(refs, compound_pincount_ptr(page));
45 }
46
47 /* Equivalent to calling put_page() @refs times. */
48 static void put_page_refs(struct page *page, int refs)
49 {
50 #ifdef CONFIG_DEBUG_VM
51         if (VM_WARN_ON_ONCE_PAGE(page_ref_count(page) < refs, page))
52                 return;
53 #endif
54
55         /*
56          * Calling put_page() for each ref is unnecessarily slow. Only the last
57          * ref needs a put_page().
58          */
59         if (refs > 1)
60                 page_ref_sub(page, refs - 1);
61         put_page(page);
62 }
63
64 /*
65  * Return the compound head page with ref appropriately incremented,
66  * or NULL if that failed.
67  */
68 static inline struct page *try_get_compound_head(struct page *page, int refs)
69 {
70         struct page *head = compound_head(page);
71
72         if (WARN_ON_ONCE(page_ref_count(head) < 0))
73                 return NULL;
74         if (unlikely(!page_cache_add_speculative(head, refs)))
75                 return NULL;
76
77         /*
78          * At this point we have a stable reference to the head page; but it
79          * could be that between the compound_head() lookup and the refcount
80          * increment, the compound page was split, in which case we'd end up
81          * holding a reference on a page that has nothing to do with the page
82          * we were given anymore.
83          * So now that the head page is stable, recheck that the pages still
84          * belong together.
85          */
86         if (unlikely(compound_head(page) != head)) {
87                 put_page_refs(head, refs);
88                 return NULL;
89         }
90
91         return head;
92 }
93
94 /*
95  * try_grab_compound_head() - attempt to elevate a page's refcount, by a
96  * flags-dependent amount.
97  *
98  * "grab" names in this file mean, "look at flags to decide whether to use
99  * FOLL_PIN or FOLL_GET behavior, when incrementing the page's refcount.
100  *
101  * Either FOLL_PIN or FOLL_GET (or neither) must be set, but not both at the
102  * same time. (That's true throughout the get_user_pages*() and
103  * pin_user_pages*() APIs.) Cases:
104  *
105  *    FOLL_GET: page's refcount will be incremented by 1.
106  *    FOLL_PIN: page's refcount will be incremented by GUP_PIN_COUNTING_BIAS.
107  *
108  * Return: head page (with refcount appropriately incremented) for success, or
109  * NULL upon failure. If neither FOLL_GET nor FOLL_PIN was set, that's
110  * considered failure, and furthermore, a likely bug in the caller, so a warning
111  * is also emitted.
112  */
113 static __maybe_unused struct page *try_grab_compound_head(struct page *page,
114                                                           int refs,
115                                                           unsigned int flags)
116 {
117         if (flags & FOLL_GET)
118                 return try_get_compound_head(page, refs);
119         else if (flags & FOLL_PIN) {
120                 int orig_refs = refs;
121
122                 /*
123                  * Can't do FOLL_LONGTERM + FOLL_PIN with CMA in the gup fast
124                  * path, so fail and let the caller fall back to the slow path.
125                  */
126                 if (unlikely(flags & FOLL_LONGTERM) &&
127                                 is_migrate_cma_page(page))
128                         return NULL;
129
130                 /*
131                  * CAUTION: Don't use compound_head() on the page before this
132                  * point, the result won't be stable.
133                  */
134                 page = try_get_compound_head(page, refs);
135                 if (!page)
136                         return NULL;
137
138                 /*
139                  * When pinning a compound page of order > 1 (which is what
140                  * hpage_pincount_available() checks for), use an exact count to
141                  * track it, via hpage_pincount_add/_sub().
142                  *
143                  * However, be sure to *also* increment the normal page refcount
144                  * field at least once, so that the page really is pinned.
145                  */
146                 if (hpage_pincount_available(page))
147                         hpage_pincount_add(page, refs);
148                 else
149                         page_ref_add(page, refs * (GUP_PIN_COUNTING_BIAS - 1));
150
151                 mod_node_page_state(page_pgdat(page), NR_FOLL_PIN_ACQUIRED,
152                                     orig_refs);
153
154                 return page;
155         }
156
157         WARN_ON_ONCE(1);
158         return NULL;
159 }
160
161 static void put_compound_head(struct page *page, int refs, unsigned int flags)
162 {
163         if (flags & FOLL_PIN) {
164                 mod_node_page_state(page_pgdat(page), NR_FOLL_PIN_RELEASED,
165                                     refs);
166
167                 if (hpage_pincount_available(page))
168                         hpage_pincount_sub(page, refs);
169                 else
170                         refs *= GUP_PIN_COUNTING_BIAS;
171         }
172
173         put_page_refs(page, refs);
174 }
175
176 /**
177  * try_grab_page() - elevate a page's refcount by a flag-dependent amount
178  *
179  * This might not do anything at all, depending on the flags argument.
180  *
181  * "grab" names in this file mean, "look at flags to decide whether to use
182  * FOLL_PIN or FOLL_GET behavior, when incrementing the page's refcount.
183  *
184  * @page:    pointer to page to be grabbed
185  * @flags:   gup flags: these are the FOLL_* flag values.
186  *
187  * Either FOLL_PIN or FOLL_GET (or neither) may be set, but not both at the same
188  * time. Cases:
189  *
190  *    FOLL_GET: page's refcount will be incremented by 1.
191  *    FOLL_PIN: page's refcount will be incremented by GUP_PIN_COUNTING_BIAS.
192  *
193  * Return: true for success, or if no action was required (if neither FOLL_PIN
194  * nor FOLL_GET was set, nothing is done). False for failure: FOLL_GET or
195  * FOLL_PIN was set, but the page could not be grabbed.
196  */
197 bool __must_check try_grab_page(struct page *page, unsigned int flags)
198 {
199         WARN_ON_ONCE((flags & (FOLL_GET | FOLL_PIN)) == (FOLL_GET | FOLL_PIN));
200
201         if (flags & FOLL_GET)
202                 return try_get_page(page);
203         else if (flags & FOLL_PIN) {
204                 int refs = 1;
205
206                 page = compound_head(page);
207
208                 if (WARN_ON_ONCE(page_ref_count(page) <= 0))
209                         return false;
210
211                 if (hpage_pincount_available(page))
212                         hpage_pincount_add(page, 1);
213                 else
214                         refs = GUP_PIN_COUNTING_BIAS;
215
216                 /*
217                  * Similar to try_grab_compound_head(): even if using the
218                  * hpage_pincount_add/_sub() routines, be sure to
219                  * *also* increment the normal page refcount field at least
220                  * once, so that the page really is pinned.
221                  */
222                 page_ref_add(page, refs);
223
224                 mod_node_page_state(page_pgdat(page), NR_FOLL_PIN_ACQUIRED, 1);
225         }
226
227         return true;
228 }
229
230 /**
231  * unpin_user_page() - release a dma-pinned page
232  * @page:            pointer to page to be released
233  *
234  * Pages that were pinned via pin_user_pages*() must be released via either
235  * unpin_user_page(), or one of the unpin_user_pages*() routines. This is so
236  * that such pages can be separately tracked and uniquely handled. In
237  * particular, interactions with RDMA and filesystems need special handling.
238  */
239 void unpin_user_page(struct page *page)
240 {
241         put_compound_head(compound_head(page), 1, FOLL_PIN);
242 }
243 EXPORT_SYMBOL(unpin_user_page);
244
245 /**
246  * unpin_user_pages_dirty_lock() - release and optionally dirty gup-pinned pages
247  * @pages:  array of pages to be maybe marked dirty, and definitely released.
248  * @npages: number of pages in the @pages array.
249  * @make_dirty: whether to mark the pages dirty
250  *
251  * "gup-pinned page" refers to a page that has had one of the get_user_pages()
252  * variants called on that page.
253  *
254  * For each page in the @pages array, make that page (or its head page, if a
255  * compound page) dirty, if @make_dirty is true, and if the page was previously
256  * listed as clean. In any case, releases all pages using unpin_user_page(),
257  * possibly via unpin_user_pages(), for the non-dirty case.
258  *
259  * Please see the unpin_user_page() documentation for details.
260  *
261  * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
262  * required, then the caller should a) verify that this is really correct,
263  * because _lock() is usually required, and b) hand code it:
264  * set_page_dirty_lock(), unpin_user_page().
265  *
266  */
267 void unpin_user_pages_dirty_lock(struct page **pages, unsigned long npages,
268                                  bool make_dirty)
269 {
270         unsigned long index;
271
272         /*
273          * TODO: this can be optimized for huge pages: if a series of pages is
274          * physically contiguous and part of the same compound page, then a
275          * single operation to the head page should suffice.
276          */
277
278         if (!make_dirty) {
279                 unpin_user_pages(pages, npages);
280                 return;
281         }
282
283         for (index = 0; index < npages; index++) {
284                 struct page *page = compound_head(pages[index]);
285                 /*
286                  * Checking PageDirty at this point may race with
287                  * clear_page_dirty_for_io(), but that's OK. Two key
288                  * cases:
289                  *
290                  * 1) This code sees the page as already dirty, so it
291                  * skips the call to set_page_dirty(). That could happen
292                  * because clear_page_dirty_for_io() called
293                  * page_mkclean(), followed by set_page_dirty().
294                  * However, now the page is going to get written back,
295                  * which meets the original intention of setting it
296                  * dirty, so all is well: clear_page_dirty_for_io() goes
297                  * on to call TestClearPageDirty(), and write the page
298                  * back.
299                  *
300                  * 2) This code sees the page as clean, so it calls
301                  * set_page_dirty(). The page stays dirty, despite being
302                  * written back, so it gets written back again in the
303                  * next writeback cycle. This is harmless.
304                  */
305                 if (!PageDirty(page))
306                         set_page_dirty_lock(page);
307                 unpin_user_page(page);
308         }
309 }
310 EXPORT_SYMBOL(unpin_user_pages_dirty_lock);
311
312 /**
313  * unpin_user_pages() - release an array of gup-pinned pages.
314  * @pages:  array of pages to be marked dirty and released.
315  * @npages: number of pages in the @pages array.
316  *
317  * For each page in the @pages array, release the page using unpin_user_page().
318  *
319  * Please see the unpin_user_page() documentation for details.
320  */
321 void unpin_user_pages(struct page **pages, unsigned long npages)
322 {
323         unsigned long index;
324
325         /*
326          * If this WARN_ON() fires, then the system *might* be leaking pages (by
327          * leaving them pinned), but probably not. More likely, gup/pup returned
328          * a hard -ERRNO error to the caller, who erroneously passed it here.
329          */
330         if (WARN_ON(IS_ERR_VALUE(npages)))
331                 return;
332         /*
333          * TODO: this can be optimized for huge pages: if a series of pages is
334          * physically contiguous and part of the same compound page, then a
335          * single operation to the head page should suffice.
336          */
337         for (index = 0; index < npages; index++)
338                 unpin_user_page(pages[index]);
339 }
340 EXPORT_SYMBOL(unpin_user_pages);
341
342 #ifdef CONFIG_MMU
343 static struct page *no_page_table(struct vm_area_struct *vma,
344                 unsigned int flags)
345 {
346         /*
347          * When core dumping an enormous anonymous area that nobody
348          * has touched so far, we don't want to allocate unnecessary pages or
349          * page tables.  Return error instead of NULL to skip handle_mm_fault,
350          * then get_dump_page() will return NULL to leave a hole in the dump.
351          * But we can only make this optimization where a hole would surely
352          * be zero-filled if handle_mm_fault() actually did handle it.
353          */
354         if ((flags & FOLL_DUMP) &&
355                         (vma_is_anonymous(vma) || !vma->vm_ops->fault))
356                 return ERR_PTR(-EFAULT);
357         return NULL;
358 }
359
360 static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
361                 pte_t *pte, unsigned int flags)
362 {
363         /* No page to get reference */
364         if (flags & FOLL_GET)
365                 return -EFAULT;
366
367         if (flags & FOLL_TOUCH) {
368                 pte_t entry = *pte;
369
370                 if (flags & FOLL_WRITE)
371                         entry = pte_mkdirty(entry);
372                 entry = pte_mkyoung(entry);
373
374                 if (!pte_same(*pte, entry)) {
375                         set_pte_at(vma->vm_mm, address, pte, entry);
376                         update_mmu_cache(vma, address, pte);
377                 }
378         }
379
380         /* Proper page table entry exists, but no corresponding struct page */
381         return -EEXIST;
382 }
383
384 /*
385  * FOLL_FORCE can write to even unwritable pte's, but only
386  * after we've gone through a COW cycle and they are dirty.
387  */
388 static inline bool can_follow_write_pte(pte_t pte, unsigned int flags)
389 {
390         return pte_write(pte) ||
391                 ((flags & FOLL_FORCE) && (flags & FOLL_COW) && pte_dirty(pte));
392 }
393
394 static struct page *follow_page_pte(struct vm_area_struct *vma,
395                 unsigned long address, pmd_t *pmd, unsigned int flags,
396                 struct dev_pagemap **pgmap)
397 {
398         struct mm_struct *mm = vma->vm_mm;
399         struct page *page;
400         spinlock_t *ptl;
401         pte_t *ptep, pte;
402         int ret;
403
404         /* FOLL_GET and FOLL_PIN are mutually exclusive. */
405         if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
406                          (FOLL_PIN | FOLL_GET)))
407                 return ERR_PTR(-EINVAL);
408 retry:
409         if (unlikely(pmd_bad(*pmd)))
410                 return no_page_table(vma, flags);
411
412         ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
413         pte = *ptep;
414         if (!pte_present(pte)) {
415                 swp_entry_t entry;
416                 /*
417                  * KSM's break_ksm() relies upon recognizing a ksm page
418                  * even while it is being migrated, so for that case we
419                  * need migration_entry_wait().
420                  */
421                 if (likely(!(flags & FOLL_MIGRATION)))
422                         goto no_page;
423                 if (pte_none(pte))
424                         goto no_page;
425                 entry = pte_to_swp_entry(pte);
426                 if (!is_migration_entry(entry))
427                         goto no_page;
428                 pte_unmap_unlock(ptep, ptl);
429                 migration_entry_wait(mm, pmd, address);
430                 goto retry;
431         }
432         if ((flags & FOLL_NUMA) && pte_protnone(pte))
433                 goto no_page;
434         if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
435                 pte_unmap_unlock(ptep, ptl);
436                 return NULL;
437         }
438
439         page = vm_normal_page(vma, address, pte);
440         if (!page && pte_devmap(pte) && (flags & (FOLL_GET | FOLL_PIN))) {
441                 /*
442                  * Only return device mapping pages in the FOLL_GET or FOLL_PIN
443                  * case since they are only valid while holding the pgmap
444                  * reference.
445                  */
446                 *pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
447                 if (*pgmap)
448                         page = pte_page(pte);
449                 else
450                         goto no_page;
451         } else if (unlikely(!page)) {
452                 if (flags & FOLL_DUMP) {
453                         /* Avoid special (like zero) pages in core dumps */
454                         page = ERR_PTR(-EFAULT);
455                         goto out;
456                 }
457
458                 if (is_zero_pfn(pte_pfn(pte))) {
459                         page = pte_page(pte);
460                 } else {
461                         ret = follow_pfn_pte(vma, address, ptep, flags);
462                         page = ERR_PTR(ret);
463                         goto out;
464                 }
465         }
466
467         if (flags & FOLL_SPLIT && PageTransCompound(page)) {
468                 get_page(page);
469                 pte_unmap_unlock(ptep, ptl);
470                 lock_page(page);
471                 ret = split_huge_page(page);
472                 unlock_page(page);
473                 put_page(page);
474                 if (ret)
475                         return ERR_PTR(ret);
476                 goto retry;
477         }
478 #ifdef CONFIG_FINEGRAINED_THP
479         else if (flags & FOLL_SPLIT_PTE && pte_cont(pte))
480                 split_huge_pte(vma, pmd, ptep, address);
481 #endif /* CONFIG_FINEGRAINED_THP */
482
483         /* try_grab_page() does nothing unless FOLL_GET or FOLL_PIN is set. */
484         if (unlikely(!try_grab_page(page, flags))) {
485                 page = ERR_PTR(-ENOMEM);
486                 goto out;
487         }
488         /*
489          * We need to make the page accessible if and only if we are going
490          * to access its content (the FOLL_PIN case).  Please see
491          * Documentation/core-api/pin_user_pages.rst for details.
492          */
493         if (flags & FOLL_PIN) {
494                 ret = arch_make_page_accessible(page);
495                 if (ret) {
496                         unpin_user_page(page);
497                         page = ERR_PTR(ret);
498                         goto out;
499                 }
500         }
501         if (flags & FOLL_TOUCH) {
502                 if ((flags & FOLL_WRITE) &&
503                     !pte_dirty(pte) && !PageDirty(page))
504                         set_page_dirty(page);
505                 /*
506                  * pte_mkyoung() would be more correct here, but atomic care
507                  * is needed to avoid losing the dirty bit: it is easier to use
508                  * mark_page_accessed().
509                  */
510                 mark_page_accessed(page);
511         }
512         if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
513                 /* Do not mlock pte-mapped THP */
514                 if (PageTransCompound(page))
515                         goto out;
516
517                 /*
518                  * The preliminary mapping check is mainly to avoid the
519                  * pointless overhead of lock_page on the ZERO_PAGE
520                  * which might bounce very badly if there is contention.
521                  *
522                  * If the page is already locked, we don't need to
523                  * handle it now - vmscan will handle it later if and
524                  * when it attempts to reclaim the page.
525                  */
526                 if (page->mapping && trylock_page(page)) {
527                         lru_add_drain();  /* push cached pages to LRU */
528                         /*
529                          * Because we lock page here, and migration is
530                          * blocked by the pte's page reference, and we
531                          * know the page is still mapped, we don't even
532                          * need to check for file-cache page truncation.
533                          */
534                         mlock_vma_page(page);
535                         unlock_page(page);
536                 }
537         }
538 out:
539         pte_unmap_unlock(ptep, ptl);
540         return page;
541 no_page:
542         pte_unmap_unlock(ptep, ptl);
543         if (!pte_none(pte))
544                 return NULL;
545         return no_page_table(vma, flags);
546 }
547
548 static struct page *follow_pmd_mask(struct vm_area_struct *vma,
549                                     unsigned long address, pud_t *pudp,
550                                     unsigned int flags,
551                                     struct follow_page_context *ctx)
552 {
553         pmd_t *pmd, pmdval;
554         spinlock_t *ptl;
555         struct page *page;
556         struct mm_struct *mm = vma->vm_mm;
557
558         pmd = pmd_offset(pudp, address);
559         /*
560          * The READ_ONCE() will stabilize the pmdval in a register or
561          * on the stack so that it will stop changing under the code.
562          */
563         pmdval = READ_ONCE(*pmd);
564         if (pmd_none(pmdval))
565                 return no_page_table(vma, flags);
566         if (pmd_huge(pmdval) && is_vm_hugetlb_page(vma)) {
567                 page = follow_huge_pmd(mm, address, pmd, flags);
568                 if (page)
569                         return page;
570                 return no_page_table(vma, flags);
571         }
572         if (is_hugepd(__hugepd(pmd_val(pmdval)))) {
573                 page = follow_huge_pd(vma, address,
574                                       __hugepd(pmd_val(pmdval)), flags,
575                                       PMD_SHIFT);
576                 if (page)
577                         return page;
578                 return no_page_table(vma, flags);
579         }
580 retry:
581         if (!pmd_present(pmdval)) {
582                 if (likely(!(flags & FOLL_MIGRATION)))
583                         return no_page_table(vma, flags);
584                 VM_BUG_ON(thp_migration_supported() &&
585                                   !is_pmd_migration_entry(pmdval));
586                 if (is_pmd_migration_entry(pmdval))
587                         pmd_migration_entry_wait(mm, pmd);
588                 pmdval = READ_ONCE(*pmd);
589                 /*
590                  * MADV_DONTNEED may convert the pmd to null because
591                  * mmap_lock is held in read mode
592                  */
593                 if (pmd_none(pmdval))
594                         return no_page_table(vma, flags);
595                 goto retry;
596         }
597         if (pmd_devmap(pmdval)) {
598                 ptl = pmd_lock(mm, pmd);
599                 page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
600                 spin_unlock(ptl);
601                 if (page)
602                         return page;
603         }
604         if (likely(!pmd_trans_huge(pmdval)))
605                 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
606
607         if ((flags & FOLL_NUMA) && pmd_protnone(pmdval))
608                 return no_page_table(vma, flags);
609
610 retry_locked:
611         ptl = pmd_lock(mm, pmd);
612         if (unlikely(pmd_none(*pmd))) {
613                 spin_unlock(ptl);
614                 return no_page_table(vma, flags);
615         }
616         if (unlikely(!pmd_present(*pmd))) {
617                 spin_unlock(ptl);
618                 if (likely(!(flags & FOLL_MIGRATION)))
619                         return no_page_table(vma, flags);
620                 pmd_migration_entry_wait(mm, pmd);
621                 goto retry_locked;
622         }
623         if (unlikely(!pmd_trans_huge(*pmd))) {
624                 spin_unlock(ptl);
625                 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
626         }
627         if (flags & (FOLL_SPLIT | FOLL_SPLIT_PMD)) {
628                 int ret;
629                 page = pmd_page(*pmd);
630                 if (is_huge_zero_page(page)) {
631                         spin_unlock(ptl);
632                         ret = 0;
633                         split_huge_pmd(vma, pmd, address);
634                         if (pmd_trans_unstable(pmd))
635                                 ret = -EBUSY;
636                 } else if (flags & FOLL_SPLIT) {
637                         if (unlikely(!try_get_page(page))) {
638                                 spin_unlock(ptl);
639                                 return ERR_PTR(-ENOMEM);
640                         }
641                         spin_unlock(ptl);
642                         lock_page(page);
643                         ret = split_huge_page(page);
644                         unlock_page(page);
645                         put_page(page);
646                         if (pmd_none(*pmd))
647                                 return no_page_table(vma, flags);
648                 } else {  /* flags & FOLL_SPLIT_PMD */
649                         spin_unlock(ptl);
650                         split_huge_pmd(vma, pmd, address);
651                         ret = pte_alloc(mm, pmd) ? -ENOMEM : 0;
652                 }
653
654                 return ret ? ERR_PTR(ret) :
655                         follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
656         }
657         page = follow_trans_huge_pmd(vma, address, pmd, flags);
658         spin_unlock(ptl);
659         ctx->page_mask = HPAGE_PMD_NR - 1;
660         return page;
661 }
662
663 static struct page *follow_pud_mask(struct vm_area_struct *vma,
664                                     unsigned long address, p4d_t *p4dp,
665                                     unsigned int flags,
666                                     struct follow_page_context *ctx)
667 {
668         pud_t *pud;
669         spinlock_t *ptl;
670         struct page *page;
671         struct mm_struct *mm = vma->vm_mm;
672
673         pud = pud_offset(p4dp, address);
674         if (pud_none(*pud))
675                 return no_page_table(vma, flags);
676         if (pud_huge(*pud) && is_vm_hugetlb_page(vma)) {
677                 page = follow_huge_pud(mm, address, pud, flags);
678                 if (page)
679                         return page;
680                 return no_page_table(vma, flags);
681         }
682         if (is_hugepd(__hugepd(pud_val(*pud)))) {
683                 page = follow_huge_pd(vma, address,
684                                       __hugepd(pud_val(*pud)), flags,
685                                       PUD_SHIFT);
686                 if (page)
687                         return page;
688                 return no_page_table(vma, flags);
689         }
690         if (pud_devmap(*pud)) {
691                 ptl = pud_lock(mm, pud);
692                 page = follow_devmap_pud(vma, address, pud, flags, &ctx->pgmap);
693                 spin_unlock(ptl);
694                 if (page)
695                         return page;
696         }
697         if (unlikely(pud_bad(*pud)))
698                 return no_page_table(vma, flags);
699
700         return follow_pmd_mask(vma, address, pud, flags, ctx);
701 }
702
703 static struct page *follow_p4d_mask(struct vm_area_struct *vma,
704                                     unsigned long address, pgd_t *pgdp,
705                                     unsigned int flags,
706                                     struct follow_page_context *ctx)
707 {
708         p4d_t *p4d;
709         struct page *page;
710
711         p4d = p4d_offset(pgdp, address);
712         if (p4d_none(*p4d))
713                 return no_page_table(vma, flags);
714         BUILD_BUG_ON(p4d_huge(*p4d));
715         if (unlikely(p4d_bad(*p4d)))
716                 return no_page_table(vma, flags);
717
718         if (is_hugepd(__hugepd(p4d_val(*p4d)))) {
719                 page = follow_huge_pd(vma, address,
720                                       __hugepd(p4d_val(*p4d)), flags,
721                                       P4D_SHIFT);
722                 if (page)
723                         return page;
724                 return no_page_table(vma, flags);
725         }
726         return follow_pud_mask(vma, address, p4d, flags, ctx);
727 }
728
729 /**
730  * follow_page_mask - look up a page descriptor from a user-virtual address
731  * @vma: vm_area_struct mapping @address
732  * @address: virtual address to look up
733  * @flags: flags modifying lookup behaviour
734  * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
735  *       pointer to output page_mask
736  *
737  * @flags can have FOLL_ flags set, defined in <linux/mm.h>
738  *
739  * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
740  * the device's dev_pagemap metadata to avoid repeating expensive lookups.
741  *
742  * On output, the @ctx->page_mask is set according to the size of the page.
743  *
744  * Return: the mapped (struct page *), %NULL if no mapping exists, or
745  * an error pointer if there is a mapping to something not represented
746  * by a page descriptor (see also vm_normal_page()).
747  */
748 static struct page *follow_page_mask(struct vm_area_struct *vma,
749                               unsigned long address, unsigned int flags,
750                               struct follow_page_context *ctx)
751 {
752         pgd_t *pgd;
753         struct page *page;
754         struct mm_struct *mm = vma->vm_mm;
755
756         ctx->page_mask = 0;
757
758         /* make this handle hugepd */
759         page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
760         if (!IS_ERR(page)) {
761                 WARN_ON_ONCE(flags & (FOLL_GET | FOLL_PIN));
762                 return page;
763         }
764
765         pgd = pgd_offset(mm, address);
766
767         if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
768                 return no_page_table(vma, flags);
769
770         if (pgd_huge(*pgd)) {
771                 page = follow_huge_pgd(mm, address, pgd, flags);
772                 if (page)
773                         return page;
774                 return no_page_table(vma, flags);
775         }
776         if (is_hugepd(__hugepd(pgd_val(*pgd)))) {
777                 page = follow_huge_pd(vma, address,
778                                       __hugepd(pgd_val(*pgd)), flags,
779                                       PGDIR_SHIFT);
780                 if (page)
781                         return page;
782                 return no_page_table(vma, flags);
783         }
784
785         return follow_p4d_mask(vma, address, pgd, flags, ctx);
786 }
787
788 struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
789                          unsigned int foll_flags)
790 {
791         struct follow_page_context ctx = { NULL };
792         struct page *page;
793
794         page = follow_page_mask(vma, address, foll_flags, &ctx);
795         if (ctx.pgmap)
796                 put_dev_pagemap(ctx.pgmap);
797         return page;
798 }
799
800 static int get_gate_page(struct mm_struct *mm, unsigned long address,
801                 unsigned int gup_flags, struct vm_area_struct **vma,
802                 struct page **page)
803 {
804         pgd_t *pgd;
805         p4d_t *p4d;
806         pud_t *pud;
807         pmd_t *pmd;
808         pte_t *pte;
809         int ret = -EFAULT;
810
811         /* user gate pages are read-only */
812         if (gup_flags & FOLL_WRITE)
813                 return -EFAULT;
814         if (address > TASK_SIZE)
815                 pgd = pgd_offset_k(address);
816         else
817                 pgd = pgd_offset_gate(mm, address);
818         if (pgd_none(*pgd))
819                 return -EFAULT;
820         p4d = p4d_offset(pgd, address);
821         if (p4d_none(*p4d))
822                 return -EFAULT;
823         pud = pud_offset(p4d, address);
824         if (pud_none(*pud))
825                 return -EFAULT;
826         pmd = pmd_offset(pud, address);
827         if (!pmd_present(*pmd))
828                 return -EFAULT;
829         VM_BUG_ON(pmd_trans_huge(*pmd));
830         pte = pte_offset_map(pmd, address);
831         if (pte_none(*pte))
832                 goto unmap;
833         *vma = get_gate_vma(mm);
834         if (!page)
835                 goto out;
836         *page = vm_normal_page(*vma, address, *pte);
837         if (!*page) {
838                 if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
839                         goto unmap;
840                 *page = pte_page(*pte);
841         }
842         if (unlikely(!try_grab_page(*page, gup_flags))) {
843                 ret = -ENOMEM;
844                 goto unmap;
845         }
846 out:
847         ret = 0;
848 unmap:
849         pte_unmap(pte);
850         return ret;
851 }
852
853 /*
854  * mmap_lock must be held on entry.  If @locked != NULL and *@flags
855  * does not include FOLL_NOWAIT, the mmap_lock may be released.  If it
856  * is, *@locked will be set to 0 and -EBUSY returned.
857  */
858 static int faultin_page(struct vm_area_struct *vma,
859                 unsigned long address, unsigned int *flags, int *locked)
860 {
861         unsigned int fault_flags = 0;
862         vm_fault_t ret;
863
864         /* mlock all present pages, but do not fault in new pages */
865         if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)
866                 return -ENOENT;
867         if (*flags & FOLL_WRITE)
868                 fault_flags |= FAULT_FLAG_WRITE;
869         if (*flags & FOLL_REMOTE)
870                 fault_flags |= FAULT_FLAG_REMOTE;
871         if (locked)
872                 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
873         if (*flags & FOLL_NOWAIT)
874                 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
875         if (*flags & FOLL_TRIED) {
876                 /*
877                  * Note: FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_TRIED
878                  * can co-exist
879                  */
880                 fault_flags |= FAULT_FLAG_TRIED;
881         }
882
883         ret = handle_mm_fault(vma, address, fault_flags, NULL);
884         if (ret & VM_FAULT_ERROR) {
885                 int err = vm_fault_to_errno(ret, *flags);
886
887                 if (err)
888                         return err;
889                 BUG();
890         }
891
892         if (ret & VM_FAULT_RETRY) {
893                 if (locked && !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
894                         *locked = 0;
895                 return -EBUSY;
896         }
897
898         /*
899          * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
900          * necessary, even if maybe_mkwrite decided not to set pte_write. We
901          * can thus safely do subsequent page lookups as if they were reads.
902          * But only do so when looping for pte_write is futile: in some cases
903          * userspace may also be wanting to write to the gotten user page,
904          * which a read fault here might prevent (a readonly page might get
905          * reCOWed by userspace write).
906          */
907         if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
908                 *flags |= FOLL_COW;
909         return 0;
910 }
911
912 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
913 {
914         vm_flags_t vm_flags = vma->vm_flags;
915         int write = (gup_flags & FOLL_WRITE);
916         int foreign = (gup_flags & FOLL_REMOTE);
917
918         if (vm_flags & (VM_IO | VM_PFNMAP))
919                 return -EFAULT;
920
921         if (gup_flags & FOLL_ANON && !vma_is_anonymous(vma))
922                 return -EFAULT;
923
924         if (write) {
925                 if (!(vm_flags & VM_WRITE)) {
926                         if (!(gup_flags & FOLL_FORCE))
927                                 return -EFAULT;
928                         /*
929                          * We used to let the write,force case do COW in a
930                          * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
931                          * set a breakpoint in a read-only mapping of an
932                          * executable, without corrupting the file (yet only
933                          * when that file had been opened for writing!).
934                          * Anon pages in shared mappings are surprising: now
935                          * just reject it.
936                          */
937                         if (!is_cow_mapping(vm_flags))
938                                 return -EFAULT;
939                 }
940         } else if (!(vm_flags & VM_READ)) {
941                 if (!(gup_flags & FOLL_FORCE))
942                         return -EFAULT;
943                 /*
944                  * Is there actually any vma we can reach here which does not
945                  * have VM_MAYREAD set?
946                  */
947                 if (!(vm_flags & VM_MAYREAD))
948                         return -EFAULT;
949         }
950         /*
951          * gups are always data accesses, not instruction
952          * fetches, so execute=false here
953          */
954         if (!arch_vma_access_permitted(vma, write, false, foreign))
955                 return -EFAULT;
956         return 0;
957 }
958
959 /**
960  * __get_user_pages() - pin user pages in memory
961  * @mm:         mm_struct of target mm
962  * @start:      starting user address
963  * @nr_pages:   number of pages from start to pin
964  * @gup_flags:  flags modifying pin behaviour
965  * @pages:      array that receives pointers to the pages pinned.
966  *              Should be at least nr_pages long. Or NULL, if caller
967  *              only intends to ensure the pages are faulted in.
968  * @vmas:       array of pointers to vmas corresponding to each page.
969  *              Or NULL if the caller does not require them.
970  * @locked:     whether we're still with the mmap_lock held
971  *
972  * Returns either number of pages pinned (which may be less than the
973  * number requested), or an error. Details about the return value:
974  *
975  * -- If nr_pages is 0, returns 0.
976  * -- If nr_pages is >0, but no pages were pinned, returns -errno.
977  * -- If nr_pages is >0, and some pages were pinned, returns the number of
978  *    pages pinned. Again, this may be less than nr_pages.
979  * -- 0 return value is possible when the fault would need to be retried.
980  *
981  * The caller is responsible for releasing returned @pages, via put_page().
982  *
983  * @vmas are valid only as long as mmap_lock is held.
984  *
985  * Must be called with mmap_lock held.  It may be released.  See below.
986  *
987  * __get_user_pages walks a process's page tables and takes a reference to
988  * each struct page that each user address corresponds to at a given
989  * instant. That is, it takes the page that would be accessed if a user
990  * thread accesses the given user virtual address at that instant.
991  *
992  * This does not guarantee that the page exists in the user mappings when
993  * __get_user_pages returns, and there may even be a completely different
994  * page there in some cases (eg. if mmapped pagecache has been invalidated
995  * and subsequently re faulted). However it does guarantee that the page
996  * won't be freed completely. And mostly callers simply care that the page
997  * contains data that was valid *at some point in time*. Typically, an IO
998  * or similar operation cannot guarantee anything stronger anyway because
999  * locks can't be held over the syscall boundary.
1000  *
1001  * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
1002  * the page is written to, set_page_dirty (or set_page_dirty_lock, as
1003  * appropriate) must be called after the page is finished with, and
1004  * before put_page is called.
1005  *
1006  * If @locked != NULL, *@locked will be set to 0 when mmap_lock is
1007  * released by an up_read().  That can happen if @gup_flags does not
1008  * have FOLL_NOWAIT.
1009  *
1010  * A caller using such a combination of @locked and @gup_flags
1011  * must therefore hold the mmap_lock for reading only, and recognize
1012  * when it's been released.  Otherwise, it must be held for either
1013  * reading or writing and will not be released.
1014  *
1015  * In most cases, get_user_pages or get_user_pages_fast should be used
1016  * instead of __get_user_pages. __get_user_pages should be used only if
1017  * you need some special @gup_flags.
1018  */
1019 static long __get_user_pages(struct mm_struct *mm,
1020                 unsigned long start, unsigned long nr_pages,
1021                 unsigned int gup_flags, struct page **pages,
1022                 struct vm_area_struct **vmas, int *locked)
1023 {
1024         long ret = 0, i = 0;
1025         struct vm_area_struct *vma = NULL;
1026         struct follow_page_context ctx = { NULL };
1027
1028         if (!nr_pages)
1029                 return 0;
1030
1031         start = untagged_addr(start);
1032
1033         VM_BUG_ON(!!pages != !!(gup_flags & (FOLL_GET | FOLL_PIN)));
1034
1035         /*
1036          * If FOLL_FORCE is set then do not force a full fault as the hinting
1037          * fault information is unrelated to the reference behaviour of a task
1038          * using the address space
1039          */
1040         if (!(gup_flags & FOLL_FORCE))
1041                 gup_flags |= FOLL_NUMA;
1042
1043         do {
1044                 struct page *page;
1045                 unsigned int foll_flags = gup_flags;
1046                 unsigned int page_increm;
1047
1048                 /* first iteration or cross vma bound */
1049                 if (!vma || start >= vma->vm_end) {
1050                         vma = find_extend_vma(mm, start);
1051                         if (!vma && in_gate_area(mm, start)) {
1052                                 ret = get_gate_page(mm, start & PAGE_MASK,
1053                                                 gup_flags, &vma,
1054                                                 pages ? &pages[i] : NULL);
1055                                 if (ret)
1056                                         goto out;
1057                                 ctx.page_mask = 0;
1058                                 goto next_page;
1059                         }
1060
1061                         if (!vma || check_vma_flags(vma, gup_flags)) {
1062                                 ret = -EFAULT;
1063                                 goto out;
1064                         }
1065                         if (is_vm_hugetlb_page(vma)) {
1066                                 i = follow_hugetlb_page(mm, vma, pages, vmas,
1067                                                 &start, &nr_pages, i,
1068                                                 gup_flags, locked);
1069                                 if (locked && *locked == 0) {
1070                                         /*
1071                                          * We've got a VM_FAULT_RETRY
1072                                          * and we've lost mmap_lock.
1073                                          * We must stop here.
1074                                          */
1075                                         BUG_ON(gup_flags & FOLL_NOWAIT);
1076                                         BUG_ON(ret != 0);
1077                                         goto out;
1078                                 }
1079                                 continue;
1080                         }
1081                 }
1082 retry:
1083                 /*
1084                  * If we have a pending SIGKILL, don't keep faulting pages and
1085                  * potentially allocating memory.
1086                  */
1087                 if (fatal_signal_pending(current)) {
1088                         ret = -EINTR;
1089                         goto out;
1090                 }
1091                 cond_resched();
1092
1093                 page = follow_page_mask(vma, start, foll_flags, &ctx);
1094                 if (!page) {
1095                         ret = faultin_page(vma, start, &foll_flags, locked);
1096                         switch (ret) {
1097                         case 0:
1098                                 goto retry;
1099                         case -EBUSY:
1100                                 ret = 0;
1101                                 fallthrough;
1102                         case -EFAULT:
1103                         case -ENOMEM:
1104                         case -EHWPOISON:
1105                                 goto out;
1106                         case -ENOENT:
1107                                 goto next_page;
1108                         }
1109                         BUG();
1110                 } else if (PTR_ERR(page) == -EEXIST) {
1111                         /*
1112                          * Proper page table entry exists, but no corresponding
1113                          * struct page.
1114                          */
1115                         goto next_page;
1116                 } else if (IS_ERR(page)) {
1117                         ret = PTR_ERR(page);
1118                         goto out;
1119                 }
1120                 if (pages) {
1121                         pages[i] = page;
1122                         flush_anon_page(vma, page, start);
1123                         flush_dcache_page(page);
1124                         ctx.page_mask = 0;
1125                 }
1126 next_page:
1127                 if (vmas) {
1128                         vmas[i] = vma;
1129                         ctx.page_mask = 0;
1130                 }
1131                 page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
1132                 if (page_increm > nr_pages)
1133                         page_increm = nr_pages;
1134                 i += page_increm;
1135                 start += page_increm * PAGE_SIZE;
1136                 nr_pages -= page_increm;
1137         } while (nr_pages);
1138 out:
1139         if (ctx.pgmap)
1140                 put_dev_pagemap(ctx.pgmap);
1141         return i ? i : ret;
1142 }
1143
1144 static bool vma_permits_fault(struct vm_area_struct *vma,
1145                               unsigned int fault_flags)
1146 {
1147         bool write   = !!(fault_flags & FAULT_FLAG_WRITE);
1148         bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
1149         vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
1150
1151         if (!(vm_flags & vma->vm_flags))
1152                 return false;
1153
1154         /*
1155          * The architecture might have a hardware protection
1156          * mechanism other than read/write that can deny access.
1157          *
1158          * gup always represents data access, not instruction
1159          * fetches, so execute=false here:
1160          */
1161         if (!arch_vma_access_permitted(vma, write, false, foreign))
1162                 return false;
1163
1164         return true;
1165 }
1166
1167 /**
1168  * fixup_user_fault() - manually resolve a user page fault
1169  * @mm:         mm_struct of target mm
1170  * @address:    user address
1171  * @fault_flags:flags to pass down to handle_mm_fault()
1172  * @unlocked:   did we unlock the mmap_lock while retrying, maybe NULL if caller
1173  *              does not allow retry. If NULL, the caller must guarantee
1174  *              that fault_flags does not contain FAULT_FLAG_ALLOW_RETRY.
1175  *
1176  * This is meant to be called in the specific scenario where for locking reasons
1177  * we try to access user memory in atomic context (within a pagefault_disable()
1178  * section), this returns -EFAULT, and we want to resolve the user fault before
1179  * trying again.
1180  *
1181  * Typically this is meant to be used by the futex code.
1182  *
1183  * The main difference with get_user_pages() is that this function will
1184  * unconditionally call handle_mm_fault() which will in turn perform all the
1185  * necessary SW fixup of the dirty and young bits in the PTE, while
1186  * get_user_pages() only guarantees to update these in the struct page.
1187  *
1188  * This is important for some architectures where those bits also gate the
1189  * access permission to the page because they are maintained in software.  On
1190  * such architectures, gup() will not be enough to make a subsequent access
1191  * succeed.
1192  *
1193  * This function will not return with an unlocked mmap_lock. So it has not the
1194  * same semantics wrt the @mm->mmap_lock as does filemap_fault().
1195  */
1196 int fixup_user_fault(struct mm_struct *mm,
1197                      unsigned long address, unsigned int fault_flags,
1198                      bool *unlocked)
1199 {
1200         struct vm_area_struct *vma;
1201         vm_fault_t ret, major = 0;
1202
1203         address = untagged_addr(address);
1204
1205         if (unlocked)
1206                 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1207
1208 retry:
1209         vma = find_extend_vma(mm, address);
1210         if (!vma || address < vma->vm_start)
1211                 return -EFAULT;
1212
1213         if (!vma_permits_fault(vma, fault_flags))
1214                 return -EFAULT;
1215
1216         if ((fault_flags & FAULT_FLAG_KILLABLE) &&
1217             fatal_signal_pending(current))
1218                 return -EINTR;
1219
1220         ret = handle_mm_fault(vma, address, fault_flags, NULL);
1221         major |= ret & VM_FAULT_MAJOR;
1222         if (ret & VM_FAULT_ERROR) {
1223                 int err = vm_fault_to_errno(ret, 0);
1224
1225                 if (err)
1226                         return err;
1227                 BUG();
1228         }
1229
1230         if (ret & VM_FAULT_RETRY) {
1231                 mmap_read_lock(mm);
1232                 *unlocked = true;
1233                 fault_flags |= FAULT_FLAG_TRIED;
1234                 goto retry;
1235         }
1236
1237         return 0;
1238 }
1239 EXPORT_SYMBOL_GPL(fixup_user_fault);
1240
1241 /*
1242  * Please note that this function, unlike __get_user_pages will not
1243  * return 0 for nr_pages > 0 without FOLL_NOWAIT
1244  */
1245 static __always_inline long __get_user_pages_locked(struct mm_struct *mm,
1246                                                 unsigned long start,
1247                                                 unsigned long nr_pages,
1248                                                 struct page **pages,
1249                                                 struct vm_area_struct **vmas,
1250                                                 int *locked,
1251                                                 unsigned int flags)
1252 {
1253         long ret, pages_done;
1254         bool lock_dropped;
1255
1256         if (locked) {
1257                 /* if VM_FAULT_RETRY can be returned, vmas become invalid */
1258                 BUG_ON(vmas);
1259                 /* check caller initialized locked */
1260                 BUG_ON(*locked != 1);
1261         }
1262
1263         if (flags & FOLL_PIN)
1264                 atomic_set(&mm->has_pinned, 1);
1265
1266         /*
1267          * FOLL_PIN and FOLL_GET are mutually exclusive. Traditional behavior
1268          * is to set FOLL_GET if the caller wants pages[] filled in (but has
1269          * carelessly failed to specify FOLL_GET), so keep doing that, but only
1270          * for FOLL_GET, not for the newer FOLL_PIN.
1271          *
1272          * FOLL_PIN always expects pages to be non-null, but no need to assert
1273          * that here, as any failures will be obvious enough.
1274          */
1275         if (pages && !(flags & FOLL_PIN))
1276                 flags |= FOLL_GET;
1277
1278         pages_done = 0;
1279         lock_dropped = false;
1280         for (;;) {
1281                 ret = __get_user_pages(mm, start, nr_pages, flags, pages,
1282                                        vmas, locked);
1283                 if (!locked)
1284                         /* VM_FAULT_RETRY couldn't trigger, bypass */
1285                         return ret;
1286
1287                 /* VM_FAULT_RETRY cannot return errors */
1288                 if (!*locked) {
1289                         BUG_ON(ret < 0);
1290                         BUG_ON(ret >= nr_pages);
1291                 }
1292
1293                 if (ret > 0) {
1294                         nr_pages -= ret;
1295                         pages_done += ret;
1296                         if (!nr_pages)
1297                                 break;
1298                 }
1299                 if (*locked) {
1300                         /*
1301                          * VM_FAULT_RETRY didn't trigger or it was a
1302                          * FOLL_NOWAIT.
1303                          */
1304                         if (!pages_done)
1305                                 pages_done = ret;
1306                         break;
1307                 }
1308                 /*
1309                  * VM_FAULT_RETRY triggered, so seek to the faulting offset.
1310                  * For the prefault case (!pages) we only update counts.
1311                  */
1312                 if (likely(pages))
1313                         pages += ret;
1314                 start += ret << PAGE_SHIFT;
1315                 lock_dropped = true;
1316
1317 retry:
1318                 /*
1319                  * Repeat on the address that fired VM_FAULT_RETRY
1320                  * with both FAULT_FLAG_ALLOW_RETRY and
1321                  * FAULT_FLAG_TRIED.  Note that GUP can be interrupted
1322                  * by fatal signals, so we need to check it before we
1323                  * start trying again otherwise it can loop forever.
1324                  */
1325
1326                 if (fatal_signal_pending(current)) {
1327                         if (!pages_done)
1328                                 pages_done = -EINTR;
1329                         break;
1330                 }
1331
1332                 ret = mmap_read_lock_killable(mm);
1333                 if (ret) {
1334                         BUG_ON(ret > 0);
1335                         if (!pages_done)
1336                                 pages_done = ret;
1337                         break;
1338                 }
1339
1340                 *locked = 1;
1341                 ret = __get_user_pages(mm, start, 1, flags | FOLL_TRIED,
1342                                        pages, NULL, locked);
1343                 if (!*locked) {
1344                         /* Continue to retry until we succeeded */
1345                         BUG_ON(ret != 0);
1346                         goto retry;
1347                 }
1348                 if (ret != 1) {
1349                         BUG_ON(ret > 1);
1350                         if (!pages_done)
1351                                 pages_done = ret;
1352                         break;
1353                 }
1354                 nr_pages--;
1355                 pages_done++;
1356                 if (!nr_pages)
1357                         break;
1358                 if (likely(pages))
1359                         pages++;
1360                 start += PAGE_SIZE;
1361         }
1362         if (lock_dropped && *locked) {
1363                 /*
1364                  * We must let the caller know we temporarily dropped the lock
1365                  * and so the critical section protected by it was lost.
1366                  */
1367                 mmap_read_unlock(mm);
1368                 *locked = 0;
1369         }
1370         return pages_done;
1371 }
1372
1373 /**
1374  * populate_vma_page_range() -  populate a range of pages in the vma.
1375  * @vma:   target vma
1376  * @start: start address
1377  * @end:   end address
1378  * @locked: whether the mmap_lock is still held
1379  *
1380  * This takes care of mlocking the pages too if VM_LOCKED is set.
1381  *
1382  * Return either number of pages pinned in the vma, or a negative error
1383  * code on error.
1384  *
1385  * vma->vm_mm->mmap_lock must be held.
1386  *
1387  * If @locked is NULL, it may be held for read or write and will
1388  * be unperturbed.
1389  *
1390  * If @locked is non-NULL, it must held for read only and may be
1391  * released.  If it's released, *@locked will be set to 0.
1392  */
1393 long populate_vma_page_range(struct vm_area_struct *vma,
1394                 unsigned long start, unsigned long end, int *locked)
1395 {
1396         struct mm_struct *mm = vma->vm_mm;
1397         unsigned long nr_pages = (end - start) / PAGE_SIZE;
1398         int gup_flags;
1399
1400         VM_BUG_ON(start & ~PAGE_MASK);
1401         VM_BUG_ON(end   & ~PAGE_MASK);
1402         VM_BUG_ON_VMA(start < vma->vm_start, vma);
1403         VM_BUG_ON_VMA(end   > vma->vm_end, vma);
1404         mmap_assert_locked(mm);
1405
1406         gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK;
1407         if (vma->vm_flags & VM_LOCKONFAULT)
1408                 gup_flags &= ~FOLL_POPULATE;
1409         /*
1410          * We want to touch writable mappings with a write fault in order
1411          * to break COW, except for shared mappings because these don't COW
1412          * and we would not want to dirty them for nothing.
1413          */
1414         if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
1415                 gup_flags |= FOLL_WRITE;
1416
1417         /*
1418          * We want mlock to succeed for regions that have any permissions
1419          * other than PROT_NONE.
1420          */
1421         if (vma_is_accessible(vma))
1422                 gup_flags |= FOLL_FORCE;
1423
1424         /*
1425          * We made sure addr is within a VMA, so the following will
1426          * not result in a stack expansion that recurses back here.
1427          */
1428         return __get_user_pages(mm, start, nr_pages, gup_flags,
1429                                 NULL, NULL, locked);
1430 }
1431
1432 /*
1433  * __mm_populate - populate and/or mlock pages within a range of address space.
1434  *
1435  * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
1436  * flags. VMAs must be already marked with the desired vm_flags, and
1437  * mmap_lock must not be held.
1438  */
1439 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
1440 {
1441         struct mm_struct *mm = current->mm;
1442         unsigned long end, nstart, nend;
1443         struct vm_area_struct *vma = NULL;
1444         int locked = 0;
1445         long ret = 0;
1446
1447         end = start + len;
1448
1449         for (nstart = start; nstart < end; nstart = nend) {
1450                 /*
1451                  * We want to fault in pages for [nstart; end) address range.
1452                  * Find first corresponding VMA.
1453                  */
1454                 if (!locked) {
1455                         locked = 1;
1456                         mmap_read_lock(mm);
1457                         vma = find_vma(mm, nstart);
1458                 } else if (nstart >= vma->vm_end)
1459                         vma = vma->vm_next;
1460                 if (!vma || vma->vm_start >= end)
1461                         break;
1462                 /*
1463                  * Set [nstart; nend) to intersection of desired address
1464                  * range with the first VMA. Also, skip undesirable VMA types.
1465                  */
1466                 nend = min(end, vma->vm_end);
1467                 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1468                         continue;
1469                 if (nstart < vma->vm_start)
1470                         nstart = vma->vm_start;
1471                 /*
1472                  * Now fault in a range of pages. populate_vma_page_range()
1473                  * double checks the vma flags, so that it won't mlock pages
1474                  * if the vma was already munlocked.
1475                  */
1476                 ret = populate_vma_page_range(vma, nstart, nend, &locked);
1477                 if (ret < 0) {
1478                         if (ignore_errors) {
1479                                 ret = 0;
1480                                 continue;       /* continue at next VMA */
1481                         }
1482                         break;
1483                 }
1484                 nend = nstart + ret * PAGE_SIZE;
1485                 ret = 0;
1486         }
1487         if (locked)
1488                 mmap_read_unlock(mm);
1489         return ret;     /* 0 or negative error code */
1490 }
1491 #else /* CONFIG_MMU */
1492 static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start,
1493                 unsigned long nr_pages, struct page **pages,
1494                 struct vm_area_struct **vmas, int *locked,
1495                 unsigned int foll_flags)
1496 {
1497         struct vm_area_struct *vma;
1498         unsigned long vm_flags;
1499         int i;
1500
1501         /* calculate required read or write permissions.
1502          * If FOLL_FORCE is set, we only require the "MAY" flags.
1503          */
1504         vm_flags  = (foll_flags & FOLL_WRITE) ?
1505                         (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
1506         vm_flags &= (foll_flags & FOLL_FORCE) ?
1507                         (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
1508
1509         for (i = 0; i < nr_pages; i++) {
1510                 vma = find_vma(mm, start);
1511                 if (!vma)
1512                         goto finish_or_fault;
1513
1514                 /* protect what we can, including chardevs */
1515                 if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
1516                     !(vm_flags & vma->vm_flags))
1517                         goto finish_or_fault;
1518
1519                 if (pages) {
1520                         pages[i] = virt_to_page(start);
1521                         if (pages[i])
1522                                 get_page(pages[i]);
1523                 }
1524                 if (vmas)
1525                         vmas[i] = vma;
1526                 start = (start + PAGE_SIZE) & PAGE_MASK;
1527         }
1528
1529         return i;
1530
1531 finish_or_fault:
1532         return i ? : -EFAULT;
1533 }
1534 #endif /* !CONFIG_MMU */
1535
1536 /**
1537  * get_dump_page() - pin user page in memory while writing it to core dump
1538  * @addr: user address
1539  *
1540  * Returns struct page pointer of user page pinned for dump,
1541  * to be freed afterwards by put_page().
1542  *
1543  * Returns NULL on any kind of failure - a hole must then be inserted into
1544  * the corefile, to preserve alignment with its headers; and also returns
1545  * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
1546  * allowing a hole to be left in the corefile to save diskspace.
1547  *
1548  * Called without mmap_lock (takes and releases the mmap_lock by itself).
1549  */
1550 #ifdef CONFIG_ELF_CORE
1551 struct page *get_dump_page(unsigned long addr)
1552 {
1553         struct mm_struct *mm = current->mm;
1554         struct page *page;
1555         int locked = 1;
1556         int ret;
1557
1558         if (mmap_read_lock_killable(mm))
1559                 return NULL;
1560         ret = __get_user_pages_locked(mm, addr, 1, &page, NULL, &locked,
1561                                       FOLL_FORCE | FOLL_DUMP | FOLL_GET);
1562         if (locked)
1563                 mmap_read_unlock(mm);
1564         return (ret == 1) ? page : NULL;
1565 }
1566 #endif /* CONFIG_ELF_CORE */
1567
1568 #if defined(CONFIG_FS_DAX) || defined (CONFIG_CMA)
1569 static bool check_dax_vmas(struct vm_area_struct **vmas, long nr_pages)
1570 {
1571         long i;
1572         struct vm_area_struct *vma_prev = NULL;
1573
1574         for (i = 0; i < nr_pages; i++) {
1575                 struct vm_area_struct *vma = vmas[i];
1576
1577                 if (vma == vma_prev)
1578                         continue;
1579
1580                 vma_prev = vma;
1581
1582                 if (vma_is_fsdax(vma))
1583                         return true;
1584         }
1585         return false;
1586 }
1587
1588 #ifdef CONFIG_CMA
1589 static long check_and_migrate_cma_pages(struct mm_struct *mm,
1590                                         unsigned long start,
1591                                         unsigned long nr_pages,
1592                                         struct page **pages,
1593                                         struct vm_area_struct **vmas,
1594                                         unsigned int gup_flags)
1595 {
1596         unsigned long i, isolation_error_count;
1597         bool drain_allow;
1598         LIST_HEAD(cma_page_list);
1599         long ret = nr_pages;
1600         struct page *prev_head, *head;
1601         struct migration_target_control mtc = {
1602                 .nid = NUMA_NO_NODE,
1603                 .gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_NOWARN,
1604         };
1605
1606 check_again:
1607         prev_head = NULL;
1608         isolation_error_count = 0;
1609         drain_allow = true;
1610         for (i = 0; i < nr_pages; i++) {
1611                 head = compound_head(pages[i]);
1612                 if (head == prev_head)
1613                         continue;
1614                 prev_head = head;
1615                 /*
1616                  * If we get a page from the CMA zone, since we are going to
1617                  * be pinning these entries, we might as well move them out
1618                  * of the CMA zone if possible.
1619                  */
1620                 if (is_migrate_cma_page(head)) {
1621                         if (PageHuge(head)) {
1622                                 if (!isolate_huge_page(head, &cma_page_list))
1623                                         isolation_error_count++;
1624                         } else {
1625                                 if (!PageLRU(head) && drain_allow) {
1626                                         lru_add_drain_all();
1627                                         drain_allow = false;
1628                                 }
1629
1630                                 if (isolate_lru_page(head)) {
1631                                         isolation_error_count++;
1632                                         continue;
1633                                 }
1634                                 list_add_tail(&head->lru, &cma_page_list);
1635                                 mod_node_page_state(page_pgdat(head),
1636                                                     NR_ISOLATED_ANON +
1637                                                     page_is_file_lru(head),
1638                                                     thp_nr_pages(head));
1639                         }
1640                 }
1641         }
1642
1643         /*
1644          * If list is empty, and no isolation errors, means that all pages are
1645          * in the correct zone.
1646          */
1647         if (list_empty(&cma_page_list) && !isolation_error_count)
1648                 return ret;
1649
1650         if (!list_empty(&cma_page_list)) {
1651                 /*
1652                  * drop the above get_user_pages reference.
1653                  */
1654                 if (gup_flags & FOLL_PIN)
1655                         unpin_user_pages(pages, nr_pages);
1656                 else
1657                         for (i = 0; i < nr_pages; i++)
1658                                 put_page(pages[i]);
1659
1660                 ret = migrate_pages(&cma_page_list, alloc_migration_target,
1661                                     NULL, (unsigned long)&mtc, MIGRATE_SYNC,
1662                                     MR_CONTIG_RANGE);
1663                 if (ret) {
1664                         if (!list_empty(&cma_page_list))
1665                                 putback_movable_pages(&cma_page_list);
1666                         return ret > 0 ? -ENOMEM : ret;
1667                 }
1668
1669                 /* We unpinned pages before migration, pin them again */
1670                 ret = __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1671                                               NULL, gup_flags);
1672                 if (ret <= 0)
1673                         return ret;
1674                 nr_pages = ret;
1675         }
1676
1677         /*
1678          * check again because pages were unpinned, and we also might have
1679          * had isolation errors and need more pages to migrate.
1680          */
1681         goto check_again;
1682 }
1683 #else
1684 static long check_and_migrate_cma_pages(struct mm_struct *mm,
1685                                         unsigned long start,
1686                                         unsigned long nr_pages,
1687                                         struct page **pages,
1688                                         struct vm_area_struct **vmas,
1689                                         unsigned int gup_flags)
1690 {
1691         return nr_pages;
1692 }
1693 #endif /* CONFIG_CMA */
1694
1695 /*
1696  * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
1697  * allows us to process the FOLL_LONGTERM flag.
1698  */
1699 static long __gup_longterm_locked(struct mm_struct *mm,
1700                                   unsigned long start,
1701                                   unsigned long nr_pages,
1702                                   struct page **pages,
1703                                   struct vm_area_struct **vmas,
1704                                   unsigned int gup_flags)
1705 {
1706         struct vm_area_struct **vmas_tmp = vmas;
1707         unsigned long flags = 0;
1708         long rc, i;
1709
1710         if (gup_flags & FOLL_LONGTERM) {
1711                 if (!pages)
1712                         return -EINVAL;
1713
1714                 if (!vmas_tmp) {
1715                         vmas_tmp = kcalloc(nr_pages,
1716                                            sizeof(struct vm_area_struct *),
1717                                            GFP_KERNEL);
1718                         if (!vmas_tmp)
1719                                 return -ENOMEM;
1720                 }
1721                 flags = memalloc_nocma_save();
1722         }
1723
1724         rc = __get_user_pages_locked(mm, start, nr_pages, pages,
1725                                      vmas_tmp, NULL, gup_flags);
1726
1727         if (gup_flags & FOLL_LONGTERM) {
1728                 if (rc < 0)
1729                         goto out;
1730
1731                 if (check_dax_vmas(vmas_tmp, rc)) {
1732                         if (gup_flags & FOLL_PIN)
1733                                 unpin_user_pages(pages, rc);
1734                         else
1735                                 for (i = 0; i < rc; i++)
1736                                         put_page(pages[i]);
1737                         rc = -EOPNOTSUPP;
1738                         goto out;
1739                 }
1740
1741                 rc = check_and_migrate_cma_pages(mm, start, rc, pages,
1742                                                  vmas_tmp, gup_flags);
1743 out:
1744                 memalloc_nocma_restore(flags);
1745         }
1746
1747         if (vmas_tmp != vmas)
1748                 kfree(vmas_tmp);
1749         return rc;
1750 }
1751 #else /* !CONFIG_FS_DAX && !CONFIG_CMA */
1752 static __always_inline long __gup_longterm_locked(struct mm_struct *mm,
1753                                                   unsigned long start,
1754                                                   unsigned long nr_pages,
1755                                                   struct page **pages,
1756                                                   struct vm_area_struct **vmas,
1757                                                   unsigned int flags)
1758 {
1759         return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1760                                        NULL, flags);
1761 }
1762 #endif /* CONFIG_FS_DAX || CONFIG_CMA */
1763
1764 static bool is_valid_gup_flags(unsigned int gup_flags)
1765 {
1766         /*
1767          * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
1768          * never directly by the caller, so enforce that with an assertion:
1769          */
1770         if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
1771                 return false;
1772         /*
1773          * FOLL_PIN is a prerequisite to FOLL_LONGTERM. Another way of saying
1774          * that is, FOLL_LONGTERM is a specific case, more restrictive case of
1775          * FOLL_PIN.
1776          */
1777         if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1778                 return false;
1779
1780         return true;
1781 }
1782
1783 #ifdef CONFIG_MMU
1784 static long __get_user_pages_remote(struct mm_struct *mm,
1785                                     unsigned long start, unsigned long nr_pages,
1786                                     unsigned int gup_flags, struct page **pages,
1787                                     struct vm_area_struct **vmas, int *locked)
1788 {
1789         /*
1790          * Parts of FOLL_LONGTERM behavior are incompatible with
1791          * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1792          * vmas. However, this only comes up if locked is set, and there are
1793          * callers that do request FOLL_LONGTERM, but do not set locked. So,
1794          * allow what we can.
1795          */
1796         if (gup_flags & FOLL_LONGTERM) {
1797                 if (WARN_ON_ONCE(locked))
1798                         return -EINVAL;
1799                 /*
1800                  * This will check the vmas (even if our vmas arg is NULL)
1801                  * and return -ENOTSUPP if DAX isn't allowed in this case:
1802                  */
1803                 return __gup_longterm_locked(mm, start, nr_pages, pages,
1804                                              vmas, gup_flags | FOLL_TOUCH |
1805                                              FOLL_REMOTE);
1806         }
1807
1808         return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1809                                        locked,
1810                                        gup_flags | FOLL_TOUCH | FOLL_REMOTE);
1811 }
1812
1813 /**
1814  * get_user_pages_remote() - pin user pages in memory
1815  * @mm:         mm_struct of target mm
1816  * @start:      starting user address
1817  * @nr_pages:   number of pages from start to pin
1818  * @gup_flags:  flags modifying lookup behaviour
1819  * @pages:      array that receives pointers to the pages pinned.
1820  *              Should be at least nr_pages long. Or NULL, if caller
1821  *              only intends to ensure the pages are faulted in.
1822  * @vmas:       array of pointers to vmas corresponding to each page.
1823  *              Or NULL if the caller does not require them.
1824  * @locked:     pointer to lock flag indicating whether lock is held and
1825  *              subsequently whether VM_FAULT_RETRY functionality can be
1826  *              utilised. Lock must initially be held.
1827  *
1828  * Returns either number of pages pinned (which may be less than the
1829  * number requested), or an error. Details about the return value:
1830  *
1831  * -- If nr_pages is 0, returns 0.
1832  * -- If nr_pages is >0, but no pages were pinned, returns -errno.
1833  * -- If nr_pages is >0, and some pages were pinned, returns the number of
1834  *    pages pinned. Again, this may be less than nr_pages.
1835  *
1836  * The caller is responsible for releasing returned @pages, via put_page().
1837  *
1838  * @vmas are valid only as long as mmap_lock is held.
1839  *
1840  * Must be called with mmap_lock held for read or write.
1841  *
1842  * get_user_pages_remote walks a process's page tables and takes a reference
1843  * to each struct page that each user address corresponds to at a given
1844  * instant. That is, it takes the page that would be accessed if a user
1845  * thread accesses the given user virtual address at that instant.
1846  *
1847  * This does not guarantee that the page exists in the user mappings when
1848  * get_user_pages_remote returns, and there may even be a completely different
1849  * page there in some cases (eg. if mmapped pagecache has been invalidated
1850  * and subsequently re faulted). However it does guarantee that the page
1851  * won't be freed completely. And mostly callers simply care that the page
1852  * contains data that was valid *at some point in time*. Typically, an IO
1853  * or similar operation cannot guarantee anything stronger anyway because
1854  * locks can't be held over the syscall boundary.
1855  *
1856  * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
1857  * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
1858  * be called after the page is finished with, and before put_page is called.
1859  *
1860  * get_user_pages_remote is typically used for fewer-copy IO operations,
1861  * to get a handle on the memory by some means other than accesses
1862  * via the user virtual addresses. The pages may be submitted for
1863  * DMA to devices or accessed via their kernel linear mapping (via the
1864  * kmap APIs). Care should be taken to use the correct cache flushing APIs.
1865  *
1866  * See also get_user_pages_fast, for performance critical applications.
1867  *
1868  * get_user_pages_remote should be phased out in favor of
1869  * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
1870  * should use get_user_pages_remote because it cannot pass
1871  * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
1872  */
1873 long get_user_pages_remote(struct mm_struct *mm,
1874                 unsigned long start, unsigned long nr_pages,
1875                 unsigned int gup_flags, struct page **pages,
1876                 struct vm_area_struct **vmas, int *locked)
1877 {
1878         if (!is_valid_gup_flags(gup_flags))
1879                 return -EINVAL;
1880
1881         return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
1882                                        pages, vmas, locked);
1883 }
1884 EXPORT_SYMBOL(get_user_pages_remote);
1885
1886 #else /* CONFIG_MMU */
1887 long get_user_pages_remote(struct mm_struct *mm,
1888                            unsigned long start, unsigned long nr_pages,
1889                            unsigned int gup_flags, struct page **pages,
1890                            struct vm_area_struct **vmas, int *locked)
1891 {
1892         return 0;
1893 }
1894
1895 static long __get_user_pages_remote(struct mm_struct *mm,
1896                                     unsigned long start, unsigned long nr_pages,
1897                                     unsigned int gup_flags, struct page **pages,
1898                                     struct vm_area_struct **vmas, int *locked)
1899 {
1900         return 0;
1901 }
1902 #endif /* !CONFIG_MMU */
1903
1904 /**
1905  * get_user_pages() - pin user pages in memory
1906  * @start:      starting user address
1907  * @nr_pages:   number of pages from start to pin
1908  * @gup_flags:  flags modifying lookup behaviour
1909  * @pages:      array that receives pointers to the pages pinned.
1910  *              Should be at least nr_pages long. Or NULL, if caller
1911  *              only intends to ensure the pages are faulted in.
1912  * @vmas:       array of pointers to vmas corresponding to each page.
1913  *              Or NULL if the caller does not require them.
1914  *
1915  * This is the same as get_user_pages_remote(), just with a less-flexible
1916  * calling convention where we assume that the mm being operated on belongs to
1917  * the current task, and doesn't allow passing of a locked parameter.  We also
1918  * obviously don't pass FOLL_REMOTE in here.
1919  */
1920 long get_user_pages(unsigned long start, unsigned long nr_pages,
1921                 unsigned int gup_flags, struct page **pages,
1922                 struct vm_area_struct **vmas)
1923 {
1924         if (!is_valid_gup_flags(gup_flags))
1925                 return -EINVAL;
1926
1927         return __gup_longterm_locked(current->mm, start, nr_pages,
1928                                      pages, vmas, gup_flags | FOLL_TOUCH);
1929 }
1930 EXPORT_SYMBOL(get_user_pages);
1931
1932 /**
1933  * get_user_pages_locked() is suitable to replace the form:
1934  *
1935  *      mmap_read_lock(mm);
1936  *      do_something()
1937  *      get_user_pages(mm, ..., pages, NULL);
1938  *      mmap_read_unlock(mm);
1939  *
1940  *  to:
1941  *
1942  *      int locked = 1;
1943  *      mmap_read_lock(mm);
1944  *      do_something()
1945  *      get_user_pages_locked(mm, ..., pages, &locked);
1946  *      if (locked)
1947  *          mmap_read_unlock(mm);
1948  *
1949  * @start:      starting user address
1950  * @nr_pages:   number of pages from start to pin
1951  * @gup_flags:  flags modifying lookup behaviour
1952  * @pages:      array that receives pointers to the pages pinned.
1953  *              Should be at least nr_pages long. Or NULL, if caller
1954  *              only intends to ensure the pages are faulted in.
1955  * @locked:     pointer to lock flag indicating whether lock is held and
1956  *              subsequently whether VM_FAULT_RETRY functionality can be
1957  *              utilised. Lock must initially be held.
1958  *
1959  * We can leverage the VM_FAULT_RETRY functionality in the page fault
1960  * paths better by using either get_user_pages_locked() or
1961  * get_user_pages_unlocked().
1962  *
1963  */
1964 long get_user_pages_locked(unsigned long start, unsigned long nr_pages,
1965                            unsigned int gup_flags, struct page **pages,
1966                            int *locked)
1967 {
1968         /*
1969          * FIXME: Current FOLL_LONGTERM behavior is incompatible with
1970          * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1971          * vmas.  As there are no users of this flag in this call we simply
1972          * disallow this option for now.
1973          */
1974         if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1975                 return -EINVAL;
1976         /*
1977          * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
1978          * never directly by the caller, so enforce that:
1979          */
1980         if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
1981                 return -EINVAL;
1982
1983         return __get_user_pages_locked(current->mm, start, nr_pages,
1984                                        pages, NULL, locked,
1985                                        gup_flags | FOLL_TOUCH);
1986 }
1987 EXPORT_SYMBOL(get_user_pages_locked);
1988
1989 /*
1990  * get_user_pages_unlocked() is suitable to replace the form:
1991  *
1992  *      mmap_read_lock(mm);
1993  *      get_user_pages(mm, ..., pages, NULL);
1994  *      mmap_read_unlock(mm);
1995  *
1996  *  with:
1997  *
1998  *      get_user_pages_unlocked(mm, ..., pages);
1999  *
2000  * It is functionally equivalent to get_user_pages_fast so
2001  * get_user_pages_fast should be used instead if specific gup_flags
2002  * (e.g. FOLL_FORCE) are not required.
2003  */
2004 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
2005                              struct page **pages, unsigned int gup_flags)
2006 {
2007         struct mm_struct *mm = current->mm;
2008         int locked = 1;
2009         long ret;
2010
2011         /*
2012          * FIXME: Current FOLL_LONGTERM behavior is incompatible with
2013          * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2014          * vmas.  As there are no users of this flag in this call we simply
2015          * disallow this option for now.
2016          */
2017         if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
2018                 return -EINVAL;
2019
2020         mmap_read_lock(mm);
2021         ret = __get_user_pages_locked(mm, start, nr_pages, pages, NULL,
2022                                       &locked, gup_flags | FOLL_TOUCH);
2023         if (locked)
2024                 mmap_read_unlock(mm);
2025         return ret;
2026 }
2027 EXPORT_SYMBOL(get_user_pages_unlocked);
2028
2029 /*
2030  * Fast GUP
2031  *
2032  * get_user_pages_fast attempts to pin user pages by walking the page
2033  * tables directly and avoids taking locks. Thus the walker needs to be
2034  * protected from page table pages being freed from under it, and should
2035  * block any THP splits.
2036  *
2037  * One way to achieve this is to have the walker disable interrupts, and
2038  * rely on IPIs from the TLB flushing code blocking before the page table
2039  * pages are freed. This is unsuitable for architectures that do not need
2040  * to broadcast an IPI when invalidating TLBs.
2041  *
2042  * Another way to achieve this is to batch up page table containing pages
2043  * belonging to more than one mm_user, then rcu_sched a callback to free those
2044  * pages. Disabling interrupts will allow the fast_gup walker to both block
2045  * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
2046  * (which is a relatively rare event). The code below adopts this strategy.
2047  *
2048  * Before activating this code, please be aware that the following assumptions
2049  * are currently made:
2050  *
2051  *  *) Either MMU_GATHER_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
2052  *  free pages containing page tables or TLB flushing requires IPI broadcast.
2053  *
2054  *  *) ptes can be read atomically by the architecture.
2055  *
2056  *  *) access_ok is sufficient to validate userspace address ranges.
2057  *
2058  * The last two assumptions can be relaxed by the addition of helper functions.
2059  *
2060  * This code is based heavily on the PowerPC implementation by Nick Piggin.
2061  */
2062 #ifdef CONFIG_HAVE_FAST_GUP
2063 #ifdef CONFIG_GUP_GET_PTE_LOW_HIGH
2064
2065 /*
2066  * WARNING: only to be used in the get_user_pages_fast() implementation.
2067  *
2068  * With get_user_pages_fast(), we walk down the pagetables without taking any
2069  * locks.  For this we would like to load the pointers atomically, but sometimes
2070  * that is not possible (e.g. without expensive cmpxchg8b on x86_32 PAE).  What
2071  * we do have is the guarantee that a PTE will only either go from not present
2072  * to present, or present to not present or both -- it will not switch to a
2073  * completely different present page without a TLB flush in between; something
2074  * that we are blocking by holding interrupts off.
2075  *
2076  * Setting ptes from not present to present goes:
2077  *
2078  *   ptep->pte_high = h;
2079  *   smp_wmb();
2080  *   ptep->pte_low = l;
2081  *
2082  * And present to not present goes:
2083  *
2084  *   ptep->pte_low = 0;
2085  *   smp_wmb();
2086  *   ptep->pte_high = 0;
2087  *
2088  * We must ensure here that the load of pte_low sees 'l' IFF pte_high sees 'h'.
2089  * We load pte_high *after* loading pte_low, which ensures we don't see an older
2090  * value of pte_high.  *Then* we recheck pte_low, which ensures that we haven't
2091  * picked up a changed pte high. We might have gotten rubbish values from
2092  * pte_low and pte_high, but we are guaranteed that pte_low will not have the
2093  * present bit set *unless* it is 'l'. Because get_user_pages_fast() only
2094  * operates on present ptes we're safe.
2095  */
2096 static inline pte_t gup_get_pte(pte_t *ptep)
2097 {
2098         pte_t pte;
2099
2100         do {
2101                 pte.pte_low = ptep->pte_low;
2102                 smp_rmb();
2103                 pte.pte_high = ptep->pte_high;
2104                 smp_rmb();
2105         } while (unlikely(pte.pte_low != ptep->pte_low));
2106
2107         return pte;
2108 }
2109 #else /* CONFIG_GUP_GET_PTE_LOW_HIGH */
2110 /*
2111  * We require that the PTE can be read atomically.
2112  */
2113 static inline pte_t gup_get_pte(pte_t *ptep)
2114 {
2115         return ptep_get(ptep);
2116 }
2117 #endif /* CONFIG_GUP_GET_PTE_LOW_HIGH */
2118
2119 static void __maybe_unused undo_dev_pagemap(int *nr, int nr_start,
2120                                             unsigned int flags,
2121                                             struct page **pages)
2122 {
2123         while ((*nr) - nr_start) {
2124                 struct page *page = pages[--(*nr)];
2125
2126                 ClearPageReferenced(page);
2127                 if (flags & FOLL_PIN)
2128                         unpin_user_page(page);
2129                 else
2130                         put_page(page);
2131         }
2132 }
2133
2134 #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
2135 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2136                          unsigned int flags, struct page **pages, int *nr)
2137 {
2138         struct dev_pagemap *pgmap = NULL;
2139         int nr_start = *nr, ret = 0;
2140         pte_t *ptep, *ptem;
2141
2142         ptem = ptep = pte_offset_map(&pmd, addr);
2143         do {
2144                 pte_t pte = gup_get_pte(ptep);
2145                 struct page *head, *page;
2146
2147                 /*
2148                  * Similar to the PMD case below, NUMA hinting must take slow
2149                  * path using the pte_protnone check.
2150                  */
2151                 if (pte_protnone(pte))
2152                         goto pte_unmap;
2153
2154                 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2155                         goto pte_unmap;
2156
2157                 if (pte_devmap(pte)) {
2158                         if (unlikely(flags & FOLL_LONGTERM))
2159                                 goto pte_unmap;
2160
2161                         pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
2162                         if (unlikely(!pgmap)) {
2163                                 undo_dev_pagemap(nr, nr_start, flags, pages);
2164                                 goto pte_unmap;
2165                         }
2166                 } else if (pte_special(pte))
2167                         goto pte_unmap;
2168
2169                 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2170                 page = pte_page(pte);
2171
2172                 head = try_grab_compound_head(page, 1, flags);
2173                 if (!head)
2174                         goto pte_unmap;
2175
2176                 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2177                         put_compound_head(head, 1, flags);
2178                         goto pte_unmap;
2179                 }
2180
2181                 VM_BUG_ON_PAGE(compound_head(page) != head, page);
2182
2183                 /*
2184                  * We need to make the page accessible if and only if we are
2185                  * going to access its content (the FOLL_PIN case).  Please
2186                  * see Documentation/core-api/pin_user_pages.rst for
2187                  * details.
2188                  */
2189                 if (flags & FOLL_PIN) {
2190                         ret = arch_make_page_accessible(page);
2191                         if (ret) {
2192                                 unpin_user_page(page);
2193                                 goto pte_unmap;
2194                         }
2195                 }
2196                 SetPageReferenced(page);
2197                 pages[*nr] = page;
2198                 (*nr)++;
2199
2200         } while (ptep++, addr += PAGE_SIZE, addr != end);
2201
2202         ret = 1;
2203
2204 pte_unmap:
2205         if (pgmap)
2206                 put_dev_pagemap(pgmap);
2207         pte_unmap(ptem);
2208         return ret;
2209 }
2210 #else
2211
2212 /*
2213  * If we can't determine whether or not a pte is special, then fail immediately
2214  * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
2215  * to be special.
2216  *
2217  * For a futex to be placed on a THP tail page, get_futex_key requires a
2218  * get_user_pages_fast_only implementation that can pin pages. Thus it's still
2219  * useful to have gup_huge_pmd even if we can't operate on ptes.
2220  */
2221 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2222                          unsigned int flags, struct page **pages, int *nr)
2223 {
2224         return 0;
2225 }
2226 #endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
2227
2228 #if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
2229 static int __gup_device_huge(unsigned long pfn, unsigned long addr,
2230                              unsigned long end, unsigned int flags,
2231                              struct page **pages, int *nr)
2232 {
2233         int nr_start = *nr;
2234         struct dev_pagemap *pgmap = NULL;
2235
2236         do {
2237                 struct page *page = pfn_to_page(pfn);
2238
2239                 pgmap = get_dev_pagemap(pfn, pgmap);
2240                 if (unlikely(!pgmap)) {
2241                         undo_dev_pagemap(nr, nr_start, flags, pages);
2242                         return 0;
2243                 }
2244                 SetPageReferenced(page);
2245                 pages[*nr] = page;
2246                 if (unlikely(!try_grab_page(page, flags))) {
2247                         undo_dev_pagemap(nr, nr_start, flags, pages);
2248                         return 0;
2249                 }
2250                 (*nr)++;
2251                 pfn++;
2252         } while (addr += PAGE_SIZE, addr != end);
2253
2254         if (pgmap)
2255                 put_dev_pagemap(pgmap);
2256         return 1;
2257 }
2258
2259 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2260                                  unsigned long end, unsigned int flags,
2261                                  struct page **pages, int *nr)
2262 {
2263         unsigned long fault_pfn;
2264         int nr_start = *nr;
2265
2266         fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2267         if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2268                 return 0;
2269
2270         if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2271                 undo_dev_pagemap(nr, nr_start, flags, pages);
2272                 return 0;
2273         }
2274         return 1;
2275 }
2276
2277 static int __gup_device_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2278                                  unsigned long end, unsigned int flags,
2279                                  struct page **pages, int *nr)
2280 {
2281         unsigned long fault_pfn;
2282         int nr_start = *nr;
2283
2284         fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2285         if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2286                 return 0;
2287
2288         if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2289                 undo_dev_pagemap(nr, nr_start, flags, pages);
2290                 return 0;
2291         }
2292         return 1;
2293 }
2294 #else
2295 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2296                                  unsigned long end, unsigned int flags,
2297                                  struct page **pages, int *nr)
2298 {
2299         BUILD_BUG();
2300         return 0;
2301 }
2302
2303 static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr,
2304                                  unsigned long end, unsigned int flags,
2305                                  struct page **pages, int *nr)
2306 {
2307         BUILD_BUG();
2308         return 0;
2309 }
2310 #endif
2311
2312 static int record_subpages(struct page *page, unsigned long addr,
2313                            unsigned long end, struct page **pages)
2314 {
2315         int nr;
2316
2317         for (nr = 0; addr != end; addr += PAGE_SIZE)
2318                 pages[nr++] = page++;
2319
2320         return nr;
2321 }
2322
2323 #ifdef CONFIG_ARCH_HAS_HUGEPD
2324 static unsigned long hugepte_addr_end(unsigned long addr, unsigned long end,
2325                                       unsigned long sz)
2326 {
2327         unsigned long __boundary = (addr + sz) & ~(sz-1);
2328         return (__boundary - 1 < end - 1) ? __boundary : end;
2329 }
2330
2331 static int gup_hugepte(pte_t *ptep, unsigned long sz, unsigned long addr,
2332                        unsigned long end, unsigned int flags,
2333                        struct page **pages, int *nr)
2334 {
2335         unsigned long pte_end;
2336         struct page *head, *page;
2337         pte_t pte;
2338         int refs;
2339
2340         pte_end = (addr + sz) & ~(sz-1);
2341         if (pte_end < end)
2342                 end = pte_end;
2343
2344         pte = huge_ptep_get(ptep);
2345
2346         if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2347                 return 0;
2348
2349         /* hugepages are never "special" */
2350         VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2351
2352         head = pte_page(pte);
2353         page = head + ((addr & (sz-1)) >> PAGE_SHIFT);
2354         refs = record_subpages(page, addr, end, pages + *nr);
2355
2356         head = try_grab_compound_head(head, refs, flags);
2357         if (!head)
2358                 return 0;
2359
2360         if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2361                 put_compound_head(head, refs, flags);
2362                 return 0;
2363         }
2364
2365         *nr += refs;
2366         SetPageReferenced(head);
2367         return 1;
2368 }
2369
2370 static int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2371                 unsigned int pdshift, unsigned long end, unsigned int flags,
2372                 struct page **pages, int *nr)
2373 {
2374         pte_t *ptep;
2375         unsigned long sz = 1UL << hugepd_shift(hugepd);
2376         unsigned long next;
2377
2378         ptep = hugepte_offset(hugepd, addr, pdshift);
2379         do {
2380                 next = hugepte_addr_end(addr, end, sz);
2381                 if (!gup_hugepte(ptep, sz, addr, end, flags, pages, nr))
2382                         return 0;
2383         } while (ptep++, addr = next, addr != end);
2384
2385         return 1;
2386 }
2387 #else
2388 static inline int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2389                 unsigned int pdshift, unsigned long end, unsigned int flags,
2390                 struct page **pages, int *nr)
2391 {
2392         return 0;
2393 }
2394 #endif /* CONFIG_ARCH_HAS_HUGEPD */
2395
2396 static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2397                         unsigned long end, unsigned int flags,
2398                         struct page **pages, int *nr)
2399 {
2400         struct page *head, *page;
2401         int refs;
2402
2403         if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
2404                 return 0;
2405
2406         if (pmd_devmap(orig)) {
2407                 if (unlikely(flags & FOLL_LONGTERM))
2408                         return 0;
2409                 return __gup_device_huge_pmd(orig, pmdp, addr, end, flags,
2410                                              pages, nr);
2411         }
2412
2413         page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2414         refs = record_subpages(page, addr, end, pages + *nr);
2415
2416         head = try_grab_compound_head(pmd_page(orig), refs, flags);
2417         if (!head)
2418                 return 0;
2419
2420         if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2421                 put_compound_head(head, refs, flags);
2422                 return 0;
2423         }
2424
2425         *nr += refs;
2426         SetPageReferenced(head);
2427         return 1;
2428 }
2429
2430 static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2431                         unsigned long end, unsigned int flags,
2432                         struct page **pages, int *nr)
2433 {
2434         struct page *head, *page;
2435         int refs;
2436
2437         if (!pud_access_permitted(orig, flags & FOLL_WRITE))
2438                 return 0;
2439
2440         if (pud_devmap(orig)) {
2441                 if (unlikely(flags & FOLL_LONGTERM))
2442                         return 0;
2443                 return __gup_device_huge_pud(orig, pudp, addr, end, flags,
2444                                              pages, nr);
2445         }
2446
2447         page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2448         refs = record_subpages(page, addr, end, pages + *nr);
2449
2450         head = try_grab_compound_head(pud_page(orig), refs, flags);
2451         if (!head)
2452                 return 0;
2453
2454         if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2455                 put_compound_head(head, refs, flags);
2456                 return 0;
2457         }
2458
2459         *nr += refs;
2460         SetPageReferenced(head);
2461         return 1;
2462 }
2463
2464 static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
2465                         unsigned long end, unsigned int flags,
2466                         struct page **pages, int *nr)
2467 {
2468         int refs;
2469         struct page *head, *page;
2470
2471         if (!pgd_access_permitted(orig, flags & FOLL_WRITE))
2472                 return 0;
2473
2474         BUILD_BUG_ON(pgd_devmap(orig));
2475
2476         page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT);
2477         refs = record_subpages(page, addr, end, pages + *nr);
2478
2479         head = try_grab_compound_head(pgd_page(orig), refs, flags);
2480         if (!head)
2481                 return 0;
2482
2483         if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
2484                 put_compound_head(head, refs, flags);
2485                 return 0;
2486         }
2487
2488         *nr += refs;
2489         SetPageReferenced(head);
2490         return 1;
2491 }
2492
2493 static int gup_pmd_range(pud_t *pudp, pud_t pud, unsigned long addr, unsigned long end,
2494                 unsigned int flags, struct page **pages, int *nr)
2495 {
2496         unsigned long next;
2497         pmd_t *pmdp;
2498
2499         pmdp = pmd_offset_lockless(pudp, pud, addr);
2500         do {
2501                 pmd_t pmd = READ_ONCE(*pmdp);
2502
2503                 next = pmd_addr_end(addr, end);
2504                 if (!pmd_present(pmd))
2505                         return 0;
2506
2507                 if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd) ||
2508                              pmd_devmap(pmd))) {
2509                         /*
2510                          * NUMA hinting faults need to be handled in the GUP
2511                          * slowpath for accounting purposes and so that they
2512                          * can be serialised against THP migration.
2513                          */
2514                         if (pmd_protnone(pmd))
2515                                 return 0;
2516
2517                         if (!gup_huge_pmd(pmd, pmdp, addr, next, flags,
2518                                 pages, nr))
2519                                 return 0;
2520
2521                 } else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
2522                         /*
2523                          * architecture have different format for hugetlbfs
2524                          * pmd format and THP pmd format
2525                          */
2526                         if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
2527                                          PMD_SHIFT, next, flags, pages, nr))
2528                                 return 0;
2529                 } else if (!gup_pte_range(pmd, addr, next, flags, pages, nr))
2530                         return 0;
2531         } while (pmdp++, addr = next, addr != end);
2532
2533         return 1;
2534 }
2535
2536 static int gup_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr, unsigned long end,
2537                          unsigned int flags, struct page **pages, int *nr)
2538 {
2539         unsigned long next;
2540         pud_t *pudp;
2541
2542         pudp = pud_offset_lockless(p4dp, p4d, addr);
2543         do {
2544                 pud_t pud = READ_ONCE(*pudp);
2545
2546                 next = pud_addr_end(addr, end);
2547                 if (unlikely(!pud_present(pud)))
2548                         return 0;
2549                 if (unlikely(pud_huge(pud))) {
2550                         if (!gup_huge_pud(pud, pudp, addr, next, flags,
2551                                           pages, nr))
2552                                 return 0;
2553                 } else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
2554                         if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
2555                                          PUD_SHIFT, next, flags, pages, nr))
2556                                 return 0;
2557                 } else if (!gup_pmd_range(pudp, pud, addr, next, flags, pages, nr))
2558                         return 0;
2559         } while (pudp++, addr = next, addr != end);
2560
2561         return 1;
2562 }
2563
2564 static int gup_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr, unsigned long end,
2565                          unsigned int flags, struct page **pages, int *nr)
2566 {
2567         unsigned long next;
2568         p4d_t *p4dp;
2569
2570         p4dp = p4d_offset_lockless(pgdp, pgd, addr);
2571         do {
2572                 p4d_t p4d = READ_ONCE(*p4dp);
2573
2574                 next = p4d_addr_end(addr, end);
2575                 if (p4d_none(p4d))
2576                         return 0;
2577                 BUILD_BUG_ON(p4d_huge(p4d));
2578                 if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
2579                         if (!gup_huge_pd(__hugepd(p4d_val(p4d)), addr,
2580                                          P4D_SHIFT, next, flags, pages, nr))
2581                                 return 0;
2582                 } else if (!gup_pud_range(p4dp, p4d, addr, next, flags, pages, nr))
2583                         return 0;
2584         } while (p4dp++, addr = next, addr != end);
2585
2586         return 1;
2587 }
2588
2589 static void gup_pgd_range(unsigned long addr, unsigned long end,
2590                 unsigned int flags, struct page **pages, int *nr)
2591 {
2592         unsigned long next;
2593         pgd_t *pgdp;
2594
2595         pgdp = pgd_offset(current->mm, addr);
2596         do {
2597                 pgd_t pgd = READ_ONCE(*pgdp);
2598
2599                 next = pgd_addr_end(addr, end);
2600                 if (pgd_none(pgd))
2601                         return;
2602                 if (unlikely(pgd_huge(pgd))) {
2603                         if (!gup_huge_pgd(pgd, pgdp, addr, next, flags,
2604                                           pages, nr))
2605                                 return;
2606                 } else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
2607                         if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
2608                                          PGDIR_SHIFT, next, flags, pages, nr))
2609                                 return;
2610                 } else if (!gup_p4d_range(pgdp, pgd, addr, next, flags, pages, nr))
2611                         return;
2612         } while (pgdp++, addr = next, addr != end);
2613 }
2614 #else
2615 static inline void gup_pgd_range(unsigned long addr, unsigned long end,
2616                 unsigned int flags, struct page **pages, int *nr)
2617 {
2618 }
2619 #endif /* CONFIG_HAVE_FAST_GUP */
2620
2621 #ifndef gup_fast_permitted
2622 /*
2623  * Check if it's allowed to use get_user_pages_fast_only() for the range, or
2624  * we need to fall back to the slow version:
2625  */
2626 static bool gup_fast_permitted(unsigned long start, unsigned long end)
2627 {
2628         return true;
2629 }
2630 #endif
2631
2632 static int __gup_longterm_unlocked(unsigned long start, int nr_pages,
2633                                    unsigned int gup_flags, struct page **pages)
2634 {
2635         int ret;
2636
2637         /*
2638          * FIXME: FOLL_LONGTERM does not work with
2639          * get_user_pages_unlocked() (see comments in that function)
2640          */
2641         if (gup_flags & FOLL_LONGTERM) {
2642                 mmap_read_lock(current->mm);
2643                 ret = __gup_longterm_locked(current->mm,
2644                                             start, nr_pages,
2645                                             pages, NULL, gup_flags);
2646                 mmap_read_unlock(current->mm);
2647         } else {
2648                 ret = get_user_pages_unlocked(start, nr_pages,
2649                                               pages, gup_flags);
2650         }
2651
2652         return ret;
2653 }
2654
2655 static unsigned long lockless_pages_from_mm(unsigned long start,
2656                                             unsigned long end,
2657                                             unsigned int gup_flags,
2658                                             struct page **pages)
2659 {
2660         unsigned long flags;
2661         int nr_pinned = 0;
2662         unsigned seq;
2663
2664         if (!IS_ENABLED(CONFIG_HAVE_FAST_GUP) ||
2665             !gup_fast_permitted(start, end))
2666                 return 0;
2667
2668         if (gup_flags & FOLL_PIN) {
2669                 seq = raw_read_seqcount(&current->mm->write_protect_seq);
2670                 if (seq & 1)
2671                         return 0;
2672         }
2673
2674         /*
2675          * Disable interrupts. The nested form is used, in order to allow full,
2676          * general purpose use of this routine.
2677          *
2678          * With interrupts disabled, we block page table pages from being freed
2679          * from under us. See struct mmu_table_batch comments in
2680          * include/asm-generic/tlb.h for more details.
2681          *
2682          * We do not adopt an rcu_read_lock() here as we also want to block IPIs
2683          * that come from THPs splitting.
2684          */
2685         local_irq_save(flags);
2686         gup_pgd_range(start, end, gup_flags, pages, &nr_pinned);
2687         local_irq_restore(flags);
2688
2689         /*
2690          * When pinning pages for DMA there could be a concurrent write protect
2691          * from fork() via copy_page_range(), in this case always fail fast GUP.
2692          */
2693         if (gup_flags & FOLL_PIN) {
2694                 if (read_seqcount_retry(&current->mm->write_protect_seq, seq)) {
2695                         unpin_user_pages(pages, nr_pinned);
2696                         return 0;
2697                 }
2698         }
2699         return nr_pinned;
2700 }
2701
2702 static int internal_get_user_pages_fast(unsigned long start,
2703                                         unsigned long nr_pages,
2704                                         unsigned int gup_flags,
2705                                         struct page **pages)
2706 {
2707         unsigned long len, end;
2708         unsigned long nr_pinned;
2709         int ret;
2710
2711         if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM |
2712                                        FOLL_FORCE | FOLL_PIN | FOLL_GET |
2713                                        FOLL_FAST_ONLY)))
2714                 return -EINVAL;
2715
2716         if (gup_flags & FOLL_PIN)
2717                 atomic_set(&current->mm->has_pinned, 1);
2718
2719         if (!(gup_flags & FOLL_FAST_ONLY))
2720                 might_lock_read(&current->mm->mmap_lock);
2721
2722         start = untagged_addr(start) & PAGE_MASK;
2723         len = nr_pages << PAGE_SHIFT;
2724         if (check_add_overflow(start, len, &end))
2725                 return 0;
2726         if (unlikely(!access_ok((void __user *)start, len)))
2727                 return -EFAULT;
2728
2729         nr_pinned = lockless_pages_from_mm(start, end, gup_flags, pages);
2730         if (nr_pinned == nr_pages || gup_flags & FOLL_FAST_ONLY)
2731                 return nr_pinned;
2732
2733         /* Slow path: try to get the remaining pages with get_user_pages */
2734         start += nr_pinned << PAGE_SHIFT;
2735         pages += nr_pinned;
2736         ret = __gup_longterm_unlocked(start, nr_pages - nr_pinned, gup_flags,
2737                                       pages);
2738         if (ret < 0) {
2739                 /*
2740                  * The caller has to unpin the pages we already pinned so
2741                  * returning -errno is not an option
2742                  */
2743                 if (nr_pinned)
2744                         return nr_pinned;
2745                 return ret;
2746         }
2747         return ret + nr_pinned;
2748 }
2749
2750 /**
2751  * get_user_pages_fast_only() - pin user pages in memory
2752  * @start:      starting user address
2753  * @nr_pages:   number of pages from start to pin
2754  * @gup_flags:  flags modifying pin behaviour
2755  * @pages:      array that receives pointers to the pages pinned.
2756  *              Should be at least nr_pages long.
2757  *
2758  * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
2759  * the regular GUP.
2760  * Note a difference with get_user_pages_fast: this always returns the
2761  * number of pages pinned, 0 if no pages were pinned.
2762  *
2763  * If the architecture does not support this function, simply return with no
2764  * pages pinned.
2765  *
2766  * Careful, careful! COW breaking can go either way, so a non-write
2767  * access can get ambiguous page results. If you call this function without
2768  * 'write' set, you'd better be sure that you're ok with that ambiguity.
2769  */
2770 int get_user_pages_fast_only(unsigned long start, int nr_pages,
2771                              unsigned int gup_flags, struct page **pages)
2772 {
2773         int nr_pinned;
2774         /*
2775          * Internally (within mm/gup.c), gup fast variants must set FOLL_GET,
2776          * because gup fast is always a "pin with a +1 page refcount" request.
2777          *
2778          * FOLL_FAST_ONLY is required in order to match the API description of
2779          * this routine: no fall back to regular ("slow") GUP.
2780          */
2781         gup_flags |= FOLL_GET | FOLL_FAST_ONLY;
2782
2783         nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
2784                                                  pages);
2785
2786         /*
2787          * As specified in the API description above, this routine is not
2788          * allowed to return negative values. However, the common core
2789          * routine internal_get_user_pages_fast() *can* return -errno.
2790          * Therefore, correct for that here:
2791          */
2792         if (nr_pinned < 0)
2793                 nr_pinned = 0;
2794
2795         return nr_pinned;
2796 }
2797 EXPORT_SYMBOL_GPL(get_user_pages_fast_only);
2798
2799 /**
2800  * get_user_pages_fast() - pin user pages in memory
2801  * @start:      starting user address
2802  * @nr_pages:   number of pages from start to pin
2803  * @gup_flags:  flags modifying pin behaviour
2804  * @pages:      array that receives pointers to the pages pinned.
2805  *              Should be at least nr_pages long.
2806  *
2807  * Attempt to pin user pages in memory without taking mm->mmap_lock.
2808  * If not successful, it will fall back to taking the lock and
2809  * calling get_user_pages().
2810  *
2811  * Returns number of pages pinned. This may be fewer than the number requested.
2812  * If nr_pages is 0 or negative, returns 0. If no pages were pinned, returns
2813  * -errno.
2814  */
2815 int get_user_pages_fast(unsigned long start, int nr_pages,
2816                         unsigned int gup_flags, struct page **pages)
2817 {
2818         if (!is_valid_gup_flags(gup_flags))
2819                 return -EINVAL;
2820
2821         /*
2822          * The caller may or may not have explicitly set FOLL_GET; either way is
2823          * OK. However, internally (within mm/gup.c), gup fast variants must set
2824          * FOLL_GET, because gup fast is always a "pin with a +1 page refcount"
2825          * request.
2826          */
2827         gup_flags |= FOLL_GET;
2828         return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
2829 }
2830 EXPORT_SYMBOL_GPL(get_user_pages_fast);
2831
2832 /**
2833  * pin_user_pages_fast() - pin user pages in memory without taking locks
2834  *
2835  * @start:      starting user address
2836  * @nr_pages:   number of pages from start to pin
2837  * @gup_flags:  flags modifying pin behaviour
2838  * @pages:      array that receives pointers to the pages pinned.
2839  *              Should be at least nr_pages long.
2840  *
2841  * Nearly the same as get_user_pages_fast(), except that FOLL_PIN is set. See
2842  * get_user_pages_fast() for documentation on the function arguments, because
2843  * the arguments here are identical.
2844  *
2845  * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
2846  * see Documentation/core-api/pin_user_pages.rst for further details.
2847  */
2848 int pin_user_pages_fast(unsigned long start, int nr_pages,
2849                         unsigned int gup_flags, struct page **pages)
2850 {
2851         /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2852         if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2853                 return -EINVAL;
2854
2855         gup_flags |= FOLL_PIN;
2856         return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
2857 }
2858 EXPORT_SYMBOL_GPL(pin_user_pages_fast);
2859
2860 /*
2861  * This is the FOLL_PIN equivalent of get_user_pages_fast_only(). Behavior
2862  * is the same, except that this one sets FOLL_PIN instead of FOLL_GET.
2863  *
2864  * The API rules are the same, too: no negative values may be returned.
2865  */
2866 int pin_user_pages_fast_only(unsigned long start, int nr_pages,
2867                              unsigned int gup_flags, struct page **pages)
2868 {
2869         int nr_pinned;
2870
2871         /*
2872          * FOLL_GET and FOLL_PIN are mutually exclusive. Note that the API
2873          * rules require returning 0, rather than -errno:
2874          */
2875         if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2876                 return 0;
2877         /*
2878          * FOLL_FAST_ONLY is required in order to match the API description of
2879          * this routine: no fall back to regular ("slow") GUP.
2880          */
2881         gup_flags |= (FOLL_PIN | FOLL_FAST_ONLY);
2882         nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
2883                                                  pages);
2884         /*
2885          * This routine is not allowed to return negative values. However,
2886          * internal_get_user_pages_fast() *can* return -errno. Therefore,
2887          * correct for that here:
2888          */
2889         if (nr_pinned < 0)
2890                 nr_pinned = 0;
2891
2892         return nr_pinned;
2893 }
2894 EXPORT_SYMBOL_GPL(pin_user_pages_fast_only);
2895
2896 /**
2897  * pin_user_pages_remote() - pin pages of a remote process
2898  *
2899  * @mm:         mm_struct of target mm
2900  * @start:      starting user address
2901  * @nr_pages:   number of pages from start to pin
2902  * @gup_flags:  flags modifying lookup behaviour
2903  * @pages:      array that receives pointers to the pages pinned.
2904  *              Should be at least nr_pages long. Or NULL, if caller
2905  *              only intends to ensure the pages are faulted in.
2906  * @vmas:       array of pointers to vmas corresponding to each page.
2907  *              Or NULL if the caller does not require them.
2908  * @locked:     pointer to lock flag indicating whether lock is held and
2909  *              subsequently whether VM_FAULT_RETRY functionality can be
2910  *              utilised. Lock must initially be held.
2911  *
2912  * Nearly the same as get_user_pages_remote(), except that FOLL_PIN is set. See
2913  * get_user_pages_remote() for documentation on the function arguments, because
2914  * the arguments here are identical.
2915  *
2916  * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
2917  * see Documentation/core-api/pin_user_pages.rst for details.
2918  */
2919 long pin_user_pages_remote(struct mm_struct *mm,
2920                            unsigned long start, unsigned long nr_pages,
2921                            unsigned int gup_flags, struct page **pages,
2922                            struct vm_area_struct **vmas, int *locked)
2923 {
2924         /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2925         if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2926                 return -EINVAL;
2927
2928         gup_flags |= FOLL_PIN;
2929         return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
2930                                        pages, vmas, locked);
2931 }
2932 EXPORT_SYMBOL(pin_user_pages_remote);
2933
2934 /**
2935  * pin_user_pages() - pin user pages in memory for use by other devices
2936  *
2937  * @start:      starting user address
2938  * @nr_pages:   number of pages from start to pin
2939  * @gup_flags:  flags modifying lookup behaviour
2940  * @pages:      array that receives pointers to the pages pinned.
2941  *              Should be at least nr_pages long. Or NULL, if caller
2942  *              only intends to ensure the pages are faulted in.
2943  * @vmas:       array of pointers to vmas corresponding to each page.
2944  *              Or NULL if the caller does not require them.
2945  *
2946  * Nearly the same as get_user_pages(), except that FOLL_TOUCH is not set, and
2947  * FOLL_PIN is set.
2948  *
2949  * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
2950  * see Documentation/core-api/pin_user_pages.rst for details.
2951  */
2952 long pin_user_pages(unsigned long start, unsigned long nr_pages,
2953                     unsigned int gup_flags, struct page **pages,
2954                     struct vm_area_struct **vmas)
2955 {
2956         /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2957         if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2958                 return -EINVAL;
2959
2960         gup_flags |= FOLL_PIN;
2961         return __gup_longterm_locked(current->mm, start, nr_pages,
2962                                      pages, vmas, gup_flags);
2963 }
2964 EXPORT_SYMBOL(pin_user_pages);
2965
2966 /*
2967  * pin_user_pages_unlocked() is the FOLL_PIN variant of
2968  * get_user_pages_unlocked(). Behavior is the same, except that this one sets
2969  * FOLL_PIN and rejects FOLL_GET.
2970  */
2971 long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
2972                              struct page **pages, unsigned int gup_flags)
2973 {
2974         /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2975         if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2976                 return -EINVAL;
2977
2978         gup_flags |= FOLL_PIN;
2979         return get_user_pages_unlocked(start, nr_pages, pages, gup_flags);
2980 }
2981 EXPORT_SYMBOL(pin_user_pages_unlocked);
2982
2983 /*
2984  * pin_user_pages_locked() is the FOLL_PIN variant of get_user_pages_locked().
2985  * Behavior is the same, except that this one sets FOLL_PIN and rejects
2986  * FOLL_GET.
2987  */
2988 long pin_user_pages_locked(unsigned long start, unsigned long nr_pages,
2989                            unsigned int gup_flags, struct page **pages,
2990                            int *locked)
2991 {
2992         /*
2993          * FIXME: Current FOLL_LONGTERM behavior is incompatible with
2994          * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2995          * vmas.  As there are no users of this flag in this call we simply
2996          * disallow this option for now.
2997          */
2998         if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
2999                 return -EINVAL;
3000
3001         /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3002         if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3003                 return -EINVAL;
3004
3005         gup_flags |= FOLL_PIN;
3006         return __get_user_pages_locked(current->mm, start, nr_pages,
3007                                        pages, NULL, locked,
3008                                        gup_flags | FOLL_TOUCH);
3009 }
3010 EXPORT_SYMBOL(pin_user_pages_locked);