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