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