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