1 // SPDX-License-Identifier: GPL-2.0-only
2 #include <linux/kernel.h>
3 #include <linux/errno.h>
5 #include <linux/spinlock.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>
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 #include <linux/shmem_fs.h>
23 #include <asm/mmu_context.h>
24 #include <asm/tlbflush.h>
28 struct follow_page_context {
29 struct dev_pagemap *pgmap;
30 unsigned int page_mask;
33 static inline void sanity_check_pinned_pages(struct page **pages,
36 if (!IS_ENABLED(CONFIG_DEBUG_VM))
40 * We only pin anonymous pages if they are exclusive. Once pinned, we
41 * can no longer turn them possibly shared and PageAnonExclusive() will
42 * stick around until the page is freed.
44 * We'd like to verify that our pinned anonymous pages are still mapped
45 * exclusively. The issue with anon THP is that we don't know how
46 * they are/were mapped when pinning them. However, for anon
47 * THP we can assume that either the given page (PTE-mapped THP) or
48 * the head page (PMD-mapped THP) should be PageAnonExclusive(). If
49 * neither is the case, there is certainly something wrong.
51 for (; npages; npages--, pages++) {
52 struct page *page = *pages;
53 struct folio *folio = page_folio(page);
55 if (is_zero_page(page) ||
56 !folio_test_anon(folio))
58 if (!folio_test_large(folio) || folio_test_hugetlb(folio))
59 VM_BUG_ON_PAGE(!PageAnonExclusive(&folio->page), page);
61 /* Either a PTE-mapped or a PMD-mapped THP. */
62 VM_BUG_ON_PAGE(!PageAnonExclusive(&folio->page) &&
63 !PageAnonExclusive(page), page);
68 * Return the folio with ref appropriately incremented,
69 * or NULL if that failed.
71 static inline struct folio *try_get_folio(struct page *page, int refs)
76 folio = page_folio(page);
77 if (WARN_ON_ONCE(folio_ref_count(folio) < 0))
79 if (unlikely(!folio_ref_try_add(folio, refs)))
83 * At this point we have a stable reference to the folio; but it
84 * could be that between calling page_folio() and the refcount
85 * increment, the folio was split, in which case we'd end up
86 * holding a reference on a folio that has nothing to do with the page
87 * we were given anymore.
88 * So now that the folio is stable, recheck that the page still
89 * belongs to this folio.
91 if (unlikely(page_folio(page) != folio)) {
92 if (!put_devmap_managed_folio_refs(folio, refs))
93 folio_put_refs(folio, refs);
100 static void gup_put_folio(struct folio *folio, int refs, unsigned int flags)
102 if (flags & FOLL_PIN) {
103 if (is_zero_folio(folio))
105 node_stat_mod_folio(folio, NR_FOLL_PIN_RELEASED, refs);
106 if (folio_test_large(folio))
107 atomic_sub(refs, &folio->_pincount);
109 refs *= GUP_PIN_COUNTING_BIAS;
112 if (!put_devmap_managed_folio_refs(folio, refs))
113 folio_put_refs(folio, refs);
117 * try_grab_folio() - add a folio's refcount by a flag-dependent amount
118 * @folio: pointer to folio to be grabbed
119 * @refs: the value to (effectively) add to the folio's refcount
120 * @flags: gup flags: these are the FOLL_* flag values
122 * This might not do anything at all, depending on the flags argument.
124 * "grab" names in this file mean, "look at flags to decide whether to use
125 * FOLL_PIN or FOLL_GET behavior, when incrementing the folio's refcount.
127 * Either FOLL_PIN or FOLL_GET (or neither) may be set, but not both at the same
130 * Return: 0 for success, or if no action was required (if neither FOLL_PIN
131 * nor FOLL_GET was set, nothing is done). A negative error code for failure:
133 * -ENOMEM FOLL_GET or FOLL_PIN was set, but the folio could not
136 * It is called when we have a stable reference for the folio, typically in
139 int __must_check try_grab_folio(struct folio *folio, int refs,
142 if (WARN_ON_ONCE(folio_ref_count(folio) <= 0))
145 if (unlikely(!(flags & FOLL_PCI_P2PDMA) && is_pci_p2pdma_page(&folio->page)))
148 if (flags & FOLL_GET)
149 folio_ref_add(folio, refs);
150 else if (flags & FOLL_PIN) {
152 * Don't take a pin on the zero page - it's not going anywhere
153 * and it is used in a *lot* of places.
155 if (is_zero_folio(folio))
159 * Increment the normal page refcount field at least once,
160 * so that the page really is pinned.
162 if (folio_test_large(folio)) {
163 folio_ref_add(folio, refs);
164 atomic_add(refs, &folio->_pincount);
166 folio_ref_add(folio, refs * GUP_PIN_COUNTING_BIAS);
169 node_stat_mod_folio(folio, NR_FOLL_PIN_ACQUIRED, refs);
176 * unpin_user_page() - release a dma-pinned page
177 * @page: pointer to page to be released
179 * Pages that were pinned via pin_user_pages*() must be released via either
180 * unpin_user_page(), or one of the unpin_user_pages*() routines. This is so
181 * that such pages can be separately tracked and uniquely handled. In
182 * particular, interactions with RDMA and filesystems need special handling.
184 void unpin_user_page(struct page *page)
186 sanity_check_pinned_pages(&page, 1);
187 gup_put_folio(page_folio(page), 1, FOLL_PIN);
189 EXPORT_SYMBOL(unpin_user_page);
192 * folio_add_pin - Try to get an additional pin on a pinned folio
193 * @folio: The folio to be pinned
195 * Get an additional pin on a folio we already have a pin on. Makes no change
196 * if the folio is a zero_page.
198 void folio_add_pin(struct folio *folio)
200 if (is_zero_folio(folio))
204 * Similar to try_grab_folio(): be sure to *also* increment the normal
205 * page refcount field at least once, so that the page really is
208 if (folio_test_large(folio)) {
209 WARN_ON_ONCE(atomic_read(&folio->_pincount) < 1);
210 folio_ref_inc(folio);
211 atomic_inc(&folio->_pincount);
213 WARN_ON_ONCE(folio_ref_count(folio) < GUP_PIN_COUNTING_BIAS);
214 folio_ref_add(folio, GUP_PIN_COUNTING_BIAS);
218 static inline struct folio *gup_folio_range_next(struct page *start,
219 unsigned long npages, unsigned long i, unsigned int *ntails)
221 struct page *next = nth_page(start, i);
222 struct folio *folio = page_folio(next);
225 if (folio_test_large(folio))
226 nr = min_t(unsigned int, npages - i,
227 folio_nr_pages(folio) - folio_page_idx(folio, next));
233 static inline struct folio *gup_folio_next(struct page **list,
234 unsigned long npages, unsigned long i, unsigned int *ntails)
236 struct folio *folio = page_folio(list[i]);
239 for (nr = i + 1; nr < npages; nr++) {
240 if (page_folio(list[nr]) != folio)
249 * unpin_user_pages_dirty_lock() - release and optionally dirty gup-pinned pages
250 * @pages: array of pages to be maybe marked dirty, and definitely released.
251 * @npages: number of pages in the @pages array.
252 * @make_dirty: whether to mark the pages dirty
254 * "gup-pinned page" refers to a page that has had one of the get_user_pages()
255 * variants called on that page.
257 * For each page in the @pages array, make that page (or its head page, if a
258 * compound page) dirty, if @make_dirty is true, and if the page was previously
259 * listed as clean. In any case, releases all pages using unpin_user_page(),
260 * possibly via unpin_user_pages(), for the non-dirty case.
262 * Please see the unpin_user_page() documentation for details.
264 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
265 * required, then the caller should a) verify that this is really correct,
266 * because _lock() is usually required, and b) hand code it:
267 * set_page_dirty_lock(), unpin_user_page().
270 void unpin_user_pages_dirty_lock(struct page **pages, unsigned long npages,
278 unpin_user_pages(pages, npages);
282 sanity_check_pinned_pages(pages, npages);
283 for (i = 0; i < npages; i += nr) {
284 folio = gup_folio_next(pages, npages, i, &nr);
286 * Checking PageDirty at this point may race with
287 * clear_page_dirty_for_io(), but that's OK. Two key
290 * 1) This code sees the page as already dirty, so it
291 * skips the call to set_page_dirty(). That could happen
292 * because clear_page_dirty_for_io() called
293 * page_mkclean(), followed by set_page_dirty().
294 * However, now the page is going to get written back,
295 * which meets the original intention of setting it
296 * dirty, so all is well: clear_page_dirty_for_io() goes
297 * on to call TestClearPageDirty(), and write the page
300 * 2) This code sees the page as clean, so it calls
301 * set_page_dirty(). The page stays dirty, despite being
302 * written back, so it gets written back again in the
303 * next writeback cycle. This is harmless.
305 if (!folio_test_dirty(folio)) {
307 folio_mark_dirty(folio);
310 gup_put_folio(folio, nr, FOLL_PIN);
313 EXPORT_SYMBOL(unpin_user_pages_dirty_lock);
316 * unpin_user_page_range_dirty_lock() - release and optionally dirty
317 * gup-pinned page range
319 * @page: the starting page of a range maybe marked dirty, and definitely released.
320 * @npages: number of consecutive pages to release.
321 * @make_dirty: whether to mark the pages dirty
323 * "gup-pinned page range" refers to a range of pages that has had one of the
324 * pin_user_pages() variants called on that page.
326 * For the page ranges defined by [page .. page+npages], make that range (or
327 * its head pages, if a compound page) dirty, if @make_dirty is true, and if the
328 * page range was previously listed as clean.
330 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
331 * required, then the caller should a) verify that this is really correct,
332 * because _lock() is usually required, and b) hand code it:
333 * set_page_dirty_lock(), unpin_user_page().
336 void unpin_user_page_range_dirty_lock(struct page *page, unsigned long npages,
343 for (i = 0; i < npages; i += nr) {
344 folio = gup_folio_range_next(page, npages, i, &nr);
345 if (make_dirty && !folio_test_dirty(folio)) {
347 folio_mark_dirty(folio);
350 gup_put_folio(folio, nr, FOLL_PIN);
353 EXPORT_SYMBOL(unpin_user_page_range_dirty_lock);
355 static void gup_fast_unpin_user_pages(struct page **pages, unsigned long npages)
362 * Don't perform any sanity checks because we might have raced with
363 * fork() and some anonymous pages might now actually be shared --
364 * which is why we're unpinning after all.
366 for (i = 0; i < npages; i += nr) {
367 folio = gup_folio_next(pages, npages, i, &nr);
368 gup_put_folio(folio, nr, FOLL_PIN);
373 * unpin_user_pages() - release an array of gup-pinned pages.
374 * @pages: array of pages to be marked dirty and released.
375 * @npages: number of pages in the @pages array.
377 * For each page in the @pages array, release the page using unpin_user_page().
379 * Please see the unpin_user_page() documentation for details.
381 void unpin_user_pages(struct page **pages, unsigned long npages)
388 * If this WARN_ON() fires, then the system *might* be leaking pages (by
389 * leaving them pinned), but probably not. More likely, gup/pup returned
390 * a hard -ERRNO error to the caller, who erroneously passed it here.
392 if (WARN_ON(IS_ERR_VALUE(npages)))
395 sanity_check_pinned_pages(pages, npages);
396 for (i = 0; i < npages; i += nr) {
397 folio = gup_folio_next(pages, npages, i, &nr);
398 gup_put_folio(folio, nr, FOLL_PIN);
401 EXPORT_SYMBOL(unpin_user_pages);
404 * Set the MMF_HAS_PINNED if not set yet; after set it'll be there for the mm's
405 * lifecycle. Avoid setting the bit unless necessary, or it might cause write
406 * cache bouncing on large SMP machines for concurrent pinned gups.
408 static inline void mm_set_has_pinned_flag(unsigned long *mm_flags)
410 if (!test_bit(MMF_HAS_PINNED, mm_flags))
411 set_bit(MMF_HAS_PINNED, mm_flags);
416 #if defined(CONFIG_ARCH_HAS_HUGEPD) || defined(CONFIG_HAVE_GUP_FAST)
417 static int record_subpages(struct page *page, unsigned long sz,
418 unsigned long addr, unsigned long end,
421 struct page *start_page;
424 start_page = nth_page(page, (addr & (sz - 1)) >> PAGE_SHIFT);
425 for (nr = 0; addr != end; nr++, addr += PAGE_SIZE)
426 pages[nr] = nth_page(start_page, nr);
432 * try_grab_folio_fast() - Attempt to get or pin a folio in fast path.
433 * @page: pointer to page to be grabbed
434 * @refs: the value to (effectively) add to the folio's refcount
435 * @flags: gup flags: these are the FOLL_* flag values.
437 * "grab" names in this file mean, "look at flags to decide whether to use
438 * FOLL_PIN or FOLL_GET behavior, when incrementing the folio's refcount.
440 * Either FOLL_PIN or FOLL_GET (or neither) must be set, but not both at the
441 * same time. (That's true throughout the get_user_pages*() and
442 * pin_user_pages*() APIs.) Cases:
444 * FOLL_GET: folio's refcount will be incremented by @refs.
446 * FOLL_PIN on large folios: folio's refcount will be incremented by
447 * @refs, and its pincount will be incremented by @refs.
449 * FOLL_PIN on single-page folios: folio's refcount will be incremented by
450 * @refs * GUP_PIN_COUNTING_BIAS.
452 * Return: The folio containing @page (with refcount appropriately
453 * incremented) for success, or NULL upon failure. If neither FOLL_GET
454 * nor FOLL_PIN was set, that's considered failure, and furthermore,
455 * a likely bug in the caller, so a warning is also emitted.
457 * It uses add ref unless zero to elevate the folio refcount and must be called
460 static struct folio *try_grab_folio_fast(struct page *page, int refs,
465 /* Raise warn if it is not called in fast GUP */
466 VM_WARN_ON_ONCE(!irqs_disabled());
468 if (WARN_ON_ONCE((flags & (FOLL_GET | FOLL_PIN)) == 0))
471 if (unlikely(!(flags & FOLL_PCI_P2PDMA) && is_pci_p2pdma_page(page)))
474 if (flags & FOLL_GET)
475 return try_get_folio(page, refs);
477 /* FOLL_PIN is set */
480 * Don't take a pin on the zero page - it's not going anywhere
481 * and it is used in a *lot* of places.
483 if (is_zero_page(page))
484 return page_folio(page);
486 folio = try_get_folio(page, refs);
491 * Can't do FOLL_LONGTERM + FOLL_PIN gup fast path if not in a
492 * right zone, so fail and let the caller fall back to the slow
495 if (unlikely((flags & FOLL_LONGTERM) &&
496 !folio_is_longterm_pinnable(folio))) {
497 if (!put_devmap_managed_folio_refs(folio, refs))
498 folio_put_refs(folio, refs);
503 * When pinning a large folio, use an exact count to track it.
505 * However, be sure to *also* increment the normal folio
506 * refcount field at least once, so that the folio really
507 * is pinned. That's why the refcount from the earlier
508 * try_get_folio() is left intact.
510 if (folio_test_large(folio))
511 atomic_add(refs, &folio->_pincount);
514 refs * (GUP_PIN_COUNTING_BIAS - 1));
516 * Adjust the pincount before re-checking the PTE for changes.
517 * This is essentially a smp_mb() and is paired with a memory
518 * barrier in folio_try_share_anon_rmap_*().
520 smp_mb__after_atomic();
522 node_stat_mod_folio(folio, NR_FOLL_PIN_ACQUIRED, refs);
526 #endif /* CONFIG_ARCH_HAS_HUGEPD || CONFIG_HAVE_GUP_FAST */
528 #ifdef CONFIG_ARCH_HAS_HUGEPD
529 static unsigned long hugepte_addr_end(unsigned long addr, unsigned long end,
532 unsigned long __boundary = (addr + sz) & ~(sz-1);
533 return (__boundary - 1 < end - 1) ? __boundary : end;
537 * Returns 1 if succeeded, 0 if failed, -EMLINK if unshare needed.
539 * NOTE: for the same entry, gup-fast and gup-slow can return different
540 * results (0 v.s. -EMLINK) depending on whether vma is available. This is
541 * the expected behavior, where we simply want gup-fast to fallback to
542 * gup-slow to take the vma reference first.
544 static int gup_hugepte(struct vm_area_struct *vma, pte_t *ptep, unsigned long sz,
545 unsigned long addr, unsigned long end, unsigned int flags,
546 struct page **pages, int *nr, bool fast)
548 unsigned long pte_end;
554 pte_end = (addr + sz) & ~(sz-1);
558 pte = huge_ptep_get(ptep);
560 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
563 /* hugepages are never "special" */
564 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
566 page = pte_page(pte);
567 refs = record_subpages(page, sz, addr, end, pages + *nr);
570 folio = try_grab_folio_fast(page, refs, flags);
574 folio = page_folio(page);
575 if (try_grab_folio(folio, refs, flags))
579 if (unlikely(pte_val(pte) != pte_val(ptep_get(ptep)))) {
580 gup_put_folio(folio, refs, flags);
584 if (!pte_write(pte) && gup_must_unshare(vma, flags, &folio->page)) {
585 gup_put_folio(folio, refs, flags);
590 folio_set_referenced(folio);
595 * NOTE: currently GUP for a hugepd is only possible on hugetlbfs file
596 * systems on Power, which does not have issue with folio writeback against
597 * GUP updates. When hugepd will be extended to support non-hugetlbfs or
598 * even anonymous memory, we need to do extra check as what we do with most
599 * of the other folios. See writable_file_mapping_allowed() and
600 * gup_fast_folio_allowed() for more information.
602 static int gup_hugepd(struct vm_area_struct *vma, hugepd_t hugepd,
603 unsigned long addr, unsigned int pdshift,
604 unsigned long end, unsigned int flags,
605 struct page **pages, int *nr, bool fast)
608 unsigned long sz = 1UL << hugepd_shift(hugepd);
612 ptep = hugepte_offset(hugepd, addr, pdshift);
614 next = hugepte_addr_end(addr, end, sz);
615 ret = gup_hugepte(vma, ptep, sz, addr, end, flags, pages, nr,
619 } while (ptep++, addr = next, addr != end);
624 static struct page *follow_hugepd(struct vm_area_struct *vma, hugepd_t hugepd,
625 unsigned long addr, unsigned int pdshift,
627 struct follow_page_context *ctx)
635 /* Only hugetlb supports hugepd */
636 if (WARN_ON_ONCE(!is_vm_hugetlb_page(vma)))
637 return ERR_PTR(-EFAULT);
640 ptep = hugepte_offset(hugepd, addr, pdshift);
641 ptl = huge_pte_lock(h, vma->vm_mm, ptep);
642 ret = gup_hugepd(vma, hugepd, addr, pdshift, addr + PAGE_SIZE,
643 flags, &page, &nr, false);
648 WARN_ON_ONCE(nr != 1);
649 ctx->page_mask = (1U << huge_page_order(h)) - 1;
653 /* ret can be either 0 (translates to NULL) or negative */
656 #else /* CONFIG_ARCH_HAS_HUGEPD */
657 static inline int gup_hugepd(struct vm_area_struct *vma, hugepd_t hugepd,
658 unsigned long addr, unsigned int pdshift,
659 unsigned long end, unsigned int flags,
660 struct page **pages, int *nr, bool fast)
665 static struct page *follow_hugepd(struct vm_area_struct *vma, hugepd_t hugepd,
666 unsigned long addr, unsigned int pdshift,
668 struct follow_page_context *ctx)
672 #endif /* CONFIG_ARCH_HAS_HUGEPD */
675 static struct page *no_page_table(struct vm_area_struct *vma,
676 unsigned int flags, unsigned long address)
678 if (!(flags & FOLL_DUMP))
682 * When core dumping, we don't want to allocate unnecessary pages or
683 * page tables. Return error instead of NULL to skip handle_mm_fault,
684 * then get_dump_page() will return NULL to leave a hole in the dump.
685 * But we can only make this optimization where a hole would surely
686 * be zero-filled if handle_mm_fault() actually did handle it.
688 if (is_vm_hugetlb_page(vma)) {
689 struct hstate *h = hstate_vma(vma);
691 if (!hugetlbfs_pagecache_present(h, vma, address))
692 return ERR_PTR(-EFAULT);
693 } else if ((vma_is_anonymous(vma) || !vma->vm_ops->fault)) {
694 return ERR_PTR(-EFAULT);
700 #ifdef CONFIG_PGTABLE_HAS_HUGE_LEAVES
701 static struct page *follow_huge_pud(struct vm_area_struct *vma,
702 unsigned long addr, pud_t *pudp,
703 int flags, struct follow_page_context *ctx)
705 struct mm_struct *mm = vma->vm_mm;
708 unsigned long pfn = pud_pfn(pud);
711 assert_spin_locked(pud_lockptr(mm, pudp));
713 if ((flags & FOLL_WRITE) && !pud_write(pud))
716 if (!pud_present(pud))
719 pfn += (addr & ~PUD_MASK) >> PAGE_SHIFT;
721 if (IS_ENABLED(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD) &&
724 * device mapped pages can only be returned if the caller
725 * will manage the page reference count.
727 * At least one of FOLL_GET | FOLL_PIN must be set, so
730 if (!(flags & (FOLL_GET | FOLL_PIN)))
731 return ERR_PTR(-EEXIST);
733 if (flags & FOLL_TOUCH)
734 touch_pud(vma, addr, pudp, flags & FOLL_WRITE);
736 ctx->pgmap = get_dev_pagemap(pfn, ctx->pgmap);
738 return ERR_PTR(-EFAULT);
741 page = pfn_to_page(pfn);
743 if (!pud_devmap(pud) && !pud_write(pud) &&
744 gup_must_unshare(vma, flags, page))
745 return ERR_PTR(-EMLINK);
747 ret = try_grab_folio(page_folio(page), 1, flags);
751 ctx->page_mask = HPAGE_PUD_NR - 1;
756 /* FOLL_FORCE can write to even unwritable PMDs in COW mappings. */
757 static inline bool can_follow_write_pmd(pmd_t pmd, struct page *page,
758 struct vm_area_struct *vma,
761 /* If the pmd is writable, we can write to the page. */
765 /* Maybe FOLL_FORCE is set to override it? */
766 if (!(flags & FOLL_FORCE))
769 /* But FOLL_FORCE has no effect on shared mappings */
770 if (vma->vm_flags & (VM_MAYSHARE | VM_SHARED))
773 /* ... or read-only private ones */
774 if (!(vma->vm_flags & VM_MAYWRITE))
777 /* ... or already writable ones that just need to take a write fault */
778 if (vma->vm_flags & VM_WRITE)
782 * See can_change_pte_writable(): we broke COW and could map the page
783 * writable if we have an exclusive anonymous page ...
785 if (!page || !PageAnon(page) || !PageAnonExclusive(page))
788 /* ... and a write-fault isn't required for other reasons. */
789 if (vma_soft_dirty_enabled(vma) && !pmd_soft_dirty(pmd))
791 return !userfaultfd_huge_pmd_wp(vma, pmd);
794 static struct page *follow_huge_pmd(struct vm_area_struct *vma,
795 unsigned long addr, pmd_t *pmd,
797 struct follow_page_context *ctx)
799 struct mm_struct *mm = vma->vm_mm;
804 assert_spin_locked(pmd_lockptr(mm, pmd));
806 page = pmd_page(pmdval);
807 if ((flags & FOLL_WRITE) &&
808 !can_follow_write_pmd(pmdval, page, vma, flags))
811 /* Avoid dumping huge zero page */
812 if ((flags & FOLL_DUMP) && is_huge_zero_pmd(pmdval))
813 return ERR_PTR(-EFAULT);
815 if (pmd_protnone(*pmd) && !gup_can_follow_protnone(vma, flags))
818 if (!pmd_write(pmdval) && gup_must_unshare(vma, flags, page))
819 return ERR_PTR(-EMLINK);
821 VM_BUG_ON_PAGE((flags & FOLL_PIN) && PageAnon(page) &&
822 !PageAnonExclusive(page), page);
824 ret = try_grab_folio(page_folio(page), 1, flags);
828 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
829 if (pmd_trans_huge(pmdval) && (flags & FOLL_TOUCH))
830 touch_pmd(vma, addr, pmd, flags & FOLL_WRITE);
831 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
833 page += (addr & ~HPAGE_PMD_MASK) >> PAGE_SHIFT;
834 ctx->page_mask = HPAGE_PMD_NR - 1;
839 #else /* CONFIG_PGTABLE_HAS_HUGE_LEAVES */
840 static struct page *follow_huge_pud(struct vm_area_struct *vma,
841 unsigned long addr, pud_t *pudp,
842 int flags, struct follow_page_context *ctx)
847 static struct page *follow_huge_pmd(struct vm_area_struct *vma,
848 unsigned long addr, pmd_t *pmd,
850 struct follow_page_context *ctx)
854 #endif /* CONFIG_PGTABLE_HAS_HUGE_LEAVES */
856 static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
857 pte_t *pte, unsigned int flags)
859 if (flags & FOLL_TOUCH) {
860 pte_t orig_entry = ptep_get(pte);
861 pte_t entry = orig_entry;
863 if (flags & FOLL_WRITE)
864 entry = pte_mkdirty(entry);
865 entry = pte_mkyoung(entry);
867 if (!pte_same(orig_entry, entry)) {
868 set_pte_at(vma->vm_mm, address, pte, entry);
869 update_mmu_cache(vma, address, pte);
873 /* Proper page table entry exists, but no corresponding struct page */
877 /* FOLL_FORCE can write to even unwritable PTEs in COW mappings. */
878 static inline bool can_follow_write_pte(pte_t pte, struct page *page,
879 struct vm_area_struct *vma,
882 /* If the pte is writable, we can write to the page. */
886 /* Maybe FOLL_FORCE is set to override it? */
887 if (!(flags & FOLL_FORCE))
890 /* But FOLL_FORCE has no effect on shared mappings */
891 if (vma->vm_flags & (VM_MAYSHARE | VM_SHARED))
894 /* ... or read-only private ones */
895 if (!(vma->vm_flags & VM_MAYWRITE))
898 /* ... or already writable ones that just need to take a write fault */
899 if (vma->vm_flags & VM_WRITE)
903 * See can_change_pte_writable(): we broke COW and could map the page
904 * writable if we have an exclusive anonymous page ...
906 if (!page || !PageAnon(page) || !PageAnonExclusive(page))
909 /* ... and a write-fault isn't required for other reasons. */
910 if (vma_soft_dirty_enabled(vma) && !pte_soft_dirty(pte))
912 return !userfaultfd_pte_wp(vma, pte);
915 static struct page *follow_page_pte(struct vm_area_struct *vma,
916 unsigned long address, pmd_t *pmd, unsigned int flags,
917 struct dev_pagemap **pgmap)
919 struct mm_struct *mm = vma->vm_mm;
925 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
926 if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
927 (FOLL_PIN | FOLL_GET)))
928 return ERR_PTR(-EINVAL);
930 ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
932 return no_page_table(vma, flags, address);
933 pte = ptep_get(ptep);
934 if (!pte_present(pte))
936 if (pte_protnone(pte) && !gup_can_follow_protnone(vma, flags))
939 page = vm_normal_page(vma, address, pte);
942 * We only care about anon pages in can_follow_write_pte() and don't
943 * have to worry about pte_devmap() because they are never anon.
945 if ((flags & FOLL_WRITE) &&
946 !can_follow_write_pte(pte, page, vma, flags)) {
951 if (!page && pte_devmap(pte) && (flags & (FOLL_GET | FOLL_PIN))) {
953 * Only return device mapping pages in the FOLL_GET or FOLL_PIN
954 * case since they are only valid while holding the pgmap
957 *pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
959 page = pte_page(pte);
962 } else if (unlikely(!page)) {
963 if (flags & FOLL_DUMP) {
964 /* Avoid special (like zero) pages in core dumps */
965 page = ERR_PTR(-EFAULT);
969 if (is_zero_pfn(pte_pfn(pte))) {
970 page = pte_page(pte);
972 ret = follow_pfn_pte(vma, address, ptep, flags);
978 if (!pte_write(pte) && gup_must_unshare(vma, flags, page)) {
979 page = ERR_PTR(-EMLINK);
983 VM_BUG_ON_PAGE((flags & FOLL_PIN) && PageAnon(page) &&
984 !PageAnonExclusive(page), page);
986 /* try_grab_folio() does nothing unless FOLL_GET or FOLL_PIN is set. */
987 ret = try_grab_folio(page_folio(page), 1, flags);
994 * We need to make the page accessible if and only if we are going
995 * to access its content (the FOLL_PIN case). Please see
996 * Documentation/core-api/pin_user_pages.rst for details.
998 if (flags & FOLL_PIN) {
999 ret = arch_make_page_accessible(page);
1001 unpin_user_page(page);
1002 page = ERR_PTR(ret);
1006 if (flags & FOLL_TOUCH) {
1007 if ((flags & FOLL_WRITE) &&
1008 !pte_dirty(pte) && !PageDirty(page))
1009 set_page_dirty(page);
1011 * pte_mkyoung() would be more correct here, but atomic care
1012 * is needed to avoid losing the dirty bit: it is easier to use
1013 * mark_page_accessed().
1015 mark_page_accessed(page);
1018 pte_unmap_unlock(ptep, ptl);
1021 pte_unmap_unlock(ptep, ptl);
1024 return no_page_table(vma, flags, address);
1027 static struct page *follow_pmd_mask(struct vm_area_struct *vma,
1028 unsigned long address, pud_t *pudp,
1030 struct follow_page_context *ctx)
1035 struct mm_struct *mm = vma->vm_mm;
1037 pmd = pmd_offset(pudp, address);
1038 pmdval = pmdp_get_lockless(pmd);
1039 if (pmd_none(pmdval))
1040 return no_page_table(vma, flags, address);
1041 if (!pmd_present(pmdval))
1042 return no_page_table(vma, flags, address);
1043 if (unlikely(is_hugepd(__hugepd(pmd_val(pmdval)))))
1044 return follow_hugepd(vma, __hugepd(pmd_val(pmdval)),
1045 address, PMD_SHIFT, flags, ctx);
1046 if (pmd_devmap(pmdval)) {
1047 ptl = pmd_lock(mm, pmd);
1048 page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
1052 return no_page_table(vma, flags, address);
1054 if (likely(!pmd_leaf(pmdval)))
1055 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
1057 if (pmd_protnone(pmdval) && !gup_can_follow_protnone(vma, flags))
1058 return no_page_table(vma, flags, address);
1060 ptl = pmd_lock(mm, pmd);
1062 if (unlikely(!pmd_present(pmdval))) {
1064 return no_page_table(vma, flags, address);
1066 if (unlikely(!pmd_leaf(pmdval))) {
1068 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
1070 if (pmd_trans_huge(pmdval) && (flags & FOLL_SPLIT_PMD)) {
1072 split_huge_pmd(vma, pmd, address);
1073 /* If pmd was left empty, stuff a page table in there quickly */
1074 return pte_alloc(mm, pmd) ? ERR_PTR(-ENOMEM) :
1075 follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
1077 page = follow_huge_pmd(vma, address, pmd, flags, ctx);
1082 static struct page *follow_pud_mask(struct vm_area_struct *vma,
1083 unsigned long address, p4d_t *p4dp,
1085 struct follow_page_context *ctx)
1090 struct mm_struct *mm = vma->vm_mm;
1092 pudp = pud_offset(p4dp, address);
1093 pud = READ_ONCE(*pudp);
1094 if (!pud_present(pud))
1095 return no_page_table(vma, flags, address);
1096 if (unlikely(is_hugepd(__hugepd(pud_val(pud)))))
1097 return follow_hugepd(vma, __hugepd(pud_val(pud)),
1098 address, PUD_SHIFT, flags, ctx);
1099 if (pud_leaf(pud)) {
1100 ptl = pud_lock(mm, pudp);
1101 page = follow_huge_pud(vma, address, pudp, flags, ctx);
1105 return no_page_table(vma, flags, address);
1107 if (unlikely(pud_bad(pud)))
1108 return no_page_table(vma, flags, address);
1110 return follow_pmd_mask(vma, address, pudp, flags, ctx);
1113 static struct page *follow_p4d_mask(struct vm_area_struct *vma,
1114 unsigned long address, pgd_t *pgdp,
1116 struct follow_page_context *ctx)
1120 p4dp = p4d_offset(pgdp, address);
1121 p4d = READ_ONCE(*p4dp);
1122 BUILD_BUG_ON(p4d_leaf(p4d));
1124 if (unlikely(is_hugepd(__hugepd(p4d_val(p4d)))))
1125 return follow_hugepd(vma, __hugepd(p4d_val(p4d)),
1126 address, P4D_SHIFT, flags, ctx);
1128 if (!p4d_present(p4d) || p4d_bad(p4d))
1129 return no_page_table(vma, flags, address);
1131 return follow_pud_mask(vma, address, p4dp, flags, ctx);
1135 * follow_page_mask - look up a page descriptor from a user-virtual address
1136 * @vma: vm_area_struct mapping @address
1137 * @address: virtual address to look up
1138 * @flags: flags modifying lookup behaviour
1139 * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
1140 * pointer to output page_mask
1142 * @flags can have FOLL_ flags set, defined in <linux/mm.h>
1144 * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
1145 * the device's dev_pagemap metadata to avoid repeating expensive lookups.
1147 * When getting an anonymous page and the caller has to trigger unsharing
1148 * of a shared anonymous page first, -EMLINK is returned. The caller should
1149 * trigger a fault with FAULT_FLAG_UNSHARE set. Note that unsharing is only
1150 * relevant with FOLL_PIN and !FOLL_WRITE.
1152 * On output, the @ctx->page_mask is set according to the size of the page.
1154 * Return: the mapped (struct page *), %NULL if no mapping exists, or
1155 * an error pointer if there is a mapping to something not represented
1156 * by a page descriptor (see also vm_normal_page()).
1158 static struct page *follow_page_mask(struct vm_area_struct *vma,
1159 unsigned long address, unsigned int flags,
1160 struct follow_page_context *ctx)
1163 struct mm_struct *mm = vma->vm_mm;
1166 vma_pgtable_walk_begin(vma);
1169 pgd = pgd_offset(mm, address);
1171 if (unlikely(is_hugepd(__hugepd(pgd_val(*pgd)))))
1172 page = follow_hugepd(vma, __hugepd(pgd_val(*pgd)),
1173 address, PGDIR_SHIFT, flags, ctx);
1174 else if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
1175 page = no_page_table(vma, flags, address);
1177 page = follow_p4d_mask(vma, address, pgd, flags, ctx);
1179 vma_pgtable_walk_end(vma);
1184 struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
1185 unsigned int foll_flags)
1187 struct follow_page_context ctx = { NULL };
1190 if (vma_is_secretmem(vma))
1193 if (WARN_ON_ONCE(foll_flags & FOLL_PIN))
1197 * We never set FOLL_HONOR_NUMA_FAULT because callers don't expect
1198 * to fail on PROT_NONE-mapped pages.
1200 page = follow_page_mask(vma, address, foll_flags, &ctx);
1202 put_dev_pagemap(ctx.pgmap);
1206 static int get_gate_page(struct mm_struct *mm, unsigned long address,
1207 unsigned int gup_flags, struct vm_area_struct **vma,
1218 /* user gate pages are read-only */
1219 if (gup_flags & FOLL_WRITE)
1221 if (address > TASK_SIZE)
1222 pgd = pgd_offset_k(address);
1224 pgd = pgd_offset_gate(mm, address);
1227 p4d = p4d_offset(pgd, address);
1230 pud = pud_offset(p4d, address);
1233 pmd = pmd_offset(pud, address);
1234 if (!pmd_present(*pmd))
1236 pte = pte_offset_map(pmd, address);
1239 entry = ptep_get(pte);
1240 if (pte_none(entry))
1242 *vma = get_gate_vma(mm);
1245 *page = vm_normal_page(*vma, address, entry);
1247 if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(entry)))
1249 *page = pte_page(entry);
1251 ret = try_grab_folio(page_folio(*page), 1, gup_flags);
1262 * mmap_lock must be held on entry. If @flags has FOLL_UNLOCKABLE but not
1263 * FOLL_NOWAIT, the mmap_lock may be released. If it is, *@locked will be set
1264 * to 0 and -EBUSY returned.
1266 static int faultin_page(struct vm_area_struct *vma,
1267 unsigned long address, unsigned int *flags, bool unshare,
1270 unsigned int fault_flags = 0;
1273 if (*flags & FOLL_NOFAULT)
1275 if (*flags & FOLL_WRITE)
1276 fault_flags |= FAULT_FLAG_WRITE;
1277 if (*flags & FOLL_REMOTE)
1278 fault_flags |= FAULT_FLAG_REMOTE;
1279 if (*flags & FOLL_UNLOCKABLE) {
1280 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1282 * FAULT_FLAG_INTERRUPTIBLE is opt-in. GUP callers must set
1283 * FOLL_INTERRUPTIBLE to enable FAULT_FLAG_INTERRUPTIBLE.
1284 * That's because some callers may not be prepared to
1285 * handle early exits caused by non-fatal signals.
1287 if (*flags & FOLL_INTERRUPTIBLE)
1288 fault_flags |= FAULT_FLAG_INTERRUPTIBLE;
1290 if (*flags & FOLL_NOWAIT)
1291 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
1292 if (*flags & FOLL_TRIED) {
1294 * Note: FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_TRIED
1297 fault_flags |= FAULT_FLAG_TRIED;
1300 fault_flags |= FAULT_FLAG_UNSHARE;
1301 /* FAULT_FLAG_WRITE and FAULT_FLAG_UNSHARE are incompatible */
1302 VM_BUG_ON(fault_flags & FAULT_FLAG_WRITE);
1305 ret = handle_mm_fault(vma, address, fault_flags, NULL);
1307 if (ret & VM_FAULT_COMPLETED) {
1309 * With FAULT_FLAG_RETRY_NOWAIT we'll never release the
1310 * mmap lock in the page fault handler. Sanity check this.
1312 WARN_ON_ONCE(fault_flags & FAULT_FLAG_RETRY_NOWAIT);
1316 * We should do the same as VM_FAULT_RETRY, but let's not
1317 * return -EBUSY since that's not reflecting the reality of
1318 * what has happened - we've just fully completed a page
1319 * fault, with the mmap lock released. Use -EAGAIN to show
1320 * that we want to take the mmap lock _again_.
1325 if (ret & VM_FAULT_ERROR) {
1326 int err = vm_fault_to_errno(ret, *flags);
1333 if (ret & VM_FAULT_RETRY) {
1334 if (!(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
1343 * Writing to file-backed mappings which require folio dirty tracking using GUP
1344 * is a fundamentally broken operation, as kernel write access to GUP mappings
1345 * do not adhere to the semantics expected by a file system.
1347 * Consider the following scenario:-
1349 * 1. A folio is written to via GUP which write-faults the memory, notifying
1350 * the file system and dirtying the folio.
1351 * 2. Later, writeback is triggered, resulting in the folio being cleaned and
1352 * the PTE being marked read-only.
1353 * 3. The GUP caller writes to the folio, as it is mapped read/write via the
1355 * 4. The GUP caller, now done with the page, unpins it and sets it dirty
1356 * (though it does not have to).
1358 * This results in both data being written to a folio without writenotify, and
1359 * the folio being dirtied unexpectedly (if the caller decides to do so).
1361 static bool writable_file_mapping_allowed(struct vm_area_struct *vma,
1362 unsigned long gup_flags)
1365 * If we aren't pinning then no problematic write can occur. A long term
1366 * pin is the most egregious case so this is the case we disallow.
1368 if ((gup_flags & (FOLL_PIN | FOLL_LONGTERM)) !=
1369 (FOLL_PIN | FOLL_LONGTERM))
1373 * If the VMA does not require dirty tracking then no problematic write
1376 return !vma_needs_dirty_tracking(vma);
1379 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
1381 vm_flags_t vm_flags = vma->vm_flags;
1382 int write = (gup_flags & FOLL_WRITE);
1383 int foreign = (gup_flags & FOLL_REMOTE);
1384 bool vma_anon = vma_is_anonymous(vma);
1386 if (vm_flags & (VM_IO | VM_PFNMAP))
1389 if ((gup_flags & FOLL_ANON) && !vma_anon)
1392 if ((gup_flags & FOLL_LONGTERM) && vma_is_fsdax(vma))
1395 if (vma_is_secretmem(vma))
1400 !writable_file_mapping_allowed(vma, gup_flags))
1403 if (!(vm_flags & VM_WRITE) || (vm_flags & VM_SHADOW_STACK)) {
1404 if (!(gup_flags & FOLL_FORCE))
1406 /* hugetlb does not support FOLL_FORCE|FOLL_WRITE. */
1407 if (is_vm_hugetlb_page(vma))
1410 * We used to let the write,force case do COW in a
1411 * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
1412 * set a breakpoint in a read-only mapping of an
1413 * executable, without corrupting the file (yet only
1414 * when that file had been opened for writing!).
1415 * Anon pages in shared mappings are surprising: now
1418 if (!is_cow_mapping(vm_flags))
1421 } else if (!(vm_flags & VM_READ)) {
1422 if (!(gup_flags & FOLL_FORCE))
1425 * Is there actually any vma we can reach here which does not
1426 * have VM_MAYREAD set?
1428 if (!(vm_flags & VM_MAYREAD))
1432 * gups are always data accesses, not instruction
1433 * fetches, so execute=false here
1435 if (!arch_vma_access_permitted(vma, write, false, foreign))
1441 * This is "vma_lookup()", but with a warning if we would have
1442 * historically expanded the stack in the GUP code.
1444 static struct vm_area_struct *gup_vma_lookup(struct mm_struct *mm,
1447 #ifdef CONFIG_STACK_GROWSUP
1448 return vma_lookup(mm, addr);
1450 static volatile unsigned long next_warn;
1451 struct vm_area_struct *vma;
1452 unsigned long now, next;
1454 vma = find_vma(mm, addr);
1455 if (!vma || (addr >= vma->vm_start))
1458 /* Only warn for half-way relevant accesses */
1459 if (!(vma->vm_flags & VM_GROWSDOWN))
1461 if (vma->vm_start - addr > 65536)
1464 /* Let's not warn more than once an hour.. */
1465 now = jiffies; next = next_warn;
1466 if (next && time_before(now, next))
1468 next_warn = now + 60*60*HZ;
1470 /* Let people know things may have changed. */
1471 pr_warn("GUP no longer grows the stack in %s (%d): %lx-%lx (%lx)\n",
1472 current->comm, task_pid_nr(current),
1473 vma->vm_start, vma->vm_end, addr);
1480 * __get_user_pages() - pin user pages in memory
1481 * @mm: mm_struct of target mm
1482 * @start: starting user address
1483 * @nr_pages: number of pages from start to pin
1484 * @gup_flags: flags modifying pin behaviour
1485 * @pages: array that receives pointers to the pages pinned.
1486 * Should be at least nr_pages long. Or NULL, if caller
1487 * only intends to ensure the pages are faulted in.
1488 * @locked: whether we're still with the mmap_lock held
1490 * Returns either number of pages pinned (which may be less than the
1491 * number requested), or an error. Details about the return value:
1493 * -- If nr_pages is 0, returns 0.
1494 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
1495 * -- If nr_pages is >0, and some pages were pinned, returns the number of
1496 * pages pinned. Again, this may be less than nr_pages.
1497 * -- 0 return value is possible when the fault would need to be retried.
1499 * The caller is responsible for releasing returned @pages, via put_page().
1501 * Must be called with mmap_lock held. It may be released. See below.
1503 * __get_user_pages walks a process's page tables and takes a reference to
1504 * each struct page that each user address corresponds to at a given
1505 * instant. That is, it takes the page that would be accessed if a user
1506 * thread accesses the given user virtual address at that instant.
1508 * This does not guarantee that the page exists in the user mappings when
1509 * __get_user_pages returns, and there may even be a completely different
1510 * page there in some cases (eg. if mmapped pagecache has been invalidated
1511 * and subsequently re-faulted). However it does guarantee that the page
1512 * won't be freed completely. And mostly callers simply care that the page
1513 * contains data that was valid *at some point in time*. Typically, an IO
1514 * or similar operation cannot guarantee anything stronger anyway because
1515 * locks can't be held over the syscall boundary.
1517 * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
1518 * the page is written to, set_page_dirty (or set_page_dirty_lock, as
1519 * appropriate) must be called after the page is finished with, and
1520 * before put_page is called.
1522 * If FOLL_UNLOCKABLE is set without FOLL_NOWAIT then the mmap_lock may
1523 * be released. If this happens *@locked will be set to 0 on return.
1525 * A caller using such a combination of @gup_flags must therefore hold the
1526 * mmap_lock for reading only, and recognize when it's been released. Otherwise,
1527 * it must be held for either reading or writing and will not be released.
1529 * In most cases, get_user_pages or get_user_pages_fast should be used
1530 * instead of __get_user_pages. __get_user_pages should be used only if
1531 * you need some special @gup_flags.
1533 static long __get_user_pages(struct mm_struct *mm,
1534 unsigned long start, unsigned long nr_pages,
1535 unsigned int gup_flags, struct page **pages,
1538 long ret = 0, i = 0;
1539 struct vm_area_struct *vma = NULL;
1540 struct follow_page_context ctx = { NULL };
1545 start = untagged_addr_remote(mm, start);
1547 VM_BUG_ON(!!pages != !!(gup_flags & (FOLL_GET | FOLL_PIN)));
1551 unsigned int foll_flags = gup_flags;
1552 unsigned int page_increm;
1554 /* first iteration or cross vma bound */
1555 if (!vma || start >= vma->vm_end) {
1557 * MADV_POPULATE_(READ|WRITE) wants to handle VMA
1558 * lookups+error reporting differently.
1560 if (gup_flags & FOLL_MADV_POPULATE) {
1561 vma = vma_lookup(mm, start);
1566 if (check_vma_flags(vma, gup_flags)) {
1572 vma = gup_vma_lookup(mm, start);
1573 if (!vma && in_gate_area(mm, start)) {
1574 ret = get_gate_page(mm, start & PAGE_MASK,
1576 pages ? &page : NULL);
1587 ret = check_vma_flags(vma, gup_flags);
1593 * If we have a pending SIGKILL, don't keep faulting pages and
1594 * potentially allocating memory.
1596 if (fatal_signal_pending(current)) {
1602 page = follow_page_mask(vma, start, foll_flags, &ctx);
1603 if (!page || PTR_ERR(page) == -EMLINK) {
1604 ret = faultin_page(vma, start, &foll_flags,
1605 PTR_ERR(page) == -EMLINK, locked);
1619 } else if (PTR_ERR(page) == -EEXIST) {
1621 * Proper page table entry exists, but no corresponding
1622 * struct page. If the caller expects **pages to be
1623 * filled in, bail out now, because that can't be done
1627 ret = PTR_ERR(page);
1630 } else if (IS_ERR(page)) {
1631 ret = PTR_ERR(page);
1635 page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
1636 if (page_increm > nr_pages)
1637 page_increm = nr_pages;
1640 struct page *subpage;
1644 * This must be a large folio (and doesn't need to
1645 * be the whole folio; it can be part of it), do
1646 * the refcount work for all the subpages too.
1648 * NOTE: here the page may not be the head page
1649 * e.g. when start addr is not thp-size aligned.
1650 * try_grab_folio() should have taken care of tail
1653 if (page_increm > 1) {
1654 struct folio *folio = page_folio(page);
1657 * Since we already hold refcount on the
1658 * large folio, this should never fail.
1660 if (try_grab_folio(folio, page_increm - 1,
1663 * Release the 1st page ref if the
1664 * folio is problematic, fail hard.
1666 gup_put_folio(folio, 1,
1673 for (j = 0; j < page_increm; j++) {
1674 subpage = nth_page(page, j);
1675 pages[i + j] = subpage;
1676 flush_anon_page(vma, subpage, start + j * PAGE_SIZE);
1677 flush_dcache_page(subpage);
1682 start += page_increm * PAGE_SIZE;
1683 nr_pages -= page_increm;
1687 put_dev_pagemap(ctx.pgmap);
1691 static bool vma_permits_fault(struct vm_area_struct *vma,
1692 unsigned int fault_flags)
1694 bool write = !!(fault_flags & FAULT_FLAG_WRITE);
1695 bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
1696 vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
1698 if (!(vm_flags & vma->vm_flags))
1702 * The architecture might have a hardware protection
1703 * mechanism other than read/write that can deny access.
1705 * gup always represents data access, not instruction
1706 * fetches, so execute=false here:
1708 if (!arch_vma_access_permitted(vma, write, false, foreign))
1715 * fixup_user_fault() - manually resolve a user page fault
1716 * @mm: mm_struct of target mm
1717 * @address: user address
1718 * @fault_flags:flags to pass down to handle_mm_fault()
1719 * @unlocked: did we unlock the mmap_lock while retrying, maybe NULL if caller
1720 * does not allow retry. If NULL, the caller must guarantee
1721 * that fault_flags does not contain FAULT_FLAG_ALLOW_RETRY.
1723 * This is meant to be called in the specific scenario where for locking reasons
1724 * we try to access user memory in atomic context (within a pagefault_disable()
1725 * section), this returns -EFAULT, and we want to resolve the user fault before
1728 * Typically this is meant to be used by the futex code.
1730 * The main difference with get_user_pages() is that this function will
1731 * unconditionally call handle_mm_fault() which will in turn perform all the
1732 * necessary SW fixup of the dirty and young bits in the PTE, while
1733 * get_user_pages() only guarantees to update these in the struct page.
1735 * This is important for some architectures where those bits also gate the
1736 * access permission to the page because they are maintained in software. On
1737 * such architectures, gup() will not be enough to make a subsequent access
1740 * This function will not return with an unlocked mmap_lock. So it has not the
1741 * same semantics wrt the @mm->mmap_lock as does filemap_fault().
1743 int fixup_user_fault(struct mm_struct *mm,
1744 unsigned long address, unsigned int fault_flags,
1747 struct vm_area_struct *vma;
1750 address = untagged_addr_remote(mm, address);
1753 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1756 vma = gup_vma_lookup(mm, address);
1760 if (!vma_permits_fault(vma, fault_flags))
1763 if ((fault_flags & FAULT_FLAG_KILLABLE) &&
1764 fatal_signal_pending(current))
1767 ret = handle_mm_fault(vma, address, fault_flags, NULL);
1769 if (ret & VM_FAULT_COMPLETED) {
1771 * NOTE: it's a pity that we need to retake the lock here
1772 * to pair with the unlock() in the callers. Ideally we
1773 * could tell the callers so they do not need to unlock.
1780 if (ret & VM_FAULT_ERROR) {
1781 int err = vm_fault_to_errno(ret, 0);
1788 if (ret & VM_FAULT_RETRY) {
1791 fault_flags |= FAULT_FLAG_TRIED;
1797 EXPORT_SYMBOL_GPL(fixup_user_fault);
1800 * GUP always responds to fatal signals. When FOLL_INTERRUPTIBLE is
1801 * specified, it'll also respond to generic signals. The caller of GUP
1802 * that has FOLL_INTERRUPTIBLE should take care of the GUP interruption.
1804 static bool gup_signal_pending(unsigned int flags)
1806 if (fatal_signal_pending(current))
1809 if (!(flags & FOLL_INTERRUPTIBLE))
1812 return signal_pending(current);
1816 * Locking: (*locked == 1) means that the mmap_lock has already been acquired by
1817 * the caller. This function may drop the mmap_lock. If it does so, then it will
1818 * set (*locked = 0).
1820 * (*locked == 0) means that the caller expects this function to acquire and
1821 * drop the mmap_lock. Therefore, the value of *locked will still be zero when
1822 * the function returns, even though it may have changed temporarily during
1823 * function execution.
1825 * Please note that this function, unlike __get_user_pages(), will not return 0
1826 * for nr_pages > 0, unless FOLL_NOWAIT is used.
1828 static __always_inline long __get_user_pages_locked(struct mm_struct *mm,
1829 unsigned long start,
1830 unsigned long nr_pages,
1831 struct page **pages,
1835 long ret, pages_done;
1836 bool must_unlock = false;
1842 * The internal caller expects GUP to manage the lock internally and the
1843 * lock must be released when this returns.
1846 if (mmap_read_lock_killable(mm))
1852 mmap_assert_locked(mm);
1854 if (flags & FOLL_PIN)
1855 mm_set_has_pinned_flag(&mm->flags);
1858 * FOLL_PIN and FOLL_GET are mutually exclusive. Traditional behavior
1859 * is to set FOLL_GET if the caller wants pages[] filled in (but has
1860 * carelessly failed to specify FOLL_GET), so keep doing that, but only
1861 * for FOLL_GET, not for the newer FOLL_PIN.
1863 * FOLL_PIN always expects pages to be non-null, but no need to assert
1864 * that here, as any failures will be obvious enough.
1866 if (pages && !(flags & FOLL_PIN))
1871 ret = __get_user_pages(mm, start, nr_pages, flags, pages,
1873 if (!(flags & FOLL_UNLOCKABLE)) {
1874 /* VM_FAULT_RETRY couldn't trigger, bypass */
1879 /* VM_FAULT_RETRY or VM_FAULT_COMPLETED cannot return errors */
1882 BUG_ON(ret >= nr_pages);
1893 * VM_FAULT_RETRY didn't trigger or it was a
1901 * VM_FAULT_RETRY triggered, so seek to the faulting offset.
1902 * For the prefault case (!pages) we only update counts.
1906 start += ret << PAGE_SHIFT;
1908 /* The lock was temporarily dropped, so we must unlock later */
1913 * Repeat on the address that fired VM_FAULT_RETRY
1914 * with both FAULT_FLAG_ALLOW_RETRY and
1915 * FAULT_FLAG_TRIED. Note that GUP can be interrupted
1916 * by fatal signals of even common signals, depending on
1917 * the caller's request. So we need to check it before we
1918 * start trying again otherwise it can loop forever.
1920 if (gup_signal_pending(flags)) {
1922 pages_done = -EINTR;
1926 ret = mmap_read_lock_killable(mm);
1935 ret = __get_user_pages(mm, start, 1, flags | FOLL_TRIED,
1938 /* Continue to retry until we succeeded */
1956 if (must_unlock && *locked) {
1958 * We either temporarily dropped the lock, or the caller
1959 * requested that we both acquire and drop the lock. Either way,
1960 * we must now unlock, and notify the caller of that state.
1962 mmap_read_unlock(mm);
1967 * Failing to pin anything implies something has gone wrong (except when
1968 * FOLL_NOWAIT is specified).
1970 if (WARN_ON_ONCE(pages_done == 0 && !(flags & FOLL_NOWAIT)))
1977 * populate_vma_page_range() - populate a range of pages in the vma.
1979 * @start: start address
1981 * @locked: whether the mmap_lock is still held
1983 * This takes care of mlocking the pages too if VM_LOCKED is set.
1985 * Return either number of pages pinned in the vma, or a negative error
1988 * vma->vm_mm->mmap_lock must be held.
1990 * If @locked is NULL, it may be held for read or write and will
1993 * If @locked is non-NULL, it must held for read only and may be
1994 * released. If it's released, *@locked will be set to 0.
1996 long populate_vma_page_range(struct vm_area_struct *vma,
1997 unsigned long start, unsigned long end, int *locked)
1999 struct mm_struct *mm = vma->vm_mm;
2000 unsigned long nr_pages = (end - start) / PAGE_SIZE;
2001 int local_locked = 1;
2005 VM_BUG_ON(!PAGE_ALIGNED(start));
2006 VM_BUG_ON(!PAGE_ALIGNED(end));
2007 VM_BUG_ON_VMA(start < vma->vm_start, vma);
2008 VM_BUG_ON_VMA(end > vma->vm_end, vma);
2009 mmap_assert_locked(mm);
2012 * Rightly or wrongly, the VM_LOCKONFAULT case has never used
2013 * faultin_page() to break COW, so it has no work to do here.
2015 if (vma->vm_flags & VM_LOCKONFAULT)
2018 /* ... similarly, we've never faulted in PROT_NONE pages */
2019 if (!vma_is_accessible(vma))
2022 gup_flags = FOLL_TOUCH;
2024 * We want to touch writable mappings with a write fault in order
2025 * to break COW, except for shared mappings because these don't COW
2026 * and we would not want to dirty them for nothing.
2028 * Otherwise, do a read fault, and use FOLL_FORCE in case it's not
2029 * readable (ie write-only or executable).
2031 if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
2032 gup_flags |= FOLL_WRITE;
2034 gup_flags |= FOLL_FORCE;
2037 gup_flags |= FOLL_UNLOCKABLE;
2040 * We made sure addr is within a VMA, so the following will
2041 * not result in a stack expansion that recurses back here.
2043 ret = __get_user_pages(mm, start, nr_pages, gup_flags,
2044 NULL, locked ? locked : &local_locked);
2050 * faultin_page_range() - populate (prefault) page tables inside the
2051 * given range readable/writable
2053 * This takes care of mlocking the pages, too, if VM_LOCKED is set.
2055 * @mm: the mm to populate page tables in
2056 * @start: start address
2058 * @write: whether to prefault readable or writable
2059 * @locked: whether the mmap_lock is still held
2061 * Returns either number of processed pages in the MM, or a negative error
2062 * code on error (see __get_user_pages()). Note that this function reports
2063 * errors related to VMAs, such as incompatible mappings, as expected by
2064 * MADV_POPULATE_(READ|WRITE).
2066 * The range must be page-aligned.
2068 * mm->mmap_lock must be held. If it's released, *@locked will be set to 0.
2070 long faultin_page_range(struct mm_struct *mm, unsigned long start,
2071 unsigned long end, bool write, int *locked)
2073 unsigned long nr_pages = (end - start) / PAGE_SIZE;
2077 VM_BUG_ON(!PAGE_ALIGNED(start));
2078 VM_BUG_ON(!PAGE_ALIGNED(end));
2079 mmap_assert_locked(mm);
2082 * FOLL_TOUCH: Mark page accessed and thereby young; will also mark
2083 * the page dirty with FOLL_WRITE -- which doesn't make a
2084 * difference with !FOLL_FORCE, because the page is writable
2085 * in the page table.
2086 * FOLL_HWPOISON: Return -EHWPOISON instead of -EFAULT when we hit
2088 * !FOLL_FORCE: Require proper access permissions.
2090 gup_flags = FOLL_TOUCH | FOLL_HWPOISON | FOLL_UNLOCKABLE |
2093 gup_flags |= FOLL_WRITE;
2095 ret = __get_user_pages_locked(mm, start, nr_pages, NULL, locked,
2102 * __mm_populate - populate and/or mlock pages within a range of address space.
2104 * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
2105 * flags. VMAs must be already marked with the desired vm_flags, and
2106 * mmap_lock must not be held.
2108 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
2110 struct mm_struct *mm = current->mm;
2111 unsigned long end, nstart, nend;
2112 struct vm_area_struct *vma = NULL;
2118 for (nstart = start; nstart < end; nstart = nend) {
2120 * We want to fault in pages for [nstart; end) address range.
2121 * Find first corresponding VMA.
2126 vma = find_vma_intersection(mm, nstart, end);
2127 } else if (nstart >= vma->vm_end)
2128 vma = find_vma_intersection(mm, vma->vm_end, end);
2133 * Set [nstart; nend) to intersection of desired address
2134 * range with the first VMA. Also, skip undesirable VMA types.
2136 nend = min(end, vma->vm_end);
2137 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
2139 if (nstart < vma->vm_start)
2140 nstart = vma->vm_start;
2142 * Now fault in a range of pages. populate_vma_page_range()
2143 * double checks the vma flags, so that it won't mlock pages
2144 * if the vma was already munlocked.
2146 ret = populate_vma_page_range(vma, nstart, nend, &locked);
2148 if (ignore_errors) {
2150 continue; /* continue at next VMA */
2154 nend = nstart + ret * PAGE_SIZE;
2158 mmap_read_unlock(mm);
2159 return ret; /* 0 or negative error code */
2161 #else /* CONFIG_MMU */
2162 static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start,
2163 unsigned long nr_pages, struct page **pages,
2164 int *locked, unsigned int foll_flags)
2166 struct vm_area_struct *vma;
2167 bool must_unlock = false;
2168 unsigned long vm_flags;
2175 * The internal caller expects GUP to manage the lock internally and the
2176 * lock must be released when this returns.
2179 if (mmap_read_lock_killable(mm))
2185 /* calculate required read or write permissions.
2186 * If FOLL_FORCE is set, we only require the "MAY" flags.
2188 vm_flags = (foll_flags & FOLL_WRITE) ?
2189 (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
2190 vm_flags &= (foll_flags & FOLL_FORCE) ?
2191 (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
2193 for (i = 0; i < nr_pages; i++) {
2194 vma = find_vma(mm, start);
2198 /* protect what we can, including chardevs */
2199 if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
2200 !(vm_flags & vma->vm_flags))
2204 pages[i] = virt_to_page((void *)start);
2209 start = (start + PAGE_SIZE) & PAGE_MASK;
2212 if (must_unlock && *locked) {
2213 mmap_read_unlock(mm);
2217 return i ? : -EFAULT;
2219 #endif /* !CONFIG_MMU */
2222 * fault_in_writeable - fault in userspace address range for writing
2223 * @uaddr: start of address range
2224 * @size: size of address range
2226 * Returns the number of bytes not faulted in (like copy_to_user() and
2227 * copy_from_user()).
2229 size_t fault_in_writeable(char __user *uaddr, size_t size)
2231 char __user *start = uaddr, *end;
2233 if (unlikely(size == 0))
2235 if (!user_write_access_begin(uaddr, size))
2237 if (!PAGE_ALIGNED(uaddr)) {
2238 unsafe_put_user(0, uaddr, out);
2239 uaddr = (char __user *)PAGE_ALIGN((unsigned long)uaddr);
2241 end = (char __user *)PAGE_ALIGN((unsigned long)start + size);
2242 if (unlikely(end < start))
2244 while (uaddr != end) {
2245 unsafe_put_user(0, uaddr, out);
2250 user_write_access_end();
2251 if (size > uaddr - start)
2252 return size - (uaddr - start);
2255 EXPORT_SYMBOL(fault_in_writeable);
2258 * fault_in_subpage_writeable - fault in an address range for writing
2259 * @uaddr: start of address range
2260 * @size: size of address range
2262 * Fault in a user address range for writing while checking for permissions at
2263 * sub-page granularity (e.g. arm64 MTE). This function should be used when
2264 * the caller cannot guarantee forward progress of a copy_to_user() loop.
2266 * Returns the number of bytes not faulted in (like copy_to_user() and
2267 * copy_from_user()).
2269 size_t fault_in_subpage_writeable(char __user *uaddr, size_t size)
2274 * Attempt faulting in at page granularity first for page table
2275 * permission checking. The arch-specific probe_subpage_writeable()
2276 * functions may not check for this.
2278 faulted_in = size - fault_in_writeable(uaddr, size);
2280 faulted_in -= probe_subpage_writeable(uaddr, faulted_in);
2282 return size - faulted_in;
2284 EXPORT_SYMBOL(fault_in_subpage_writeable);
2287 * fault_in_safe_writeable - fault in an address range for writing
2288 * @uaddr: start of address range
2289 * @size: length of address range
2291 * Faults in an address range for writing. This is primarily useful when we
2292 * already know that some or all of the pages in the address range aren't in
2295 * Unlike fault_in_writeable(), this function is non-destructive.
2297 * Note that we don't pin or otherwise hold the pages referenced that we fault
2298 * in. There's no guarantee that they'll stay in memory for any duration of
2301 * Returns the number of bytes not faulted in, like copy_to_user() and
2304 size_t fault_in_safe_writeable(const char __user *uaddr, size_t size)
2306 unsigned long start = (unsigned long)uaddr, end;
2307 struct mm_struct *mm = current->mm;
2308 bool unlocked = false;
2310 if (unlikely(size == 0))
2312 end = PAGE_ALIGN(start + size);
2318 if (fixup_user_fault(mm, start, FAULT_FLAG_WRITE, &unlocked))
2320 start = (start + PAGE_SIZE) & PAGE_MASK;
2321 } while (start != end);
2322 mmap_read_unlock(mm);
2324 if (size > (unsigned long)uaddr - start)
2325 return size - ((unsigned long)uaddr - start);
2328 EXPORT_SYMBOL(fault_in_safe_writeable);
2331 * fault_in_readable - fault in userspace address range for reading
2332 * @uaddr: start of user address range
2333 * @size: size of user address range
2335 * Returns the number of bytes not faulted in (like copy_to_user() and
2336 * copy_from_user()).
2338 size_t fault_in_readable(const char __user *uaddr, size_t size)
2340 const char __user *start = uaddr, *end;
2343 if (unlikely(size == 0))
2345 if (!user_read_access_begin(uaddr, size))
2347 if (!PAGE_ALIGNED(uaddr)) {
2348 unsafe_get_user(c, uaddr, out);
2349 uaddr = (const char __user *)PAGE_ALIGN((unsigned long)uaddr);
2351 end = (const char __user *)PAGE_ALIGN((unsigned long)start + size);
2352 if (unlikely(end < start))
2354 while (uaddr != end) {
2355 unsafe_get_user(c, uaddr, out);
2360 user_read_access_end();
2362 if (size > uaddr - start)
2363 return size - (uaddr - start);
2366 EXPORT_SYMBOL(fault_in_readable);
2369 * get_dump_page() - pin user page in memory while writing it to core dump
2370 * @addr: user address
2372 * Returns struct page pointer of user page pinned for dump,
2373 * to be freed afterwards by put_page().
2375 * Returns NULL on any kind of failure - a hole must then be inserted into
2376 * the corefile, to preserve alignment with its headers; and also returns
2377 * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
2378 * allowing a hole to be left in the corefile to save disk space.
2380 * Called without mmap_lock (takes and releases the mmap_lock by itself).
2382 #ifdef CONFIG_ELF_CORE
2383 struct page *get_dump_page(unsigned long addr)
2389 ret = __get_user_pages_locked(current->mm, addr, 1, &page, &locked,
2390 FOLL_FORCE | FOLL_DUMP | FOLL_GET);
2391 return (ret == 1) ? page : NULL;
2393 #endif /* CONFIG_ELF_CORE */
2395 #ifdef CONFIG_MIGRATION
2397 * Returns the number of collected pages. Return value is always >= 0.
2399 static unsigned long collect_longterm_unpinnable_pages(
2400 struct list_head *movable_page_list,
2401 unsigned long nr_pages,
2402 struct page **pages)
2404 unsigned long i, collected = 0;
2405 struct folio *prev_folio = NULL;
2406 bool drain_allow = true;
2408 for (i = 0; i < nr_pages; i++) {
2409 struct folio *folio = page_folio(pages[i]);
2411 if (folio == prev_folio)
2415 if (folio_is_longterm_pinnable(folio))
2420 if (folio_is_device_coherent(folio))
2423 if (folio_test_hugetlb(folio)) {
2424 isolate_hugetlb(folio, movable_page_list);
2428 if (!folio_test_lru(folio) && drain_allow) {
2429 lru_add_drain_all();
2430 drain_allow = false;
2433 if (!folio_isolate_lru(folio))
2436 list_add_tail(&folio->lru, movable_page_list);
2437 node_stat_mod_folio(folio,
2438 NR_ISOLATED_ANON + folio_is_file_lru(folio),
2439 folio_nr_pages(folio));
2446 * Unpins all pages and migrates device coherent pages and movable_page_list.
2447 * Returns -EAGAIN if all pages were successfully migrated or -errno for failure
2448 * (or partial success).
2450 static int migrate_longterm_unpinnable_pages(
2451 struct list_head *movable_page_list,
2452 unsigned long nr_pages,
2453 struct page **pages)
2458 for (i = 0; i < nr_pages; i++) {
2459 struct folio *folio = page_folio(pages[i]);
2461 if (folio_is_device_coherent(folio)) {
2463 * Migration will fail if the page is pinned, so convert
2464 * the pin on the source page to a normal reference.
2468 gup_put_folio(folio, 1, FOLL_PIN);
2470 if (migrate_device_coherent_page(&folio->page)) {
2479 * We can't migrate pages with unexpected references, so drop
2480 * the reference obtained by __get_user_pages_locked().
2481 * Migrating pages have been added to movable_page_list after
2482 * calling folio_isolate_lru() which takes a reference so the
2483 * page won't be freed if it's migrating.
2485 unpin_user_page(pages[i]);
2489 if (!list_empty(movable_page_list)) {
2490 struct migration_target_control mtc = {
2491 .nid = NUMA_NO_NODE,
2492 .gfp_mask = GFP_USER | __GFP_NOWARN,
2493 .reason = MR_LONGTERM_PIN,
2496 if (migrate_pages(movable_page_list, alloc_migration_target,
2497 NULL, (unsigned long)&mtc, MIGRATE_SYNC,
2498 MR_LONGTERM_PIN, NULL)) {
2504 putback_movable_pages(movable_page_list);
2509 for (i = 0; i < nr_pages; i++)
2511 unpin_user_page(pages[i]);
2512 putback_movable_pages(movable_page_list);
2518 * Check whether all pages are *allowed* to be pinned. Rather confusingly, all
2519 * pages in the range are required to be pinned via FOLL_PIN, before calling
2522 * If any pages in the range are not allowed to be pinned, then this routine
2523 * will migrate those pages away, unpin all the pages in the range and return
2524 * -EAGAIN. The caller should re-pin the entire range with FOLL_PIN and then
2525 * call this routine again.
2527 * If an error other than -EAGAIN occurs, this indicates a migration failure.
2528 * The caller should give up, and propagate the error back up the call stack.
2530 * If everything is OK and all pages in the range are allowed to be pinned, then
2531 * this routine leaves all pages pinned and returns zero for success.
2533 static long check_and_migrate_movable_pages(unsigned long nr_pages,
2534 struct page **pages)
2536 unsigned long collected;
2537 LIST_HEAD(movable_page_list);
2539 collected = collect_longterm_unpinnable_pages(&movable_page_list,
2544 return migrate_longterm_unpinnable_pages(&movable_page_list, nr_pages,
2548 static long check_and_migrate_movable_pages(unsigned long nr_pages,
2549 struct page **pages)
2553 #endif /* CONFIG_MIGRATION */
2556 * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
2557 * allows us to process the FOLL_LONGTERM flag.
2559 static long __gup_longterm_locked(struct mm_struct *mm,
2560 unsigned long start,
2561 unsigned long nr_pages,
2562 struct page **pages,
2564 unsigned int gup_flags)
2567 long rc, nr_pinned_pages;
2569 if (!(gup_flags & FOLL_LONGTERM))
2570 return __get_user_pages_locked(mm, start, nr_pages, pages,
2573 flags = memalloc_pin_save();
2575 nr_pinned_pages = __get_user_pages_locked(mm, start, nr_pages,
2578 if (nr_pinned_pages <= 0) {
2579 rc = nr_pinned_pages;
2583 /* FOLL_LONGTERM implies FOLL_PIN */
2584 rc = check_and_migrate_movable_pages(nr_pinned_pages, pages);
2585 } while (rc == -EAGAIN);
2586 memalloc_pin_restore(flags);
2587 return rc ? rc : nr_pinned_pages;
2591 * Check that the given flags are valid for the exported gup/pup interface, and
2592 * update them with the required flags that the caller must have set.
2594 static bool is_valid_gup_args(struct page **pages, int *locked,
2595 unsigned int *gup_flags_p, unsigned int to_set)
2597 unsigned int gup_flags = *gup_flags_p;
2600 * These flags not allowed to be specified externally to the gup
2602 * - FOLL_TOUCH/FOLL_PIN/FOLL_TRIED/FOLL_FAST_ONLY are internal only
2603 * - FOLL_REMOTE is internal only and used on follow_page()
2604 * - FOLL_UNLOCKABLE is internal only and used if locked is !NULL
2606 if (WARN_ON_ONCE(gup_flags & INTERNAL_GUP_FLAGS))
2609 gup_flags |= to_set;
2611 /* At the external interface locked must be set */
2612 if (WARN_ON_ONCE(*locked != 1))
2615 gup_flags |= FOLL_UNLOCKABLE;
2618 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2619 if (WARN_ON_ONCE((gup_flags & (FOLL_PIN | FOLL_GET)) ==
2620 (FOLL_PIN | FOLL_GET)))
2623 /* LONGTERM can only be specified when pinning */
2624 if (WARN_ON_ONCE(!(gup_flags & FOLL_PIN) && (gup_flags & FOLL_LONGTERM)))
2627 /* Pages input must be given if using GET/PIN */
2628 if (WARN_ON_ONCE((gup_flags & (FOLL_GET | FOLL_PIN)) && !pages))
2631 /* We want to allow the pgmap to be hot-unplugged at all times */
2632 if (WARN_ON_ONCE((gup_flags & FOLL_LONGTERM) &&
2633 (gup_flags & FOLL_PCI_P2PDMA)))
2636 *gup_flags_p = gup_flags;
2642 * get_user_pages_remote() - pin user pages in memory
2643 * @mm: mm_struct of target mm
2644 * @start: starting user address
2645 * @nr_pages: number of pages from start to pin
2646 * @gup_flags: flags modifying lookup behaviour
2647 * @pages: array that receives pointers to the pages pinned.
2648 * Should be at least nr_pages long. Or NULL, if caller
2649 * only intends to ensure the pages are faulted in.
2650 * @locked: pointer to lock flag indicating whether lock is held and
2651 * subsequently whether VM_FAULT_RETRY functionality can be
2652 * utilised. Lock must initially be held.
2654 * Returns either number of pages pinned (which may be less than the
2655 * number requested), or an error. Details about the return value:
2657 * -- If nr_pages is 0, returns 0.
2658 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
2659 * -- If nr_pages is >0, and some pages were pinned, returns the number of
2660 * pages pinned. Again, this may be less than nr_pages.
2662 * The caller is responsible for releasing returned @pages, via put_page().
2664 * Must be called with mmap_lock held for read or write.
2666 * get_user_pages_remote walks a process's page tables and takes a reference
2667 * to each struct page that each user address corresponds to at a given
2668 * instant. That is, it takes the page that would be accessed if a user
2669 * thread accesses the given user virtual address at that instant.
2671 * This does not guarantee that the page exists in the user mappings when
2672 * get_user_pages_remote returns, and there may even be a completely different
2673 * page there in some cases (eg. if mmapped pagecache has been invalidated
2674 * and subsequently re-faulted). However it does guarantee that the page
2675 * won't be freed completely. And mostly callers simply care that the page
2676 * contains data that was valid *at some point in time*. Typically, an IO
2677 * or similar operation cannot guarantee anything stronger anyway because
2678 * locks can't be held over the syscall boundary.
2680 * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
2681 * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
2682 * be called after the page is finished with, and before put_page is called.
2684 * get_user_pages_remote is typically used for fewer-copy IO operations,
2685 * to get a handle on the memory by some means other than accesses
2686 * via the user virtual addresses. The pages may be submitted for
2687 * DMA to devices or accessed via their kernel linear mapping (via the
2688 * kmap APIs). Care should be taken to use the correct cache flushing APIs.
2690 * See also get_user_pages_fast, for performance critical applications.
2692 * get_user_pages_remote should be phased out in favor of
2693 * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
2694 * should use get_user_pages_remote because it cannot pass
2695 * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
2697 long get_user_pages_remote(struct mm_struct *mm,
2698 unsigned long start, unsigned long nr_pages,
2699 unsigned int gup_flags, struct page **pages,
2702 int local_locked = 1;
2704 if (!is_valid_gup_args(pages, locked, &gup_flags,
2705 FOLL_TOUCH | FOLL_REMOTE))
2708 return __get_user_pages_locked(mm, start, nr_pages, pages,
2709 locked ? locked : &local_locked,
2712 EXPORT_SYMBOL(get_user_pages_remote);
2714 #else /* CONFIG_MMU */
2715 long get_user_pages_remote(struct mm_struct *mm,
2716 unsigned long start, unsigned long nr_pages,
2717 unsigned int gup_flags, struct page **pages,
2722 #endif /* !CONFIG_MMU */
2725 * get_user_pages() - pin user pages in memory
2726 * @start: starting user address
2727 * @nr_pages: number of pages from start to pin
2728 * @gup_flags: flags modifying lookup behaviour
2729 * @pages: array that receives pointers to the pages pinned.
2730 * Should be at least nr_pages long. Or NULL, if caller
2731 * only intends to ensure the pages are faulted in.
2733 * This is the same as get_user_pages_remote(), just with a less-flexible
2734 * calling convention where we assume that the mm being operated on belongs to
2735 * the current task, and doesn't allow passing of a locked parameter. We also
2736 * obviously don't pass FOLL_REMOTE in here.
2738 long get_user_pages(unsigned long start, unsigned long nr_pages,
2739 unsigned int gup_flags, struct page **pages)
2743 if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_TOUCH))
2746 return __get_user_pages_locked(current->mm, start, nr_pages, pages,
2747 &locked, gup_flags);
2749 EXPORT_SYMBOL(get_user_pages);
2752 * get_user_pages_unlocked() is suitable to replace the form:
2754 * mmap_read_lock(mm);
2755 * get_user_pages(mm, ..., pages, NULL);
2756 * mmap_read_unlock(mm);
2760 * get_user_pages_unlocked(mm, ..., pages);
2762 * It is functionally equivalent to get_user_pages_fast so
2763 * get_user_pages_fast should be used instead if specific gup_flags
2764 * (e.g. FOLL_FORCE) are not required.
2766 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
2767 struct page **pages, unsigned int gup_flags)
2771 if (!is_valid_gup_args(pages, NULL, &gup_flags,
2772 FOLL_TOUCH | FOLL_UNLOCKABLE))
2775 return __get_user_pages_locked(current->mm, start, nr_pages, pages,
2776 &locked, gup_flags);
2778 EXPORT_SYMBOL(get_user_pages_unlocked);
2783 * get_user_pages_fast attempts to pin user pages by walking the page
2784 * tables directly and avoids taking locks. Thus the walker needs to be
2785 * protected from page table pages being freed from under it, and should
2786 * block any THP splits.
2788 * One way to achieve this is to have the walker disable interrupts, and
2789 * rely on IPIs from the TLB flushing code blocking before the page table
2790 * pages are freed. This is unsuitable for architectures that do not need
2791 * to broadcast an IPI when invalidating TLBs.
2793 * Another way to achieve this is to batch up page table containing pages
2794 * belonging to more than one mm_user, then rcu_sched a callback to free those
2795 * pages. Disabling interrupts will allow the gup_fast() walker to both block
2796 * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
2797 * (which is a relatively rare event). The code below adopts this strategy.
2799 * Before activating this code, please be aware that the following assumptions
2800 * are currently made:
2802 * *) Either MMU_GATHER_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
2803 * free pages containing page tables or TLB flushing requires IPI broadcast.
2805 * *) ptes can be read atomically by the architecture.
2807 * *) access_ok is sufficient to validate userspace address ranges.
2809 * The last two assumptions can be relaxed by the addition of helper functions.
2811 * This code is based heavily on the PowerPC implementation by Nick Piggin.
2813 #ifdef CONFIG_HAVE_GUP_FAST
2815 * Used in the GUP-fast path to determine whether GUP is permitted to work on
2818 * This call assumes the caller has pinned the folio, that the lowest page table
2819 * level still points to this folio, and that interrupts have been disabled.
2821 * GUP-fast must reject all secretmem folios.
2823 * Writing to pinned file-backed dirty tracked folios is inherently problematic
2824 * (see comment describing the writable_file_mapping_allowed() function). We
2825 * therefore try to avoid the most egregious case of a long-term mapping doing
2828 * This function cannot be as thorough as that one as the VMA is not available
2829 * in the fast path, so instead we whitelist known good cases and if in doubt,
2830 * fall back to the slow path.
2832 static bool gup_fast_folio_allowed(struct folio *folio, unsigned int flags)
2834 bool reject_file_backed = false;
2835 struct address_space *mapping;
2836 bool check_secretmem = false;
2837 unsigned long mapping_flags;
2840 * If we aren't pinning then no problematic write can occur. A long term
2841 * pin is the most egregious case so this is the one we disallow.
2843 if ((flags & (FOLL_PIN | FOLL_LONGTERM | FOLL_WRITE)) ==
2844 (FOLL_PIN | FOLL_LONGTERM | FOLL_WRITE))
2845 reject_file_backed = true;
2847 /* We hold a folio reference, so we can safely access folio fields. */
2849 /* secretmem folios are always order-0 folios. */
2850 if (IS_ENABLED(CONFIG_SECRETMEM) && !folio_test_large(folio))
2851 check_secretmem = true;
2853 if (!reject_file_backed && !check_secretmem)
2856 if (WARN_ON_ONCE(folio_test_slab(folio)))
2859 /* hugetlb neither requires dirty-tracking nor can be secretmem. */
2860 if (folio_test_hugetlb(folio))
2864 * GUP-fast disables IRQs. When IRQS are disabled, RCU grace periods
2865 * cannot proceed, which means no actions performed under RCU can
2868 * inodes and thus their mappings are freed under RCU, which means the
2869 * mapping cannot be freed beneath us and thus we can safely dereference
2872 lockdep_assert_irqs_disabled();
2875 * However, there may be operations which _alter_ the mapping, so ensure
2876 * we read it once and only once.
2878 mapping = READ_ONCE(folio->mapping);
2881 * The mapping may have been truncated, in any case we cannot determine
2882 * if this mapping is safe - fall back to slow path to determine how to
2888 /* Anonymous folios pose no problem. */
2889 mapping_flags = (unsigned long)mapping & PAGE_MAPPING_FLAGS;
2891 return mapping_flags & PAGE_MAPPING_ANON;
2894 * At this point, we know the mapping is non-null and points to an
2895 * address_space object.
2897 if (check_secretmem && secretmem_mapping(mapping))
2899 /* The only remaining allowed file system is shmem. */
2900 return !reject_file_backed || shmem_mapping(mapping);
2903 static void __maybe_unused gup_fast_undo_dev_pagemap(int *nr, int nr_start,
2904 unsigned int flags, struct page **pages)
2906 while ((*nr) - nr_start) {
2907 struct folio *folio = page_folio(pages[--(*nr)]);
2909 folio_clear_referenced(folio);
2910 gup_put_folio(folio, 1, flags);
2914 #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
2916 * GUP-fast relies on pte change detection to avoid concurrent pgtable
2919 * To pin the page, GUP-fast needs to do below in order:
2920 * (1) pin the page (by prefetching pte), then (2) check pte not changed.
2922 * For the rest of pgtable operations where pgtable updates can be racy
2923 * with GUP-fast, we need to do (1) clear pte, then (2) check whether page
2926 * Above will work for all pte-level operations, including THP split.
2928 * For THP collapse, it's a bit more complicated because GUP-fast may be
2929 * walking a pgtable page that is being freed (pte is still valid but pmd
2930 * can be cleared already). To avoid race in such condition, we need to
2931 * also check pmd here to make sure pmd doesn't change (corresponds to
2932 * pmdp_collapse_flush() in the THP collapse code path).
2934 static int gup_fast_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr,
2935 unsigned long end, unsigned int flags, struct page **pages,
2938 struct dev_pagemap *pgmap = NULL;
2939 int nr_start = *nr, ret = 0;
2942 ptem = ptep = pte_offset_map(&pmd, addr);
2946 pte_t pte = ptep_get_lockless(ptep);
2948 struct folio *folio;
2951 * Always fallback to ordinary GUP on PROT_NONE-mapped pages:
2952 * pte_access_permitted() better should reject these pages
2953 * either way: otherwise, GUP-fast might succeed in
2954 * cases where ordinary GUP would fail due to VMA access
2957 if (pte_protnone(pte))
2960 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2963 if (pte_devmap(pte)) {
2964 if (unlikely(flags & FOLL_LONGTERM))
2967 pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
2968 if (unlikely(!pgmap)) {
2969 gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages);
2972 } else if (pte_special(pte))
2975 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2976 page = pte_page(pte);
2978 folio = try_grab_folio_fast(page, 1, flags);
2982 if (unlikely(pmd_val(pmd) != pmd_val(*pmdp)) ||
2983 unlikely(pte_val(pte) != pte_val(ptep_get(ptep)))) {
2984 gup_put_folio(folio, 1, flags);
2988 if (!gup_fast_folio_allowed(folio, flags)) {
2989 gup_put_folio(folio, 1, flags);
2993 if (!pte_write(pte) && gup_must_unshare(NULL, flags, page)) {
2994 gup_put_folio(folio, 1, flags);
2999 * We need to make the page accessible if and only if we are
3000 * going to access its content (the FOLL_PIN case). Please
3001 * see Documentation/core-api/pin_user_pages.rst for
3004 if (flags & FOLL_PIN) {
3005 ret = arch_make_page_accessible(page);
3007 gup_put_folio(folio, 1, flags);
3011 folio_set_referenced(folio);
3014 } while (ptep++, addr += PAGE_SIZE, addr != end);
3020 put_dev_pagemap(pgmap);
3027 * If we can't determine whether or not a pte is special, then fail immediately
3028 * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
3031 * For a futex to be placed on a THP tail page, get_futex_key requires a
3032 * get_user_pages_fast_only implementation that can pin pages. Thus it's still
3033 * useful to have gup_fast_pmd_leaf even if we can't operate on ptes.
3035 static int gup_fast_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr,
3036 unsigned long end, unsigned int flags, struct page **pages,
3041 #endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
3043 #if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
3044 static int gup_fast_devmap_leaf(unsigned long pfn, unsigned long addr,
3045 unsigned long end, unsigned int flags, struct page **pages, int *nr)
3048 struct dev_pagemap *pgmap = NULL;
3051 struct folio *folio;
3052 struct page *page = pfn_to_page(pfn);
3054 pgmap = get_dev_pagemap(pfn, pgmap);
3055 if (unlikely(!pgmap)) {
3056 gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages);
3060 if (!(flags & FOLL_PCI_P2PDMA) && is_pci_p2pdma_page(page)) {
3061 gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages);
3065 folio = try_grab_folio_fast(page, 1, flags);
3067 gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages);
3070 folio_set_referenced(folio);
3074 } while (addr += PAGE_SIZE, addr != end);
3076 put_dev_pagemap(pgmap);
3080 static int gup_fast_devmap_pmd_leaf(pmd_t orig, pmd_t *pmdp, unsigned long addr,
3081 unsigned long end, unsigned int flags, struct page **pages,
3084 unsigned long fault_pfn;
3087 fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
3088 if (!gup_fast_devmap_leaf(fault_pfn, addr, end, flags, pages, nr))
3091 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
3092 gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages);
3098 static int gup_fast_devmap_pud_leaf(pud_t orig, pud_t *pudp, unsigned long addr,
3099 unsigned long end, unsigned int flags, struct page **pages,
3102 unsigned long fault_pfn;
3105 fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
3106 if (!gup_fast_devmap_leaf(fault_pfn, addr, end, flags, pages, nr))
3109 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
3110 gup_fast_undo_dev_pagemap(nr, nr_start, flags, pages);
3116 static int gup_fast_devmap_pmd_leaf(pmd_t orig, pmd_t *pmdp, unsigned long addr,
3117 unsigned long end, unsigned int flags, struct page **pages,
3124 static int gup_fast_devmap_pud_leaf(pud_t pud, pud_t *pudp, unsigned long addr,
3125 unsigned long end, unsigned int flags, struct page **pages,
3133 static int gup_fast_pmd_leaf(pmd_t orig, pmd_t *pmdp, unsigned long addr,
3134 unsigned long end, unsigned int flags, struct page **pages,
3138 struct folio *folio;
3141 if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
3144 if (pmd_devmap(orig)) {
3145 if (unlikely(flags & FOLL_LONGTERM))
3147 return gup_fast_devmap_pmd_leaf(orig, pmdp, addr, end, flags,
3151 page = pmd_page(orig);
3152 refs = record_subpages(page, PMD_SIZE, addr, end, pages + *nr);
3154 folio = try_grab_folio_fast(page, refs, flags);
3158 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
3159 gup_put_folio(folio, refs, flags);
3163 if (!gup_fast_folio_allowed(folio, flags)) {
3164 gup_put_folio(folio, refs, flags);
3167 if (!pmd_write(orig) && gup_must_unshare(NULL, flags, &folio->page)) {
3168 gup_put_folio(folio, refs, flags);
3173 folio_set_referenced(folio);
3177 static int gup_fast_pud_leaf(pud_t orig, pud_t *pudp, unsigned long addr,
3178 unsigned long end, unsigned int flags, struct page **pages,
3182 struct folio *folio;
3185 if (!pud_access_permitted(orig, flags & FOLL_WRITE))
3188 if (pud_devmap(orig)) {
3189 if (unlikely(flags & FOLL_LONGTERM))
3191 return gup_fast_devmap_pud_leaf(orig, pudp, addr, end, flags,
3195 page = pud_page(orig);
3196 refs = record_subpages(page, PUD_SIZE, addr, end, pages + *nr);
3198 folio = try_grab_folio_fast(page, refs, flags);
3202 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
3203 gup_put_folio(folio, refs, flags);
3207 if (!gup_fast_folio_allowed(folio, flags)) {
3208 gup_put_folio(folio, refs, flags);
3212 if (!pud_write(orig) && gup_must_unshare(NULL, flags, &folio->page)) {
3213 gup_put_folio(folio, refs, flags);
3218 folio_set_referenced(folio);
3222 static int gup_fast_pgd_leaf(pgd_t orig, pgd_t *pgdp, unsigned long addr,
3223 unsigned long end, unsigned int flags, struct page **pages,
3228 struct folio *folio;
3230 if (!pgd_access_permitted(orig, flags & FOLL_WRITE))
3233 BUILD_BUG_ON(pgd_devmap(orig));
3235 page = pgd_page(orig);
3236 refs = record_subpages(page, PGDIR_SIZE, addr, end, pages + *nr);
3238 folio = try_grab_folio_fast(page, refs, flags);
3242 if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
3243 gup_put_folio(folio, refs, flags);
3247 if (!pgd_write(orig) && gup_must_unshare(NULL, flags, &folio->page)) {
3248 gup_put_folio(folio, refs, flags);
3252 if (!gup_fast_folio_allowed(folio, flags)) {
3253 gup_put_folio(folio, refs, flags);
3258 folio_set_referenced(folio);
3262 static int gup_fast_pmd_range(pud_t *pudp, pud_t pud, unsigned long addr,
3263 unsigned long end, unsigned int flags, struct page **pages,
3269 pmdp = pmd_offset_lockless(pudp, pud, addr);
3271 pmd_t pmd = pmdp_get_lockless(pmdp);
3273 next = pmd_addr_end(addr, end);
3274 if (!pmd_present(pmd))
3277 if (unlikely(pmd_leaf(pmd))) {
3278 /* See gup_fast_pte_range() */
3279 if (pmd_protnone(pmd))
3282 if (!gup_fast_pmd_leaf(pmd, pmdp, addr, next, flags,
3286 } else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
3288 * architecture have different format for hugetlbfs
3289 * pmd format and THP pmd format
3291 if (gup_hugepd(NULL, __hugepd(pmd_val(pmd)), addr,
3292 PMD_SHIFT, next, flags, pages, nr,
3295 } else if (!gup_fast_pte_range(pmd, pmdp, addr, next, flags,
3298 } while (pmdp++, addr = next, addr != end);
3303 static int gup_fast_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr,
3304 unsigned long end, unsigned int flags, struct page **pages,
3310 pudp = pud_offset_lockless(p4dp, p4d, addr);
3312 pud_t pud = READ_ONCE(*pudp);
3314 next = pud_addr_end(addr, end);
3315 if (unlikely(!pud_present(pud)))
3317 if (unlikely(pud_leaf(pud))) {
3318 if (!gup_fast_pud_leaf(pud, pudp, addr, next, flags,
3321 } else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
3322 if (gup_hugepd(NULL, __hugepd(pud_val(pud)), addr,
3323 PUD_SHIFT, next, flags, pages, nr,
3326 } else if (!gup_fast_pmd_range(pudp, pud, addr, next, flags,
3329 } while (pudp++, addr = next, addr != end);
3334 static int gup_fast_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr,
3335 unsigned long end, unsigned int flags, struct page **pages,
3341 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
3343 p4d_t p4d = READ_ONCE(*p4dp);
3345 next = p4d_addr_end(addr, end);
3346 if (!p4d_present(p4d))
3348 BUILD_BUG_ON(p4d_leaf(p4d));
3349 if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
3350 if (gup_hugepd(NULL, __hugepd(p4d_val(p4d)), addr,
3351 P4D_SHIFT, next, flags, pages, nr,
3354 } else if (!gup_fast_pud_range(p4dp, p4d, addr, next, flags,
3357 } while (p4dp++, addr = next, addr != end);
3362 static void gup_fast_pgd_range(unsigned long addr, unsigned long end,
3363 unsigned int flags, struct page **pages, int *nr)
3368 pgdp = pgd_offset(current->mm, addr);
3370 pgd_t pgd = READ_ONCE(*pgdp);
3372 next = pgd_addr_end(addr, end);
3375 if (unlikely(pgd_leaf(pgd))) {
3376 if (!gup_fast_pgd_leaf(pgd, pgdp, addr, next, flags,
3379 } else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
3380 if (gup_hugepd(NULL, __hugepd(pgd_val(pgd)), addr,
3381 PGDIR_SHIFT, next, flags, pages, nr,
3384 } else if (!gup_fast_p4d_range(pgdp, pgd, addr, next, flags,
3387 } while (pgdp++, addr = next, addr != end);
3390 static inline void gup_fast_pgd_range(unsigned long addr, unsigned long end,
3391 unsigned int flags, struct page **pages, int *nr)
3394 #endif /* CONFIG_HAVE_GUP_FAST */
3396 #ifndef gup_fast_permitted
3398 * Check if it's allowed to use get_user_pages_fast_only() for the range, or
3399 * we need to fall back to the slow version:
3401 static bool gup_fast_permitted(unsigned long start, unsigned long end)
3407 static unsigned long gup_fast(unsigned long start, unsigned long end,
3408 unsigned int gup_flags, struct page **pages)
3410 unsigned long flags;
3414 if (!IS_ENABLED(CONFIG_HAVE_GUP_FAST) ||
3415 !gup_fast_permitted(start, end))
3418 if (gup_flags & FOLL_PIN) {
3419 seq = raw_read_seqcount(¤t->mm->write_protect_seq);
3425 * Disable interrupts. The nested form is used, in order to allow full,
3426 * general purpose use of this routine.
3428 * With interrupts disabled, we block page table pages from being freed
3429 * from under us. See struct mmu_table_batch comments in
3430 * include/asm-generic/tlb.h for more details.
3432 * We do not adopt an rcu_read_lock() here as we also want to block IPIs
3433 * that come from THPs splitting.
3435 local_irq_save(flags);
3436 gup_fast_pgd_range(start, end, gup_flags, pages, &nr_pinned);
3437 local_irq_restore(flags);
3440 * When pinning pages for DMA there could be a concurrent write protect
3441 * from fork() via copy_page_range(), in this case always fail GUP-fast.
3443 if (gup_flags & FOLL_PIN) {
3444 if (read_seqcount_retry(¤t->mm->write_protect_seq, seq)) {
3445 gup_fast_unpin_user_pages(pages, nr_pinned);
3448 sanity_check_pinned_pages(pages, nr_pinned);
3454 static int gup_fast_fallback(unsigned long start, unsigned long nr_pages,
3455 unsigned int gup_flags, struct page **pages)
3457 unsigned long len, end;
3458 unsigned long nr_pinned;
3462 if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM |
3463 FOLL_FORCE | FOLL_PIN | FOLL_GET |
3464 FOLL_FAST_ONLY | FOLL_NOFAULT |
3465 FOLL_PCI_P2PDMA | FOLL_HONOR_NUMA_FAULT)))
3468 if (gup_flags & FOLL_PIN)
3469 mm_set_has_pinned_flag(¤t->mm->flags);
3471 if (!(gup_flags & FOLL_FAST_ONLY))
3472 might_lock_read(¤t->mm->mmap_lock);
3474 start = untagged_addr(start) & PAGE_MASK;
3475 len = nr_pages << PAGE_SHIFT;
3476 if (check_add_overflow(start, len, &end))
3478 if (end > TASK_SIZE_MAX)
3480 if (unlikely(!access_ok((void __user *)start, len)))
3483 nr_pinned = gup_fast(start, end, gup_flags, pages);
3484 if (nr_pinned == nr_pages || gup_flags & FOLL_FAST_ONLY)
3487 /* Slow path: try to get the remaining pages with get_user_pages */
3488 start += nr_pinned << PAGE_SHIFT;
3490 ret = __gup_longterm_locked(current->mm, start, nr_pages - nr_pinned,
3492 gup_flags | FOLL_TOUCH | FOLL_UNLOCKABLE);
3495 * The caller has to unpin the pages we already pinned so
3496 * returning -errno is not an option
3502 return ret + nr_pinned;
3506 * get_user_pages_fast_only() - pin user pages in memory
3507 * @start: starting user address
3508 * @nr_pages: number of pages from start to pin
3509 * @gup_flags: flags modifying pin behaviour
3510 * @pages: array that receives pointers to the pages pinned.
3511 * Should be at least nr_pages long.
3513 * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
3516 * If the architecture does not support this function, simply return with no
3519 * Careful, careful! COW breaking can go either way, so a non-write
3520 * access can get ambiguous page results. If you call this function without
3521 * 'write' set, you'd better be sure that you're ok with that ambiguity.
3523 int get_user_pages_fast_only(unsigned long start, int nr_pages,
3524 unsigned int gup_flags, struct page **pages)
3527 * Internally (within mm/gup.c), gup fast variants must set FOLL_GET,
3528 * because gup fast is always a "pin with a +1 page refcount" request.
3530 * FOLL_FAST_ONLY is required in order to match the API description of
3531 * this routine: no fall back to regular ("slow") GUP.
3533 if (!is_valid_gup_args(pages, NULL, &gup_flags,
3534 FOLL_GET | FOLL_FAST_ONLY))
3537 return gup_fast_fallback(start, nr_pages, gup_flags, pages);
3539 EXPORT_SYMBOL_GPL(get_user_pages_fast_only);
3542 * get_user_pages_fast() - pin user pages in memory
3543 * @start: starting user address
3544 * @nr_pages: number of pages from start to pin
3545 * @gup_flags: flags modifying pin behaviour
3546 * @pages: array that receives pointers to the pages pinned.
3547 * Should be at least nr_pages long.
3549 * Attempt to pin user pages in memory without taking mm->mmap_lock.
3550 * If not successful, it will fall back to taking the lock and
3551 * calling get_user_pages().
3553 * Returns number of pages pinned. This may be fewer than the number requested.
3554 * If nr_pages is 0 or negative, returns 0. If no pages were pinned, returns
3557 int get_user_pages_fast(unsigned long start, int nr_pages,
3558 unsigned int gup_flags, struct page **pages)
3561 * The caller may or may not have explicitly set FOLL_GET; either way is
3562 * OK. However, internally (within mm/gup.c), gup fast variants must set
3563 * FOLL_GET, because gup fast is always a "pin with a +1 page refcount"
3566 if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_GET))
3568 return gup_fast_fallback(start, nr_pages, gup_flags, pages);
3570 EXPORT_SYMBOL_GPL(get_user_pages_fast);
3573 * pin_user_pages_fast() - pin user pages in memory without taking locks
3575 * @start: starting user address
3576 * @nr_pages: number of pages from start to pin
3577 * @gup_flags: flags modifying pin behaviour
3578 * @pages: array that receives pointers to the pages pinned.
3579 * Should be at least nr_pages long.
3581 * Nearly the same as get_user_pages_fast(), except that FOLL_PIN is set. See
3582 * get_user_pages_fast() for documentation on the function arguments, because
3583 * the arguments here are identical.
3585 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3586 * see Documentation/core-api/pin_user_pages.rst for further details.
3588 * Note that if a zero_page is amongst the returned pages, it will not have
3589 * pins in it and unpin_user_page() will not remove pins from it.
3591 int pin_user_pages_fast(unsigned long start, int nr_pages,
3592 unsigned int gup_flags, struct page **pages)
3594 if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_PIN))
3596 return gup_fast_fallback(start, nr_pages, gup_flags, pages);
3598 EXPORT_SYMBOL_GPL(pin_user_pages_fast);
3601 * pin_user_pages_remote() - pin pages of a remote process
3603 * @mm: mm_struct of target mm
3604 * @start: starting user address
3605 * @nr_pages: number of pages from start to pin
3606 * @gup_flags: flags modifying lookup behaviour
3607 * @pages: array that receives pointers to the pages pinned.
3608 * Should be at least nr_pages long.
3609 * @locked: pointer to lock flag indicating whether lock is held and
3610 * subsequently whether VM_FAULT_RETRY functionality can be
3611 * utilised. Lock must initially be held.
3613 * Nearly the same as get_user_pages_remote(), except that FOLL_PIN is set. See
3614 * get_user_pages_remote() for documentation on the function arguments, because
3615 * the arguments here are identical.
3617 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3618 * see Documentation/core-api/pin_user_pages.rst for details.
3620 * Note that if a zero_page is amongst the returned pages, it will not have
3621 * pins in it and unpin_user_page*() will not remove pins from it.
3623 long pin_user_pages_remote(struct mm_struct *mm,
3624 unsigned long start, unsigned long nr_pages,
3625 unsigned int gup_flags, struct page **pages,
3628 int local_locked = 1;
3630 if (!is_valid_gup_args(pages, locked, &gup_flags,
3631 FOLL_PIN | FOLL_TOUCH | FOLL_REMOTE))
3633 return __gup_longterm_locked(mm, start, nr_pages, pages,
3634 locked ? locked : &local_locked,
3637 EXPORT_SYMBOL(pin_user_pages_remote);
3640 * pin_user_pages() - pin user pages in memory for use by other devices
3642 * @start: starting user address
3643 * @nr_pages: number of pages from start to pin
3644 * @gup_flags: flags modifying lookup behaviour
3645 * @pages: array that receives pointers to the pages pinned.
3646 * Should be at least nr_pages long.
3648 * Nearly the same as get_user_pages(), except that FOLL_TOUCH is not set, and
3651 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3652 * see Documentation/core-api/pin_user_pages.rst for details.
3654 * Note that if a zero_page is amongst the returned pages, it will not have
3655 * pins in it and unpin_user_page*() will not remove pins from it.
3657 long pin_user_pages(unsigned long start, unsigned long nr_pages,
3658 unsigned int gup_flags, struct page **pages)
3662 if (!is_valid_gup_args(pages, NULL, &gup_flags, FOLL_PIN))
3664 return __gup_longterm_locked(current->mm, start, nr_pages,
3665 pages, &locked, gup_flags);
3667 EXPORT_SYMBOL(pin_user_pages);
3670 * pin_user_pages_unlocked() is the FOLL_PIN variant of
3671 * get_user_pages_unlocked(). Behavior is the same, except that this one sets
3672 * FOLL_PIN and rejects FOLL_GET.
3674 * Note that if a zero_page is amongst the returned pages, it will not have
3675 * pins in it and unpin_user_page*() will not remove pins from it.
3677 long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
3678 struct page **pages, unsigned int gup_flags)
3682 if (!is_valid_gup_args(pages, NULL, &gup_flags,
3683 FOLL_PIN | FOLL_TOUCH | FOLL_UNLOCKABLE))
3686 return __gup_longterm_locked(current->mm, start, nr_pages, pages,
3687 &locked, gup_flags);
3689 EXPORT_SYMBOL(pin_user_pages_unlocked);