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