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