OSDN Git Service

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