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