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