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>
22 #include <asm/mmu_context.h>
23 #include <asm/tlbflush.h>
27 struct follow_page_context {
28 struct dev_pagemap *pgmap;
29 unsigned int page_mask;
32 static inline void sanity_check_pinned_pages(struct page **pages,
35 if (!IS_ENABLED(CONFIG_DEBUG_VM))
39 * We only pin anonymous pages if they are exclusive. Once pinned, we
40 * can no longer turn them possibly shared and PageAnonExclusive() will
41 * stick around until the page is freed.
43 * We'd like to verify that our pinned anonymous pages are still mapped
44 * exclusively. The issue with anon THP is that we don't know how
45 * they are/were mapped when pinning them. However, for anon
46 * THP we can assume that either the given page (PTE-mapped THP) or
47 * the head page (PMD-mapped THP) should be PageAnonExclusive(). If
48 * neither is the case, there is certainly something wrong.
50 for (; npages; npages--, pages++) {
51 struct page *page = *pages;
52 struct folio *folio = page_folio(page);
54 if (is_zero_page(page) ||
55 !folio_test_anon(folio))
57 if (!folio_test_large(folio) || folio_test_hugetlb(folio))
58 VM_BUG_ON_PAGE(!PageAnonExclusive(&folio->page), page);
60 /* Either a PTE-mapped or a PMD-mapped THP. */
61 VM_BUG_ON_PAGE(!PageAnonExclusive(&folio->page) &&
62 !PageAnonExclusive(page), page);
67 * Return the folio with ref appropriately incremented,
68 * or NULL if that failed.
70 static inline struct folio *try_get_folio(struct page *page, int refs)
75 folio = page_folio(page);
76 if (WARN_ON_ONCE(folio_ref_count(folio) < 0))
78 if (unlikely(!folio_ref_try_add_rcu(folio, refs)))
82 * At this point we have a stable reference to the folio; but it
83 * could be that between calling page_folio() and the refcount
84 * increment, the folio was split, in which case we'd end up
85 * holding a reference on a folio that has nothing to do with the page
86 * we were given anymore.
87 * So now that the folio is stable, recheck that the page still
88 * belongs to this folio.
90 if (unlikely(page_folio(page) != folio)) {
91 if (!put_devmap_managed_page_refs(&folio->page, refs))
92 folio_put_refs(folio, refs);
100 * try_grab_folio() - Attempt to get or pin a folio.
101 * @page: pointer to page to be grabbed
102 * @refs: the value to (effectively) add to the folio's refcount
103 * @flags: gup flags: these are the FOLL_* flag values.
105 * "grab" names in this file mean, "look at flags to decide whether to use
106 * FOLL_PIN or FOLL_GET behavior, when incrementing the folio's refcount.
108 * Either FOLL_PIN or FOLL_GET (or neither) must be set, but not both at the
109 * same time. (That's true throughout the get_user_pages*() and
110 * pin_user_pages*() APIs.) Cases:
112 * FOLL_GET: folio's refcount will be incremented by @refs.
114 * FOLL_PIN on large folios: folio's refcount will be incremented by
115 * @refs, and its pincount will be incremented by @refs.
117 * FOLL_PIN on single-page folios: folio's refcount will be incremented by
118 * @refs * GUP_PIN_COUNTING_BIAS.
120 * Return: The folio containing @page (with refcount appropriately
121 * incremented) for success, or NULL upon failure. If neither FOLL_GET
122 * nor FOLL_PIN was set, that's considered failure, and furthermore,
123 * a likely bug in the caller, so a warning is also emitted.
125 struct folio *try_grab_folio(struct page *page, int refs, unsigned int flags)
127 if (unlikely(!(flags & FOLL_PCI_P2PDMA) && is_pci_p2pdma_page(page)))
130 if (flags & FOLL_GET)
131 return try_get_folio(page, refs);
132 else if (flags & FOLL_PIN) {
136 * Don't take a pin on the zero page - it's not going anywhere
137 * and it is used in a *lot* of places.
139 if (is_zero_page(page))
140 return page_folio(page);
143 * Can't do FOLL_LONGTERM + FOLL_PIN gup fast path if not in a
144 * right zone, so fail and let the caller fall back to the slow
147 if (unlikely((flags & FOLL_LONGTERM) &&
148 !is_longterm_pinnable_page(page)))
152 * CAUTION: Don't use compound_head() on the page before this
153 * point, the result won't be stable.
155 folio = try_get_folio(page, refs);
160 * When pinning a large folio, use an exact count to track it.
162 * However, be sure to *also* increment the normal folio
163 * refcount field at least once, so that the folio really
164 * is pinned. That's why the refcount from the earlier
165 * try_get_folio() is left intact.
167 if (folio_test_large(folio))
168 atomic_add(refs, &folio->_pincount);
171 refs * (GUP_PIN_COUNTING_BIAS - 1));
173 * Adjust the pincount before re-checking the PTE for changes.
174 * This is essentially a smp_mb() and is paired with a memory
175 * barrier in page_try_share_anon_rmap().
177 smp_mb__after_atomic();
179 node_stat_mod_folio(folio, NR_FOLL_PIN_ACQUIRED, refs);
188 static void gup_put_folio(struct folio *folio, int refs, unsigned int flags)
190 if (flags & FOLL_PIN) {
191 if (is_zero_folio(folio))
193 node_stat_mod_folio(folio, NR_FOLL_PIN_RELEASED, refs);
194 if (folio_test_large(folio))
195 atomic_sub(refs, &folio->_pincount);
197 refs *= GUP_PIN_COUNTING_BIAS;
200 if (!put_devmap_managed_page_refs(&folio->page, refs))
201 folio_put_refs(folio, refs);
205 * try_grab_page() - elevate a page's refcount by a flag-dependent amount
206 * @page: pointer to page to be grabbed
207 * @flags: gup flags: these are the FOLL_* flag values.
209 * This might not do anything at all, depending on the flags argument.
211 * "grab" names in this file mean, "look at flags to decide whether to use
212 * FOLL_PIN or FOLL_GET behavior, when incrementing the page's refcount.
214 * Either FOLL_PIN or FOLL_GET (or neither) may be set, but not both at the same
215 * time. Cases: please see the try_grab_folio() documentation, with
218 * Return: 0 for success, or if no action was required (if neither FOLL_PIN
219 * nor FOLL_GET was set, nothing is done). A negative error code for failure:
221 * -ENOMEM FOLL_GET or FOLL_PIN was set, but the page could not
224 int __must_check try_grab_page(struct page *page, unsigned int flags)
226 struct folio *folio = page_folio(page);
228 if (WARN_ON_ONCE(folio_ref_count(folio) <= 0))
231 if (unlikely(!(flags & FOLL_PCI_P2PDMA) && is_pci_p2pdma_page(page)))
234 if (flags & FOLL_GET)
235 folio_ref_inc(folio);
236 else if (flags & FOLL_PIN) {
238 * Don't take a pin on the zero page - it's not going anywhere
239 * and it is used in a *lot* of places.
241 if (is_zero_page(page))
245 * Similar to try_grab_folio(): be sure to *also*
246 * increment the normal page refcount field at least once,
247 * so that the page really is pinned.
249 if (folio_test_large(folio)) {
250 folio_ref_add(folio, 1);
251 atomic_add(1, &folio->_pincount);
253 folio_ref_add(folio, GUP_PIN_COUNTING_BIAS);
256 node_stat_mod_folio(folio, NR_FOLL_PIN_ACQUIRED, 1);
263 * unpin_user_page() - release a dma-pinned page
264 * @page: pointer to page to be released
266 * Pages that were pinned via pin_user_pages*() must be released via either
267 * unpin_user_page(), or one of the unpin_user_pages*() routines. This is so
268 * that such pages can be separately tracked and uniquely handled. In
269 * particular, interactions with RDMA and filesystems need special handling.
271 void unpin_user_page(struct page *page)
273 sanity_check_pinned_pages(&page, 1);
274 gup_put_folio(page_folio(page), 1, FOLL_PIN);
276 EXPORT_SYMBOL(unpin_user_page);
278 static inline struct folio *gup_folio_range_next(struct page *start,
279 unsigned long npages, unsigned long i, unsigned int *ntails)
281 struct page *next = nth_page(start, i);
282 struct folio *folio = page_folio(next);
285 if (folio_test_large(folio))
286 nr = min_t(unsigned int, npages - i,
287 folio_nr_pages(folio) - folio_page_idx(folio, next));
293 static inline struct folio *gup_folio_next(struct page **list,
294 unsigned long npages, unsigned long i, unsigned int *ntails)
296 struct folio *folio = page_folio(list[i]);
299 for (nr = i + 1; nr < npages; nr++) {
300 if (page_folio(list[nr]) != folio)
309 * unpin_user_pages_dirty_lock() - release and optionally dirty gup-pinned pages
310 * @pages: array of pages to be maybe marked dirty, and definitely released.
311 * @npages: number of pages in the @pages array.
312 * @make_dirty: whether to mark the pages dirty
314 * "gup-pinned page" refers to a page that has had one of the get_user_pages()
315 * variants called on that page.
317 * For each page in the @pages array, make that page (or its head page, if a
318 * compound page) dirty, if @make_dirty is true, and if the page was previously
319 * listed as clean. In any case, releases all pages using unpin_user_page(),
320 * possibly via unpin_user_pages(), for the non-dirty case.
322 * Please see the unpin_user_page() documentation for details.
324 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
325 * required, then the caller should a) verify that this is really correct,
326 * because _lock() is usually required, and b) hand code it:
327 * set_page_dirty_lock(), unpin_user_page().
330 void unpin_user_pages_dirty_lock(struct page **pages, unsigned long npages,
338 unpin_user_pages(pages, npages);
342 sanity_check_pinned_pages(pages, npages);
343 for (i = 0; i < npages; i += nr) {
344 folio = gup_folio_next(pages, npages, i, &nr);
346 * Checking PageDirty at this point may race with
347 * clear_page_dirty_for_io(), but that's OK. Two key
350 * 1) This code sees the page as already dirty, so it
351 * skips the call to set_page_dirty(). That could happen
352 * because clear_page_dirty_for_io() called
353 * page_mkclean(), followed by set_page_dirty().
354 * However, now the page is going to get written back,
355 * which meets the original intention of setting it
356 * dirty, so all is well: clear_page_dirty_for_io() goes
357 * on to call TestClearPageDirty(), and write the page
360 * 2) This code sees the page as clean, so it calls
361 * set_page_dirty(). The page stays dirty, despite being
362 * written back, so it gets written back again in the
363 * next writeback cycle. This is harmless.
365 if (!folio_test_dirty(folio)) {
367 folio_mark_dirty(folio);
370 gup_put_folio(folio, nr, FOLL_PIN);
373 EXPORT_SYMBOL(unpin_user_pages_dirty_lock);
376 * unpin_user_page_range_dirty_lock() - release and optionally dirty
377 * gup-pinned page range
379 * @page: the starting page of a range maybe marked dirty, and definitely released.
380 * @npages: number of consecutive pages to release.
381 * @make_dirty: whether to mark the pages dirty
383 * "gup-pinned page range" refers to a range of pages that has had one of the
384 * pin_user_pages() variants called on that page.
386 * For the page ranges defined by [page .. page+npages], make that range (or
387 * its head pages, if a compound page) dirty, if @make_dirty is true, and if the
388 * page range was previously listed as clean.
390 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
391 * required, then the caller should a) verify that this is really correct,
392 * because _lock() is usually required, and b) hand code it:
393 * set_page_dirty_lock(), unpin_user_page().
396 void unpin_user_page_range_dirty_lock(struct page *page, unsigned long npages,
403 for (i = 0; i < npages; i += nr) {
404 folio = gup_folio_range_next(page, npages, i, &nr);
405 if (make_dirty && !folio_test_dirty(folio)) {
407 folio_mark_dirty(folio);
410 gup_put_folio(folio, nr, FOLL_PIN);
413 EXPORT_SYMBOL(unpin_user_page_range_dirty_lock);
415 static void unpin_user_pages_lockless(struct page **pages, unsigned long npages)
422 * Don't perform any sanity checks because we might have raced with
423 * fork() and some anonymous pages might now actually be shared --
424 * which is why we're unpinning after all.
426 for (i = 0; i < npages; i += nr) {
427 folio = gup_folio_next(pages, npages, i, &nr);
428 gup_put_folio(folio, nr, FOLL_PIN);
433 * unpin_user_pages() - release an array of gup-pinned pages.
434 * @pages: array of pages to be marked dirty and released.
435 * @npages: number of pages in the @pages array.
437 * For each page in the @pages array, release the page using unpin_user_page().
439 * Please see the unpin_user_page() documentation for details.
441 void unpin_user_pages(struct page **pages, unsigned long npages)
448 * If this WARN_ON() fires, then the system *might* be leaking pages (by
449 * leaving them pinned), but probably not. More likely, gup/pup returned
450 * a hard -ERRNO error to the caller, who erroneously passed it here.
452 if (WARN_ON(IS_ERR_VALUE(npages)))
455 sanity_check_pinned_pages(pages, npages);
456 for (i = 0; i < npages; i += nr) {
457 folio = gup_folio_next(pages, npages, i, &nr);
458 gup_put_folio(folio, nr, FOLL_PIN);
461 EXPORT_SYMBOL(unpin_user_pages);
464 * Set the MMF_HAS_PINNED if not set yet; after set it'll be there for the mm's
465 * lifecycle. Avoid setting the bit unless necessary, or it might cause write
466 * cache bouncing on large SMP machines for concurrent pinned gups.
468 static inline void mm_set_has_pinned_flag(unsigned long *mm_flags)
470 if (!test_bit(MMF_HAS_PINNED, mm_flags))
471 set_bit(MMF_HAS_PINNED, mm_flags);
475 static struct page *no_page_table(struct vm_area_struct *vma,
479 * When core dumping an enormous anonymous area that nobody
480 * has touched so far, we don't want to allocate unnecessary pages or
481 * page tables. Return error instead of NULL to skip handle_mm_fault,
482 * then get_dump_page() will return NULL to leave a hole in the dump.
483 * But we can only make this optimization where a hole would surely
484 * be zero-filled if handle_mm_fault() actually did handle it.
486 if ((flags & FOLL_DUMP) &&
487 (vma_is_anonymous(vma) || !vma->vm_ops->fault))
488 return ERR_PTR(-EFAULT);
492 static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
493 pte_t *pte, unsigned int flags)
495 if (flags & FOLL_TOUCH) {
498 if (flags & FOLL_WRITE)
499 entry = pte_mkdirty(entry);
500 entry = pte_mkyoung(entry);
502 if (!pte_same(*pte, entry)) {
503 set_pte_at(vma->vm_mm, address, pte, entry);
504 update_mmu_cache(vma, address, pte);
508 /* Proper page table entry exists, but no corresponding struct page */
512 /* FOLL_FORCE can write to even unwritable PTEs in COW mappings. */
513 static inline bool can_follow_write_pte(pte_t pte, struct page *page,
514 struct vm_area_struct *vma,
517 /* If the pte is writable, we can write to the page. */
521 /* Maybe FOLL_FORCE is set to override it? */
522 if (!(flags & FOLL_FORCE))
525 /* But FOLL_FORCE has no effect on shared mappings */
526 if (vma->vm_flags & (VM_MAYSHARE | VM_SHARED))
529 /* ... or read-only private ones */
530 if (!(vma->vm_flags & VM_MAYWRITE))
533 /* ... or already writable ones that just need to take a write fault */
534 if (vma->vm_flags & VM_WRITE)
538 * See can_change_pte_writable(): we broke COW and could map the page
539 * writable if we have an exclusive anonymous page ...
541 if (!page || !PageAnon(page) || !PageAnonExclusive(page))
544 /* ... and a write-fault isn't required for other reasons. */
545 if (vma_soft_dirty_enabled(vma) && !pte_soft_dirty(pte))
547 return !userfaultfd_pte_wp(vma, pte);
550 static struct page *follow_page_pte(struct vm_area_struct *vma,
551 unsigned long address, pmd_t *pmd, unsigned int flags,
552 struct dev_pagemap **pgmap)
554 struct mm_struct *mm = vma->vm_mm;
560 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
561 if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
562 (FOLL_PIN | FOLL_GET)))
563 return ERR_PTR(-EINVAL);
564 if (unlikely(pmd_bad(*pmd)))
565 return no_page_table(vma, flags);
567 ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
569 if (!pte_present(pte))
571 if (pte_protnone(pte) && !gup_can_follow_protnone(flags))
574 page = vm_normal_page(vma, address, pte);
577 * We only care about anon pages in can_follow_write_pte() and don't
578 * have to worry about pte_devmap() because they are never anon.
580 if ((flags & FOLL_WRITE) &&
581 !can_follow_write_pte(pte, page, vma, flags)) {
586 if (!page && pte_devmap(pte) && (flags & (FOLL_GET | FOLL_PIN))) {
588 * Only return device mapping pages in the FOLL_GET or FOLL_PIN
589 * case since they are only valid while holding the pgmap
592 *pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
594 page = pte_page(pte);
597 } else if (unlikely(!page)) {
598 if (flags & FOLL_DUMP) {
599 /* Avoid special (like zero) pages in core dumps */
600 page = ERR_PTR(-EFAULT);
604 if (is_zero_pfn(pte_pfn(pte))) {
605 page = pte_page(pte);
607 ret = follow_pfn_pte(vma, address, ptep, flags);
613 if (!pte_write(pte) && gup_must_unshare(vma, flags, page)) {
614 page = ERR_PTR(-EMLINK);
618 VM_BUG_ON_PAGE((flags & FOLL_PIN) && PageAnon(page) &&
619 !PageAnonExclusive(page), page);
621 /* try_grab_page() does nothing unless FOLL_GET or FOLL_PIN is set. */
622 ret = try_grab_page(page, flags);
629 * We need to make the page accessible if and only if we are going
630 * to access its content (the FOLL_PIN case). Please see
631 * Documentation/core-api/pin_user_pages.rst for details.
633 if (flags & FOLL_PIN) {
634 ret = arch_make_page_accessible(page);
636 unpin_user_page(page);
641 if (flags & FOLL_TOUCH) {
642 if ((flags & FOLL_WRITE) &&
643 !pte_dirty(pte) && !PageDirty(page))
644 set_page_dirty(page);
646 * pte_mkyoung() would be more correct here, but atomic care
647 * is needed to avoid losing the dirty bit: it is easier to use
648 * mark_page_accessed().
650 mark_page_accessed(page);
653 pte_unmap_unlock(ptep, ptl);
656 pte_unmap_unlock(ptep, ptl);
659 return no_page_table(vma, flags);
662 static struct page *follow_pmd_mask(struct vm_area_struct *vma,
663 unsigned long address, pud_t *pudp,
665 struct follow_page_context *ctx)
670 struct mm_struct *mm = vma->vm_mm;
672 pmd = pmd_offset(pudp, address);
674 * The READ_ONCE() will stabilize the pmdval in a register or
675 * on the stack so that it will stop changing under the code.
677 pmdval = READ_ONCE(*pmd);
678 if (pmd_none(pmdval))
679 return no_page_table(vma, flags);
680 if (!pmd_present(pmdval))
681 return no_page_table(vma, flags);
682 if (pmd_devmap(pmdval)) {
683 ptl = pmd_lock(mm, pmd);
684 page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
689 if (likely(!pmd_trans_huge(pmdval)))
690 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
692 if (pmd_protnone(pmdval) && !gup_can_follow_protnone(flags))
693 return no_page_table(vma, flags);
695 ptl = pmd_lock(mm, pmd);
696 if (unlikely(!pmd_present(*pmd))) {
698 return no_page_table(vma, flags);
700 if (unlikely(!pmd_trans_huge(*pmd))) {
702 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
704 if (flags & FOLL_SPLIT_PMD) {
706 page = pmd_page(*pmd);
707 if (is_huge_zero_page(page)) {
710 split_huge_pmd(vma, pmd, address);
711 if (pmd_trans_unstable(pmd))
715 split_huge_pmd(vma, pmd, address);
716 ret = pte_alloc(mm, pmd) ? -ENOMEM : 0;
719 return ret ? ERR_PTR(ret) :
720 follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
722 page = follow_trans_huge_pmd(vma, address, pmd, flags);
724 ctx->page_mask = HPAGE_PMD_NR - 1;
728 static struct page *follow_pud_mask(struct vm_area_struct *vma,
729 unsigned long address, p4d_t *p4dp,
731 struct follow_page_context *ctx)
736 struct mm_struct *mm = vma->vm_mm;
738 pud = pud_offset(p4dp, address);
740 return no_page_table(vma, flags);
741 if (pud_devmap(*pud)) {
742 ptl = pud_lock(mm, pud);
743 page = follow_devmap_pud(vma, address, pud, flags, &ctx->pgmap);
748 if (unlikely(pud_bad(*pud)))
749 return no_page_table(vma, flags);
751 return follow_pmd_mask(vma, address, pud, flags, ctx);
754 static struct page *follow_p4d_mask(struct vm_area_struct *vma,
755 unsigned long address, pgd_t *pgdp,
757 struct follow_page_context *ctx)
761 p4d = p4d_offset(pgdp, address);
763 return no_page_table(vma, flags);
764 BUILD_BUG_ON(p4d_huge(*p4d));
765 if (unlikely(p4d_bad(*p4d)))
766 return no_page_table(vma, flags);
768 return follow_pud_mask(vma, address, p4d, flags, ctx);
772 * follow_page_mask - look up a page descriptor from a user-virtual address
773 * @vma: vm_area_struct mapping @address
774 * @address: virtual address to look up
775 * @flags: flags modifying lookup behaviour
776 * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
777 * pointer to output page_mask
779 * @flags can have FOLL_ flags set, defined in <linux/mm.h>
781 * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
782 * the device's dev_pagemap metadata to avoid repeating expensive lookups.
784 * When getting an anonymous page and the caller has to trigger unsharing
785 * of a shared anonymous page first, -EMLINK is returned. The caller should
786 * trigger a fault with FAULT_FLAG_UNSHARE set. Note that unsharing is only
787 * relevant with FOLL_PIN and !FOLL_WRITE.
789 * On output, the @ctx->page_mask is set according to the size of the page.
791 * Return: the mapped (struct page *), %NULL if no mapping exists, or
792 * an error pointer if there is a mapping to something not represented
793 * by a page descriptor (see also vm_normal_page()).
795 static struct page *follow_page_mask(struct vm_area_struct *vma,
796 unsigned long address, unsigned int flags,
797 struct follow_page_context *ctx)
801 struct mm_struct *mm = vma->vm_mm;
806 * Call hugetlb_follow_page_mask for hugetlb vmas as it will use
807 * special hugetlb page table walking code. This eliminates the
808 * need to check for hugetlb entries in the general walking code.
810 * hugetlb_follow_page_mask is only for follow_page() handling here.
811 * Ordinary GUP uses follow_hugetlb_page for hugetlb processing.
813 if (is_vm_hugetlb_page(vma)) {
814 page = hugetlb_follow_page_mask(vma, address, flags);
816 page = no_page_table(vma, flags);
820 pgd = pgd_offset(mm, address);
822 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
823 return no_page_table(vma, flags);
825 return follow_p4d_mask(vma, address, pgd, flags, ctx);
828 struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
829 unsigned int foll_flags)
831 struct follow_page_context ctx = { NULL };
834 if (vma_is_secretmem(vma))
837 if (WARN_ON_ONCE(foll_flags & FOLL_PIN))
840 page = follow_page_mask(vma, address, foll_flags, &ctx);
842 put_dev_pagemap(ctx.pgmap);
846 static int get_gate_page(struct mm_struct *mm, unsigned long address,
847 unsigned int gup_flags, struct vm_area_struct **vma,
857 /* user gate pages are read-only */
858 if (gup_flags & FOLL_WRITE)
860 if (address > TASK_SIZE)
861 pgd = pgd_offset_k(address);
863 pgd = pgd_offset_gate(mm, address);
866 p4d = p4d_offset(pgd, address);
869 pud = pud_offset(p4d, address);
872 pmd = pmd_offset(pud, address);
873 if (!pmd_present(*pmd))
875 VM_BUG_ON(pmd_trans_huge(*pmd));
876 pte = pte_offset_map(pmd, address);
879 *vma = get_gate_vma(mm);
882 *page = vm_normal_page(*vma, address, *pte);
884 if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
886 *page = pte_page(*pte);
888 ret = try_grab_page(*page, gup_flags);
899 * mmap_lock must be held on entry. If @flags has FOLL_UNLOCKABLE but not
900 * FOLL_NOWAIT, the mmap_lock may be released. If it is, *@locked will be set
901 * to 0 and -EBUSY returned.
903 static int faultin_page(struct vm_area_struct *vma,
904 unsigned long address, unsigned int *flags, bool unshare,
907 unsigned int fault_flags = 0;
910 if (*flags & FOLL_NOFAULT)
912 if (*flags & FOLL_WRITE)
913 fault_flags |= FAULT_FLAG_WRITE;
914 if (*flags & FOLL_REMOTE)
915 fault_flags |= FAULT_FLAG_REMOTE;
916 if (*flags & FOLL_UNLOCKABLE) {
917 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
919 * FAULT_FLAG_INTERRUPTIBLE is opt-in. GUP callers must set
920 * FOLL_INTERRUPTIBLE to enable FAULT_FLAG_INTERRUPTIBLE.
921 * That's because some callers may not be prepared to
922 * handle early exits caused by non-fatal signals.
924 if (*flags & FOLL_INTERRUPTIBLE)
925 fault_flags |= FAULT_FLAG_INTERRUPTIBLE;
927 if (*flags & FOLL_NOWAIT)
928 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
929 if (*flags & FOLL_TRIED) {
931 * Note: FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_TRIED
934 fault_flags |= FAULT_FLAG_TRIED;
937 fault_flags |= FAULT_FLAG_UNSHARE;
938 /* FAULT_FLAG_WRITE and FAULT_FLAG_UNSHARE are incompatible */
939 VM_BUG_ON(fault_flags & FAULT_FLAG_WRITE);
942 ret = handle_mm_fault(vma, address, fault_flags, NULL);
944 if (ret & VM_FAULT_COMPLETED) {
946 * With FAULT_FLAG_RETRY_NOWAIT we'll never release the
947 * mmap lock in the page fault handler. Sanity check this.
949 WARN_ON_ONCE(fault_flags & FAULT_FLAG_RETRY_NOWAIT);
953 * We should do the same as VM_FAULT_RETRY, but let's not
954 * return -EBUSY since that's not reflecting the reality of
955 * what has happened - we've just fully completed a page
956 * fault, with the mmap lock released. Use -EAGAIN to show
957 * that we want to take the mmap lock _again_.
962 if (ret & VM_FAULT_ERROR) {
963 int err = vm_fault_to_errno(ret, *flags);
970 if (ret & VM_FAULT_RETRY) {
971 if (!(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
979 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
981 vm_flags_t vm_flags = vma->vm_flags;
982 int write = (gup_flags & FOLL_WRITE);
983 int foreign = (gup_flags & FOLL_REMOTE);
985 if (vm_flags & (VM_IO | VM_PFNMAP))
988 if (gup_flags & FOLL_ANON && !vma_is_anonymous(vma))
991 if ((gup_flags & FOLL_LONGTERM) && vma_is_fsdax(vma))
994 if (vma_is_secretmem(vma))
998 if (!(vm_flags & VM_WRITE)) {
999 if (!(gup_flags & FOLL_FORCE))
1001 /* hugetlb does not support FOLL_FORCE|FOLL_WRITE. */
1002 if (is_vm_hugetlb_page(vma))
1005 * We used to let the write,force case do COW in a
1006 * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
1007 * set a breakpoint in a read-only mapping of an
1008 * executable, without corrupting the file (yet only
1009 * when that file had been opened for writing!).
1010 * Anon pages in shared mappings are surprising: now
1013 if (!is_cow_mapping(vm_flags))
1016 } else if (!(vm_flags & VM_READ)) {
1017 if (!(gup_flags & FOLL_FORCE))
1020 * Is there actually any vma we can reach here which does not
1021 * have VM_MAYREAD set?
1023 if (!(vm_flags & VM_MAYREAD))
1027 * gups are always data accesses, not instruction
1028 * fetches, so execute=false here
1030 if (!arch_vma_access_permitted(vma, write, false, foreign))
1036 * __get_user_pages() - pin user pages in memory
1037 * @mm: mm_struct of target mm
1038 * @start: starting user address
1039 * @nr_pages: number of pages from start to pin
1040 * @gup_flags: flags modifying pin behaviour
1041 * @pages: array that receives pointers to the pages pinned.
1042 * Should be at least nr_pages long. Or NULL, if caller
1043 * only intends to ensure the pages are faulted in.
1044 * @vmas: array of pointers to vmas corresponding to each page.
1045 * Or NULL if the caller does not require them.
1046 * @locked: whether we're still with the mmap_lock held
1048 * Returns either number of pages pinned (which may be less than the
1049 * number requested), or an error. Details about the return value:
1051 * -- If nr_pages is 0, returns 0.
1052 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
1053 * -- If nr_pages is >0, and some pages were pinned, returns the number of
1054 * pages pinned. Again, this may be less than nr_pages.
1055 * -- 0 return value is possible when the fault would need to be retried.
1057 * The caller is responsible for releasing returned @pages, via put_page().
1059 * @vmas are valid only as long as mmap_lock is held.
1061 * Must be called with mmap_lock held. It may be released. See below.
1063 * __get_user_pages walks a process's page tables and takes a reference to
1064 * each struct page that each user address corresponds to at a given
1065 * instant. That is, it takes the page that would be accessed if a user
1066 * thread accesses the given user virtual address at that instant.
1068 * This does not guarantee that the page exists in the user mappings when
1069 * __get_user_pages returns, and there may even be a completely different
1070 * page there in some cases (eg. if mmapped pagecache has been invalidated
1071 * and subsequently re-faulted). However it does guarantee that the page
1072 * won't be freed completely. And mostly callers simply care that the page
1073 * contains data that was valid *at some point in time*. Typically, an IO
1074 * or similar operation cannot guarantee anything stronger anyway because
1075 * locks can't be held over the syscall boundary.
1077 * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
1078 * the page is written to, set_page_dirty (or set_page_dirty_lock, as
1079 * appropriate) must be called after the page is finished with, and
1080 * before put_page is called.
1082 * If FOLL_UNLOCKABLE is set without FOLL_NOWAIT then the mmap_lock may
1083 * be released. If this happens *@locked will be set to 0 on return.
1085 * A caller using such a combination of @gup_flags must therefore hold the
1086 * mmap_lock for reading only, and recognize when it's been released. Otherwise,
1087 * it must be held for either reading or writing and will not be released.
1089 * In most cases, get_user_pages or get_user_pages_fast should be used
1090 * instead of __get_user_pages. __get_user_pages should be used only if
1091 * you need some special @gup_flags.
1093 static long __get_user_pages(struct mm_struct *mm,
1094 unsigned long start, unsigned long nr_pages,
1095 unsigned int gup_flags, struct page **pages,
1096 struct vm_area_struct **vmas, int *locked)
1098 long ret = 0, i = 0;
1099 struct vm_area_struct *vma = NULL;
1100 struct follow_page_context ctx = { NULL };
1105 start = untagged_addr_remote(mm, start);
1107 VM_BUG_ON(!!pages != !!(gup_flags & (FOLL_GET | FOLL_PIN)));
1111 unsigned int foll_flags = gup_flags;
1112 unsigned int page_increm;
1114 /* first iteration or cross vma bound */
1115 if (!vma || start >= vma->vm_end) {
1116 vma = find_extend_vma(mm, start);
1117 if (!vma && in_gate_area(mm, start)) {
1118 ret = get_gate_page(mm, start & PAGE_MASK,
1120 pages ? &pages[i] : NULL);
1131 ret = check_vma_flags(vma, gup_flags);
1135 if (is_vm_hugetlb_page(vma)) {
1136 i = follow_hugetlb_page(mm, vma, pages, vmas,
1137 &start, &nr_pages, i,
1141 * We've got a VM_FAULT_RETRY
1142 * and we've lost mmap_lock.
1143 * We must stop here.
1145 BUG_ON(gup_flags & FOLL_NOWAIT);
1153 * If we have a pending SIGKILL, don't keep faulting pages and
1154 * potentially allocating memory.
1156 if (fatal_signal_pending(current)) {
1162 page = follow_page_mask(vma, start, foll_flags, &ctx);
1163 if (!page || PTR_ERR(page) == -EMLINK) {
1164 ret = faultin_page(vma, start, &foll_flags,
1165 PTR_ERR(page) == -EMLINK, locked);
1179 } else if (PTR_ERR(page) == -EEXIST) {
1181 * Proper page table entry exists, but no corresponding
1182 * struct page. If the caller expects **pages to be
1183 * filled in, bail out now, because that can't be done
1187 ret = PTR_ERR(page);
1192 } else if (IS_ERR(page)) {
1193 ret = PTR_ERR(page);
1198 flush_anon_page(vma, page, start);
1199 flush_dcache_page(page);
1207 page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
1208 if (page_increm > nr_pages)
1209 page_increm = nr_pages;
1211 start += page_increm * PAGE_SIZE;
1212 nr_pages -= page_increm;
1216 put_dev_pagemap(ctx.pgmap);
1220 static bool vma_permits_fault(struct vm_area_struct *vma,
1221 unsigned int fault_flags)
1223 bool write = !!(fault_flags & FAULT_FLAG_WRITE);
1224 bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
1225 vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
1227 if (!(vm_flags & vma->vm_flags))
1231 * The architecture might have a hardware protection
1232 * mechanism other than read/write that can deny access.
1234 * gup always represents data access, not instruction
1235 * fetches, so execute=false here:
1237 if (!arch_vma_access_permitted(vma, write, false, foreign))
1244 * fixup_user_fault() - manually resolve a user page fault
1245 * @mm: mm_struct of target mm
1246 * @address: user address
1247 * @fault_flags:flags to pass down to handle_mm_fault()
1248 * @unlocked: did we unlock the mmap_lock while retrying, maybe NULL if caller
1249 * does not allow retry. If NULL, the caller must guarantee
1250 * that fault_flags does not contain FAULT_FLAG_ALLOW_RETRY.
1252 * This is meant to be called in the specific scenario where for locking reasons
1253 * we try to access user memory in atomic context (within a pagefault_disable()
1254 * section), this returns -EFAULT, and we want to resolve the user fault before
1257 * Typically this is meant to be used by the futex code.
1259 * The main difference with get_user_pages() is that this function will
1260 * unconditionally call handle_mm_fault() which will in turn perform all the
1261 * necessary SW fixup of the dirty and young bits in the PTE, while
1262 * get_user_pages() only guarantees to update these in the struct page.
1264 * This is important for some architectures where those bits also gate the
1265 * access permission to the page because they are maintained in software. On
1266 * such architectures, gup() will not be enough to make a subsequent access
1269 * This function will not return with an unlocked mmap_lock. So it has not the
1270 * same semantics wrt the @mm->mmap_lock as does filemap_fault().
1272 int fixup_user_fault(struct mm_struct *mm,
1273 unsigned long address, unsigned int fault_flags,
1276 struct vm_area_struct *vma;
1279 address = untagged_addr_remote(mm, address);
1282 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1285 vma = find_extend_vma(mm, address);
1286 if (!vma || address < vma->vm_start)
1289 if (!vma_permits_fault(vma, fault_flags))
1292 if ((fault_flags & FAULT_FLAG_KILLABLE) &&
1293 fatal_signal_pending(current))
1296 ret = handle_mm_fault(vma, address, fault_flags, NULL);
1298 if (ret & VM_FAULT_COMPLETED) {
1300 * NOTE: it's a pity that we need to retake the lock here
1301 * to pair with the unlock() in the callers. Ideally we
1302 * could tell the callers so they do not need to unlock.
1309 if (ret & VM_FAULT_ERROR) {
1310 int err = vm_fault_to_errno(ret, 0);
1317 if (ret & VM_FAULT_RETRY) {
1320 fault_flags |= FAULT_FLAG_TRIED;
1326 EXPORT_SYMBOL_GPL(fixup_user_fault);
1329 * GUP always responds to fatal signals. When FOLL_INTERRUPTIBLE is
1330 * specified, it'll also respond to generic signals. The caller of GUP
1331 * that has FOLL_INTERRUPTIBLE should take care of the GUP interruption.
1333 static bool gup_signal_pending(unsigned int flags)
1335 if (fatal_signal_pending(current))
1338 if (!(flags & FOLL_INTERRUPTIBLE))
1341 return signal_pending(current);
1345 * Locking: (*locked == 1) means that the mmap_lock has already been acquired by
1346 * the caller. This function may drop the mmap_lock. If it does so, then it will
1347 * set (*locked = 0).
1349 * (*locked == 0) means that the caller expects this function to acquire and
1350 * drop the mmap_lock. Therefore, the value of *locked will still be zero when
1351 * the function returns, even though it may have changed temporarily during
1352 * function execution.
1354 * Please note that this function, unlike __get_user_pages(), will not return 0
1355 * for nr_pages > 0, unless FOLL_NOWAIT is used.
1357 static __always_inline long __get_user_pages_locked(struct mm_struct *mm,
1358 unsigned long start,
1359 unsigned long nr_pages,
1360 struct page **pages,
1361 struct vm_area_struct **vmas,
1365 long ret, pages_done;
1366 bool must_unlock = false;
1369 * The internal caller expects GUP to manage the lock internally and the
1370 * lock must be released when this returns.
1373 if (mmap_read_lock_killable(mm))
1379 mmap_assert_locked(mm);
1381 if (flags & FOLL_PIN)
1382 mm_set_has_pinned_flag(&mm->flags);
1385 * FOLL_PIN and FOLL_GET are mutually exclusive. Traditional behavior
1386 * is to set FOLL_GET if the caller wants pages[] filled in (but has
1387 * carelessly failed to specify FOLL_GET), so keep doing that, but only
1388 * for FOLL_GET, not for the newer FOLL_PIN.
1390 * FOLL_PIN always expects pages to be non-null, but no need to assert
1391 * that here, as any failures will be obvious enough.
1393 if (pages && !(flags & FOLL_PIN))
1398 ret = __get_user_pages(mm, start, nr_pages, flags, pages,
1400 if (!(flags & FOLL_UNLOCKABLE)) {
1401 /* VM_FAULT_RETRY couldn't trigger, bypass */
1406 /* VM_FAULT_RETRY or VM_FAULT_COMPLETED cannot return errors */
1409 BUG_ON(ret >= nr_pages);
1420 * VM_FAULT_RETRY didn't trigger or it was a
1428 * VM_FAULT_RETRY triggered, so seek to the faulting offset.
1429 * For the prefault case (!pages) we only update counts.
1433 start += ret << PAGE_SHIFT;
1435 /* The lock was temporarily dropped, so we must unlock later */
1440 * Repeat on the address that fired VM_FAULT_RETRY
1441 * with both FAULT_FLAG_ALLOW_RETRY and
1442 * FAULT_FLAG_TRIED. Note that GUP can be interrupted
1443 * by fatal signals of even common signals, depending on
1444 * the caller's request. So we need to check it before we
1445 * start trying again otherwise it can loop forever.
1447 if (gup_signal_pending(flags)) {
1449 pages_done = -EINTR;
1453 ret = mmap_read_lock_killable(mm);
1462 ret = __get_user_pages(mm, start, 1, flags | FOLL_TRIED,
1463 pages, NULL, locked);
1465 /* Continue to retry until we succeeded */
1483 if (must_unlock && *locked) {
1485 * We either temporarily dropped the lock, or the caller
1486 * requested that we both acquire and drop the lock. Either way,
1487 * we must now unlock, and notify the caller of that state.
1489 mmap_read_unlock(mm);
1496 * populate_vma_page_range() - populate a range of pages in the vma.
1498 * @start: start address
1500 * @locked: whether the mmap_lock is still held
1502 * This takes care of mlocking the pages too if VM_LOCKED is set.
1504 * Return either number of pages pinned in the vma, or a negative error
1507 * vma->vm_mm->mmap_lock must be held.
1509 * If @locked is NULL, it may be held for read or write and will
1512 * If @locked is non-NULL, it must held for read only and may be
1513 * released. If it's released, *@locked will be set to 0.
1515 long populate_vma_page_range(struct vm_area_struct *vma,
1516 unsigned long start, unsigned long end, int *locked)
1518 struct mm_struct *mm = vma->vm_mm;
1519 unsigned long nr_pages = (end - start) / PAGE_SIZE;
1520 int local_locked = 1;
1524 VM_BUG_ON(!PAGE_ALIGNED(start));
1525 VM_BUG_ON(!PAGE_ALIGNED(end));
1526 VM_BUG_ON_VMA(start < vma->vm_start, vma);
1527 VM_BUG_ON_VMA(end > vma->vm_end, vma);
1528 mmap_assert_locked(mm);
1531 * Rightly or wrongly, the VM_LOCKONFAULT case has never used
1532 * faultin_page() to break COW, so it has no work to do here.
1534 if (vma->vm_flags & VM_LOCKONFAULT)
1537 gup_flags = FOLL_TOUCH;
1539 * We want to touch writable mappings with a write fault in order
1540 * to break COW, except for shared mappings because these don't COW
1541 * and we would not want to dirty them for nothing.
1543 if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
1544 gup_flags |= FOLL_WRITE;
1547 * We want mlock to succeed for regions that have any permissions
1548 * other than PROT_NONE.
1550 if (vma_is_accessible(vma))
1551 gup_flags |= FOLL_FORCE;
1554 gup_flags |= FOLL_UNLOCKABLE;
1557 * We made sure addr is within a VMA, so the following will
1558 * not result in a stack expansion that recurses back here.
1560 ret = __get_user_pages(mm, start, nr_pages, gup_flags,
1561 NULL, NULL, locked ? locked : &local_locked);
1567 * faultin_vma_page_range() - populate (prefault) page tables inside the
1568 * given VMA range readable/writable
1570 * This takes care of mlocking the pages, too, if VM_LOCKED is set.
1573 * @start: start address
1575 * @write: whether to prefault readable or writable
1576 * @locked: whether the mmap_lock is still held
1578 * Returns either number of processed pages in the vma, or a negative error
1579 * code on error (see __get_user_pages()).
1581 * vma->vm_mm->mmap_lock must be held. The range must be page-aligned and
1582 * covered by the VMA. If it's released, *@locked will be set to 0.
1584 long faultin_vma_page_range(struct vm_area_struct *vma, unsigned long start,
1585 unsigned long end, bool write, int *locked)
1587 struct mm_struct *mm = vma->vm_mm;
1588 unsigned long nr_pages = (end - start) / PAGE_SIZE;
1592 VM_BUG_ON(!PAGE_ALIGNED(start));
1593 VM_BUG_ON(!PAGE_ALIGNED(end));
1594 VM_BUG_ON_VMA(start < vma->vm_start, vma);
1595 VM_BUG_ON_VMA(end > vma->vm_end, vma);
1596 mmap_assert_locked(mm);
1599 * FOLL_TOUCH: Mark page accessed and thereby young; will also mark
1600 * the page dirty with FOLL_WRITE -- which doesn't make a
1601 * difference with !FOLL_FORCE, because the page is writable
1602 * in the page table.
1603 * FOLL_HWPOISON: Return -EHWPOISON instead of -EFAULT when we hit
1605 * !FOLL_FORCE: Require proper access permissions.
1607 gup_flags = FOLL_TOUCH | FOLL_HWPOISON | FOLL_UNLOCKABLE;
1609 gup_flags |= FOLL_WRITE;
1612 * We want to report -EINVAL instead of -EFAULT for any permission
1613 * problems or incompatible mappings.
1615 if (check_vma_flags(vma, gup_flags))
1618 ret = __get_user_pages(mm, start, nr_pages, gup_flags,
1619 NULL, NULL, locked);
1625 * __mm_populate - populate and/or mlock pages within a range of address space.
1627 * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
1628 * flags. VMAs must be already marked with the desired vm_flags, and
1629 * mmap_lock must not be held.
1631 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
1633 struct mm_struct *mm = current->mm;
1634 unsigned long end, nstart, nend;
1635 struct vm_area_struct *vma = NULL;
1641 for (nstart = start; nstart < end; nstart = nend) {
1643 * We want to fault in pages for [nstart; end) address range.
1644 * Find first corresponding VMA.
1649 vma = find_vma_intersection(mm, nstart, end);
1650 } else if (nstart >= vma->vm_end)
1651 vma = find_vma_intersection(mm, vma->vm_end, end);
1656 * Set [nstart; nend) to intersection of desired address
1657 * range with the first VMA. Also, skip undesirable VMA types.
1659 nend = min(end, vma->vm_end);
1660 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1662 if (nstart < vma->vm_start)
1663 nstart = vma->vm_start;
1665 * Now fault in a range of pages. populate_vma_page_range()
1666 * double checks the vma flags, so that it won't mlock pages
1667 * if the vma was already munlocked.
1669 ret = populate_vma_page_range(vma, nstart, nend, &locked);
1671 if (ignore_errors) {
1673 continue; /* continue at next VMA */
1677 nend = nstart + ret * PAGE_SIZE;
1681 mmap_read_unlock(mm);
1682 return ret; /* 0 or negative error code */
1684 #else /* CONFIG_MMU */
1685 static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start,
1686 unsigned long nr_pages, struct page **pages,
1687 struct vm_area_struct **vmas, int *locked,
1688 unsigned int foll_flags)
1690 struct vm_area_struct *vma;
1691 bool must_unlock = false;
1692 unsigned long vm_flags;
1699 * The internal caller expects GUP to manage the lock internally and the
1700 * lock must be released when this returns.
1703 if (mmap_read_lock_killable(mm))
1709 /* calculate required read or write permissions.
1710 * If FOLL_FORCE is set, we only require the "MAY" flags.
1712 vm_flags = (foll_flags & FOLL_WRITE) ?
1713 (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
1714 vm_flags &= (foll_flags & FOLL_FORCE) ?
1715 (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
1717 for (i = 0; i < nr_pages; i++) {
1718 vma = find_vma(mm, start);
1722 /* protect what we can, including chardevs */
1723 if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
1724 !(vm_flags & vma->vm_flags))
1728 pages[i] = virt_to_page((void *)start);
1734 start = (start + PAGE_SIZE) & PAGE_MASK;
1737 if (must_unlock && *locked) {
1738 mmap_read_unlock(mm);
1742 return i ? : -EFAULT;
1744 #endif /* !CONFIG_MMU */
1747 * fault_in_writeable - fault in userspace address range for writing
1748 * @uaddr: start of address range
1749 * @size: size of address range
1751 * Returns the number of bytes not faulted in (like copy_to_user() and
1752 * copy_from_user()).
1754 size_t fault_in_writeable(char __user *uaddr, size_t size)
1756 char __user *start = uaddr, *end;
1758 if (unlikely(size == 0))
1760 if (!user_write_access_begin(uaddr, size))
1762 if (!PAGE_ALIGNED(uaddr)) {
1763 unsafe_put_user(0, uaddr, out);
1764 uaddr = (char __user *)PAGE_ALIGN((unsigned long)uaddr);
1766 end = (char __user *)PAGE_ALIGN((unsigned long)start + size);
1767 if (unlikely(end < start))
1769 while (uaddr != end) {
1770 unsafe_put_user(0, uaddr, out);
1775 user_write_access_end();
1776 if (size > uaddr - start)
1777 return size - (uaddr - start);
1780 EXPORT_SYMBOL(fault_in_writeable);
1783 * fault_in_subpage_writeable - fault in an address range for writing
1784 * @uaddr: start of address range
1785 * @size: size of address range
1787 * Fault in a user address range for writing while checking for permissions at
1788 * sub-page granularity (e.g. arm64 MTE). This function should be used when
1789 * the caller cannot guarantee forward progress of a copy_to_user() loop.
1791 * Returns the number of bytes not faulted in (like copy_to_user() and
1792 * copy_from_user()).
1794 size_t fault_in_subpage_writeable(char __user *uaddr, size_t size)
1799 * Attempt faulting in at page granularity first for page table
1800 * permission checking. The arch-specific probe_subpage_writeable()
1801 * functions may not check for this.
1803 faulted_in = size - fault_in_writeable(uaddr, size);
1805 faulted_in -= probe_subpage_writeable(uaddr, faulted_in);
1807 return size - faulted_in;
1809 EXPORT_SYMBOL(fault_in_subpage_writeable);
1812 * fault_in_safe_writeable - fault in an address range for writing
1813 * @uaddr: start of address range
1814 * @size: length of address range
1816 * Faults in an address range for writing. This is primarily useful when we
1817 * already know that some or all of the pages in the address range aren't in
1820 * Unlike fault_in_writeable(), this function is non-destructive.
1822 * Note that we don't pin or otherwise hold the pages referenced that we fault
1823 * in. There's no guarantee that they'll stay in memory for any duration of
1826 * Returns the number of bytes not faulted in, like copy_to_user() and
1829 size_t fault_in_safe_writeable(const char __user *uaddr, size_t size)
1831 unsigned long start = (unsigned long)uaddr, end;
1832 struct mm_struct *mm = current->mm;
1833 bool unlocked = false;
1835 if (unlikely(size == 0))
1837 end = PAGE_ALIGN(start + size);
1843 if (fixup_user_fault(mm, start, FAULT_FLAG_WRITE, &unlocked))
1845 start = (start + PAGE_SIZE) & PAGE_MASK;
1846 } while (start != end);
1847 mmap_read_unlock(mm);
1849 if (size > (unsigned long)uaddr - start)
1850 return size - ((unsigned long)uaddr - start);
1853 EXPORT_SYMBOL(fault_in_safe_writeable);
1856 * fault_in_readable - fault in userspace address range for reading
1857 * @uaddr: start of user address range
1858 * @size: size of user address range
1860 * Returns the number of bytes not faulted in (like copy_to_user() and
1861 * copy_from_user()).
1863 size_t fault_in_readable(const char __user *uaddr, size_t size)
1865 const char __user *start = uaddr, *end;
1868 if (unlikely(size == 0))
1870 if (!user_read_access_begin(uaddr, size))
1872 if (!PAGE_ALIGNED(uaddr)) {
1873 unsafe_get_user(c, uaddr, out);
1874 uaddr = (const char __user *)PAGE_ALIGN((unsigned long)uaddr);
1876 end = (const char __user *)PAGE_ALIGN((unsigned long)start + size);
1877 if (unlikely(end < start))
1879 while (uaddr != end) {
1880 unsafe_get_user(c, uaddr, out);
1885 user_read_access_end();
1887 if (size > uaddr - start)
1888 return size - (uaddr - start);
1891 EXPORT_SYMBOL(fault_in_readable);
1894 * get_dump_page() - pin user page in memory while writing it to core dump
1895 * @addr: user address
1897 * Returns struct page pointer of user page pinned for dump,
1898 * to be freed afterwards by put_page().
1900 * Returns NULL on any kind of failure - a hole must then be inserted into
1901 * the corefile, to preserve alignment with its headers; and also returns
1902 * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
1903 * allowing a hole to be left in the corefile to save disk space.
1905 * Called without mmap_lock (takes and releases the mmap_lock by itself).
1907 #ifdef CONFIG_ELF_CORE
1908 struct page *get_dump_page(unsigned long addr)
1914 ret = __get_user_pages_locked(current->mm, addr, 1, &page, NULL,
1916 FOLL_FORCE | FOLL_DUMP | FOLL_GET);
1917 return (ret == 1) ? page : NULL;
1919 #endif /* CONFIG_ELF_CORE */
1921 #ifdef CONFIG_MIGRATION
1923 * Returns the number of collected pages. Return value is always >= 0.
1925 static unsigned long collect_longterm_unpinnable_pages(
1926 struct list_head *movable_page_list,
1927 unsigned long nr_pages,
1928 struct page **pages)
1930 unsigned long i, collected = 0;
1931 struct folio *prev_folio = NULL;
1932 bool drain_allow = true;
1934 for (i = 0; i < nr_pages; i++) {
1935 struct folio *folio = page_folio(pages[i]);
1937 if (folio == prev_folio)
1941 if (folio_is_longterm_pinnable(folio))
1946 if (folio_is_device_coherent(folio))
1949 if (folio_test_hugetlb(folio)) {
1950 isolate_hugetlb(folio, movable_page_list);
1954 if (!folio_test_lru(folio) && drain_allow) {
1955 lru_add_drain_all();
1956 drain_allow = false;
1959 if (!folio_isolate_lru(folio))
1962 list_add_tail(&folio->lru, movable_page_list);
1963 node_stat_mod_folio(folio,
1964 NR_ISOLATED_ANON + folio_is_file_lru(folio),
1965 folio_nr_pages(folio));
1972 * Unpins all pages and migrates device coherent pages and movable_page_list.
1973 * Returns -EAGAIN if all pages were successfully migrated or -errno for failure
1974 * (or partial success).
1976 static int migrate_longterm_unpinnable_pages(
1977 struct list_head *movable_page_list,
1978 unsigned long nr_pages,
1979 struct page **pages)
1984 for (i = 0; i < nr_pages; i++) {
1985 struct folio *folio = page_folio(pages[i]);
1987 if (folio_is_device_coherent(folio)) {
1989 * Migration will fail if the page is pinned, so convert
1990 * the pin on the source page to a normal reference.
1994 gup_put_folio(folio, 1, FOLL_PIN);
1996 if (migrate_device_coherent_page(&folio->page)) {
2005 * We can't migrate pages with unexpected references, so drop
2006 * the reference obtained by __get_user_pages_locked().
2007 * Migrating pages have been added to movable_page_list after
2008 * calling folio_isolate_lru() which takes a reference so the
2009 * page won't be freed if it's migrating.
2011 unpin_user_page(pages[i]);
2015 if (!list_empty(movable_page_list)) {
2016 struct migration_target_control mtc = {
2017 .nid = NUMA_NO_NODE,
2018 .gfp_mask = GFP_USER | __GFP_NOWARN,
2021 if (migrate_pages(movable_page_list, alloc_migration_target,
2022 NULL, (unsigned long)&mtc, MIGRATE_SYNC,
2023 MR_LONGTERM_PIN, NULL)) {
2029 putback_movable_pages(movable_page_list);
2034 for (i = 0; i < nr_pages; i++)
2036 unpin_user_page(pages[i]);
2037 putback_movable_pages(movable_page_list);
2043 * Check whether all pages are *allowed* to be pinned. Rather confusingly, all
2044 * pages in the range are required to be pinned via FOLL_PIN, before calling
2047 * If any pages in the range are not allowed to be pinned, then this routine
2048 * will migrate those pages away, unpin all the pages in the range and return
2049 * -EAGAIN. The caller should re-pin the entire range with FOLL_PIN and then
2050 * call this routine again.
2052 * If an error other than -EAGAIN occurs, this indicates a migration failure.
2053 * The caller should give up, and propagate the error back up the call stack.
2055 * If everything is OK and all pages in the range are allowed to be pinned, then
2056 * this routine leaves all pages pinned and returns zero for success.
2058 static long check_and_migrate_movable_pages(unsigned long nr_pages,
2059 struct page **pages)
2061 unsigned long collected;
2062 LIST_HEAD(movable_page_list);
2064 collected = collect_longterm_unpinnable_pages(&movable_page_list,
2069 return migrate_longterm_unpinnable_pages(&movable_page_list, nr_pages,
2073 static long check_and_migrate_movable_pages(unsigned long nr_pages,
2074 struct page **pages)
2078 #endif /* CONFIG_MIGRATION */
2081 * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
2082 * allows us to process the FOLL_LONGTERM flag.
2084 static long __gup_longterm_locked(struct mm_struct *mm,
2085 unsigned long start,
2086 unsigned long nr_pages,
2087 struct page **pages,
2088 struct vm_area_struct **vmas,
2090 unsigned int gup_flags)
2093 long rc, nr_pinned_pages;
2095 if (!(gup_flags & FOLL_LONGTERM))
2096 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
2099 flags = memalloc_pin_save();
2101 nr_pinned_pages = __get_user_pages_locked(mm, start, nr_pages,
2102 pages, vmas, locked,
2104 if (nr_pinned_pages <= 0) {
2105 rc = nr_pinned_pages;
2109 /* FOLL_LONGTERM implies FOLL_PIN */
2110 rc = check_and_migrate_movable_pages(nr_pinned_pages, pages);
2111 } while (rc == -EAGAIN);
2112 memalloc_pin_restore(flags);
2113 return rc ? rc : nr_pinned_pages;
2117 * Check that the given flags are valid for the exported gup/pup interface, and
2118 * update them with the required flags that the caller must have set.
2120 static bool is_valid_gup_args(struct page **pages, struct vm_area_struct **vmas,
2121 int *locked, unsigned int *gup_flags_p,
2122 unsigned int to_set)
2124 unsigned int gup_flags = *gup_flags_p;
2127 * These flags not allowed to be specified externally to the gup
2129 * - FOLL_PIN/FOLL_TRIED/FOLL_FAST_ONLY are internal only
2130 * - FOLL_REMOTE is internal only and used on follow_page()
2131 * - FOLL_UNLOCKABLE is internal only and used if locked is !NULL
2133 if (WARN_ON_ONCE(gup_flags & (FOLL_PIN | FOLL_TRIED | FOLL_UNLOCKABLE |
2134 FOLL_REMOTE | FOLL_FAST_ONLY)))
2137 gup_flags |= to_set;
2139 /* At the external interface locked must be set */
2140 if (WARN_ON_ONCE(*locked != 1))
2143 gup_flags |= FOLL_UNLOCKABLE;
2146 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2147 if (WARN_ON_ONCE((gup_flags & (FOLL_PIN | FOLL_GET)) ==
2148 (FOLL_PIN | FOLL_GET)))
2151 /* LONGTERM can only be specified when pinning */
2152 if (WARN_ON_ONCE(!(gup_flags & FOLL_PIN) && (gup_flags & FOLL_LONGTERM)))
2155 /* Pages input must be given if using GET/PIN */
2156 if (WARN_ON_ONCE((gup_flags & (FOLL_GET | FOLL_PIN)) && !pages))
2159 /* We want to allow the pgmap to be hot-unplugged at all times */
2160 if (WARN_ON_ONCE((gup_flags & FOLL_LONGTERM) &&
2161 (gup_flags & FOLL_PCI_P2PDMA)))
2165 * Can't use VMAs with locked, as locked allows GUP to unlock
2166 * which invalidates the vmas array
2168 if (WARN_ON_ONCE(vmas && (gup_flags & FOLL_UNLOCKABLE)))
2171 *gup_flags_p = gup_flags;
2177 * get_user_pages_remote() - pin user pages in memory
2178 * @mm: mm_struct of target mm
2179 * @start: starting user address
2180 * @nr_pages: number of pages from start to pin
2181 * @gup_flags: flags modifying lookup behaviour
2182 * @pages: array that receives pointers to the pages pinned.
2183 * Should be at least nr_pages long. Or NULL, if caller
2184 * only intends to ensure the pages are faulted in.
2185 * @vmas: array of pointers to vmas corresponding to each page.
2186 * Or NULL if the caller does not require them.
2187 * @locked: pointer to lock flag indicating whether lock is held and
2188 * subsequently whether VM_FAULT_RETRY functionality can be
2189 * utilised. Lock must initially be held.
2191 * Returns either number of pages pinned (which may be less than the
2192 * number requested), or an error. Details about the return value:
2194 * -- If nr_pages is 0, returns 0.
2195 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
2196 * -- If nr_pages is >0, and some pages were pinned, returns the number of
2197 * pages pinned. Again, this may be less than nr_pages.
2199 * The caller is responsible for releasing returned @pages, via put_page().
2201 * @vmas are valid only as long as mmap_lock is held.
2203 * Must be called with mmap_lock held for read or write.
2205 * get_user_pages_remote walks a process's page tables and takes a reference
2206 * to each struct page that each user address corresponds to at a given
2207 * instant. That is, it takes the page that would be accessed if a user
2208 * thread accesses the given user virtual address at that instant.
2210 * This does not guarantee that the page exists in the user mappings when
2211 * get_user_pages_remote returns, and there may even be a completely different
2212 * page there in some cases (eg. if mmapped pagecache has been invalidated
2213 * and subsequently re-faulted). However it does guarantee that the page
2214 * won't be freed completely. And mostly callers simply care that the page
2215 * contains data that was valid *at some point in time*. Typically, an IO
2216 * or similar operation cannot guarantee anything stronger anyway because
2217 * locks can't be held over the syscall boundary.
2219 * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
2220 * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
2221 * be called after the page is finished with, and before put_page is called.
2223 * get_user_pages_remote is typically used for fewer-copy IO operations,
2224 * to get a handle on the memory by some means other than accesses
2225 * via the user virtual addresses. The pages may be submitted for
2226 * DMA to devices or accessed via their kernel linear mapping (via the
2227 * kmap APIs). Care should be taken to use the correct cache flushing APIs.
2229 * See also get_user_pages_fast, for performance critical applications.
2231 * get_user_pages_remote should be phased out in favor of
2232 * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
2233 * should use get_user_pages_remote because it cannot pass
2234 * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
2236 long get_user_pages_remote(struct mm_struct *mm,
2237 unsigned long start, unsigned long nr_pages,
2238 unsigned int gup_flags, struct page **pages,
2239 struct vm_area_struct **vmas, int *locked)
2241 int local_locked = 1;
2243 if (!is_valid_gup_args(pages, vmas, locked, &gup_flags,
2244 FOLL_TOUCH | FOLL_REMOTE))
2247 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
2248 locked ? locked : &local_locked,
2251 EXPORT_SYMBOL(get_user_pages_remote);
2253 #else /* CONFIG_MMU */
2254 long get_user_pages_remote(struct mm_struct *mm,
2255 unsigned long start, unsigned long nr_pages,
2256 unsigned int gup_flags, struct page **pages,
2257 struct vm_area_struct **vmas, int *locked)
2261 #endif /* !CONFIG_MMU */
2264 * get_user_pages() - pin user pages in memory
2265 * @start: starting user address
2266 * @nr_pages: number of pages from start to pin
2267 * @gup_flags: flags modifying lookup behaviour
2268 * @pages: array that receives pointers to the pages pinned.
2269 * Should be at least nr_pages long. Or NULL, if caller
2270 * only intends to ensure the pages are faulted in.
2271 * @vmas: array of pointers to vmas corresponding to each page.
2272 * Or NULL if the caller does not require them.
2274 * This is the same as get_user_pages_remote(), just with a less-flexible
2275 * calling convention where we assume that the mm being operated on belongs to
2276 * the current task, and doesn't allow passing of a locked parameter. We also
2277 * obviously don't pass FOLL_REMOTE in here.
2279 long get_user_pages(unsigned long start, unsigned long nr_pages,
2280 unsigned int gup_flags, struct page **pages,
2281 struct vm_area_struct **vmas)
2285 if (!is_valid_gup_args(pages, vmas, NULL, &gup_flags, FOLL_TOUCH))
2288 return __get_user_pages_locked(current->mm, start, nr_pages, pages,
2289 vmas, &locked, gup_flags);
2291 EXPORT_SYMBOL(get_user_pages);
2294 * get_user_pages_unlocked() is suitable to replace the form:
2296 * mmap_read_lock(mm);
2297 * get_user_pages(mm, ..., pages, NULL);
2298 * mmap_read_unlock(mm);
2302 * get_user_pages_unlocked(mm, ..., pages);
2304 * It is functionally equivalent to get_user_pages_fast so
2305 * get_user_pages_fast should be used instead if specific gup_flags
2306 * (e.g. FOLL_FORCE) are not required.
2308 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
2309 struct page **pages, unsigned int gup_flags)
2313 if (!is_valid_gup_args(pages, NULL, NULL, &gup_flags,
2314 FOLL_TOUCH | FOLL_UNLOCKABLE))
2317 return __get_user_pages_locked(current->mm, start, nr_pages, pages,
2318 NULL, &locked, gup_flags);
2320 EXPORT_SYMBOL(get_user_pages_unlocked);
2325 * get_user_pages_fast attempts to pin user pages by walking the page
2326 * tables directly and avoids taking locks. Thus the walker needs to be
2327 * protected from page table pages being freed from under it, and should
2328 * block any THP splits.
2330 * One way to achieve this is to have the walker disable interrupts, and
2331 * rely on IPIs from the TLB flushing code blocking before the page table
2332 * pages are freed. This is unsuitable for architectures that do not need
2333 * to broadcast an IPI when invalidating TLBs.
2335 * Another way to achieve this is to batch up page table containing pages
2336 * belonging to more than one mm_user, then rcu_sched a callback to free those
2337 * pages. Disabling interrupts will allow the fast_gup walker to both block
2338 * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
2339 * (which is a relatively rare event). The code below adopts this strategy.
2341 * Before activating this code, please be aware that the following assumptions
2342 * are currently made:
2344 * *) Either MMU_GATHER_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
2345 * free pages containing page tables or TLB flushing requires IPI broadcast.
2347 * *) ptes can be read atomically by the architecture.
2349 * *) access_ok is sufficient to validate userspace address ranges.
2351 * The last two assumptions can be relaxed by the addition of helper functions.
2353 * This code is based heavily on the PowerPC implementation by Nick Piggin.
2355 #ifdef CONFIG_HAVE_FAST_GUP
2357 static void __maybe_unused undo_dev_pagemap(int *nr, int nr_start,
2359 struct page **pages)
2361 while ((*nr) - nr_start) {
2362 struct page *page = pages[--(*nr)];
2364 ClearPageReferenced(page);
2365 if (flags & FOLL_PIN)
2366 unpin_user_page(page);
2372 #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
2374 * Fast-gup relies on pte change detection to avoid concurrent pgtable
2377 * To pin the page, fast-gup needs to do below in order:
2378 * (1) pin the page (by prefetching pte), then (2) check pte not changed.
2380 * For the rest of pgtable operations where pgtable updates can be racy
2381 * with fast-gup, we need to do (1) clear pte, then (2) check whether page
2384 * Above will work for all pte-level operations, including THP split.
2386 * For THP collapse, it's a bit more complicated because fast-gup may be
2387 * walking a pgtable page that is being freed (pte is still valid but pmd
2388 * can be cleared already). To avoid race in such condition, we need to
2389 * also check pmd here to make sure pmd doesn't change (corresponds to
2390 * pmdp_collapse_flush() in the THP collapse code path).
2392 static int gup_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr,
2393 unsigned long end, unsigned int flags,
2394 struct page **pages, int *nr)
2396 struct dev_pagemap *pgmap = NULL;
2397 int nr_start = *nr, ret = 0;
2400 ptem = ptep = pte_offset_map(&pmd, addr);
2402 pte_t pte = ptep_get_lockless(ptep);
2404 struct folio *folio;
2406 if (pte_protnone(pte) && !gup_can_follow_protnone(flags))
2409 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2412 if (pte_devmap(pte)) {
2413 if (unlikely(flags & FOLL_LONGTERM))
2416 pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
2417 if (unlikely(!pgmap)) {
2418 undo_dev_pagemap(nr, nr_start, flags, pages);
2421 } else if (pte_special(pte))
2424 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2425 page = pte_page(pte);
2427 folio = try_grab_folio(page, 1, flags);
2431 if (unlikely(page_is_secretmem(page))) {
2432 gup_put_folio(folio, 1, flags);
2436 if (unlikely(pmd_val(pmd) != pmd_val(*pmdp)) ||
2437 unlikely(pte_val(pte) != pte_val(*ptep))) {
2438 gup_put_folio(folio, 1, flags);
2442 if (!pte_write(pte) && gup_must_unshare(NULL, flags, page)) {
2443 gup_put_folio(folio, 1, flags);
2448 * We need to make the page accessible if and only if we are
2449 * going to access its content (the FOLL_PIN case). Please
2450 * see Documentation/core-api/pin_user_pages.rst for
2453 if (flags & FOLL_PIN) {
2454 ret = arch_make_page_accessible(page);
2456 gup_put_folio(folio, 1, flags);
2460 folio_set_referenced(folio);
2463 } while (ptep++, addr += PAGE_SIZE, addr != end);
2469 put_dev_pagemap(pgmap);
2476 * If we can't determine whether or not a pte is special, then fail immediately
2477 * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
2480 * For a futex to be placed on a THP tail page, get_futex_key requires a
2481 * get_user_pages_fast_only implementation that can pin pages. Thus it's still
2482 * useful to have gup_huge_pmd even if we can't operate on ptes.
2484 static int gup_pte_range(pmd_t pmd, pmd_t *pmdp, unsigned long addr,
2485 unsigned long end, unsigned int flags,
2486 struct page **pages, int *nr)
2490 #endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
2492 #if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
2493 static int __gup_device_huge(unsigned long pfn, unsigned long addr,
2494 unsigned long end, unsigned int flags,
2495 struct page **pages, int *nr)
2498 struct dev_pagemap *pgmap = NULL;
2501 struct page *page = pfn_to_page(pfn);
2503 pgmap = get_dev_pagemap(pfn, pgmap);
2504 if (unlikely(!pgmap)) {
2505 undo_dev_pagemap(nr, nr_start, flags, pages);
2509 if (!(flags & FOLL_PCI_P2PDMA) && is_pci_p2pdma_page(page)) {
2510 undo_dev_pagemap(nr, nr_start, flags, pages);
2514 SetPageReferenced(page);
2516 if (unlikely(try_grab_page(page, flags))) {
2517 undo_dev_pagemap(nr, nr_start, flags, pages);
2522 } while (addr += PAGE_SIZE, addr != end);
2524 put_dev_pagemap(pgmap);
2528 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2529 unsigned long end, unsigned int flags,
2530 struct page **pages, int *nr)
2532 unsigned long fault_pfn;
2535 fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2536 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2539 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2540 undo_dev_pagemap(nr, nr_start, flags, pages);
2546 static int __gup_device_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2547 unsigned long end, unsigned int flags,
2548 struct page **pages, int *nr)
2550 unsigned long fault_pfn;
2553 fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2554 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2557 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2558 undo_dev_pagemap(nr, nr_start, flags, pages);
2564 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2565 unsigned long end, unsigned int flags,
2566 struct page **pages, int *nr)
2572 static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr,
2573 unsigned long end, unsigned int flags,
2574 struct page **pages, int *nr)
2581 static int record_subpages(struct page *page, unsigned long addr,
2582 unsigned long end, struct page **pages)
2586 for (nr = 0; addr != end; nr++, addr += PAGE_SIZE)
2587 pages[nr] = nth_page(page, nr);
2592 #ifdef CONFIG_ARCH_HAS_HUGEPD
2593 static unsigned long hugepte_addr_end(unsigned long addr, unsigned long end,
2596 unsigned long __boundary = (addr + sz) & ~(sz-1);
2597 return (__boundary - 1 < end - 1) ? __boundary : end;
2600 static int gup_hugepte(pte_t *ptep, unsigned long sz, unsigned long addr,
2601 unsigned long end, unsigned int flags,
2602 struct page **pages, int *nr)
2604 unsigned long pte_end;
2606 struct folio *folio;
2610 pte_end = (addr + sz) & ~(sz-1);
2614 pte = huge_ptep_get(ptep);
2616 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2619 /* hugepages are never "special" */
2620 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2622 page = nth_page(pte_page(pte), (addr & (sz - 1)) >> PAGE_SHIFT);
2623 refs = record_subpages(page, addr, end, pages + *nr);
2625 folio = try_grab_folio(page, refs, flags);
2629 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2630 gup_put_folio(folio, refs, flags);
2634 if (!pte_write(pte) && gup_must_unshare(NULL, flags, &folio->page)) {
2635 gup_put_folio(folio, refs, flags);
2640 folio_set_referenced(folio);
2644 static int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2645 unsigned int pdshift, unsigned long end, unsigned int flags,
2646 struct page **pages, int *nr)
2649 unsigned long sz = 1UL << hugepd_shift(hugepd);
2652 ptep = hugepte_offset(hugepd, addr, pdshift);
2654 next = hugepte_addr_end(addr, end, sz);
2655 if (!gup_hugepte(ptep, sz, addr, end, flags, pages, nr))
2657 } while (ptep++, addr = next, addr != end);
2662 static inline int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2663 unsigned int pdshift, unsigned long end, unsigned int flags,
2664 struct page **pages, int *nr)
2668 #endif /* CONFIG_ARCH_HAS_HUGEPD */
2670 static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2671 unsigned long end, unsigned int flags,
2672 struct page **pages, int *nr)
2675 struct folio *folio;
2678 if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
2681 if (pmd_devmap(orig)) {
2682 if (unlikely(flags & FOLL_LONGTERM))
2684 return __gup_device_huge_pmd(orig, pmdp, addr, end, flags,
2688 page = nth_page(pmd_page(orig), (addr & ~PMD_MASK) >> PAGE_SHIFT);
2689 refs = record_subpages(page, addr, end, pages + *nr);
2691 folio = try_grab_folio(page, refs, flags);
2695 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2696 gup_put_folio(folio, refs, flags);
2700 if (!pmd_write(orig) && gup_must_unshare(NULL, flags, &folio->page)) {
2701 gup_put_folio(folio, refs, flags);
2706 folio_set_referenced(folio);
2710 static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2711 unsigned long end, unsigned int flags,
2712 struct page **pages, int *nr)
2715 struct folio *folio;
2718 if (!pud_access_permitted(orig, flags & FOLL_WRITE))
2721 if (pud_devmap(orig)) {
2722 if (unlikely(flags & FOLL_LONGTERM))
2724 return __gup_device_huge_pud(orig, pudp, addr, end, flags,
2728 page = nth_page(pud_page(orig), (addr & ~PUD_MASK) >> PAGE_SHIFT);
2729 refs = record_subpages(page, addr, end, pages + *nr);
2731 folio = try_grab_folio(page, refs, flags);
2735 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2736 gup_put_folio(folio, refs, flags);
2740 if (!pud_write(orig) && gup_must_unshare(NULL, flags, &folio->page)) {
2741 gup_put_folio(folio, refs, flags);
2746 folio_set_referenced(folio);
2750 static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
2751 unsigned long end, unsigned int flags,
2752 struct page **pages, int *nr)
2756 struct folio *folio;
2758 if (!pgd_access_permitted(orig, flags & FOLL_WRITE))
2761 BUILD_BUG_ON(pgd_devmap(orig));
2763 page = nth_page(pgd_page(orig), (addr & ~PGDIR_MASK) >> PAGE_SHIFT);
2764 refs = record_subpages(page, addr, end, pages + *nr);
2766 folio = try_grab_folio(page, refs, flags);
2770 if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
2771 gup_put_folio(folio, refs, flags);
2776 folio_set_referenced(folio);
2780 static int gup_pmd_range(pud_t *pudp, pud_t pud, unsigned long addr, unsigned long end,
2781 unsigned int flags, struct page **pages, int *nr)
2786 pmdp = pmd_offset_lockless(pudp, pud, addr);
2788 pmd_t pmd = pmdp_get_lockless(pmdp);
2790 next = pmd_addr_end(addr, end);
2791 if (!pmd_present(pmd))
2794 if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd) ||
2796 if (pmd_protnone(pmd) &&
2797 !gup_can_follow_protnone(flags))
2800 if (!gup_huge_pmd(pmd, pmdp, addr, next, flags,
2804 } else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
2806 * architecture have different format for hugetlbfs
2807 * pmd format and THP pmd format
2809 if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
2810 PMD_SHIFT, next, flags, pages, nr))
2812 } else if (!gup_pte_range(pmd, pmdp, addr, next, flags, pages, nr))
2814 } while (pmdp++, addr = next, addr != end);
2819 static int gup_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr, unsigned long end,
2820 unsigned int flags, struct page **pages, int *nr)
2825 pudp = pud_offset_lockless(p4dp, p4d, addr);
2827 pud_t pud = READ_ONCE(*pudp);
2829 next = pud_addr_end(addr, end);
2830 if (unlikely(!pud_present(pud)))
2832 if (unlikely(pud_huge(pud) || pud_devmap(pud))) {
2833 if (!gup_huge_pud(pud, pudp, addr, next, flags,
2836 } else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
2837 if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
2838 PUD_SHIFT, next, flags, pages, nr))
2840 } else if (!gup_pmd_range(pudp, pud, addr, next, flags, pages, nr))
2842 } while (pudp++, addr = next, addr != end);
2847 static int gup_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr, unsigned long end,
2848 unsigned int flags, struct page **pages, int *nr)
2853 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
2855 p4d_t p4d = READ_ONCE(*p4dp);
2857 next = p4d_addr_end(addr, end);
2860 BUILD_BUG_ON(p4d_huge(p4d));
2861 if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
2862 if (!gup_huge_pd(__hugepd(p4d_val(p4d)), addr,
2863 P4D_SHIFT, next, flags, pages, nr))
2865 } else if (!gup_pud_range(p4dp, p4d, addr, next, flags, pages, nr))
2867 } while (p4dp++, addr = next, addr != end);
2872 static void gup_pgd_range(unsigned long addr, unsigned long end,
2873 unsigned int flags, struct page **pages, int *nr)
2878 pgdp = pgd_offset(current->mm, addr);
2880 pgd_t pgd = READ_ONCE(*pgdp);
2882 next = pgd_addr_end(addr, end);
2885 if (unlikely(pgd_huge(pgd))) {
2886 if (!gup_huge_pgd(pgd, pgdp, addr, next, flags,
2889 } else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
2890 if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
2891 PGDIR_SHIFT, next, flags, pages, nr))
2893 } else if (!gup_p4d_range(pgdp, pgd, addr, next, flags, pages, nr))
2895 } while (pgdp++, addr = next, addr != end);
2898 static inline void gup_pgd_range(unsigned long addr, unsigned long end,
2899 unsigned int flags, struct page **pages, int *nr)
2902 #endif /* CONFIG_HAVE_FAST_GUP */
2904 #ifndef gup_fast_permitted
2906 * Check if it's allowed to use get_user_pages_fast_only() for the range, or
2907 * we need to fall back to the slow version:
2909 static bool gup_fast_permitted(unsigned long start, unsigned long end)
2915 static unsigned long lockless_pages_from_mm(unsigned long start,
2917 unsigned int gup_flags,
2918 struct page **pages)
2920 unsigned long flags;
2924 if (!IS_ENABLED(CONFIG_HAVE_FAST_GUP) ||
2925 !gup_fast_permitted(start, end))
2928 if (gup_flags & FOLL_PIN) {
2929 seq = raw_read_seqcount(¤t->mm->write_protect_seq);
2935 * Disable interrupts. The nested form is used, in order to allow full,
2936 * general purpose use of this routine.
2938 * With interrupts disabled, we block page table pages from being freed
2939 * from under us. See struct mmu_table_batch comments in
2940 * include/asm-generic/tlb.h for more details.
2942 * We do not adopt an rcu_read_lock() here as we also want to block IPIs
2943 * that come from THPs splitting.
2945 local_irq_save(flags);
2946 gup_pgd_range(start, end, gup_flags, pages, &nr_pinned);
2947 local_irq_restore(flags);
2950 * When pinning pages for DMA there could be a concurrent write protect
2951 * from fork() via copy_page_range(), in this case always fail fast GUP.
2953 if (gup_flags & FOLL_PIN) {
2954 if (read_seqcount_retry(¤t->mm->write_protect_seq, seq)) {
2955 unpin_user_pages_lockless(pages, nr_pinned);
2958 sanity_check_pinned_pages(pages, nr_pinned);
2964 static int internal_get_user_pages_fast(unsigned long start,
2965 unsigned long nr_pages,
2966 unsigned int gup_flags,
2967 struct page **pages)
2969 unsigned long len, end;
2970 unsigned long nr_pinned;
2974 if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM |
2975 FOLL_FORCE | FOLL_PIN | FOLL_GET |
2976 FOLL_FAST_ONLY | FOLL_NOFAULT |
2980 if (gup_flags & FOLL_PIN)
2981 mm_set_has_pinned_flag(¤t->mm->flags);
2983 if (!(gup_flags & FOLL_FAST_ONLY))
2984 might_lock_read(¤t->mm->mmap_lock);
2986 start = untagged_addr(start) & PAGE_MASK;
2987 len = nr_pages << PAGE_SHIFT;
2988 if (check_add_overflow(start, len, &end))
2990 if (end > TASK_SIZE_MAX)
2992 if (unlikely(!access_ok((void __user *)start, len)))
2995 nr_pinned = lockless_pages_from_mm(start, end, gup_flags, pages);
2996 if (nr_pinned == nr_pages || gup_flags & FOLL_FAST_ONLY)
2999 /* Slow path: try to get the remaining pages with get_user_pages */
3000 start += nr_pinned << PAGE_SHIFT;
3002 ret = __gup_longterm_locked(current->mm, start, nr_pages - nr_pinned,
3003 pages, NULL, &locked,
3004 gup_flags | FOLL_TOUCH | FOLL_UNLOCKABLE);
3007 * The caller has to unpin the pages we already pinned so
3008 * returning -errno is not an option
3014 return ret + nr_pinned;
3018 * get_user_pages_fast_only() - pin user pages in memory
3019 * @start: starting user address
3020 * @nr_pages: number of pages from start to pin
3021 * @gup_flags: flags modifying pin behaviour
3022 * @pages: array that receives pointers to the pages pinned.
3023 * Should be at least nr_pages long.
3025 * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
3028 * If the architecture does not support this function, simply return with no
3031 * Careful, careful! COW breaking can go either way, so a non-write
3032 * access can get ambiguous page results. If you call this function without
3033 * 'write' set, you'd better be sure that you're ok with that ambiguity.
3035 int get_user_pages_fast_only(unsigned long start, int nr_pages,
3036 unsigned int gup_flags, struct page **pages)
3039 * Internally (within mm/gup.c), gup fast variants must set FOLL_GET,
3040 * because gup fast is always a "pin with a +1 page refcount" request.
3042 * FOLL_FAST_ONLY is required in order to match the API description of
3043 * this routine: no fall back to regular ("slow") GUP.
3045 if (!is_valid_gup_args(pages, NULL, NULL, &gup_flags,
3046 FOLL_GET | FOLL_FAST_ONLY))
3049 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
3051 EXPORT_SYMBOL_GPL(get_user_pages_fast_only);
3054 * get_user_pages_fast() - pin user pages in memory
3055 * @start: starting user address
3056 * @nr_pages: number of pages from start to pin
3057 * @gup_flags: flags modifying pin behaviour
3058 * @pages: array that receives pointers to the pages pinned.
3059 * Should be at least nr_pages long.
3061 * Attempt to pin user pages in memory without taking mm->mmap_lock.
3062 * If not successful, it will fall back to taking the lock and
3063 * calling get_user_pages().
3065 * Returns number of pages pinned. This may be fewer than the number requested.
3066 * If nr_pages is 0 or negative, returns 0. If no pages were pinned, returns
3069 int get_user_pages_fast(unsigned long start, int nr_pages,
3070 unsigned int gup_flags, struct page **pages)
3073 * The caller may or may not have explicitly set FOLL_GET; either way is
3074 * OK. However, internally (within mm/gup.c), gup fast variants must set
3075 * FOLL_GET, because gup fast is always a "pin with a +1 page refcount"
3078 if (!is_valid_gup_args(pages, NULL, NULL, &gup_flags, FOLL_GET))
3080 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
3082 EXPORT_SYMBOL_GPL(get_user_pages_fast);
3085 * pin_user_pages_fast() - pin user pages in memory without taking locks
3087 * @start: starting user address
3088 * @nr_pages: number of pages from start to pin
3089 * @gup_flags: flags modifying pin behaviour
3090 * @pages: array that receives pointers to the pages pinned.
3091 * Should be at least nr_pages long.
3093 * Nearly the same as get_user_pages_fast(), except that FOLL_PIN is set. See
3094 * get_user_pages_fast() for documentation on the function arguments, because
3095 * the arguments here are identical.
3097 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3098 * see Documentation/core-api/pin_user_pages.rst for further details.
3100 * Note that if a zero_page is amongst the returned pages, it will not have
3101 * pins in it and unpin_user_page() will not remove pins from it.
3103 int pin_user_pages_fast(unsigned long start, int nr_pages,
3104 unsigned int gup_flags, struct page **pages)
3106 if (!is_valid_gup_args(pages, NULL, NULL, &gup_flags, FOLL_PIN))
3108 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
3110 EXPORT_SYMBOL_GPL(pin_user_pages_fast);
3113 * pin_user_pages_remote() - pin pages of a remote process
3115 * @mm: mm_struct of target mm
3116 * @start: starting user address
3117 * @nr_pages: number of pages from start to pin
3118 * @gup_flags: flags modifying lookup behaviour
3119 * @pages: array that receives pointers to the pages pinned.
3120 * Should be at least nr_pages long.
3121 * @vmas: array of pointers to vmas corresponding to each page.
3122 * Or NULL if the caller does not require them.
3123 * @locked: pointer to lock flag indicating whether lock is held and
3124 * subsequently whether VM_FAULT_RETRY functionality can be
3125 * utilised. Lock must initially be held.
3127 * Nearly the same as get_user_pages_remote(), except that FOLL_PIN is set. See
3128 * get_user_pages_remote() for documentation on the function arguments, because
3129 * the arguments here are identical.
3131 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3132 * see Documentation/core-api/pin_user_pages.rst for details.
3134 * Note that if a zero_page is amongst the returned pages, it will not have
3135 * pins in it and unpin_user_page*() will not remove pins from it.
3137 long pin_user_pages_remote(struct mm_struct *mm,
3138 unsigned long start, unsigned long nr_pages,
3139 unsigned int gup_flags, struct page **pages,
3140 struct vm_area_struct **vmas, int *locked)
3142 int local_locked = 1;
3144 if (!is_valid_gup_args(pages, vmas, locked, &gup_flags,
3145 FOLL_PIN | FOLL_TOUCH | FOLL_REMOTE))
3147 return __gup_longterm_locked(mm, start, nr_pages, pages, vmas,
3148 locked ? locked : &local_locked,
3151 EXPORT_SYMBOL(pin_user_pages_remote);
3154 * pin_user_pages() - pin user pages in memory for use by other devices
3156 * @start: starting user address
3157 * @nr_pages: number of pages from start to pin
3158 * @gup_flags: flags modifying lookup behaviour
3159 * @pages: array that receives pointers to the pages pinned.
3160 * Should be at least nr_pages long.
3161 * @vmas: array of pointers to vmas corresponding to each page.
3162 * Or NULL if the caller does not require them.
3164 * Nearly the same as get_user_pages(), except that FOLL_TOUCH is not set, and
3167 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3168 * see Documentation/core-api/pin_user_pages.rst for details.
3170 * Note that if a zero_page is amongst the returned pages, it will not have
3171 * pins in it and unpin_user_page*() will not remove pins from it.
3173 long pin_user_pages(unsigned long start, unsigned long nr_pages,
3174 unsigned int gup_flags, struct page **pages,
3175 struct vm_area_struct **vmas)
3179 if (!is_valid_gup_args(pages, vmas, NULL, &gup_flags, FOLL_PIN))
3181 return __gup_longterm_locked(current->mm, start, nr_pages,
3182 pages, vmas, &locked, gup_flags);
3184 EXPORT_SYMBOL(pin_user_pages);
3187 * pin_user_pages_unlocked() is the FOLL_PIN variant of
3188 * get_user_pages_unlocked(). Behavior is the same, except that this one sets
3189 * FOLL_PIN and rejects FOLL_GET.
3191 * Note that if a zero_page is amongst the returned pages, it will not have
3192 * pins in it and unpin_user_page*() will not remove pins from it.
3194 long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
3195 struct page **pages, unsigned int gup_flags)
3199 if (!is_valid_gup_args(pages, NULL, NULL, &gup_flags,
3200 FOLL_PIN | FOLL_TOUCH | FOLL_UNLOCKABLE))
3203 return __gup_longterm_locked(current->mm, start, nr_pages, pages, NULL,
3204 &locked, gup_flags);
3206 EXPORT_SYMBOL(pin_user_pages_unlocked);