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