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