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 void hpage_pincount_add(struct page *page, int refs)
34 VM_BUG_ON_PAGE(!hpage_pincount_available(page), page);
35 VM_BUG_ON_PAGE(page != compound_head(page), page);
37 atomic_add(refs, compound_pincount_ptr(page));
40 static void hpage_pincount_sub(struct page *page, int refs)
42 VM_BUG_ON_PAGE(!hpage_pincount_available(page), page);
43 VM_BUG_ON_PAGE(page != compound_head(page), page);
45 atomic_sub(refs, compound_pincount_ptr(page));
48 /* Equivalent to calling put_page() @refs times. */
49 static void put_page_refs(struct page *page, int refs)
51 #ifdef CONFIG_DEBUG_VM
52 if (VM_WARN_ON_ONCE_PAGE(page_ref_count(page) < refs, page))
57 * Calling put_page() for each ref is unnecessarily slow. Only the last
58 * ref needs a put_page().
61 page_ref_sub(page, refs - 1);
66 * Return the compound head page with ref appropriately incremented,
67 * or NULL if that failed.
69 static inline struct page *try_get_compound_head(struct page *page, int refs)
71 struct page *head = compound_head(page);
73 if (WARN_ON_ONCE(page_ref_count(head) < 0))
75 if (unlikely(!page_cache_add_speculative(head, refs)))
79 * At this point we have a stable reference to the head page; but it
80 * could be that between the compound_head() lookup and the refcount
81 * increment, the compound page was split, in which case we'd end up
82 * holding a reference on a page that has nothing to do with the page
83 * we were given anymore.
84 * So now that the head page is stable, recheck that the pages still
87 if (unlikely(compound_head(page) != head)) {
88 put_page_refs(head, refs);
96 * try_grab_compound_head() - attempt to elevate a page's refcount, by a
97 * flags-dependent amount.
99 * Even though the name includes "compound_head", this function is still
100 * appropriate for callers that have a non-compound @page to get.
102 * @page: pointer to page to be grabbed
103 * @refs: the value to (effectively) add to the page's refcount
104 * @flags: gup flags: these are the FOLL_* flag values.
106 * "grab" names in this file mean, "look at flags to decide whether to use
107 * FOLL_PIN or FOLL_GET behavior, when incrementing the page's refcount.
109 * Either FOLL_PIN or FOLL_GET (or neither) must be set, but not both at the
110 * same time. (That's true throughout the get_user_pages*() and
111 * pin_user_pages*() APIs.) Cases:
113 * FOLL_GET: page's refcount will be incremented by @refs.
115 * FOLL_PIN on compound pages that are > two pages long: page's refcount will
116 * be incremented by @refs, and page[2].hpage_pinned_refcount will be
117 * incremented by @refs * GUP_PIN_COUNTING_BIAS.
119 * FOLL_PIN on normal pages, or compound pages that are two pages long:
120 * page's refcount will be incremented by @refs * GUP_PIN_COUNTING_BIAS.
122 * Return: head page (with refcount appropriately incremented) for success, or
123 * NULL upon failure. If neither FOLL_GET nor FOLL_PIN was set, that's
124 * considered failure, and furthermore, a likely bug in the caller, so a warning
127 __maybe_unused struct page *try_grab_compound_head(struct page *page,
128 int refs, unsigned int flags)
130 if (flags & FOLL_GET)
131 return try_get_compound_head(page, refs);
132 else if (flags & FOLL_PIN) {
134 * Can't do FOLL_LONGTERM + FOLL_PIN gup fast path if not in a
135 * right zone, so fail and let the caller fall back to the slow
138 if (unlikely((flags & FOLL_LONGTERM) &&
139 !is_pinnable_page(page)))
143 * CAUTION: Don't use compound_head() on the page before this
144 * point, the result won't be stable.
146 page = try_get_compound_head(page, refs);
151 * When pinning a compound page of order > 1 (which is what
152 * hpage_pincount_available() checks for), use an exact count to
153 * track it, via hpage_pincount_add/_sub().
155 * However, be sure to *also* increment the normal page refcount
156 * field at least once, so that the page really is pinned.
157 * That's why the refcount from the earlier
158 * try_get_compound_head() is left intact.
160 if (hpage_pincount_available(page))
161 hpage_pincount_add(page, refs);
163 page_ref_add(page, refs * (GUP_PIN_COUNTING_BIAS - 1));
165 mod_node_page_state(page_pgdat(page), NR_FOLL_PIN_ACQUIRED,
175 static void put_compound_head(struct page *page, int refs, unsigned int flags)
177 if (flags & FOLL_PIN) {
178 mod_node_page_state(page_pgdat(page), NR_FOLL_PIN_RELEASED,
181 if (hpage_pincount_available(page))
182 hpage_pincount_sub(page, refs);
184 refs *= GUP_PIN_COUNTING_BIAS;
187 put_page_refs(page, refs);
191 * try_grab_page() - elevate a page's refcount by a flag-dependent amount
193 * This might not do anything at all, depending on the flags argument.
195 * "grab" names in this file mean, "look at flags to decide whether to use
196 * FOLL_PIN or FOLL_GET behavior, when incrementing the page's refcount.
198 * @page: pointer to page to be grabbed
199 * @flags: gup flags: these are the FOLL_* flag values.
201 * Either FOLL_PIN or FOLL_GET (or neither) may be set, but not both at the same
202 * time. Cases: please see the try_grab_compound_head() documentation, with
205 * Return: true for success, or if no action was required (if neither FOLL_PIN
206 * nor FOLL_GET was set, nothing is done). False for failure: FOLL_GET or
207 * FOLL_PIN was set, but the page could not be grabbed.
209 bool __must_check try_grab_page(struct page *page, unsigned int flags)
211 WARN_ON_ONCE((flags & (FOLL_GET | FOLL_PIN)) == (FOLL_GET | FOLL_PIN));
213 if (flags & FOLL_GET)
214 return try_get_page(page);
215 else if (flags & FOLL_PIN) {
218 page = compound_head(page);
220 if (WARN_ON_ONCE(page_ref_count(page) <= 0))
223 if (hpage_pincount_available(page))
224 hpage_pincount_add(page, 1);
226 refs = GUP_PIN_COUNTING_BIAS;
229 * Similar to try_grab_compound_head(): even if using the
230 * hpage_pincount_add/_sub() routines, be sure to
231 * *also* increment the normal page refcount field at least
232 * once, so that the page really is pinned.
234 page_ref_add(page, refs);
236 mod_node_page_state(page_pgdat(page), NR_FOLL_PIN_ACQUIRED, 1);
243 * unpin_user_page() - release a dma-pinned page
244 * @page: pointer to page to be released
246 * Pages that were pinned via pin_user_pages*() must be released via either
247 * unpin_user_page(), or one of the unpin_user_pages*() routines. This is so
248 * that such pages can be separately tracked and uniquely handled. In
249 * particular, interactions with RDMA and filesystems need special handling.
251 void unpin_user_page(struct page *page)
253 put_compound_head(compound_head(page), 1, FOLL_PIN);
255 EXPORT_SYMBOL(unpin_user_page);
257 static inline void compound_range_next(unsigned long i, unsigned long npages,
258 struct page **list, struct page **head,
259 unsigned int *ntails)
261 struct page *next, *page;
268 page = compound_head(next);
269 if (PageCompound(page) && compound_order(page) >= 1)
270 nr = min_t(unsigned int,
271 page + compound_nr(page) - next, npages - i);
277 #define for_each_compound_range(__i, __list, __npages, __head, __ntails) \
279 compound_range_next(__i, __npages, __list, &(__head), &(__ntails)); \
280 __i < __npages; __i += __ntails, \
281 compound_range_next(__i, __npages, __list, &(__head), &(__ntails)))
283 static inline void compound_next(unsigned long i, unsigned long npages,
284 struct page **list, struct page **head,
285 unsigned int *ntails)
293 page = compound_head(list[i]);
294 for (nr = i + 1; nr < npages; nr++) {
295 if (compound_head(list[nr]) != page)
303 #define for_each_compound_head(__i, __list, __npages, __head, __ntails) \
305 compound_next(__i, __npages, __list, &(__head), &(__ntails)); \
306 __i < __npages; __i += __ntails, \
307 compound_next(__i, __npages, __list, &(__head), &(__ntails)))
310 * unpin_user_pages_dirty_lock() - release and optionally dirty gup-pinned pages
311 * @pages: array of pages to be maybe marked dirty, and definitely released.
312 * @npages: number of pages in the @pages array.
313 * @make_dirty: whether to mark the pages dirty
315 * "gup-pinned page" refers to a page that has had one of the get_user_pages()
316 * variants called on that page.
318 * For each page in the @pages array, make that page (or its head page, if a
319 * compound page) dirty, if @make_dirty is true, and if the page was previously
320 * listed as clean. In any case, releases all pages using unpin_user_page(),
321 * possibly via unpin_user_pages(), for the non-dirty case.
323 * Please see the unpin_user_page() documentation for details.
325 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
326 * required, then the caller should a) verify that this is really correct,
327 * because _lock() is usually required, and b) hand code it:
328 * set_page_dirty_lock(), unpin_user_page().
331 void unpin_user_pages_dirty_lock(struct page **pages, unsigned long npages,
339 unpin_user_pages(pages, npages);
343 for_each_compound_head(index, pages, npages, head, ntails) {
345 * Checking PageDirty at this point may race with
346 * clear_page_dirty_for_io(), but that's OK. Two key
349 * 1) This code sees the page as already dirty, so it
350 * skips the call to set_page_dirty(). That could happen
351 * because clear_page_dirty_for_io() called
352 * page_mkclean(), followed by set_page_dirty().
353 * However, now the page is going to get written back,
354 * which meets the original intention of setting it
355 * dirty, so all is well: clear_page_dirty_for_io() goes
356 * on to call TestClearPageDirty(), and write the page
359 * 2) This code sees the page as clean, so it calls
360 * set_page_dirty(). The page stays dirty, despite being
361 * written back, so it gets written back again in the
362 * next writeback cycle. This is harmless.
364 if (!PageDirty(head))
365 set_page_dirty_lock(head);
366 put_compound_head(head, ntails, FOLL_PIN);
369 EXPORT_SYMBOL(unpin_user_pages_dirty_lock);
372 * unpin_user_page_range_dirty_lock() - release and optionally dirty
373 * gup-pinned page range
375 * @page: the starting page of a range maybe marked dirty, and definitely released.
376 * @npages: number of consecutive pages to release.
377 * @make_dirty: whether to mark the pages dirty
379 * "gup-pinned page range" refers to a range of pages that has had one of the
380 * pin_user_pages() variants called on that page.
382 * For the page ranges defined by [page .. page+npages], make that range (or
383 * its head pages, if a compound page) dirty, if @make_dirty is true, and if the
384 * page range was previously listed as clean.
386 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
387 * required, then the caller should a) verify that this is really correct,
388 * because _lock() is usually required, and b) hand code it:
389 * set_page_dirty_lock(), unpin_user_page().
392 void unpin_user_page_range_dirty_lock(struct page *page, unsigned long npages,
399 for_each_compound_range(index, &page, npages, head, ntails) {
400 if (make_dirty && !PageDirty(head))
401 set_page_dirty_lock(head);
402 put_compound_head(head, ntails, FOLL_PIN);
405 EXPORT_SYMBOL(unpin_user_page_range_dirty_lock);
408 * unpin_user_pages() - release an array of gup-pinned pages.
409 * @pages: array of pages to be marked dirty and released.
410 * @npages: number of pages in the @pages array.
412 * For each page in the @pages array, release the page using unpin_user_page().
414 * Please see the unpin_user_page() documentation for details.
416 void unpin_user_pages(struct page **pages, unsigned long npages)
423 * If this WARN_ON() fires, then the system *might* be leaking pages (by
424 * leaving them pinned), but probably not. More likely, gup/pup returned
425 * a hard -ERRNO error to the caller, who erroneously passed it here.
427 if (WARN_ON(IS_ERR_VALUE(npages)))
430 for_each_compound_head(index, pages, npages, head, ntails)
431 put_compound_head(head, ntails, FOLL_PIN);
433 EXPORT_SYMBOL(unpin_user_pages);
436 * Set the MMF_HAS_PINNED if not set yet; after set it'll be there for the mm's
437 * lifecycle. Avoid setting the bit unless necessary, or it might cause write
438 * cache bouncing on large SMP machines for concurrent pinned gups.
440 static inline void mm_set_has_pinned_flag(unsigned long *mm_flags)
442 if (!test_bit(MMF_HAS_PINNED, mm_flags))
443 set_bit(MMF_HAS_PINNED, mm_flags);
447 static struct page *no_page_table(struct vm_area_struct *vma,
451 * When core dumping an enormous anonymous area that nobody
452 * has touched so far, we don't want to allocate unnecessary pages or
453 * page tables. Return error instead of NULL to skip handle_mm_fault,
454 * then get_dump_page() will return NULL to leave a hole in the dump.
455 * But we can only make this optimization where a hole would surely
456 * be zero-filled if handle_mm_fault() actually did handle it.
458 if ((flags & FOLL_DUMP) &&
459 (vma_is_anonymous(vma) || !vma->vm_ops->fault))
460 return ERR_PTR(-EFAULT);
464 static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
465 pte_t *pte, unsigned int flags)
467 /* No page to get reference */
468 if (flags & FOLL_GET)
471 if (flags & FOLL_TOUCH) {
474 if (flags & FOLL_WRITE)
475 entry = pte_mkdirty(entry);
476 entry = pte_mkyoung(entry);
478 if (!pte_same(*pte, entry)) {
479 set_pte_at(vma->vm_mm, address, pte, entry);
480 update_mmu_cache(vma, address, pte);
484 /* Proper page table entry exists, but no corresponding struct page */
489 * FOLL_FORCE can write to even unwritable pte's, but only
490 * after we've gone through a COW cycle and they are dirty.
492 static inline bool can_follow_write_pte(pte_t pte, unsigned int flags)
494 return pte_write(pte) ||
495 ((flags & FOLL_FORCE) && (flags & FOLL_COW) && pte_dirty(pte));
498 static struct page *follow_page_pte(struct vm_area_struct *vma,
499 unsigned long address, pmd_t *pmd, unsigned int flags,
500 struct dev_pagemap **pgmap)
502 struct mm_struct *mm = vma->vm_mm;
508 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
509 if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
510 (FOLL_PIN | FOLL_GET)))
511 return ERR_PTR(-EINVAL);
513 if (unlikely(pmd_bad(*pmd)))
514 return no_page_table(vma, flags);
516 ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
518 if (!pte_present(pte)) {
521 * KSM's break_ksm() relies upon recognizing a ksm page
522 * even while it is being migrated, so for that case we
523 * need migration_entry_wait().
525 if (likely(!(flags & FOLL_MIGRATION)))
529 entry = pte_to_swp_entry(pte);
530 if (!is_migration_entry(entry))
532 pte_unmap_unlock(ptep, ptl);
533 migration_entry_wait(mm, pmd, address);
536 if ((flags & FOLL_NUMA) && pte_protnone(pte))
538 if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
539 pte_unmap_unlock(ptep, ptl);
543 page = vm_normal_page(vma, address, pte);
544 if (!page && pte_devmap(pte) && (flags & (FOLL_GET | FOLL_PIN))) {
546 * Only return device mapping pages in the FOLL_GET or FOLL_PIN
547 * case since they are only valid while holding the pgmap
550 *pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
552 page = pte_page(pte);
555 } else if (unlikely(!page)) {
556 if (flags & FOLL_DUMP) {
557 /* Avoid special (like zero) pages in core dumps */
558 page = ERR_PTR(-EFAULT);
562 if (is_zero_pfn(pte_pfn(pte))) {
563 page = pte_page(pte);
565 ret = follow_pfn_pte(vma, address, ptep, flags);
571 /* try_grab_page() does nothing unless FOLL_GET or FOLL_PIN is set. */
572 if (unlikely(!try_grab_page(page, flags))) {
573 page = ERR_PTR(-ENOMEM);
577 * We need to make the page accessible if and only if we are going
578 * to access its content (the FOLL_PIN case). Please see
579 * Documentation/core-api/pin_user_pages.rst for details.
581 if (flags & FOLL_PIN) {
582 ret = arch_make_page_accessible(page);
584 unpin_user_page(page);
589 if (flags & FOLL_TOUCH) {
590 if ((flags & FOLL_WRITE) &&
591 !pte_dirty(pte) && !PageDirty(page))
592 set_page_dirty(page);
594 * pte_mkyoung() would be more correct here, but atomic care
595 * is needed to avoid losing the dirty bit: it is easier to use
596 * mark_page_accessed().
598 mark_page_accessed(page);
601 pte_unmap_unlock(ptep, ptl);
604 pte_unmap_unlock(ptep, ptl);
607 return no_page_table(vma, flags);
610 static struct page *follow_pmd_mask(struct vm_area_struct *vma,
611 unsigned long address, pud_t *pudp,
613 struct follow_page_context *ctx)
618 struct mm_struct *mm = vma->vm_mm;
620 pmd = pmd_offset(pudp, address);
622 * The READ_ONCE() will stabilize the pmdval in a register or
623 * on the stack so that it will stop changing under the code.
625 pmdval = READ_ONCE(*pmd);
626 if (pmd_none(pmdval))
627 return no_page_table(vma, flags);
628 if (pmd_huge(pmdval) && is_vm_hugetlb_page(vma)) {
629 page = follow_huge_pmd(mm, address, pmd, flags);
632 return no_page_table(vma, flags);
634 if (is_hugepd(__hugepd(pmd_val(pmdval)))) {
635 page = follow_huge_pd(vma, address,
636 __hugepd(pmd_val(pmdval)), flags,
640 return no_page_table(vma, flags);
643 if (!pmd_present(pmdval)) {
645 * Should never reach here, if thp migration is not supported;
646 * Otherwise, it must be a thp migration entry.
648 VM_BUG_ON(!thp_migration_supported() ||
649 !is_pmd_migration_entry(pmdval));
651 if (likely(!(flags & FOLL_MIGRATION)))
652 return no_page_table(vma, flags);
654 pmd_migration_entry_wait(mm, pmd);
655 pmdval = READ_ONCE(*pmd);
657 * MADV_DONTNEED may convert the pmd to null because
658 * mmap_lock is held in read mode
660 if (pmd_none(pmdval))
661 return no_page_table(vma, flags);
664 if (pmd_devmap(pmdval)) {
665 ptl = pmd_lock(mm, pmd);
666 page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
671 if (likely(!pmd_trans_huge(pmdval)))
672 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
674 if ((flags & FOLL_NUMA) && pmd_protnone(pmdval))
675 return no_page_table(vma, flags);
678 ptl = pmd_lock(mm, pmd);
679 if (unlikely(pmd_none(*pmd))) {
681 return no_page_table(vma, flags);
683 if (unlikely(!pmd_present(*pmd))) {
685 if (likely(!(flags & FOLL_MIGRATION)))
686 return no_page_table(vma, flags);
687 pmd_migration_entry_wait(mm, pmd);
690 if (unlikely(!pmd_trans_huge(*pmd))) {
692 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
694 if (flags & FOLL_SPLIT_PMD) {
696 page = pmd_page(*pmd);
697 if (is_huge_zero_page(page)) {
700 split_huge_pmd(vma, pmd, address);
701 if (pmd_trans_unstable(pmd))
705 split_huge_pmd(vma, pmd, address);
706 ret = pte_alloc(mm, pmd) ? -ENOMEM : 0;
709 return ret ? ERR_PTR(ret) :
710 follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
712 page = follow_trans_huge_pmd(vma, address, pmd, flags);
714 ctx->page_mask = HPAGE_PMD_NR - 1;
718 static struct page *follow_pud_mask(struct vm_area_struct *vma,
719 unsigned long address, p4d_t *p4dp,
721 struct follow_page_context *ctx)
726 struct mm_struct *mm = vma->vm_mm;
728 pud = pud_offset(p4dp, address);
730 return no_page_table(vma, flags);
731 if (pud_huge(*pud) && is_vm_hugetlb_page(vma)) {
732 page = follow_huge_pud(mm, address, pud, flags);
735 return no_page_table(vma, flags);
737 if (is_hugepd(__hugepd(pud_val(*pud)))) {
738 page = follow_huge_pd(vma, address,
739 __hugepd(pud_val(*pud)), flags,
743 return no_page_table(vma, flags);
745 if (pud_devmap(*pud)) {
746 ptl = pud_lock(mm, pud);
747 page = follow_devmap_pud(vma, address, pud, flags, &ctx->pgmap);
752 if (unlikely(pud_bad(*pud)))
753 return no_page_table(vma, flags);
755 return follow_pmd_mask(vma, address, pud, flags, ctx);
758 static struct page *follow_p4d_mask(struct vm_area_struct *vma,
759 unsigned long address, pgd_t *pgdp,
761 struct follow_page_context *ctx)
766 p4d = p4d_offset(pgdp, address);
768 return no_page_table(vma, flags);
769 BUILD_BUG_ON(p4d_huge(*p4d));
770 if (unlikely(p4d_bad(*p4d)))
771 return no_page_table(vma, flags);
773 if (is_hugepd(__hugepd(p4d_val(*p4d)))) {
774 page = follow_huge_pd(vma, address,
775 __hugepd(p4d_val(*p4d)), flags,
779 return no_page_table(vma, flags);
781 return follow_pud_mask(vma, address, p4d, flags, ctx);
785 * follow_page_mask - look up a page descriptor from a user-virtual address
786 * @vma: vm_area_struct mapping @address
787 * @address: virtual address to look up
788 * @flags: flags modifying lookup behaviour
789 * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
790 * pointer to output page_mask
792 * @flags can have FOLL_ flags set, defined in <linux/mm.h>
794 * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
795 * the device's dev_pagemap metadata to avoid repeating expensive lookups.
797 * On output, the @ctx->page_mask is set according to the size of the page.
799 * Return: the mapped (struct page *), %NULL if no mapping exists, or
800 * an error pointer if there is a mapping to something not represented
801 * by a page descriptor (see also vm_normal_page()).
803 static struct page *follow_page_mask(struct vm_area_struct *vma,
804 unsigned long address, unsigned int flags,
805 struct follow_page_context *ctx)
809 struct mm_struct *mm = vma->vm_mm;
813 /* make this handle hugepd */
814 page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
816 WARN_ON_ONCE(flags & (FOLL_GET | FOLL_PIN));
820 pgd = pgd_offset(mm, address);
822 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
823 return no_page_table(vma, flags);
825 if (pgd_huge(*pgd)) {
826 page = follow_huge_pgd(mm, address, pgd, flags);
829 return no_page_table(vma, flags);
831 if (is_hugepd(__hugepd(pgd_val(*pgd)))) {
832 page = follow_huge_pd(vma, address,
833 __hugepd(pgd_val(*pgd)), flags,
837 return no_page_table(vma, flags);
840 return follow_p4d_mask(vma, address, pgd, flags, ctx);
843 struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
844 unsigned int foll_flags)
846 struct follow_page_context ctx = { NULL };
849 if (vma_is_secretmem(vma))
852 page = follow_page_mask(vma, address, foll_flags, &ctx);
854 put_dev_pagemap(ctx.pgmap);
858 static int get_gate_page(struct mm_struct *mm, unsigned long address,
859 unsigned int gup_flags, struct vm_area_struct **vma,
869 /* user gate pages are read-only */
870 if (gup_flags & FOLL_WRITE)
872 if (address > TASK_SIZE)
873 pgd = pgd_offset_k(address);
875 pgd = pgd_offset_gate(mm, address);
878 p4d = p4d_offset(pgd, address);
881 pud = pud_offset(p4d, address);
884 pmd = pmd_offset(pud, address);
885 if (!pmd_present(*pmd))
887 VM_BUG_ON(pmd_trans_huge(*pmd));
888 pte = pte_offset_map(pmd, address);
891 *vma = get_gate_vma(mm);
894 *page = vm_normal_page(*vma, address, *pte);
896 if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
898 *page = pte_page(*pte);
900 if (unlikely(!try_grab_page(*page, gup_flags))) {
912 * mmap_lock must be held on entry. If @locked != NULL and *@flags
913 * does not include FOLL_NOWAIT, the mmap_lock may be released. If it
914 * is, *@locked will be set to 0 and -EBUSY returned.
916 static int faultin_page(struct vm_area_struct *vma,
917 unsigned long address, unsigned int *flags, int *locked)
919 unsigned int fault_flags = 0;
922 if (*flags & FOLL_NOFAULT)
924 if (*flags & FOLL_WRITE)
925 fault_flags |= FAULT_FLAG_WRITE;
926 if (*flags & FOLL_REMOTE)
927 fault_flags |= FAULT_FLAG_REMOTE;
929 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
930 if (*flags & FOLL_NOWAIT)
931 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
932 if (*flags & FOLL_TRIED) {
934 * Note: FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_TRIED
937 fault_flags |= FAULT_FLAG_TRIED;
940 ret = handle_mm_fault(vma, address, fault_flags, NULL);
941 if (ret & VM_FAULT_ERROR) {
942 int err = vm_fault_to_errno(ret, *flags);
949 if (ret & VM_FAULT_RETRY) {
950 if (locked && !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
956 * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
957 * necessary, even if maybe_mkwrite decided not to set pte_write. We
958 * can thus safely do subsequent page lookups as if they were reads.
959 * But only do so when looping for pte_write is futile: in some cases
960 * userspace may also be wanting to write to the gotten user page,
961 * which a read fault here might prevent (a readonly page might get
962 * reCOWed by userspace write).
964 if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
969 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
971 vm_flags_t vm_flags = vma->vm_flags;
972 int write = (gup_flags & FOLL_WRITE);
973 int foreign = (gup_flags & FOLL_REMOTE);
975 if (vm_flags & (VM_IO | VM_PFNMAP))
978 if (gup_flags & FOLL_ANON && !vma_is_anonymous(vma))
981 if ((gup_flags & FOLL_LONGTERM) && vma_is_fsdax(vma))
984 if (vma_is_secretmem(vma))
988 if (!(vm_flags & VM_WRITE)) {
989 if (!(gup_flags & FOLL_FORCE))
992 * We used to let the write,force case do COW in a
993 * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
994 * set a breakpoint in a read-only mapping of an
995 * executable, without corrupting the file (yet only
996 * when that file had been opened for writing!).
997 * Anon pages in shared mappings are surprising: now
1000 if (!is_cow_mapping(vm_flags))
1003 } else if (!(vm_flags & VM_READ)) {
1004 if (!(gup_flags & FOLL_FORCE))
1007 * Is there actually any vma we can reach here which does not
1008 * have VM_MAYREAD set?
1010 if (!(vm_flags & VM_MAYREAD))
1014 * gups are always data accesses, not instruction
1015 * fetches, so execute=false here
1017 if (!arch_vma_access_permitted(vma, write, false, foreign))
1023 * __get_user_pages() - pin user pages in memory
1024 * @mm: mm_struct of target mm
1025 * @start: starting user address
1026 * @nr_pages: number of pages from start to pin
1027 * @gup_flags: flags modifying pin behaviour
1028 * @pages: array that receives pointers to the pages pinned.
1029 * Should be at least nr_pages long. Or NULL, if caller
1030 * only intends to ensure the pages are faulted in.
1031 * @vmas: array of pointers to vmas corresponding to each page.
1032 * Or NULL if the caller does not require them.
1033 * @locked: whether we're still with the mmap_lock held
1035 * Returns either number of pages pinned (which may be less than the
1036 * number requested), or an error. Details about the return value:
1038 * -- If nr_pages is 0, returns 0.
1039 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
1040 * -- If nr_pages is >0, and some pages were pinned, returns the number of
1041 * pages pinned. Again, this may be less than nr_pages.
1042 * -- 0 return value is possible when the fault would need to be retried.
1044 * The caller is responsible for releasing returned @pages, via put_page().
1046 * @vmas are valid only as long as mmap_lock is held.
1048 * Must be called with mmap_lock held. It may be released. See below.
1050 * __get_user_pages walks a process's page tables and takes a reference to
1051 * each struct page that each user address corresponds to at a given
1052 * instant. That is, it takes the page that would be accessed if a user
1053 * thread accesses the given user virtual address at that instant.
1055 * This does not guarantee that the page exists in the user mappings when
1056 * __get_user_pages returns, and there may even be a completely different
1057 * page there in some cases (eg. if mmapped pagecache has been invalidated
1058 * and subsequently re faulted). However it does guarantee that the page
1059 * won't be freed completely. And mostly callers simply care that the page
1060 * contains data that was valid *at some point in time*. Typically, an IO
1061 * or similar operation cannot guarantee anything stronger anyway because
1062 * locks can't be held over the syscall boundary.
1064 * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
1065 * the page is written to, set_page_dirty (or set_page_dirty_lock, as
1066 * appropriate) must be called after the page is finished with, and
1067 * before put_page is called.
1069 * If @locked != NULL, *@locked will be set to 0 when mmap_lock is
1070 * released by an up_read(). That can happen if @gup_flags does not
1073 * A caller using such a combination of @locked and @gup_flags
1074 * must therefore hold the mmap_lock for reading only, and recognize
1075 * when it's been released. Otherwise, it must be held for either
1076 * reading or writing and will not be released.
1078 * In most cases, get_user_pages or get_user_pages_fast should be used
1079 * instead of __get_user_pages. __get_user_pages should be used only if
1080 * you need some special @gup_flags.
1082 static long __get_user_pages(struct mm_struct *mm,
1083 unsigned long start, unsigned long nr_pages,
1084 unsigned int gup_flags, struct page **pages,
1085 struct vm_area_struct **vmas, int *locked)
1087 long ret = 0, i = 0;
1088 struct vm_area_struct *vma = NULL;
1089 struct follow_page_context ctx = { NULL };
1094 start = untagged_addr(start);
1096 VM_BUG_ON(!!pages != !!(gup_flags & (FOLL_GET | FOLL_PIN)));
1099 * If FOLL_FORCE is set then do not force a full fault as the hinting
1100 * fault information is unrelated to the reference behaviour of a task
1101 * using the address space
1103 if (!(gup_flags & FOLL_FORCE))
1104 gup_flags |= FOLL_NUMA;
1108 unsigned int foll_flags = gup_flags;
1109 unsigned int page_increm;
1111 /* first iteration or cross vma bound */
1112 if (!vma || start >= vma->vm_end) {
1113 vma = find_extend_vma(mm, start);
1114 if (!vma && in_gate_area(mm, start)) {
1115 ret = get_gate_page(mm, start & PAGE_MASK,
1117 pages ? &pages[i] : NULL);
1128 ret = check_vma_flags(vma, gup_flags);
1132 if (is_vm_hugetlb_page(vma)) {
1133 i = follow_hugetlb_page(mm, vma, pages, vmas,
1134 &start, &nr_pages, i,
1136 if (locked && *locked == 0) {
1138 * We've got a VM_FAULT_RETRY
1139 * and we've lost mmap_lock.
1140 * We must stop here.
1142 BUG_ON(gup_flags & FOLL_NOWAIT);
1150 * If we have a pending SIGKILL, don't keep faulting pages and
1151 * potentially allocating memory.
1153 if (fatal_signal_pending(current)) {
1159 page = follow_page_mask(vma, start, foll_flags, &ctx);
1161 ret = faultin_page(vma, start, &foll_flags, locked);
1174 } else if (PTR_ERR(page) == -EEXIST) {
1176 * Proper page table entry exists, but no corresponding
1180 } else if (IS_ERR(page)) {
1181 ret = PTR_ERR(page);
1186 flush_anon_page(vma, page, start);
1187 flush_dcache_page(page);
1195 page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
1196 if (page_increm > nr_pages)
1197 page_increm = nr_pages;
1199 start += page_increm * PAGE_SIZE;
1200 nr_pages -= page_increm;
1204 put_dev_pagemap(ctx.pgmap);
1208 static bool vma_permits_fault(struct vm_area_struct *vma,
1209 unsigned int fault_flags)
1211 bool write = !!(fault_flags & FAULT_FLAG_WRITE);
1212 bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
1213 vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
1215 if (!(vm_flags & vma->vm_flags))
1219 * The architecture might have a hardware protection
1220 * mechanism other than read/write that can deny access.
1222 * gup always represents data access, not instruction
1223 * fetches, so execute=false here:
1225 if (!arch_vma_access_permitted(vma, write, false, foreign))
1232 * fixup_user_fault() - manually resolve a user page fault
1233 * @mm: mm_struct of target mm
1234 * @address: user address
1235 * @fault_flags:flags to pass down to handle_mm_fault()
1236 * @unlocked: did we unlock the mmap_lock while retrying, maybe NULL if caller
1237 * does not allow retry. If NULL, the caller must guarantee
1238 * that fault_flags does not contain FAULT_FLAG_ALLOW_RETRY.
1240 * This is meant to be called in the specific scenario where for locking reasons
1241 * we try to access user memory in atomic context (within a pagefault_disable()
1242 * section), this returns -EFAULT, and we want to resolve the user fault before
1245 * Typically this is meant to be used by the futex code.
1247 * The main difference with get_user_pages() is that this function will
1248 * unconditionally call handle_mm_fault() which will in turn perform all the
1249 * necessary SW fixup of the dirty and young bits in the PTE, while
1250 * get_user_pages() only guarantees to update these in the struct page.
1252 * This is important for some architectures where those bits also gate the
1253 * access permission to the page because they are maintained in software. On
1254 * such architectures, gup() will not be enough to make a subsequent access
1257 * This function will not return with an unlocked mmap_lock. So it has not the
1258 * same semantics wrt the @mm->mmap_lock as does filemap_fault().
1260 int fixup_user_fault(struct mm_struct *mm,
1261 unsigned long address, unsigned int fault_flags,
1264 struct vm_area_struct *vma;
1267 address = untagged_addr(address);
1270 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1273 vma = find_extend_vma(mm, address);
1274 if (!vma || address < vma->vm_start)
1277 if (!vma_permits_fault(vma, fault_flags))
1280 if ((fault_flags & FAULT_FLAG_KILLABLE) &&
1281 fatal_signal_pending(current))
1284 ret = handle_mm_fault(vma, address, fault_flags, NULL);
1285 if (ret & VM_FAULT_ERROR) {
1286 int err = vm_fault_to_errno(ret, 0);
1293 if (ret & VM_FAULT_RETRY) {
1296 fault_flags |= FAULT_FLAG_TRIED;
1302 EXPORT_SYMBOL_GPL(fixup_user_fault);
1305 * Please note that this function, unlike __get_user_pages will not
1306 * return 0 for nr_pages > 0 without FOLL_NOWAIT
1308 static __always_inline long __get_user_pages_locked(struct mm_struct *mm,
1309 unsigned long start,
1310 unsigned long nr_pages,
1311 struct page **pages,
1312 struct vm_area_struct **vmas,
1316 long ret, pages_done;
1320 /* if VM_FAULT_RETRY can be returned, vmas become invalid */
1322 /* check caller initialized locked */
1323 BUG_ON(*locked != 1);
1326 if (flags & FOLL_PIN)
1327 mm_set_has_pinned_flag(&mm->flags);
1330 * FOLL_PIN and FOLL_GET are mutually exclusive. Traditional behavior
1331 * is to set FOLL_GET if the caller wants pages[] filled in (but has
1332 * carelessly failed to specify FOLL_GET), so keep doing that, but only
1333 * for FOLL_GET, not for the newer FOLL_PIN.
1335 * FOLL_PIN always expects pages to be non-null, but no need to assert
1336 * that here, as any failures will be obvious enough.
1338 if (pages && !(flags & FOLL_PIN))
1342 lock_dropped = false;
1344 ret = __get_user_pages(mm, start, nr_pages, flags, pages,
1347 /* VM_FAULT_RETRY couldn't trigger, bypass */
1350 /* VM_FAULT_RETRY cannot return errors */
1353 BUG_ON(ret >= nr_pages);
1364 * VM_FAULT_RETRY didn't trigger or it was a
1372 * VM_FAULT_RETRY triggered, so seek to the faulting offset.
1373 * For the prefault case (!pages) we only update counts.
1377 start += ret << PAGE_SHIFT;
1378 lock_dropped = true;
1382 * Repeat on the address that fired VM_FAULT_RETRY
1383 * with both FAULT_FLAG_ALLOW_RETRY and
1384 * FAULT_FLAG_TRIED. Note that GUP can be interrupted
1385 * by fatal signals, so we need to check it before we
1386 * start trying again otherwise it can loop forever.
1389 if (fatal_signal_pending(current)) {
1391 pages_done = -EINTR;
1395 ret = mmap_read_lock_killable(mm);
1404 ret = __get_user_pages(mm, start, 1, flags | FOLL_TRIED,
1405 pages, NULL, locked);
1407 /* Continue to retry until we succeeded */
1425 if (lock_dropped && *locked) {
1427 * We must let the caller know we temporarily dropped the lock
1428 * and so the critical section protected by it was lost.
1430 mmap_read_unlock(mm);
1437 * populate_vma_page_range() - populate a range of pages in the vma.
1439 * @start: start address
1441 * @locked: whether the mmap_lock is still held
1443 * This takes care of mlocking the pages too if VM_LOCKED is set.
1445 * Return either number of pages pinned in the vma, or a negative error
1448 * vma->vm_mm->mmap_lock must be held.
1450 * If @locked is NULL, it may be held for read or write and will
1453 * If @locked is non-NULL, it must held for read only and may be
1454 * released. If it's released, *@locked will be set to 0.
1456 long populate_vma_page_range(struct vm_area_struct *vma,
1457 unsigned long start, unsigned long end, int *locked)
1459 struct mm_struct *mm = vma->vm_mm;
1460 unsigned long nr_pages = (end - start) / PAGE_SIZE;
1463 VM_BUG_ON(!PAGE_ALIGNED(start));
1464 VM_BUG_ON(!PAGE_ALIGNED(end));
1465 VM_BUG_ON_VMA(start < vma->vm_start, vma);
1466 VM_BUG_ON_VMA(end > vma->vm_end, vma);
1467 mmap_assert_locked(mm);
1470 * Rightly or wrongly, the VM_LOCKONFAULT case has never used
1471 * faultin_page() to break COW, so it has no work to do here.
1473 if (vma->vm_flags & VM_LOCKONFAULT)
1476 gup_flags = FOLL_TOUCH;
1478 * We want to touch writable mappings with a write fault in order
1479 * to break COW, except for shared mappings because these don't COW
1480 * and we would not want to dirty them for nothing.
1482 if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
1483 gup_flags |= FOLL_WRITE;
1486 * We want mlock to succeed for regions that have any permissions
1487 * other than PROT_NONE.
1489 if (vma_is_accessible(vma))
1490 gup_flags |= FOLL_FORCE;
1493 * We made sure addr is within a VMA, so the following will
1494 * not result in a stack expansion that recurses back here.
1496 return __get_user_pages(mm, start, nr_pages, gup_flags,
1497 NULL, NULL, locked);
1501 * faultin_vma_page_range() - populate (prefault) page tables inside the
1502 * given VMA range readable/writable
1504 * This takes care of mlocking the pages, too, if VM_LOCKED is set.
1507 * @start: start address
1509 * @write: whether to prefault readable or writable
1510 * @locked: whether the mmap_lock is still held
1512 * Returns either number of processed pages in the vma, or a negative error
1513 * code on error (see __get_user_pages()).
1515 * vma->vm_mm->mmap_lock must be held. The range must be page-aligned and
1516 * covered by the VMA.
1518 * If @locked is NULL, it may be held for read or write and will be unperturbed.
1520 * If @locked is non-NULL, it must held for read only and may be released. If
1521 * it's released, *@locked will be set to 0.
1523 long faultin_vma_page_range(struct vm_area_struct *vma, unsigned long start,
1524 unsigned long end, bool write, int *locked)
1526 struct mm_struct *mm = vma->vm_mm;
1527 unsigned long nr_pages = (end - start) / PAGE_SIZE;
1530 VM_BUG_ON(!PAGE_ALIGNED(start));
1531 VM_BUG_ON(!PAGE_ALIGNED(end));
1532 VM_BUG_ON_VMA(start < vma->vm_start, vma);
1533 VM_BUG_ON_VMA(end > vma->vm_end, vma);
1534 mmap_assert_locked(mm);
1537 * FOLL_TOUCH: Mark page accessed and thereby young; will also mark
1538 * the page dirty with FOLL_WRITE -- which doesn't make a
1539 * difference with !FOLL_FORCE, because the page is writable
1540 * in the page table.
1541 * FOLL_HWPOISON: Return -EHWPOISON instead of -EFAULT when we hit
1543 * !FOLL_FORCE: Require proper access permissions.
1545 gup_flags = FOLL_TOUCH | FOLL_HWPOISON;
1547 gup_flags |= FOLL_WRITE;
1550 * We want to report -EINVAL instead of -EFAULT for any permission
1551 * problems or incompatible mappings.
1553 if (check_vma_flags(vma, gup_flags))
1556 return __get_user_pages(mm, start, nr_pages, gup_flags,
1557 NULL, NULL, locked);
1561 * __mm_populate - populate and/or mlock pages within a range of address space.
1563 * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
1564 * flags. VMAs must be already marked with the desired vm_flags, and
1565 * mmap_lock must not be held.
1567 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
1569 struct mm_struct *mm = current->mm;
1570 unsigned long end, nstart, nend;
1571 struct vm_area_struct *vma = NULL;
1577 for (nstart = start; nstart < end; nstart = nend) {
1579 * We want to fault in pages for [nstart; end) address range.
1580 * Find first corresponding VMA.
1585 vma = find_vma(mm, nstart);
1586 } else if (nstart >= vma->vm_end)
1588 if (!vma || vma->vm_start >= end)
1591 * Set [nstart; nend) to intersection of desired address
1592 * range with the first VMA. Also, skip undesirable VMA types.
1594 nend = min(end, vma->vm_end);
1595 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1597 if (nstart < vma->vm_start)
1598 nstart = vma->vm_start;
1600 * Now fault in a range of pages. populate_vma_page_range()
1601 * double checks the vma flags, so that it won't mlock pages
1602 * if the vma was already munlocked.
1604 ret = populate_vma_page_range(vma, nstart, nend, &locked);
1606 if (ignore_errors) {
1608 continue; /* continue at next VMA */
1612 nend = nstart + ret * PAGE_SIZE;
1616 mmap_read_unlock(mm);
1617 return ret; /* 0 or negative error code */
1619 #else /* CONFIG_MMU */
1620 static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start,
1621 unsigned long nr_pages, struct page **pages,
1622 struct vm_area_struct **vmas, int *locked,
1623 unsigned int foll_flags)
1625 struct vm_area_struct *vma;
1626 unsigned long vm_flags;
1629 /* calculate required read or write permissions.
1630 * If FOLL_FORCE is set, we only require the "MAY" flags.
1632 vm_flags = (foll_flags & FOLL_WRITE) ?
1633 (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
1634 vm_flags &= (foll_flags & FOLL_FORCE) ?
1635 (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
1637 for (i = 0; i < nr_pages; i++) {
1638 vma = find_vma(mm, start);
1640 goto finish_or_fault;
1642 /* protect what we can, including chardevs */
1643 if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
1644 !(vm_flags & vma->vm_flags))
1645 goto finish_or_fault;
1648 pages[i] = virt_to_page(start);
1654 start = (start + PAGE_SIZE) & PAGE_MASK;
1660 return i ? : -EFAULT;
1662 #endif /* !CONFIG_MMU */
1665 * fault_in_writeable - fault in userspace address range for writing
1666 * @uaddr: start of address range
1667 * @size: size of address range
1669 * Returns the number of bytes not faulted in (like copy_to_user() and
1670 * copy_from_user()).
1672 size_t fault_in_writeable(char __user *uaddr, size_t size)
1674 char __user *start = uaddr, *end;
1676 if (unlikely(size == 0))
1678 if (!user_write_access_begin(uaddr, size))
1680 if (!PAGE_ALIGNED(uaddr)) {
1681 unsafe_put_user(0, uaddr, out);
1682 uaddr = (char __user *)PAGE_ALIGN((unsigned long)uaddr);
1684 end = (char __user *)PAGE_ALIGN((unsigned long)start + size);
1685 if (unlikely(end < start))
1687 while (uaddr != end) {
1688 unsafe_put_user(0, uaddr, out);
1693 user_write_access_end();
1694 if (size > uaddr - start)
1695 return size - (uaddr - start);
1698 EXPORT_SYMBOL(fault_in_writeable);
1701 * fault_in_safe_writeable - fault in an address range for writing
1702 * @uaddr: start of address range
1703 * @size: length of address range
1705 * Faults in an address range using get_user_pages, i.e., without triggering
1706 * hardware page faults. This is primarily useful when we already know that
1707 * some or all of the pages in the address range aren't in memory.
1709 * Other than fault_in_writeable(), this function is non-destructive.
1711 * Note that we don't pin or otherwise hold the pages referenced that we fault
1712 * in. There's no guarantee that they'll stay in memory for any duration of
1715 * Returns the number of bytes not faulted in, like copy_to_user() and
1718 size_t fault_in_safe_writeable(const char __user *uaddr, size_t size)
1720 unsigned long start = (unsigned long)untagged_addr(uaddr);
1721 unsigned long end, nstart, nend;
1722 struct mm_struct *mm = current->mm;
1723 struct vm_area_struct *vma = NULL;
1726 nstart = start & PAGE_MASK;
1727 end = PAGE_ALIGN(start + size);
1730 for (; nstart != end; nstart = nend) {
1731 unsigned long nr_pages;
1737 vma = find_vma(mm, nstart);
1738 } else if (nstart >= vma->vm_end)
1740 if (!vma || vma->vm_start >= end)
1742 nend = end ? min(end, vma->vm_end) : vma->vm_end;
1743 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1745 if (nstart < vma->vm_start)
1746 nstart = vma->vm_start;
1747 nr_pages = (nend - nstart) / PAGE_SIZE;
1748 ret = __get_user_pages_locked(mm, nstart, nr_pages,
1749 NULL, NULL, &locked,
1750 FOLL_TOUCH | FOLL_WRITE);
1753 nend = nstart + ret * PAGE_SIZE;
1756 mmap_read_unlock(mm);
1759 return size - min_t(size_t, nstart - start, size);
1761 EXPORT_SYMBOL(fault_in_safe_writeable);
1764 * fault_in_readable - fault in userspace address range for reading
1765 * @uaddr: start of user address range
1766 * @size: size of user address range
1768 * Returns the number of bytes not faulted in (like copy_to_user() and
1769 * copy_from_user()).
1771 size_t fault_in_readable(const char __user *uaddr, size_t size)
1773 const char __user *start = uaddr, *end;
1776 if (unlikely(size == 0))
1778 if (!user_read_access_begin(uaddr, size))
1780 if (!PAGE_ALIGNED(uaddr)) {
1781 unsafe_get_user(c, uaddr, out);
1782 uaddr = (const char __user *)PAGE_ALIGN((unsigned long)uaddr);
1784 end = (const char __user *)PAGE_ALIGN((unsigned long)start + size);
1785 if (unlikely(end < start))
1787 while (uaddr != end) {
1788 unsafe_get_user(c, uaddr, out);
1793 user_read_access_end();
1795 if (size > uaddr - start)
1796 return size - (uaddr - start);
1799 EXPORT_SYMBOL(fault_in_readable);
1802 * get_dump_page() - pin user page in memory while writing it to core dump
1803 * @addr: user address
1805 * Returns struct page pointer of user page pinned for dump,
1806 * to be freed afterwards by put_page().
1808 * Returns NULL on any kind of failure - a hole must then be inserted into
1809 * the corefile, to preserve alignment with its headers; and also returns
1810 * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
1811 * allowing a hole to be left in the corefile to save disk space.
1813 * Called without mmap_lock (takes and releases the mmap_lock by itself).
1815 #ifdef CONFIG_ELF_CORE
1816 struct page *get_dump_page(unsigned long addr)
1818 struct mm_struct *mm = current->mm;
1823 if (mmap_read_lock_killable(mm))
1825 ret = __get_user_pages_locked(mm, addr, 1, &page, NULL, &locked,
1826 FOLL_FORCE | FOLL_DUMP | FOLL_GET);
1828 mmap_read_unlock(mm);
1829 return (ret == 1) ? page : NULL;
1831 #endif /* CONFIG_ELF_CORE */
1833 #ifdef CONFIG_MIGRATION
1835 * Check whether all pages are pinnable, if so return number of pages. If some
1836 * pages are not pinnable, migrate them, and unpin all pages. Return zero if
1837 * pages were migrated, or if some pages were not successfully isolated.
1838 * Return negative error if migration fails.
1840 static long check_and_migrate_movable_pages(unsigned long nr_pages,
1841 struct page **pages,
1842 unsigned int gup_flags)
1845 unsigned long isolation_error_count = 0;
1846 bool drain_allow = true;
1847 LIST_HEAD(movable_page_list);
1849 struct page *prev_head = NULL;
1851 struct migration_target_control mtc = {
1852 .nid = NUMA_NO_NODE,
1853 .gfp_mask = GFP_USER | __GFP_NOWARN,
1856 for (i = 0; i < nr_pages; i++) {
1857 head = compound_head(pages[i]);
1858 if (head == prev_head)
1862 * If we get a movable page, since we are going to be pinning
1863 * these entries, try to move them out if possible.
1865 if (!is_pinnable_page(head)) {
1866 if (PageHuge(head)) {
1867 if (!isolate_huge_page(head, &movable_page_list))
1868 isolation_error_count++;
1870 if (!PageLRU(head) && drain_allow) {
1871 lru_add_drain_all();
1872 drain_allow = false;
1875 if (isolate_lru_page(head)) {
1876 isolation_error_count++;
1879 list_add_tail(&head->lru, &movable_page_list);
1880 mod_node_page_state(page_pgdat(head),
1882 page_is_file_lru(head),
1883 thp_nr_pages(head));
1889 * If list is empty, and no isolation errors, means that all pages are
1890 * in the correct zone.
1892 if (list_empty(&movable_page_list) && !isolation_error_count)
1895 if (gup_flags & FOLL_PIN) {
1896 unpin_user_pages(pages, nr_pages);
1898 for (i = 0; i < nr_pages; i++)
1901 if (!list_empty(&movable_page_list)) {
1902 ret = migrate_pages(&movable_page_list, alloc_migration_target,
1903 NULL, (unsigned long)&mtc, MIGRATE_SYNC,
1904 MR_LONGTERM_PIN, NULL);
1905 if (ret && !list_empty(&movable_page_list))
1906 putback_movable_pages(&movable_page_list);
1909 return ret > 0 ? -ENOMEM : ret;
1912 static long check_and_migrate_movable_pages(unsigned long nr_pages,
1913 struct page **pages,
1914 unsigned int gup_flags)
1918 #endif /* CONFIG_MIGRATION */
1921 * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
1922 * allows us to process the FOLL_LONGTERM flag.
1924 static long __gup_longterm_locked(struct mm_struct *mm,
1925 unsigned long start,
1926 unsigned long nr_pages,
1927 struct page **pages,
1928 struct vm_area_struct **vmas,
1929 unsigned int gup_flags)
1934 if (!(gup_flags & FOLL_LONGTERM))
1935 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1937 flags = memalloc_pin_save();
1939 rc = __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1943 rc = check_and_migrate_movable_pages(rc, pages, gup_flags);
1945 memalloc_pin_restore(flags);
1950 static bool is_valid_gup_flags(unsigned int gup_flags)
1953 * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
1954 * never directly by the caller, so enforce that with an assertion:
1956 if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
1959 * FOLL_PIN is a prerequisite to FOLL_LONGTERM. Another way of saying
1960 * that is, FOLL_LONGTERM is a specific case, more restrictive case of
1963 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1970 static long __get_user_pages_remote(struct mm_struct *mm,
1971 unsigned long start, unsigned long nr_pages,
1972 unsigned int gup_flags, struct page **pages,
1973 struct vm_area_struct **vmas, int *locked)
1976 * Parts of FOLL_LONGTERM behavior are incompatible with
1977 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1978 * vmas. However, this only comes up if locked is set, and there are
1979 * callers that do request FOLL_LONGTERM, but do not set locked. So,
1980 * allow what we can.
1982 if (gup_flags & FOLL_LONGTERM) {
1983 if (WARN_ON_ONCE(locked))
1986 * This will check the vmas (even if our vmas arg is NULL)
1987 * and return -ENOTSUPP if DAX isn't allowed in this case:
1989 return __gup_longterm_locked(mm, start, nr_pages, pages,
1990 vmas, gup_flags | FOLL_TOUCH |
1994 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1996 gup_flags | FOLL_TOUCH | FOLL_REMOTE);
2000 * get_user_pages_remote() - pin user pages in memory
2001 * @mm: mm_struct of target mm
2002 * @start: starting user address
2003 * @nr_pages: number of pages from start to pin
2004 * @gup_flags: flags modifying lookup behaviour
2005 * @pages: array that receives pointers to the pages pinned.
2006 * Should be at least nr_pages long. Or NULL, if caller
2007 * only intends to ensure the pages are faulted in.
2008 * @vmas: array of pointers to vmas corresponding to each page.
2009 * Or NULL if the caller does not require them.
2010 * @locked: pointer to lock flag indicating whether lock is held and
2011 * subsequently whether VM_FAULT_RETRY functionality can be
2012 * utilised. Lock must initially be held.
2014 * Returns either number of pages pinned (which may be less than the
2015 * number requested), or an error. Details about the return value:
2017 * -- If nr_pages is 0, returns 0.
2018 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
2019 * -- If nr_pages is >0, and some pages were pinned, returns the number of
2020 * pages pinned. Again, this may be less than nr_pages.
2022 * The caller is responsible for releasing returned @pages, via put_page().
2024 * @vmas are valid only as long as mmap_lock is held.
2026 * Must be called with mmap_lock held for read or write.
2028 * get_user_pages_remote walks a process's page tables and takes a reference
2029 * to each struct page that each user address corresponds to at a given
2030 * instant. That is, it takes the page that would be accessed if a user
2031 * thread accesses the given user virtual address at that instant.
2033 * This does not guarantee that the page exists in the user mappings when
2034 * get_user_pages_remote returns, and there may even be a completely different
2035 * page there in some cases (eg. if mmapped pagecache has been invalidated
2036 * and subsequently re faulted). However it does guarantee that the page
2037 * won't be freed completely. And mostly callers simply care that the page
2038 * contains data that was valid *at some point in time*. Typically, an IO
2039 * or similar operation cannot guarantee anything stronger anyway because
2040 * locks can't be held over the syscall boundary.
2042 * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
2043 * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
2044 * be called after the page is finished with, and before put_page is called.
2046 * get_user_pages_remote is typically used for fewer-copy IO operations,
2047 * to get a handle on the memory by some means other than accesses
2048 * via the user virtual addresses. The pages may be submitted for
2049 * DMA to devices or accessed via their kernel linear mapping (via the
2050 * kmap APIs). Care should be taken to use the correct cache flushing APIs.
2052 * See also get_user_pages_fast, for performance critical applications.
2054 * get_user_pages_remote should be phased out in favor of
2055 * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
2056 * should use get_user_pages_remote because it cannot pass
2057 * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
2059 long get_user_pages_remote(struct mm_struct *mm,
2060 unsigned long start, unsigned long nr_pages,
2061 unsigned int gup_flags, struct page **pages,
2062 struct vm_area_struct **vmas, int *locked)
2064 if (!is_valid_gup_flags(gup_flags))
2067 return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
2068 pages, vmas, locked);
2070 EXPORT_SYMBOL(get_user_pages_remote);
2072 #else /* CONFIG_MMU */
2073 long get_user_pages_remote(struct mm_struct *mm,
2074 unsigned long start, unsigned long nr_pages,
2075 unsigned int gup_flags, struct page **pages,
2076 struct vm_area_struct **vmas, int *locked)
2081 static long __get_user_pages_remote(struct mm_struct *mm,
2082 unsigned long start, unsigned long nr_pages,
2083 unsigned int gup_flags, struct page **pages,
2084 struct vm_area_struct **vmas, int *locked)
2088 #endif /* !CONFIG_MMU */
2091 * get_user_pages() - pin user pages in memory
2092 * @start: starting user address
2093 * @nr_pages: number of pages from start to pin
2094 * @gup_flags: flags modifying lookup behaviour
2095 * @pages: array that receives pointers to the pages pinned.
2096 * Should be at least nr_pages long. Or NULL, if caller
2097 * only intends to ensure the pages are faulted in.
2098 * @vmas: array of pointers to vmas corresponding to each page.
2099 * Or NULL if the caller does not require them.
2101 * This is the same as get_user_pages_remote(), just with a less-flexible
2102 * calling convention where we assume that the mm being operated on belongs to
2103 * the current task, and doesn't allow passing of a locked parameter. We also
2104 * obviously don't pass FOLL_REMOTE in here.
2106 long get_user_pages(unsigned long start, unsigned long nr_pages,
2107 unsigned int gup_flags, struct page **pages,
2108 struct vm_area_struct **vmas)
2110 if (!is_valid_gup_flags(gup_flags))
2113 return __gup_longterm_locked(current->mm, start, nr_pages,
2114 pages, vmas, gup_flags | FOLL_TOUCH);
2116 EXPORT_SYMBOL(get_user_pages);
2119 * get_user_pages_locked() - variant of get_user_pages()
2121 * @start: starting user address
2122 * @nr_pages: number of pages from start to pin
2123 * @gup_flags: flags modifying lookup behaviour
2124 * @pages: array that receives pointers to the pages pinned.
2125 * Should be at least nr_pages long. Or NULL, if caller
2126 * only intends to ensure the pages are faulted in.
2127 * @locked: pointer to lock flag indicating whether lock is held and
2128 * subsequently whether VM_FAULT_RETRY functionality can be
2129 * utilised. Lock must initially be held.
2131 * It is suitable to replace the form:
2133 * mmap_read_lock(mm);
2135 * get_user_pages(mm, ..., pages, NULL);
2136 * mmap_read_unlock(mm);
2141 * mmap_read_lock(mm);
2143 * get_user_pages_locked(mm, ..., pages, &locked);
2145 * mmap_read_unlock(mm);
2147 * We can leverage the VM_FAULT_RETRY functionality in the page fault
2148 * paths better by using either get_user_pages_locked() or
2149 * get_user_pages_unlocked().
2152 long get_user_pages_locked(unsigned long start, unsigned long nr_pages,
2153 unsigned int gup_flags, struct page **pages,
2157 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
2158 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2159 * vmas. As there are no users of this flag in this call we simply
2160 * disallow this option for now.
2162 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
2165 * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
2166 * never directly by the caller, so enforce that:
2168 if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
2171 return __get_user_pages_locked(current->mm, start, nr_pages,
2172 pages, NULL, locked,
2173 gup_flags | FOLL_TOUCH);
2175 EXPORT_SYMBOL(get_user_pages_locked);
2178 * get_user_pages_unlocked() is suitable to replace the form:
2180 * mmap_read_lock(mm);
2181 * get_user_pages(mm, ..., pages, NULL);
2182 * mmap_read_unlock(mm);
2186 * get_user_pages_unlocked(mm, ..., pages);
2188 * It is functionally equivalent to get_user_pages_fast so
2189 * get_user_pages_fast should be used instead if specific gup_flags
2190 * (e.g. FOLL_FORCE) are not required.
2192 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
2193 struct page **pages, unsigned int gup_flags)
2195 struct mm_struct *mm = current->mm;
2200 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
2201 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2202 * vmas. As there are no users of this flag in this call we simply
2203 * disallow this option for now.
2205 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
2209 ret = __get_user_pages_locked(mm, start, nr_pages, pages, NULL,
2210 &locked, gup_flags | FOLL_TOUCH);
2212 mmap_read_unlock(mm);
2215 EXPORT_SYMBOL(get_user_pages_unlocked);
2220 * get_user_pages_fast attempts to pin user pages by walking the page
2221 * tables directly and avoids taking locks. Thus the walker needs to be
2222 * protected from page table pages being freed from under it, and should
2223 * block any THP splits.
2225 * One way to achieve this is to have the walker disable interrupts, and
2226 * rely on IPIs from the TLB flushing code blocking before the page table
2227 * pages are freed. This is unsuitable for architectures that do not need
2228 * to broadcast an IPI when invalidating TLBs.
2230 * Another way to achieve this is to batch up page table containing pages
2231 * belonging to more than one mm_user, then rcu_sched a callback to free those
2232 * pages. Disabling interrupts will allow the fast_gup walker to both block
2233 * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
2234 * (which is a relatively rare event). The code below adopts this strategy.
2236 * Before activating this code, please be aware that the following assumptions
2237 * are currently made:
2239 * *) Either MMU_GATHER_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
2240 * free pages containing page tables or TLB flushing requires IPI broadcast.
2242 * *) ptes can be read atomically by the architecture.
2244 * *) access_ok is sufficient to validate userspace address ranges.
2246 * The last two assumptions can be relaxed by the addition of helper functions.
2248 * This code is based heavily on the PowerPC implementation by Nick Piggin.
2250 #ifdef CONFIG_HAVE_FAST_GUP
2252 static void __maybe_unused undo_dev_pagemap(int *nr, int nr_start,
2254 struct page **pages)
2256 while ((*nr) - nr_start) {
2257 struct page *page = pages[--(*nr)];
2259 ClearPageReferenced(page);
2260 if (flags & FOLL_PIN)
2261 unpin_user_page(page);
2267 #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
2268 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2269 unsigned int flags, struct page **pages, int *nr)
2271 struct dev_pagemap *pgmap = NULL;
2272 int nr_start = *nr, ret = 0;
2275 ptem = ptep = pte_offset_map(&pmd, addr);
2277 pte_t pte = ptep_get_lockless(ptep);
2278 struct page *head, *page;
2281 * Similar to the PMD case below, NUMA hinting must take slow
2282 * path using the pte_protnone check.
2284 if (pte_protnone(pte))
2287 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2290 if (pte_devmap(pte)) {
2291 if (unlikely(flags & FOLL_LONGTERM))
2294 pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
2295 if (unlikely(!pgmap)) {
2296 undo_dev_pagemap(nr, nr_start, flags, pages);
2299 } else if (pte_special(pte))
2302 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2303 page = pte_page(pte);
2305 head = try_grab_compound_head(page, 1, flags);
2309 if (unlikely(page_is_secretmem(page))) {
2310 put_compound_head(head, 1, flags);
2314 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2315 put_compound_head(head, 1, flags);
2319 VM_BUG_ON_PAGE(compound_head(page) != head, page);
2322 * We need to make the page accessible if and only if we are
2323 * going to access its content (the FOLL_PIN case). Please
2324 * see Documentation/core-api/pin_user_pages.rst for
2327 if (flags & FOLL_PIN) {
2328 ret = arch_make_page_accessible(page);
2330 unpin_user_page(page);
2334 SetPageReferenced(page);
2338 } while (ptep++, addr += PAGE_SIZE, addr != end);
2344 put_dev_pagemap(pgmap);
2351 * If we can't determine whether or not a pte is special, then fail immediately
2352 * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
2355 * For a futex to be placed on a THP tail page, get_futex_key requires a
2356 * get_user_pages_fast_only implementation that can pin pages. Thus it's still
2357 * useful to have gup_huge_pmd even if we can't operate on ptes.
2359 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2360 unsigned int flags, struct page **pages, int *nr)
2364 #endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
2366 #if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
2367 static int __gup_device_huge(unsigned long pfn, unsigned long addr,
2368 unsigned long end, unsigned int flags,
2369 struct page **pages, int *nr)
2372 struct dev_pagemap *pgmap = NULL;
2375 struct page *page = pfn_to_page(pfn);
2377 pgmap = get_dev_pagemap(pfn, pgmap);
2378 if (unlikely(!pgmap)) {
2379 undo_dev_pagemap(nr, nr_start, flags, pages);
2382 SetPageReferenced(page);
2384 if (unlikely(!try_grab_page(page, flags))) {
2385 undo_dev_pagemap(nr, nr_start, flags, pages);
2390 } while (addr += PAGE_SIZE, addr != end);
2392 put_dev_pagemap(pgmap);
2396 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2397 unsigned long end, unsigned int flags,
2398 struct page **pages, int *nr)
2400 unsigned long fault_pfn;
2403 fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2404 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2407 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2408 undo_dev_pagemap(nr, nr_start, flags, pages);
2414 static int __gup_device_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2415 unsigned long end, unsigned int flags,
2416 struct page **pages, int *nr)
2418 unsigned long fault_pfn;
2421 fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2422 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2425 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2426 undo_dev_pagemap(nr, nr_start, flags, pages);
2432 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2433 unsigned long end, unsigned int flags,
2434 struct page **pages, int *nr)
2440 static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr,
2441 unsigned long end, unsigned int flags,
2442 struct page **pages, int *nr)
2449 static int record_subpages(struct page *page, unsigned long addr,
2450 unsigned long end, struct page **pages)
2454 for (nr = 0; addr != end; addr += PAGE_SIZE)
2455 pages[nr++] = page++;
2460 #ifdef CONFIG_ARCH_HAS_HUGEPD
2461 static unsigned long hugepte_addr_end(unsigned long addr, unsigned long end,
2464 unsigned long __boundary = (addr + sz) & ~(sz-1);
2465 return (__boundary - 1 < end - 1) ? __boundary : end;
2468 static int gup_hugepte(pte_t *ptep, unsigned long sz, unsigned long addr,
2469 unsigned long end, unsigned int flags,
2470 struct page **pages, int *nr)
2472 unsigned long pte_end;
2473 struct page *head, *page;
2477 pte_end = (addr + sz) & ~(sz-1);
2481 pte = huge_ptep_get(ptep);
2483 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2486 /* hugepages are never "special" */
2487 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2489 head = pte_page(pte);
2490 page = head + ((addr & (sz-1)) >> PAGE_SHIFT);
2491 refs = record_subpages(page, addr, end, pages + *nr);
2493 head = try_grab_compound_head(head, refs, flags);
2497 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2498 put_compound_head(head, refs, flags);
2503 SetPageReferenced(head);
2507 static int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2508 unsigned int pdshift, unsigned long end, unsigned int flags,
2509 struct page **pages, int *nr)
2512 unsigned long sz = 1UL << hugepd_shift(hugepd);
2515 ptep = hugepte_offset(hugepd, addr, pdshift);
2517 next = hugepte_addr_end(addr, end, sz);
2518 if (!gup_hugepte(ptep, sz, addr, end, flags, pages, nr))
2520 } while (ptep++, addr = next, addr != end);
2525 static inline int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2526 unsigned int pdshift, unsigned long end, unsigned int flags,
2527 struct page **pages, int *nr)
2531 #endif /* CONFIG_ARCH_HAS_HUGEPD */
2533 static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2534 unsigned long end, unsigned int flags,
2535 struct page **pages, int *nr)
2537 struct page *head, *page;
2540 if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
2543 if (pmd_devmap(orig)) {
2544 if (unlikely(flags & FOLL_LONGTERM))
2546 return __gup_device_huge_pmd(orig, pmdp, addr, end, flags,
2550 page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2551 refs = record_subpages(page, addr, end, pages + *nr);
2553 head = try_grab_compound_head(pmd_page(orig), refs, flags);
2557 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2558 put_compound_head(head, refs, flags);
2563 SetPageReferenced(head);
2567 static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2568 unsigned long end, unsigned int flags,
2569 struct page **pages, int *nr)
2571 struct page *head, *page;
2574 if (!pud_access_permitted(orig, flags & FOLL_WRITE))
2577 if (pud_devmap(orig)) {
2578 if (unlikely(flags & FOLL_LONGTERM))
2580 return __gup_device_huge_pud(orig, pudp, addr, end, flags,
2584 page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2585 refs = record_subpages(page, addr, end, pages + *nr);
2587 head = try_grab_compound_head(pud_page(orig), refs, flags);
2591 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2592 put_compound_head(head, refs, flags);
2597 SetPageReferenced(head);
2601 static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
2602 unsigned long end, unsigned int flags,
2603 struct page **pages, int *nr)
2606 struct page *head, *page;
2608 if (!pgd_access_permitted(orig, flags & FOLL_WRITE))
2611 BUILD_BUG_ON(pgd_devmap(orig));
2613 page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT);
2614 refs = record_subpages(page, addr, end, pages + *nr);
2616 head = try_grab_compound_head(pgd_page(orig), refs, flags);
2620 if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
2621 put_compound_head(head, refs, flags);
2626 SetPageReferenced(head);
2630 static int gup_pmd_range(pud_t *pudp, pud_t pud, unsigned long addr, unsigned long end,
2631 unsigned int flags, struct page **pages, int *nr)
2636 pmdp = pmd_offset_lockless(pudp, pud, addr);
2638 pmd_t pmd = READ_ONCE(*pmdp);
2640 next = pmd_addr_end(addr, end);
2641 if (!pmd_present(pmd))
2644 if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd) ||
2647 * NUMA hinting faults need to be handled in the GUP
2648 * slowpath for accounting purposes and so that they
2649 * can be serialised against THP migration.
2651 if (pmd_protnone(pmd))
2654 if (!gup_huge_pmd(pmd, pmdp, addr, next, flags,
2658 } else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
2660 * architecture have different format for hugetlbfs
2661 * pmd format and THP pmd format
2663 if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
2664 PMD_SHIFT, next, flags, pages, nr))
2666 } else if (!gup_pte_range(pmd, addr, next, flags, pages, nr))
2668 } while (pmdp++, addr = next, addr != end);
2673 static int gup_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr, unsigned long end,
2674 unsigned int flags, struct page **pages, int *nr)
2679 pudp = pud_offset_lockless(p4dp, p4d, addr);
2681 pud_t pud = READ_ONCE(*pudp);
2683 next = pud_addr_end(addr, end);
2684 if (unlikely(!pud_present(pud)))
2686 if (unlikely(pud_huge(pud))) {
2687 if (!gup_huge_pud(pud, pudp, addr, next, flags,
2690 } else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
2691 if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
2692 PUD_SHIFT, next, flags, pages, nr))
2694 } else if (!gup_pmd_range(pudp, pud, addr, next, flags, pages, nr))
2696 } while (pudp++, addr = next, addr != end);
2701 static int gup_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr, unsigned long end,
2702 unsigned int flags, struct page **pages, int *nr)
2707 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
2709 p4d_t p4d = READ_ONCE(*p4dp);
2711 next = p4d_addr_end(addr, end);
2714 BUILD_BUG_ON(p4d_huge(p4d));
2715 if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
2716 if (!gup_huge_pd(__hugepd(p4d_val(p4d)), addr,
2717 P4D_SHIFT, next, flags, pages, nr))
2719 } else if (!gup_pud_range(p4dp, p4d, addr, next, flags, pages, nr))
2721 } while (p4dp++, addr = next, addr != end);
2726 static void gup_pgd_range(unsigned long addr, unsigned long end,
2727 unsigned int flags, struct page **pages, int *nr)
2732 pgdp = pgd_offset(current->mm, addr);
2734 pgd_t pgd = READ_ONCE(*pgdp);
2736 next = pgd_addr_end(addr, end);
2739 if (unlikely(pgd_huge(pgd))) {
2740 if (!gup_huge_pgd(pgd, pgdp, addr, next, flags,
2743 } else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
2744 if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
2745 PGDIR_SHIFT, next, flags, pages, nr))
2747 } else if (!gup_p4d_range(pgdp, pgd, addr, next, flags, pages, nr))
2749 } while (pgdp++, addr = next, addr != end);
2752 static inline void gup_pgd_range(unsigned long addr, unsigned long end,
2753 unsigned int flags, struct page **pages, int *nr)
2756 #endif /* CONFIG_HAVE_FAST_GUP */
2758 #ifndef gup_fast_permitted
2760 * Check if it's allowed to use get_user_pages_fast_only() for the range, or
2761 * we need to fall back to the slow version:
2763 static bool gup_fast_permitted(unsigned long start, unsigned long end)
2769 static int __gup_longterm_unlocked(unsigned long start, int nr_pages,
2770 unsigned int gup_flags, struct page **pages)
2775 * FIXME: FOLL_LONGTERM does not work with
2776 * get_user_pages_unlocked() (see comments in that function)
2778 if (gup_flags & FOLL_LONGTERM) {
2779 mmap_read_lock(current->mm);
2780 ret = __gup_longterm_locked(current->mm,
2782 pages, NULL, gup_flags);
2783 mmap_read_unlock(current->mm);
2785 ret = get_user_pages_unlocked(start, nr_pages,
2792 static unsigned long lockless_pages_from_mm(unsigned long start,
2794 unsigned int gup_flags,
2795 struct page **pages)
2797 unsigned long flags;
2801 if (!IS_ENABLED(CONFIG_HAVE_FAST_GUP) ||
2802 !gup_fast_permitted(start, end))
2805 if (gup_flags & FOLL_PIN) {
2806 seq = raw_read_seqcount(¤t->mm->write_protect_seq);
2812 * Disable interrupts. The nested form is used, in order to allow full,
2813 * general purpose use of this routine.
2815 * With interrupts disabled, we block page table pages from being freed
2816 * from under us. See struct mmu_table_batch comments in
2817 * include/asm-generic/tlb.h for more details.
2819 * We do not adopt an rcu_read_lock() here as we also want to block IPIs
2820 * that come from THPs splitting.
2822 local_irq_save(flags);
2823 gup_pgd_range(start, end, gup_flags, pages, &nr_pinned);
2824 local_irq_restore(flags);
2827 * When pinning pages for DMA there could be a concurrent write protect
2828 * from fork() via copy_page_range(), in this case always fail fast GUP.
2830 if (gup_flags & FOLL_PIN) {
2831 if (read_seqcount_retry(¤t->mm->write_protect_seq, seq)) {
2832 unpin_user_pages(pages, nr_pinned);
2839 static int internal_get_user_pages_fast(unsigned long start,
2840 unsigned long nr_pages,
2841 unsigned int gup_flags,
2842 struct page **pages)
2844 unsigned long len, end;
2845 unsigned long nr_pinned;
2848 if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM |
2849 FOLL_FORCE | FOLL_PIN | FOLL_GET |
2850 FOLL_FAST_ONLY | FOLL_NOFAULT)))
2853 if (gup_flags & FOLL_PIN)
2854 mm_set_has_pinned_flag(¤t->mm->flags);
2856 if (!(gup_flags & FOLL_FAST_ONLY))
2857 might_lock_read(¤t->mm->mmap_lock);
2859 start = untagged_addr(start) & PAGE_MASK;
2860 len = nr_pages << PAGE_SHIFT;
2861 if (check_add_overflow(start, len, &end))
2863 if (unlikely(!access_ok((void __user *)start, len)))
2866 nr_pinned = lockless_pages_from_mm(start, end, gup_flags, pages);
2867 if (nr_pinned == nr_pages || gup_flags & FOLL_FAST_ONLY)
2870 /* Slow path: try to get the remaining pages with get_user_pages */
2871 start += nr_pinned << PAGE_SHIFT;
2873 ret = __gup_longterm_unlocked(start, nr_pages - nr_pinned, gup_flags,
2877 * The caller has to unpin the pages we already pinned so
2878 * returning -errno is not an option
2884 return ret + nr_pinned;
2888 * get_user_pages_fast_only() - pin user pages in memory
2889 * @start: starting user address
2890 * @nr_pages: number of pages from start to pin
2891 * @gup_flags: flags modifying pin behaviour
2892 * @pages: array that receives pointers to the pages pinned.
2893 * Should be at least nr_pages long.
2895 * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
2897 * Note a difference with get_user_pages_fast: this always returns the
2898 * number of pages pinned, 0 if no pages were pinned.
2900 * If the architecture does not support this function, simply return with no
2903 * Careful, careful! COW breaking can go either way, so a non-write
2904 * access can get ambiguous page results. If you call this function without
2905 * 'write' set, you'd better be sure that you're ok with that ambiguity.
2907 int get_user_pages_fast_only(unsigned long start, int nr_pages,
2908 unsigned int gup_flags, struct page **pages)
2912 * Internally (within mm/gup.c), gup fast variants must set FOLL_GET,
2913 * because gup fast is always a "pin with a +1 page refcount" request.
2915 * FOLL_FAST_ONLY is required in order to match the API description of
2916 * this routine: no fall back to regular ("slow") GUP.
2918 gup_flags |= FOLL_GET | FOLL_FAST_ONLY;
2920 nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
2924 * As specified in the API description above, this routine is not
2925 * allowed to return negative values. However, the common core
2926 * routine internal_get_user_pages_fast() *can* return -errno.
2927 * Therefore, correct for that here:
2934 EXPORT_SYMBOL_GPL(get_user_pages_fast_only);
2937 * get_user_pages_fast() - pin user pages in memory
2938 * @start: starting user address
2939 * @nr_pages: number of pages from start to pin
2940 * @gup_flags: flags modifying pin behaviour
2941 * @pages: array that receives pointers to the pages pinned.
2942 * Should be at least nr_pages long.
2944 * Attempt to pin user pages in memory without taking mm->mmap_lock.
2945 * If not successful, it will fall back to taking the lock and
2946 * calling get_user_pages().
2948 * Returns number of pages pinned. This may be fewer than the number requested.
2949 * If nr_pages is 0 or negative, returns 0. If no pages were pinned, returns
2952 int get_user_pages_fast(unsigned long start, int nr_pages,
2953 unsigned int gup_flags, struct page **pages)
2955 if (!is_valid_gup_flags(gup_flags))
2959 * The caller may or may not have explicitly set FOLL_GET; either way is
2960 * OK. However, internally (within mm/gup.c), gup fast variants must set
2961 * FOLL_GET, because gup fast is always a "pin with a +1 page refcount"
2964 gup_flags |= FOLL_GET;
2965 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
2967 EXPORT_SYMBOL_GPL(get_user_pages_fast);
2970 * pin_user_pages_fast() - pin user pages in memory without taking locks
2972 * @start: starting user address
2973 * @nr_pages: number of pages from start to pin
2974 * @gup_flags: flags modifying pin behaviour
2975 * @pages: array that receives pointers to the pages pinned.
2976 * Should be at least nr_pages long.
2978 * Nearly the same as get_user_pages_fast(), except that FOLL_PIN is set. See
2979 * get_user_pages_fast() for documentation on the function arguments, because
2980 * the arguments here are identical.
2982 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
2983 * see Documentation/core-api/pin_user_pages.rst for further details.
2985 int pin_user_pages_fast(unsigned long start, int nr_pages,
2986 unsigned int gup_flags, struct page **pages)
2988 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2989 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2992 gup_flags |= FOLL_PIN;
2993 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
2995 EXPORT_SYMBOL_GPL(pin_user_pages_fast);
2998 * This is the FOLL_PIN equivalent of get_user_pages_fast_only(). Behavior
2999 * is the same, except that this one sets FOLL_PIN instead of FOLL_GET.
3001 * The API rules are the same, too: no negative values may be returned.
3003 int pin_user_pages_fast_only(unsigned long start, int nr_pages,
3004 unsigned int gup_flags, struct page **pages)
3009 * FOLL_GET and FOLL_PIN are mutually exclusive. Note that the API
3010 * rules require returning 0, rather than -errno:
3012 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3015 * FOLL_FAST_ONLY is required in order to match the API description of
3016 * this routine: no fall back to regular ("slow") GUP.
3018 gup_flags |= (FOLL_PIN | FOLL_FAST_ONLY);
3019 nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
3022 * This routine is not allowed to return negative values. However,
3023 * internal_get_user_pages_fast() *can* return -errno. Therefore,
3024 * correct for that here:
3031 EXPORT_SYMBOL_GPL(pin_user_pages_fast_only);
3034 * pin_user_pages_remote() - pin pages of a remote process
3036 * @mm: mm_struct of target mm
3037 * @start: starting user address
3038 * @nr_pages: number of pages from start to pin
3039 * @gup_flags: flags modifying lookup behaviour
3040 * @pages: array that receives pointers to the pages pinned.
3041 * Should be at least nr_pages long. Or NULL, if caller
3042 * only intends to ensure the pages are faulted in.
3043 * @vmas: array of pointers to vmas corresponding to each page.
3044 * Or NULL if the caller does not require them.
3045 * @locked: pointer to lock flag indicating whether lock is held and
3046 * subsequently whether VM_FAULT_RETRY functionality can be
3047 * utilised. Lock must initially be held.
3049 * Nearly the same as get_user_pages_remote(), except that FOLL_PIN is set. See
3050 * get_user_pages_remote() for documentation on the function arguments, because
3051 * the arguments here are identical.
3053 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3054 * see Documentation/core-api/pin_user_pages.rst for details.
3056 long pin_user_pages_remote(struct mm_struct *mm,
3057 unsigned long start, unsigned long nr_pages,
3058 unsigned int gup_flags, struct page **pages,
3059 struct vm_area_struct **vmas, int *locked)
3061 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3062 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3065 gup_flags |= FOLL_PIN;
3066 return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
3067 pages, vmas, locked);
3069 EXPORT_SYMBOL(pin_user_pages_remote);
3072 * pin_user_pages() - pin user pages in memory for use by other devices
3074 * @start: starting user address
3075 * @nr_pages: number of pages from start to pin
3076 * @gup_flags: flags modifying lookup behaviour
3077 * @pages: array that receives pointers to the pages pinned.
3078 * Should be at least nr_pages long. Or NULL, if caller
3079 * only intends to ensure the pages are faulted in.
3080 * @vmas: array of pointers to vmas corresponding to each page.
3081 * Or NULL if the caller does not require them.
3083 * Nearly the same as get_user_pages(), except that FOLL_TOUCH is not set, and
3086 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3087 * see Documentation/core-api/pin_user_pages.rst for details.
3089 long pin_user_pages(unsigned long start, unsigned long nr_pages,
3090 unsigned int gup_flags, struct page **pages,
3091 struct vm_area_struct **vmas)
3093 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3094 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3097 gup_flags |= FOLL_PIN;
3098 return __gup_longterm_locked(current->mm, start, nr_pages,
3099 pages, vmas, gup_flags);
3101 EXPORT_SYMBOL(pin_user_pages);
3104 * pin_user_pages_unlocked() is the FOLL_PIN variant of
3105 * get_user_pages_unlocked(). Behavior is the same, except that this one sets
3106 * FOLL_PIN and rejects FOLL_GET.
3108 long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
3109 struct page **pages, unsigned int gup_flags)
3111 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3112 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3115 gup_flags |= FOLL_PIN;
3116 return get_user_pages_unlocked(start, nr_pages, pages, gup_flags);
3118 EXPORT_SYMBOL(pin_user_pages_unlocked);
3121 * pin_user_pages_locked() is the FOLL_PIN variant of get_user_pages_locked().
3122 * Behavior is the same, except that this one sets FOLL_PIN and rejects
3125 long pin_user_pages_locked(unsigned long start, unsigned long nr_pages,
3126 unsigned int gup_flags, struct page **pages,
3130 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
3131 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
3132 * vmas. As there are no users of this flag in this call we simply
3133 * disallow this option for now.
3135 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
3138 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3139 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3142 gup_flags |= FOLL_PIN;
3143 return __get_user_pages_locked(current->mm, start, nr_pages,
3144 pages, NULL, locked,
3145 gup_flags | FOLL_TOUCH);
3147 EXPORT_SYMBOL(pin_user_pages_locked);