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 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 if (!(flags & (FOLL_GET | FOLL_PIN)))
214 return try_grab_compound_head(page, 1, flags);
218 * unpin_user_page() - release a dma-pinned page
219 * @page: pointer to page to be released
221 * Pages that were pinned via pin_user_pages*() must be released via either
222 * unpin_user_page(), or one of the unpin_user_pages*() routines. This is so
223 * that such pages can be separately tracked and uniquely handled. In
224 * particular, interactions with RDMA and filesystems need special handling.
226 void unpin_user_page(struct page *page)
228 put_compound_head(compound_head(page), 1, FOLL_PIN);
230 EXPORT_SYMBOL(unpin_user_page);
232 static inline void compound_range_next(unsigned long i, unsigned long npages,
233 struct page **list, struct page **head,
234 unsigned int *ntails)
236 struct page *next, *page;
243 page = compound_head(next);
244 if (PageCompound(page) && compound_order(page) >= 1)
245 nr = min_t(unsigned int,
246 page + compound_nr(page) - next, npages - i);
252 #define for_each_compound_range(__i, __list, __npages, __head, __ntails) \
254 compound_range_next(__i, __npages, __list, &(__head), &(__ntails)); \
255 __i < __npages; __i += __ntails, \
256 compound_range_next(__i, __npages, __list, &(__head), &(__ntails)))
258 static inline void compound_next(unsigned long i, unsigned long npages,
259 struct page **list, struct page **head,
260 unsigned int *ntails)
268 page = compound_head(list[i]);
269 for (nr = i + 1; nr < npages; nr++) {
270 if (compound_head(list[nr]) != page)
278 #define for_each_compound_head(__i, __list, __npages, __head, __ntails) \
280 compound_next(__i, __npages, __list, &(__head), &(__ntails)); \
281 __i < __npages; __i += __ntails, \
282 compound_next(__i, __npages, __list, &(__head), &(__ntails)))
285 * unpin_user_pages_dirty_lock() - release and optionally dirty gup-pinned pages
286 * @pages: array of pages to be maybe marked dirty, and definitely released.
287 * @npages: number of pages in the @pages array.
288 * @make_dirty: whether to mark the pages dirty
290 * "gup-pinned page" refers to a page that has had one of the get_user_pages()
291 * variants called on that page.
293 * For each page in the @pages array, make that page (or its head page, if a
294 * compound page) dirty, if @make_dirty is true, and if the page was previously
295 * listed as clean. In any case, releases all pages using unpin_user_page(),
296 * possibly via unpin_user_pages(), for the non-dirty case.
298 * Please see the unpin_user_page() documentation for details.
300 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
301 * required, then the caller should a) verify that this is really correct,
302 * because _lock() is usually required, and b) hand code it:
303 * set_page_dirty_lock(), unpin_user_page().
306 void unpin_user_pages_dirty_lock(struct page **pages, unsigned long npages,
314 unpin_user_pages(pages, npages);
318 for_each_compound_head(index, pages, npages, head, ntails) {
320 * Checking PageDirty at this point may race with
321 * clear_page_dirty_for_io(), but that's OK. Two key
324 * 1) This code sees the page as already dirty, so it
325 * skips the call to set_page_dirty(). That could happen
326 * because clear_page_dirty_for_io() called
327 * page_mkclean(), followed by set_page_dirty().
328 * However, now the page is going to get written back,
329 * which meets the original intention of setting it
330 * dirty, so all is well: clear_page_dirty_for_io() goes
331 * on to call TestClearPageDirty(), and write the page
334 * 2) This code sees the page as clean, so it calls
335 * set_page_dirty(). The page stays dirty, despite being
336 * written back, so it gets written back again in the
337 * next writeback cycle. This is harmless.
339 if (!PageDirty(head))
340 set_page_dirty_lock(head);
341 put_compound_head(head, ntails, FOLL_PIN);
344 EXPORT_SYMBOL(unpin_user_pages_dirty_lock);
347 * unpin_user_page_range_dirty_lock() - release and optionally dirty
348 * gup-pinned page range
350 * @page: the starting page of a range maybe marked dirty, and definitely released.
351 * @npages: number of consecutive pages to release.
352 * @make_dirty: whether to mark the pages dirty
354 * "gup-pinned page range" refers to a range of pages that has had one of the
355 * pin_user_pages() variants called on that page.
357 * For the page ranges defined by [page .. page+npages], make that range (or
358 * its head pages, if a compound page) dirty, if @make_dirty is true, and if the
359 * page range was previously listed as clean.
361 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
362 * required, then the caller should a) verify that this is really correct,
363 * because _lock() is usually required, and b) hand code it:
364 * set_page_dirty_lock(), unpin_user_page().
367 void unpin_user_page_range_dirty_lock(struct page *page, unsigned long npages,
374 for_each_compound_range(index, &page, npages, head, ntails) {
375 if (make_dirty && !PageDirty(head))
376 set_page_dirty_lock(head);
377 put_compound_head(head, ntails, FOLL_PIN);
380 EXPORT_SYMBOL(unpin_user_page_range_dirty_lock);
383 * unpin_user_pages() - release an array of gup-pinned pages.
384 * @pages: array of pages to be marked dirty and released.
385 * @npages: number of pages in the @pages array.
387 * For each page in the @pages array, release the page using unpin_user_page().
389 * Please see the unpin_user_page() documentation for details.
391 void unpin_user_pages(struct page **pages, unsigned long npages)
398 * If this WARN_ON() fires, then the system *might* be leaking pages (by
399 * leaving them pinned), but probably not. More likely, gup/pup returned
400 * a hard -ERRNO error to the caller, who erroneously passed it here.
402 if (WARN_ON(IS_ERR_VALUE(npages)))
405 for_each_compound_head(index, pages, npages, head, ntails)
406 put_compound_head(head, ntails, FOLL_PIN);
408 EXPORT_SYMBOL(unpin_user_pages);
411 * Set the MMF_HAS_PINNED if not set yet; after set it'll be there for the mm's
412 * lifecycle. Avoid setting the bit unless necessary, or it might cause write
413 * cache bouncing on large SMP machines for concurrent pinned gups.
415 static inline void mm_set_has_pinned_flag(unsigned long *mm_flags)
417 if (!test_bit(MMF_HAS_PINNED, mm_flags))
418 set_bit(MMF_HAS_PINNED, mm_flags);
422 static struct page *no_page_table(struct vm_area_struct *vma,
426 * When core dumping an enormous anonymous area that nobody
427 * has touched so far, we don't want to allocate unnecessary pages or
428 * page tables. Return error instead of NULL to skip handle_mm_fault,
429 * then get_dump_page() will return NULL to leave a hole in the dump.
430 * But we can only make this optimization where a hole would surely
431 * be zero-filled if handle_mm_fault() actually did handle it.
433 if ((flags & FOLL_DUMP) &&
434 (vma_is_anonymous(vma) || !vma->vm_ops->fault))
435 return ERR_PTR(-EFAULT);
439 static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
440 pte_t *pte, unsigned int flags)
442 /* No page to get reference */
443 if (flags & FOLL_GET)
446 if (flags & FOLL_TOUCH) {
449 if (flags & FOLL_WRITE)
450 entry = pte_mkdirty(entry);
451 entry = pte_mkyoung(entry);
453 if (!pte_same(*pte, entry)) {
454 set_pte_at(vma->vm_mm, address, pte, entry);
455 update_mmu_cache(vma, address, pte);
459 /* Proper page table entry exists, but no corresponding struct page */
464 * FOLL_FORCE can write to even unwritable pte's, but only
465 * after we've gone through a COW cycle and they are dirty.
467 static inline bool can_follow_write_pte(pte_t pte, unsigned int flags)
469 return pte_write(pte) ||
470 ((flags & FOLL_FORCE) && (flags & FOLL_COW) && pte_dirty(pte));
473 static struct page *follow_page_pte(struct vm_area_struct *vma,
474 unsigned long address, pmd_t *pmd, unsigned int flags,
475 struct dev_pagemap **pgmap)
477 struct mm_struct *mm = vma->vm_mm;
483 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
484 if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
485 (FOLL_PIN | FOLL_GET)))
486 return ERR_PTR(-EINVAL);
488 if (unlikely(pmd_bad(*pmd)))
489 return no_page_table(vma, flags);
491 ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
493 if (!pte_present(pte)) {
496 * KSM's break_ksm() relies upon recognizing a ksm page
497 * even while it is being migrated, so for that case we
498 * need migration_entry_wait().
500 if (likely(!(flags & FOLL_MIGRATION)))
504 entry = pte_to_swp_entry(pte);
505 if (!is_migration_entry(entry))
507 pte_unmap_unlock(ptep, ptl);
508 migration_entry_wait(mm, pmd, address);
511 if ((flags & FOLL_NUMA) && pte_protnone(pte))
513 if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
514 pte_unmap_unlock(ptep, ptl);
518 page = vm_normal_page(vma, address, pte);
519 if (!page && pte_devmap(pte) && (flags & (FOLL_GET | FOLL_PIN))) {
521 * Only return device mapping pages in the FOLL_GET or FOLL_PIN
522 * case since they are only valid while holding the pgmap
525 *pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
527 page = pte_page(pte);
530 } else if (unlikely(!page)) {
531 if (flags & FOLL_DUMP) {
532 /* Avoid special (like zero) pages in core dumps */
533 page = ERR_PTR(-EFAULT);
537 if (is_zero_pfn(pte_pfn(pte))) {
538 page = pte_page(pte);
540 ret = follow_pfn_pte(vma, address, ptep, flags);
546 /* try_grab_page() does nothing unless FOLL_GET or FOLL_PIN is set. */
547 if (unlikely(!try_grab_page(page, flags))) {
548 page = ERR_PTR(-ENOMEM);
552 * We need to make the page accessible if and only if we are going
553 * to access its content (the FOLL_PIN case). Please see
554 * Documentation/core-api/pin_user_pages.rst for details.
556 if (flags & FOLL_PIN) {
557 ret = arch_make_page_accessible(page);
559 unpin_user_page(page);
564 if (flags & FOLL_TOUCH) {
565 if ((flags & FOLL_WRITE) &&
566 !pte_dirty(pte) && !PageDirty(page))
567 set_page_dirty(page);
569 * pte_mkyoung() would be more correct here, but atomic care
570 * is needed to avoid losing the dirty bit: it is easier to use
571 * mark_page_accessed().
573 mark_page_accessed(page);
575 if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
576 /* Do not mlock pte-mapped THP */
577 if (PageTransCompound(page))
581 * The preliminary mapping check is mainly to avoid the
582 * pointless overhead of lock_page on the ZERO_PAGE
583 * which might bounce very badly if there is contention.
585 * If the page is already locked, we don't need to
586 * handle it now - vmscan will handle it later if and
587 * when it attempts to reclaim the page.
589 if (page->mapping && trylock_page(page)) {
590 lru_add_drain(); /* push cached pages to LRU */
592 * Because we lock page here, and migration is
593 * blocked by the pte's page reference, and we
594 * know the page is still mapped, we don't even
595 * need to check for file-cache page truncation.
597 mlock_vma_page(page);
602 pte_unmap_unlock(ptep, ptl);
605 pte_unmap_unlock(ptep, ptl);
608 return no_page_table(vma, flags);
611 static struct page *follow_pmd_mask(struct vm_area_struct *vma,
612 unsigned long address, pud_t *pudp,
614 struct follow_page_context *ctx)
619 struct mm_struct *mm = vma->vm_mm;
621 pmd = pmd_offset(pudp, address);
623 * The READ_ONCE() will stabilize the pmdval in a register or
624 * on the stack so that it will stop changing under the code.
626 pmdval = READ_ONCE(*pmd);
627 if (pmd_none(pmdval))
628 return no_page_table(vma, flags);
629 if (pmd_huge(pmdval) && is_vm_hugetlb_page(vma)) {
630 page = follow_huge_pmd(mm, address, pmd, flags);
633 return no_page_table(vma, flags);
635 if (is_hugepd(__hugepd(pmd_val(pmdval)))) {
636 page = follow_huge_pd(vma, address,
637 __hugepd(pmd_val(pmdval)), flags,
641 return no_page_table(vma, flags);
644 if (!pmd_present(pmdval)) {
646 * Should never reach here, if thp migration is not supported;
647 * Otherwise, it must be a thp migration entry.
649 VM_BUG_ON(!thp_migration_supported() ||
650 !is_pmd_migration_entry(pmdval));
652 if (likely(!(flags & FOLL_MIGRATION)))
653 return no_page_table(vma, flags);
655 pmd_migration_entry_wait(mm, pmd);
656 pmdval = READ_ONCE(*pmd);
658 * MADV_DONTNEED may convert the pmd to null because
659 * mmap_lock is held in read mode
661 if (pmd_none(pmdval))
662 return no_page_table(vma, flags);
665 if (pmd_devmap(pmdval)) {
666 ptl = pmd_lock(mm, pmd);
667 page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
672 if (likely(!pmd_trans_huge(pmdval)))
673 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
675 if ((flags & FOLL_NUMA) && pmd_protnone(pmdval))
676 return no_page_table(vma, flags);
679 ptl = pmd_lock(mm, pmd);
680 if (unlikely(pmd_none(*pmd))) {
682 return no_page_table(vma, flags);
684 if (unlikely(!pmd_present(*pmd))) {
686 if (likely(!(flags & FOLL_MIGRATION)))
687 return no_page_table(vma, flags);
688 pmd_migration_entry_wait(mm, pmd);
691 if (unlikely(!pmd_trans_huge(*pmd))) {
693 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
695 if (flags & FOLL_SPLIT_PMD) {
697 page = pmd_page(*pmd);
698 if (is_huge_zero_page(page)) {
701 split_huge_pmd(vma, pmd, address);
702 if (pmd_trans_unstable(pmd))
706 split_huge_pmd(vma, pmd, address);
707 ret = pte_alloc(mm, pmd) ? -ENOMEM : 0;
710 return ret ? ERR_PTR(ret) :
711 follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
713 page = follow_trans_huge_pmd(vma, address, pmd, flags);
715 ctx->page_mask = HPAGE_PMD_NR - 1;
719 static struct page *follow_pud_mask(struct vm_area_struct *vma,
720 unsigned long address, p4d_t *p4dp,
722 struct follow_page_context *ctx)
727 struct mm_struct *mm = vma->vm_mm;
729 pud = pud_offset(p4dp, address);
731 return no_page_table(vma, flags);
732 if (pud_huge(*pud) && is_vm_hugetlb_page(vma)) {
733 page = follow_huge_pud(mm, address, pud, flags);
736 return no_page_table(vma, flags);
738 if (is_hugepd(__hugepd(pud_val(*pud)))) {
739 page = follow_huge_pd(vma, address,
740 __hugepd(pud_val(*pud)), flags,
744 return no_page_table(vma, flags);
746 if (pud_devmap(*pud)) {
747 ptl = pud_lock(mm, pud);
748 page = follow_devmap_pud(vma, address, pud, flags, &ctx->pgmap);
753 if (unlikely(pud_bad(*pud)))
754 return no_page_table(vma, flags);
756 return follow_pmd_mask(vma, address, pud, flags, ctx);
759 static struct page *follow_p4d_mask(struct vm_area_struct *vma,
760 unsigned long address, pgd_t *pgdp,
762 struct follow_page_context *ctx)
767 p4d = p4d_offset(pgdp, address);
769 return no_page_table(vma, flags);
770 BUILD_BUG_ON(p4d_huge(*p4d));
771 if (unlikely(p4d_bad(*p4d)))
772 return no_page_table(vma, flags);
774 if (is_hugepd(__hugepd(p4d_val(*p4d)))) {
775 page = follow_huge_pd(vma, address,
776 __hugepd(p4d_val(*p4d)), flags,
780 return no_page_table(vma, flags);
782 return follow_pud_mask(vma, address, p4d, flags, ctx);
786 * follow_page_mask - look up a page descriptor from a user-virtual address
787 * @vma: vm_area_struct mapping @address
788 * @address: virtual address to look up
789 * @flags: flags modifying lookup behaviour
790 * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
791 * pointer to output page_mask
793 * @flags can have FOLL_ flags set, defined in <linux/mm.h>
795 * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
796 * the device's dev_pagemap metadata to avoid repeating expensive lookups.
798 * On output, the @ctx->page_mask is set according to the size of the page.
800 * Return: the mapped (struct page *), %NULL if no mapping exists, or
801 * an error pointer if there is a mapping to something not represented
802 * by a page descriptor (see also vm_normal_page()).
804 static struct page *follow_page_mask(struct vm_area_struct *vma,
805 unsigned long address, unsigned int flags,
806 struct follow_page_context *ctx)
810 struct mm_struct *mm = vma->vm_mm;
814 /* make this handle hugepd */
815 page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
817 WARN_ON_ONCE(flags & (FOLL_GET | FOLL_PIN));
821 pgd = pgd_offset(mm, address);
823 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
824 return no_page_table(vma, flags);
826 if (pgd_huge(*pgd)) {
827 page = follow_huge_pgd(mm, address, pgd, flags);
830 return no_page_table(vma, flags);
832 if (is_hugepd(__hugepd(pgd_val(*pgd)))) {
833 page = follow_huge_pd(vma, address,
834 __hugepd(pgd_val(*pgd)), flags,
838 return no_page_table(vma, flags);
841 return follow_p4d_mask(vma, address, pgd, flags, ctx);
844 struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
845 unsigned int foll_flags)
847 struct follow_page_context ctx = { NULL };
850 if (vma_is_secretmem(vma))
853 page = follow_page_mask(vma, address, foll_flags, &ctx);
855 put_dev_pagemap(ctx.pgmap);
859 static int get_gate_page(struct mm_struct *mm, unsigned long address,
860 unsigned int gup_flags, struct vm_area_struct **vma,
870 /* user gate pages are read-only */
871 if (gup_flags & FOLL_WRITE)
873 if (address > TASK_SIZE)
874 pgd = pgd_offset_k(address);
876 pgd = pgd_offset_gate(mm, address);
879 p4d = p4d_offset(pgd, address);
882 pud = pud_offset(p4d, address);
885 pmd = pmd_offset(pud, address);
886 if (!pmd_present(*pmd))
888 VM_BUG_ON(pmd_trans_huge(*pmd));
889 pte = pte_offset_map(pmd, address);
892 *vma = get_gate_vma(mm);
895 *page = vm_normal_page(*vma, address, *pte);
897 if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
899 *page = pte_page(*pte);
901 if (unlikely(!try_grab_page(*page, gup_flags))) {
913 * mmap_lock must be held on entry. If @locked != NULL and *@flags
914 * does not include FOLL_NOWAIT, the mmap_lock may be released. If it
915 * is, *@locked will be set to 0 and -EBUSY returned.
917 static int faultin_page(struct vm_area_struct *vma,
918 unsigned long address, unsigned int *flags, int *locked)
920 unsigned int fault_flags = 0;
923 /* mlock all present pages, but do not fault in new pages */
924 if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)
926 if (*flags & FOLL_NOFAULT)
928 if (*flags & FOLL_WRITE)
929 fault_flags |= FAULT_FLAG_WRITE;
930 if (*flags & FOLL_REMOTE)
931 fault_flags |= FAULT_FLAG_REMOTE;
933 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
934 if (*flags & FOLL_NOWAIT)
935 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
936 if (*flags & FOLL_TRIED) {
938 * Note: FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_TRIED
941 fault_flags |= FAULT_FLAG_TRIED;
944 ret = handle_mm_fault(vma, address, fault_flags, NULL);
945 if (ret & VM_FAULT_ERROR) {
946 int err = vm_fault_to_errno(ret, *flags);
953 if (ret & VM_FAULT_RETRY) {
954 if (locked && !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
960 * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
961 * necessary, even if maybe_mkwrite decided not to set pte_write. We
962 * can thus safely do subsequent page lookups as if they were reads.
963 * But only do so when looping for pte_write is futile: in some cases
964 * userspace may also be wanting to write to the gotten user page,
965 * which a read fault here might prevent (a readonly page might get
966 * reCOWed by userspace write).
968 if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
973 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
975 vm_flags_t vm_flags = vma->vm_flags;
976 int write = (gup_flags & FOLL_WRITE);
977 int foreign = (gup_flags & FOLL_REMOTE);
979 if (vm_flags & (VM_IO | VM_PFNMAP))
982 if (gup_flags & FOLL_ANON && !vma_is_anonymous(vma))
985 if ((gup_flags & FOLL_LONGTERM) && vma_is_fsdax(vma))
988 if (vma_is_secretmem(vma))
992 if (!(vm_flags & VM_WRITE)) {
993 if (!(gup_flags & FOLL_FORCE))
996 * We used to let the write,force case do COW in a
997 * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
998 * set a breakpoint in a read-only mapping of an
999 * executable, without corrupting the file (yet only
1000 * when that file had been opened for writing!).
1001 * Anon pages in shared mappings are surprising: now
1004 if (!is_cow_mapping(vm_flags))
1007 } else if (!(vm_flags & VM_READ)) {
1008 if (!(gup_flags & FOLL_FORCE))
1011 * Is there actually any vma we can reach here which does not
1012 * have VM_MAYREAD set?
1014 if (!(vm_flags & VM_MAYREAD))
1018 * gups are always data accesses, not instruction
1019 * fetches, so execute=false here
1021 if (!arch_vma_access_permitted(vma, write, false, foreign))
1027 * __get_user_pages() - pin user pages in memory
1028 * @mm: mm_struct of target mm
1029 * @start: starting user address
1030 * @nr_pages: number of pages from start to pin
1031 * @gup_flags: flags modifying pin behaviour
1032 * @pages: array that receives pointers to the pages pinned.
1033 * Should be at least nr_pages long. Or NULL, if caller
1034 * only intends to ensure the pages are faulted in.
1035 * @vmas: array of pointers to vmas corresponding to each page.
1036 * Or NULL if the caller does not require them.
1037 * @locked: whether we're still with the mmap_lock held
1039 * Returns either number of pages pinned (which may be less than the
1040 * number requested), or an error. Details about the return value:
1042 * -- If nr_pages is 0, returns 0.
1043 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
1044 * -- If nr_pages is >0, and some pages were pinned, returns the number of
1045 * pages pinned. Again, this may be less than nr_pages.
1046 * -- 0 return value is possible when the fault would need to be retried.
1048 * The caller is responsible for releasing returned @pages, via put_page().
1050 * @vmas are valid only as long as mmap_lock is held.
1052 * Must be called with mmap_lock held. It may be released. See below.
1054 * __get_user_pages walks a process's page tables and takes a reference to
1055 * each struct page that each user address corresponds to at a given
1056 * instant. That is, it takes the page that would be accessed if a user
1057 * thread accesses the given user virtual address at that instant.
1059 * This does not guarantee that the page exists in the user mappings when
1060 * __get_user_pages returns, and there may even be a completely different
1061 * page there in some cases (eg. if mmapped pagecache has been invalidated
1062 * and subsequently re faulted). However it does guarantee that the page
1063 * won't be freed completely. And mostly callers simply care that the page
1064 * contains data that was valid *at some point in time*. Typically, an IO
1065 * or similar operation cannot guarantee anything stronger anyway because
1066 * locks can't be held over the syscall boundary.
1068 * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
1069 * the page is written to, set_page_dirty (or set_page_dirty_lock, as
1070 * appropriate) must be called after the page is finished with, and
1071 * before put_page is called.
1073 * If @locked != NULL, *@locked will be set to 0 when mmap_lock is
1074 * released by an up_read(). That can happen if @gup_flags does not
1077 * A caller using such a combination of @locked and @gup_flags
1078 * must therefore hold the mmap_lock for reading only, and recognize
1079 * when it's been released. Otherwise, it must be held for either
1080 * reading or writing and will not be released.
1082 * In most cases, get_user_pages or get_user_pages_fast should be used
1083 * instead of __get_user_pages. __get_user_pages should be used only if
1084 * you need some special @gup_flags.
1086 static long __get_user_pages(struct mm_struct *mm,
1087 unsigned long start, unsigned long nr_pages,
1088 unsigned int gup_flags, struct page **pages,
1089 struct vm_area_struct **vmas, int *locked)
1091 long ret = 0, i = 0;
1092 struct vm_area_struct *vma = NULL;
1093 struct follow_page_context ctx = { NULL };
1098 start = untagged_addr(start);
1100 VM_BUG_ON(!!pages != !!(gup_flags & (FOLL_GET | FOLL_PIN)));
1103 * If FOLL_FORCE is set then do not force a full fault as the hinting
1104 * fault information is unrelated to the reference behaviour of a task
1105 * using the address space
1107 if (!(gup_flags & FOLL_FORCE))
1108 gup_flags |= FOLL_NUMA;
1112 unsigned int foll_flags = gup_flags;
1113 unsigned int page_increm;
1115 /* first iteration or cross vma bound */
1116 if (!vma || start >= vma->vm_end) {
1117 vma = find_extend_vma(mm, start);
1118 if (!vma && in_gate_area(mm, start)) {
1119 ret = get_gate_page(mm, start & PAGE_MASK,
1121 pages ? &pages[i] : NULL);
1132 ret = check_vma_flags(vma, gup_flags);
1136 if (is_vm_hugetlb_page(vma)) {
1137 i = follow_hugetlb_page(mm, vma, pages, vmas,
1138 &start, &nr_pages, i,
1140 if (locked && *locked == 0) {
1142 * We've got a VM_FAULT_RETRY
1143 * and we've lost mmap_lock.
1144 * We must stop here.
1146 BUG_ON(gup_flags & FOLL_NOWAIT);
1154 * If we have a pending SIGKILL, don't keep faulting pages and
1155 * potentially allocating memory.
1157 if (fatal_signal_pending(current)) {
1163 page = follow_page_mask(vma, start, foll_flags, &ctx);
1165 ret = faultin_page(vma, start, &foll_flags, locked);
1180 } else if (PTR_ERR(page) == -EEXIST) {
1182 * Proper page table entry exists, but no corresponding
1186 } else if (IS_ERR(page)) {
1187 ret = PTR_ERR(page);
1192 flush_anon_page(vma, page, start);
1193 flush_dcache_page(page);
1201 page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
1202 if (page_increm > nr_pages)
1203 page_increm = nr_pages;
1205 start += page_increm * PAGE_SIZE;
1206 nr_pages -= page_increm;
1210 put_dev_pagemap(ctx.pgmap);
1214 static bool vma_permits_fault(struct vm_area_struct *vma,
1215 unsigned int fault_flags)
1217 bool write = !!(fault_flags & FAULT_FLAG_WRITE);
1218 bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
1219 vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
1221 if (!(vm_flags & vma->vm_flags))
1225 * The architecture might have a hardware protection
1226 * mechanism other than read/write that can deny access.
1228 * gup always represents data access, not instruction
1229 * fetches, so execute=false here:
1231 if (!arch_vma_access_permitted(vma, write, false, foreign))
1238 * fixup_user_fault() - manually resolve a user page fault
1239 * @mm: mm_struct of target mm
1240 * @address: user address
1241 * @fault_flags:flags to pass down to handle_mm_fault()
1242 * @unlocked: did we unlock the mmap_lock while retrying, maybe NULL if caller
1243 * does not allow retry. If NULL, the caller must guarantee
1244 * that fault_flags does not contain FAULT_FLAG_ALLOW_RETRY.
1246 * This is meant to be called in the specific scenario where for locking reasons
1247 * we try to access user memory in atomic context (within a pagefault_disable()
1248 * section), this returns -EFAULT, and we want to resolve the user fault before
1251 * Typically this is meant to be used by the futex code.
1253 * The main difference with get_user_pages() is that this function will
1254 * unconditionally call handle_mm_fault() which will in turn perform all the
1255 * necessary SW fixup of the dirty and young bits in the PTE, while
1256 * get_user_pages() only guarantees to update these in the struct page.
1258 * This is important for some architectures where those bits also gate the
1259 * access permission to the page because they are maintained in software. On
1260 * such architectures, gup() will not be enough to make a subsequent access
1263 * This function will not return with an unlocked mmap_lock. So it has not the
1264 * same semantics wrt the @mm->mmap_lock as does filemap_fault().
1266 int fixup_user_fault(struct mm_struct *mm,
1267 unsigned long address, unsigned int fault_flags,
1270 struct vm_area_struct *vma;
1273 address = untagged_addr(address);
1276 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1279 vma = find_extend_vma(mm, address);
1280 if (!vma || address < vma->vm_start)
1283 if (!vma_permits_fault(vma, fault_flags))
1286 if ((fault_flags & FAULT_FLAG_KILLABLE) &&
1287 fatal_signal_pending(current))
1290 ret = handle_mm_fault(vma, address, fault_flags, NULL);
1291 if (ret & VM_FAULT_ERROR) {
1292 int err = vm_fault_to_errno(ret, 0);
1299 if (ret & VM_FAULT_RETRY) {
1302 fault_flags |= FAULT_FLAG_TRIED;
1308 EXPORT_SYMBOL_GPL(fixup_user_fault);
1311 * Please note that this function, unlike __get_user_pages will not
1312 * return 0 for nr_pages > 0 without FOLL_NOWAIT
1314 static __always_inline long __get_user_pages_locked(struct mm_struct *mm,
1315 unsigned long start,
1316 unsigned long nr_pages,
1317 struct page **pages,
1318 struct vm_area_struct **vmas,
1322 long ret, pages_done;
1326 /* if VM_FAULT_RETRY can be returned, vmas become invalid */
1328 /* check caller initialized locked */
1329 BUG_ON(*locked != 1);
1332 if (flags & FOLL_PIN)
1333 mm_set_has_pinned_flag(&mm->flags);
1336 * FOLL_PIN and FOLL_GET are mutually exclusive. Traditional behavior
1337 * is to set FOLL_GET if the caller wants pages[] filled in (but has
1338 * carelessly failed to specify FOLL_GET), so keep doing that, but only
1339 * for FOLL_GET, not for the newer FOLL_PIN.
1341 * FOLL_PIN always expects pages to be non-null, but no need to assert
1342 * that here, as any failures will be obvious enough.
1344 if (pages && !(flags & FOLL_PIN))
1348 lock_dropped = false;
1350 ret = __get_user_pages(mm, start, nr_pages, flags, pages,
1353 /* VM_FAULT_RETRY couldn't trigger, bypass */
1356 /* VM_FAULT_RETRY cannot return errors */
1359 BUG_ON(ret >= nr_pages);
1370 * VM_FAULT_RETRY didn't trigger or it was a
1378 * VM_FAULT_RETRY triggered, so seek to the faulting offset.
1379 * For the prefault case (!pages) we only update counts.
1383 start += ret << PAGE_SHIFT;
1384 lock_dropped = true;
1388 * Repeat on the address that fired VM_FAULT_RETRY
1389 * with both FAULT_FLAG_ALLOW_RETRY and
1390 * FAULT_FLAG_TRIED. Note that GUP can be interrupted
1391 * by fatal signals, so we need to check it before we
1392 * start trying again otherwise it can loop forever.
1395 if (fatal_signal_pending(current)) {
1397 pages_done = -EINTR;
1401 ret = mmap_read_lock_killable(mm);
1410 ret = __get_user_pages(mm, start, 1, flags | FOLL_TRIED,
1411 pages, NULL, locked);
1413 /* Continue to retry until we succeeded */
1431 if (lock_dropped && *locked) {
1433 * We must let the caller know we temporarily dropped the lock
1434 * and so the critical section protected by it was lost.
1436 mmap_read_unlock(mm);
1443 * populate_vma_page_range() - populate a range of pages in the vma.
1445 * @start: start address
1447 * @locked: whether the mmap_lock is still held
1449 * This takes care of mlocking the pages too if VM_LOCKED is set.
1451 * Return either number of pages pinned in the vma, or a negative error
1454 * vma->vm_mm->mmap_lock must be held.
1456 * If @locked is NULL, it may be held for read or write and will
1459 * If @locked is non-NULL, it must held for read only and may be
1460 * released. If it's released, *@locked will be set to 0.
1462 long populate_vma_page_range(struct vm_area_struct *vma,
1463 unsigned long start, unsigned long end, int *locked)
1465 struct mm_struct *mm = vma->vm_mm;
1466 unsigned long nr_pages = (end - start) / PAGE_SIZE;
1469 VM_BUG_ON(!PAGE_ALIGNED(start));
1470 VM_BUG_ON(!PAGE_ALIGNED(end));
1471 VM_BUG_ON_VMA(start < vma->vm_start, vma);
1472 VM_BUG_ON_VMA(end > vma->vm_end, vma);
1473 mmap_assert_locked(mm);
1475 gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK;
1476 if (vma->vm_flags & VM_LOCKONFAULT)
1477 gup_flags &= ~FOLL_POPULATE;
1479 * We want to touch writable mappings with a write fault in order
1480 * to break COW, except for shared mappings because these don't COW
1481 * and we would not want to dirty them for nothing.
1483 if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
1484 gup_flags |= FOLL_WRITE;
1487 * We want mlock to succeed for regions that have any permissions
1488 * other than PROT_NONE.
1490 if (vma_is_accessible(vma))
1491 gup_flags |= FOLL_FORCE;
1494 * We made sure addr is within a VMA, so the following will
1495 * not result in a stack expansion that recurses back here.
1497 return __get_user_pages(mm, start, nr_pages, gup_flags,
1498 NULL, NULL, locked);
1502 * faultin_vma_page_range() - populate (prefault) page tables inside the
1503 * given VMA range readable/writable
1505 * This takes care of mlocking the pages, too, if VM_LOCKED is set.
1508 * @start: start address
1510 * @write: whether to prefault readable or writable
1511 * @locked: whether the mmap_lock is still held
1513 * Returns either number of processed pages in the vma, or a negative error
1514 * code on error (see __get_user_pages()).
1516 * vma->vm_mm->mmap_lock must be held. The range must be page-aligned and
1517 * covered by the VMA.
1519 * If @locked is NULL, it may be held for read or write and will be unperturbed.
1521 * If @locked is non-NULL, it must held for read only and may be released. If
1522 * it's released, *@locked will be set to 0.
1524 long faultin_vma_page_range(struct vm_area_struct *vma, unsigned long start,
1525 unsigned long end, bool write, int *locked)
1527 struct mm_struct *mm = vma->vm_mm;
1528 unsigned long nr_pages = (end - start) / PAGE_SIZE;
1531 VM_BUG_ON(!PAGE_ALIGNED(start));
1532 VM_BUG_ON(!PAGE_ALIGNED(end));
1533 VM_BUG_ON_VMA(start < vma->vm_start, vma);
1534 VM_BUG_ON_VMA(end > vma->vm_end, vma);
1535 mmap_assert_locked(mm);
1538 * FOLL_TOUCH: Mark page accessed and thereby young; will also mark
1539 * the page dirty with FOLL_WRITE -- which doesn't make a
1540 * difference with !FOLL_FORCE, because the page is writable
1541 * in the page table.
1542 * FOLL_HWPOISON: Return -EHWPOISON instead of -EFAULT when we hit
1544 * FOLL_POPULATE: Always populate memory with VM_LOCKONFAULT.
1545 * !FOLL_FORCE: Require proper access permissions.
1547 gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK | FOLL_HWPOISON;
1549 gup_flags |= FOLL_WRITE;
1552 * We want to report -EINVAL instead of -EFAULT for any permission
1553 * problems or incompatible mappings.
1555 if (check_vma_flags(vma, gup_flags))
1558 return __get_user_pages(mm, start, nr_pages, gup_flags,
1559 NULL, NULL, locked);
1563 * __mm_populate - populate and/or mlock pages within a range of address space.
1565 * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
1566 * flags. VMAs must be already marked with the desired vm_flags, and
1567 * mmap_lock must not be held.
1569 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
1571 struct mm_struct *mm = current->mm;
1572 unsigned long end, nstart, nend;
1573 struct vm_area_struct *vma = NULL;
1579 for (nstart = start; nstart < end; nstart = nend) {
1581 * We want to fault in pages for [nstart; end) address range.
1582 * Find first corresponding VMA.
1587 vma = find_vma(mm, nstart);
1588 } else if (nstart >= vma->vm_end)
1590 if (!vma || vma->vm_start >= end)
1593 * Set [nstart; nend) to intersection of desired address
1594 * range with the first VMA. Also, skip undesirable VMA types.
1596 nend = min(end, vma->vm_end);
1597 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1599 if (nstart < vma->vm_start)
1600 nstart = vma->vm_start;
1602 * Now fault in a range of pages. populate_vma_page_range()
1603 * double checks the vma flags, so that it won't mlock pages
1604 * if the vma was already munlocked.
1606 ret = populate_vma_page_range(vma, nstart, nend, &locked);
1608 if (ignore_errors) {
1610 continue; /* continue at next VMA */
1614 nend = nstart + ret * PAGE_SIZE;
1618 mmap_read_unlock(mm);
1619 return ret; /* 0 or negative error code */
1621 #else /* CONFIG_MMU */
1622 static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start,
1623 unsigned long nr_pages, struct page **pages,
1624 struct vm_area_struct **vmas, int *locked,
1625 unsigned int foll_flags)
1627 struct vm_area_struct *vma;
1628 unsigned long vm_flags;
1631 /* calculate required read or write permissions.
1632 * If FOLL_FORCE is set, we only require the "MAY" flags.
1634 vm_flags = (foll_flags & FOLL_WRITE) ?
1635 (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
1636 vm_flags &= (foll_flags & FOLL_FORCE) ?
1637 (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
1639 for (i = 0; i < nr_pages; i++) {
1640 vma = find_vma(mm, start);
1642 goto finish_or_fault;
1644 /* protect what we can, including chardevs */
1645 if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
1646 !(vm_flags & vma->vm_flags))
1647 goto finish_or_fault;
1650 pages[i] = virt_to_page(start);
1656 start = (start + PAGE_SIZE) & PAGE_MASK;
1662 return i ? : -EFAULT;
1664 #endif /* !CONFIG_MMU */
1667 * fault_in_writeable - fault in userspace address range for writing
1668 * @uaddr: start of address range
1669 * @size: size of address range
1671 * Returns the number of bytes not faulted in (like copy_to_user() and
1672 * copy_from_user()).
1674 size_t fault_in_writeable(char __user *uaddr, size_t size)
1676 char __user *start = uaddr, *end;
1678 if (unlikely(size == 0))
1680 if (!user_write_access_begin(uaddr, size))
1682 if (!PAGE_ALIGNED(uaddr)) {
1683 unsafe_put_user(0, uaddr, out);
1684 uaddr = (char __user *)PAGE_ALIGN((unsigned long)uaddr);
1686 end = (char __user *)PAGE_ALIGN((unsigned long)start + size);
1687 if (unlikely(end < start))
1689 while (uaddr != end) {
1690 unsafe_put_user(0, uaddr, out);
1695 user_write_access_end();
1696 if (size > uaddr - start)
1697 return size - (uaddr - start);
1700 EXPORT_SYMBOL(fault_in_writeable);
1703 * fault_in_safe_writeable - fault in an address range for writing
1704 * @uaddr: start of address range
1705 * @size: length of address range
1707 * Faults in an address range using get_user_pages, i.e., without triggering
1708 * hardware page faults. This is primarily useful when we already know that
1709 * some or all of the pages in the address range aren't in memory.
1711 * Other than fault_in_writeable(), this function is non-destructive.
1713 * Note that we don't pin or otherwise hold the pages referenced that we fault
1714 * in. There's no guarantee that they'll stay in memory for any duration of
1717 * Returns the number of bytes not faulted in, like copy_to_user() and
1720 size_t fault_in_safe_writeable(const char __user *uaddr, size_t size)
1722 unsigned long start = (unsigned long)untagged_addr(uaddr);
1723 unsigned long end, nstart, nend;
1724 struct mm_struct *mm = current->mm;
1725 struct vm_area_struct *vma = NULL;
1728 nstart = start & PAGE_MASK;
1729 end = PAGE_ALIGN(start + size);
1732 for (; nstart != end; nstart = nend) {
1733 unsigned long nr_pages;
1739 vma = find_vma(mm, nstart);
1740 } else if (nstart >= vma->vm_end)
1742 if (!vma || vma->vm_start >= end)
1744 nend = end ? min(end, vma->vm_end) : vma->vm_end;
1745 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1747 if (nstart < vma->vm_start)
1748 nstart = vma->vm_start;
1749 nr_pages = (nend - nstart) / PAGE_SIZE;
1750 ret = __get_user_pages_locked(mm, nstart, nr_pages,
1751 NULL, NULL, &locked,
1752 FOLL_TOUCH | FOLL_WRITE);
1755 nend = nstart + ret * PAGE_SIZE;
1758 mmap_read_unlock(mm);
1761 return size - min_t(size_t, nstart - start, size);
1763 EXPORT_SYMBOL(fault_in_safe_writeable);
1766 * fault_in_readable - fault in userspace address range for reading
1767 * @uaddr: start of user address range
1768 * @size: size of user address range
1770 * Returns the number of bytes not faulted in (like copy_to_user() and
1771 * copy_from_user()).
1773 size_t fault_in_readable(const char __user *uaddr, size_t size)
1775 const char __user *start = uaddr, *end;
1778 if (unlikely(size == 0))
1780 if (!user_read_access_begin(uaddr, size))
1782 if (!PAGE_ALIGNED(uaddr)) {
1783 unsafe_get_user(c, uaddr, out);
1784 uaddr = (const char __user *)PAGE_ALIGN((unsigned long)uaddr);
1786 end = (const char __user *)PAGE_ALIGN((unsigned long)start + size);
1787 if (unlikely(end < start))
1789 while (uaddr != end) {
1790 unsafe_get_user(c, uaddr, out);
1795 user_read_access_end();
1797 if (size > uaddr - start)
1798 return size - (uaddr - start);
1801 EXPORT_SYMBOL(fault_in_readable);
1804 * get_dump_page() - pin user page in memory while writing it to core dump
1805 * @addr: user address
1807 * Returns struct page pointer of user page pinned for dump,
1808 * to be freed afterwards by put_page().
1810 * Returns NULL on any kind of failure - a hole must then be inserted into
1811 * the corefile, to preserve alignment with its headers; and also returns
1812 * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
1813 * allowing a hole to be left in the corefile to save disk space.
1815 * Called without mmap_lock (takes and releases the mmap_lock by itself).
1817 #ifdef CONFIG_ELF_CORE
1818 struct page *get_dump_page(unsigned long addr)
1820 struct mm_struct *mm = current->mm;
1825 if (mmap_read_lock_killable(mm))
1827 ret = __get_user_pages_locked(mm, addr, 1, &page, NULL, &locked,
1828 FOLL_FORCE | FOLL_DUMP | FOLL_GET);
1830 mmap_read_unlock(mm);
1831 return (ret == 1) ? page : NULL;
1833 #endif /* CONFIG_ELF_CORE */
1835 #ifdef CONFIG_MIGRATION
1837 * Check whether all pages are pinnable, if so return number of pages. If some
1838 * pages are not pinnable, migrate them, and unpin all pages. Return zero if
1839 * pages were migrated, or if some pages were not successfully isolated.
1840 * Return negative error if migration fails.
1842 static long check_and_migrate_movable_pages(unsigned long nr_pages,
1843 struct page **pages,
1844 unsigned int gup_flags)
1847 unsigned long isolation_error_count = 0;
1848 bool drain_allow = true;
1849 LIST_HEAD(movable_page_list);
1851 struct page *prev_head = NULL;
1853 struct migration_target_control mtc = {
1854 .nid = NUMA_NO_NODE,
1855 .gfp_mask = GFP_USER | __GFP_NOWARN,
1858 for (i = 0; i < nr_pages; i++) {
1859 head = compound_head(pages[i]);
1860 if (head == prev_head)
1864 * If we get a movable page, since we are going to be pinning
1865 * these entries, try to move them out if possible.
1867 if (!is_pinnable_page(head)) {
1868 if (PageHuge(head)) {
1869 if (!isolate_huge_page(head, &movable_page_list))
1870 isolation_error_count++;
1872 if (!PageLRU(head) && drain_allow) {
1873 lru_add_drain_all();
1874 drain_allow = false;
1877 if (isolate_lru_page(head)) {
1878 isolation_error_count++;
1881 list_add_tail(&head->lru, &movable_page_list);
1882 mod_node_page_state(page_pgdat(head),
1884 page_is_file_lru(head),
1885 thp_nr_pages(head));
1891 * If list is empty, and no isolation errors, means that all pages are
1892 * in the correct zone.
1894 if (list_empty(&movable_page_list) && !isolation_error_count)
1897 if (gup_flags & FOLL_PIN) {
1898 unpin_user_pages(pages, nr_pages);
1900 for (i = 0; i < nr_pages; i++)
1903 if (!list_empty(&movable_page_list)) {
1904 ret = migrate_pages(&movable_page_list, alloc_migration_target,
1905 NULL, (unsigned long)&mtc, MIGRATE_SYNC,
1906 MR_LONGTERM_PIN, NULL);
1907 if (ret && !list_empty(&movable_page_list))
1908 putback_movable_pages(&movable_page_list);
1911 return ret > 0 ? -ENOMEM : ret;
1914 static long check_and_migrate_movable_pages(unsigned long nr_pages,
1915 struct page **pages,
1916 unsigned int gup_flags)
1920 #endif /* CONFIG_MIGRATION */
1923 * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
1924 * allows us to process the FOLL_LONGTERM flag.
1926 static long __gup_longterm_locked(struct mm_struct *mm,
1927 unsigned long start,
1928 unsigned long nr_pages,
1929 struct page **pages,
1930 struct vm_area_struct **vmas,
1931 unsigned int gup_flags)
1936 if (!(gup_flags & FOLL_LONGTERM))
1937 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1939 flags = memalloc_pin_save();
1941 rc = __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1945 rc = check_and_migrate_movable_pages(rc, pages, gup_flags);
1947 memalloc_pin_restore(flags);
1952 static bool is_valid_gup_flags(unsigned int gup_flags)
1955 * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
1956 * never directly by the caller, so enforce that with an assertion:
1958 if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
1961 * FOLL_PIN is a prerequisite to FOLL_LONGTERM. Another way of saying
1962 * that is, FOLL_LONGTERM is a specific case, more restrictive case of
1965 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1972 static long __get_user_pages_remote(struct mm_struct *mm,
1973 unsigned long start, unsigned long nr_pages,
1974 unsigned int gup_flags, struct page **pages,
1975 struct vm_area_struct **vmas, int *locked)
1978 * Parts of FOLL_LONGTERM behavior are incompatible with
1979 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1980 * vmas. However, this only comes up if locked is set, and there are
1981 * callers that do request FOLL_LONGTERM, but do not set locked. So,
1982 * allow what we can.
1984 if (gup_flags & FOLL_LONGTERM) {
1985 if (WARN_ON_ONCE(locked))
1988 * This will check the vmas (even if our vmas arg is NULL)
1989 * and return -ENOTSUPP if DAX isn't allowed in this case:
1991 return __gup_longterm_locked(mm, start, nr_pages, pages,
1992 vmas, gup_flags | FOLL_TOUCH |
1996 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1998 gup_flags | FOLL_TOUCH | FOLL_REMOTE);
2002 * get_user_pages_remote() - pin user pages in memory
2003 * @mm: mm_struct of target mm
2004 * @start: starting user address
2005 * @nr_pages: number of pages from start to pin
2006 * @gup_flags: flags modifying lookup behaviour
2007 * @pages: array that receives pointers to the pages pinned.
2008 * Should be at least nr_pages long. Or NULL, if caller
2009 * only intends to ensure the pages are faulted in.
2010 * @vmas: array of pointers to vmas corresponding to each page.
2011 * Or NULL if the caller does not require them.
2012 * @locked: pointer to lock flag indicating whether lock is held and
2013 * subsequently whether VM_FAULT_RETRY functionality can be
2014 * utilised. Lock must initially be held.
2016 * Returns either number of pages pinned (which may be less than the
2017 * number requested), or an error. Details about the return value:
2019 * -- If nr_pages is 0, returns 0.
2020 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
2021 * -- If nr_pages is >0, and some pages were pinned, returns the number of
2022 * pages pinned. Again, this may be less than nr_pages.
2024 * The caller is responsible for releasing returned @pages, via put_page().
2026 * @vmas are valid only as long as mmap_lock is held.
2028 * Must be called with mmap_lock held for read or write.
2030 * get_user_pages_remote walks a process's page tables and takes a reference
2031 * to each struct page that each user address corresponds to at a given
2032 * instant. That is, it takes the page that would be accessed if a user
2033 * thread accesses the given user virtual address at that instant.
2035 * This does not guarantee that the page exists in the user mappings when
2036 * get_user_pages_remote returns, and there may even be a completely different
2037 * page there in some cases (eg. if mmapped pagecache has been invalidated
2038 * and subsequently re faulted). However it does guarantee that the page
2039 * won't be freed completely. And mostly callers simply care that the page
2040 * contains data that was valid *at some point in time*. Typically, an IO
2041 * or similar operation cannot guarantee anything stronger anyway because
2042 * locks can't be held over the syscall boundary.
2044 * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
2045 * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
2046 * be called after the page is finished with, and before put_page is called.
2048 * get_user_pages_remote is typically used for fewer-copy IO operations,
2049 * to get a handle on the memory by some means other than accesses
2050 * via the user virtual addresses. The pages may be submitted for
2051 * DMA to devices or accessed via their kernel linear mapping (via the
2052 * kmap APIs). Care should be taken to use the correct cache flushing APIs.
2054 * See also get_user_pages_fast, for performance critical applications.
2056 * get_user_pages_remote should be phased out in favor of
2057 * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
2058 * should use get_user_pages_remote because it cannot pass
2059 * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
2061 long get_user_pages_remote(struct mm_struct *mm,
2062 unsigned long start, unsigned long nr_pages,
2063 unsigned int gup_flags, struct page **pages,
2064 struct vm_area_struct **vmas, int *locked)
2066 if (!is_valid_gup_flags(gup_flags))
2069 return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
2070 pages, vmas, locked);
2072 EXPORT_SYMBOL(get_user_pages_remote);
2074 #else /* CONFIG_MMU */
2075 long get_user_pages_remote(struct mm_struct *mm,
2076 unsigned long start, unsigned long nr_pages,
2077 unsigned int gup_flags, struct page **pages,
2078 struct vm_area_struct **vmas, int *locked)
2083 static long __get_user_pages_remote(struct mm_struct *mm,
2084 unsigned long start, unsigned long nr_pages,
2085 unsigned int gup_flags, struct page **pages,
2086 struct vm_area_struct **vmas, int *locked)
2090 #endif /* !CONFIG_MMU */
2093 * get_user_pages() - pin user pages in memory
2094 * @start: starting user address
2095 * @nr_pages: number of pages from start to pin
2096 * @gup_flags: flags modifying lookup behaviour
2097 * @pages: array that receives pointers to the pages pinned.
2098 * Should be at least nr_pages long. Or NULL, if caller
2099 * only intends to ensure the pages are faulted in.
2100 * @vmas: array of pointers to vmas corresponding to each page.
2101 * Or NULL if the caller does not require them.
2103 * This is the same as get_user_pages_remote(), just with a less-flexible
2104 * calling convention where we assume that the mm being operated on belongs to
2105 * the current task, and doesn't allow passing of a locked parameter. We also
2106 * obviously don't pass FOLL_REMOTE in here.
2108 long get_user_pages(unsigned long start, unsigned long nr_pages,
2109 unsigned int gup_flags, struct page **pages,
2110 struct vm_area_struct **vmas)
2112 if (!is_valid_gup_flags(gup_flags))
2115 return __gup_longterm_locked(current->mm, start, nr_pages,
2116 pages, vmas, gup_flags | FOLL_TOUCH);
2118 EXPORT_SYMBOL(get_user_pages);
2121 * get_user_pages_locked() - variant of get_user_pages()
2123 * @start: starting user address
2124 * @nr_pages: number of pages from start to pin
2125 * @gup_flags: flags modifying lookup behaviour
2126 * @pages: array that receives pointers to the pages pinned.
2127 * Should be at least nr_pages long. Or NULL, if caller
2128 * only intends to ensure the pages are faulted in.
2129 * @locked: pointer to lock flag indicating whether lock is held and
2130 * subsequently whether VM_FAULT_RETRY functionality can be
2131 * utilised. Lock must initially be held.
2133 * It is suitable to replace the form:
2135 * mmap_read_lock(mm);
2137 * get_user_pages(mm, ..., pages, NULL);
2138 * mmap_read_unlock(mm);
2143 * mmap_read_lock(mm);
2145 * get_user_pages_locked(mm, ..., pages, &locked);
2147 * mmap_read_unlock(mm);
2149 * We can leverage the VM_FAULT_RETRY functionality in the page fault
2150 * paths better by using either get_user_pages_locked() or
2151 * get_user_pages_unlocked().
2154 long get_user_pages_locked(unsigned long start, unsigned long nr_pages,
2155 unsigned int gup_flags, struct page **pages,
2159 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
2160 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2161 * vmas. As there are no users of this flag in this call we simply
2162 * disallow this option for now.
2164 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
2167 * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
2168 * never directly by the caller, so enforce that:
2170 if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
2173 return __get_user_pages_locked(current->mm, start, nr_pages,
2174 pages, NULL, locked,
2175 gup_flags | FOLL_TOUCH);
2177 EXPORT_SYMBOL(get_user_pages_locked);
2180 * get_user_pages_unlocked() is suitable to replace the form:
2182 * mmap_read_lock(mm);
2183 * get_user_pages(mm, ..., pages, NULL);
2184 * mmap_read_unlock(mm);
2188 * get_user_pages_unlocked(mm, ..., pages);
2190 * It is functionally equivalent to get_user_pages_fast so
2191 * get_user_pages_fast should be used instead if specific gup_flags
2192 * (e.g. FOLL_FORCE) are not required.
2194 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
2195 struct page **pages, unsigned int gup_flags)
2197 struct mm_struct *mm = current->mm;
2202 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
2203 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2204 * vmas. As there are no users of this flag in this call we simply
2205 * disallow this option for now.
2207 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
2211 ret = __get_user_pages_locked(mm, start, nr_pages, pages, NULL,
2212 &locked, gup_flags | FOLL_TOUCH);
2214 mmap_read_unlock(mm);
2217 EXPORT_SYMBOL(get_user_pages_unlocked);
2222 * get_user_pages_fast attempts to pin user pages by walking the page
2223 * tables directly and avoids taking locks. Thus the walker needs to be
2224 * protected from page table pages being freed from under it, and should
2225 * block any THP splits.
2227 * One way to achieve this is to have the walker disable interrupts, and
2228 * rely on IPIs from the TLB flushing code blocking before the page table
2229 * pages are freed. This is unsuitable for architectures that do not need
2230 * to broadcast an IPI when invalidating TLBs.
2232 * Another way to achieve this is to batch up page table containing pages
2233 * belonging to more than one mm_user, then rcu_sched a callback to free those
2234 * pages. Disabling interrupts will allow the fast_gup walker to both block
2235 * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
2236 * (which is a relatively rare event). The code below adopts this strategy.
2238 * Before activating this code, please be aware that the following assumptions
2239 * are currently made:
2241 * *) Either MMU_GATHER_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
2242 * free pages containing page tables or TLB flushing requires IPI broadcast.
2244 * *) ptes can be read atomically by the architecture.
2246 * *) access_ok is sufficient to validate userspace address ranges.
2248 * The last two assumptions can be relaxed by the addition of helper functions.
2250 * This code is based heavily on the PowerPC implementation by Nick Piggin.
2252 #ifdef CONFIG_HAVE_FAST_GUP
2254 static void __maybe_unused undo_dev_pagemap(int *nr, int nr_start,
2256 struct page **pages)
2258 while ((*nr) - nr_start) {
2259 struct page *page = pages[--(*nr)];
2261 ClearPageReferenced(page);
2262 if (flags & FOLL_PIN)
2263 unpin_user_page(page);
2269 #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
2270 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2271 unsigned int flags, struct page **pages, int *nr)
2273 struct dev_pagemap *pgmap = NULL;
2274 int nr_start = *nr, ret = 0;
2277 ptem = ptep = pte_offset_map(&pmd, addr);
2279 pte_t pte = ptep_get_lockless(ptep);
2280 struct page *head, *page;
2283 * Similar to the PMD case below, NUMA hinting must take slow
2284 * path using the pte_protnone check.
2286 if (pte_protnone(pte))
2289 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2292 if (pte_devmap(pte)) {
2293 if (unlikely(flags & FOLL_LONGTERM))
2296 pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
2297 if (unlikely(!pgmap)) {
2298 undo_dev_pagemap(nr, nr_start, flags, pages);
2301 } else if (pte_special(pte))
2304 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2305 page = pte_page(pte);
2307 head = try_grab_compound_head(page, 1, flags);
2311 if (unlikely(page_is_secretmem(page))) {
2312 put_compound_head(head, 1, flags);
2316 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2317 put_compound_head(head, 1, flags);
2321 VM_BUG_ON_PAGE(compound_head(page) != head, page);
2324 * We need to make the page accessible if and only if we are
2325 * going to access its content (the FOLL_PIN case). Please
2326 * see Documentation/core-api/pin_user_pages.rst for
2329 if (flags & FOLL_PIN) {
2330 ret = arch_make_page_accessible(page);
2332 unpin_user_page(page);
2336 SetPageReferenced(page);
2340 } while (ptep++, addr += PAGE_SIZE, addr != end);
2346 put_dev_pagemap(pgmap);
2353 * If we can't determine whether or not a pte is special, then fail immediately
2354 * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
2357 * For a futex to be placed on a THP tail page, get_futex_key requires a
2358 * get_user_pages_fast_only implementation that can pin pages. Thus it's still
2359 * useful to have gup_huge_pmd even if we can't operate on ptes.
2361 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2362 unsigned int flags, struct page **pages, int *nr)
2366 #endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
2368 #if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
2369 static int __gup_device_huge(unsigned long pfn, unsigned long addr,
2370 unsigned long end, unsigned int flags,
2371 struct page **pages, int *nr)
2374 struct dev_pagemap *pgmap = NULL;
2377 struct page *page = pfn_to_page(pfn);
2379 pgmap = get_dev_pagemap(pfn, pgmap);
2380 if (unlikely(!pgmap)) {
2381 undo_dev_pagemap(nr, nr_start, flags, pages);
2384 SetPageReferenced(page);
2386 if (unlikely(!try_grab_page(page, flags))) {
2387 undo_dev_pagemap(nr, nr_start, flags, pages);
2392 } while (addr += PAGE_SIZE, addr != end);
2394 put_dev_pagemap(pgmap);
2398 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2399 unsigned long end, unsigned int flags,
2400 struct page **pages, int *nr)
2402 unsigned long fault_pfn;
2405 fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2406 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2409 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2410 undo_dev_pagemap(nr, nr_start, flags, pages);
2416 static int __gup_device_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2417 unsigned long end, unsigned int flags,
2418 struct page **pages, int *nr)
2420 unsigned long fault_pfn;
2423 fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2424 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2427 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2428 undo_dev_pagemap(nr, nr_start, flags, pages);
2434 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2435 unsigned long end, unsigned int flags,
2436 struct page **pages, int *nr)
2442 static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr,
2443 unsigned long end, unsigned int flags,
2444 struct page **pages, int *nr)
2451 static int record_subpages(struct page *page, unsigned long addr,
2452 unsigned long end, struct page **pages)
2456 for (nr = 0; addr != end; addr += PAGE_SIZE)
2457 pages[nr++] = page++;
2462 #ifdef CONFIG_ARCH_HAS_HUGEPD
2463 static unsigned long hugepte_addr_end(unsigned long addr, unsigned long end,
2466 unsigned long __boundary = (addr + sz) & ~(sz-1);
2467 return (__boundary - 1 < end - 1) ? __boundary : end;
2470 static int gup_hugepte(pte_t *ptep, unsigned long sz, unsigned long addr,
2471 unsigned long end, unsigned int flags,
2472 struct page **pages, int *nr)
2474 unsigned long pte_end;
2475 struct page *head, *page;
2479 pte_end = (addr + sz) & ~(sz-1);
2483 pte = huge_ptep_get(ptep);
2485 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2488 /* hugepages are never "special" */
2489 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2491 head = pte_page(pte);
2492 page = head + ((addr & (sz-1)) >> PAGE_SHIFT);
2493 refs = record_subpages(page, addr, end, pages + *nr);
2495 head = try_grab_compound_head(head, refs, flags);
2499 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2500 put_compound_head(head, refs, flags);
2505 SetPageReferenced(head);
2509 static int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2510 unsigned int pdshift, unsigned long end, unsigned int flags,
2511 struct page **pages, int *nr)
2514 unsigned long sz = 1UL << hugepd_shift(hugepd);
2517 ptep = hugepte_offset(hugepd, addr, pdshift);
2519 next = hugepte_addr_end(addr, end, sz);
2520 if (!gup_hugepte(ptep, sz, addr, end, flags, pages, nr))
2522 } while (ptep++, addr = next, addr != end);
2527 static inline int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2528 unsigned int pdshift, unsigned long end, unsigned int flags,
2529 struct page **pages, int *nr)
2533 #endif /* CONFIG_ARCH_HAS_HUGEPD */
2535 static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2536 unsigned long end, unsigned int flags,
2537 struct page **pages, int *nr)
2539 struct page *head, *page;
2542 if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
2545 if (pmd_devmap(orig)) {
2546 if (unlikely(flags & FOLL_LONGTERM))
2548 return __gup_device_huge_pmd(orig, pmdp, addr, end, flags,
2552 page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2553 refs = record_subpages(page, addr, end, pages + *nr);
2555 head = try_grab_compound_head(pmd_page(orig), refs, flags);
2559 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2560 put_compound_head(head, refs, flags);
2565 SetPageReferenced(head);
2569 static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2570 unsigned long end, unsigned int flags,
2571 struct page **pages, int *nr)
2573 struct page *head, *page;
2576 if (!pud_access_permitted(orig, flags & FOLL_WRITE))
2579 if (pud_devmap(orig)) {
2580 if (unlikely(flags & FOLL_LONGTERM))
2582 return __gup_device_huge_pud(orig, pudp, addr, end, flags,
2586 page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2587 refs = record_subpages(page, addr, end, pages + *nr);
2589 head = try_grab_compound_head(pud_page(orig), refs, flags);
2593 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2594 put_compound_head(head, refs, flags);
2599 SetPageReferenced(head);
2603 static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
2604 unsigned long end, unsigned int flags,
2605 struct page **pages, int *nr)
2608 struct page *head, *page;
2610 if (!pgd_access_permitted(orig, flags & FOLL_WRITE))
2613 BUILD_BUG_ON(pgd_devmap(orig));
2615 page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT);
2616 refs = record_subpages(page, addr, end, pages + *nr);
2618 head = try_grab_compound_head(pgd_page(orig), refs, flags);
2622 if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
2623 put_compound_head(head, refs, flags);
2628 SetPageReferenced(head);
2632 static int gup_pmd_range(pud_t *pudp, pud_t pud, unsigned long addr, unsigned long end,
2633 unsigned int flags, struct page **pages, int *nr)
2638 pmdp = pmd_offset_lockless(pudp, pud, addr);
2640 pmd_t pmd = READ_ONCE(*pmdp);
2642 next = pmd_addr_end(addr, end);
2643 if (!pmd_present(pmd))
2646 if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd) ||
2649 * NUMA hinting faults need to be handled in the GUP
2650 * slowpath for accounting purposes and so that they
2651 * can be serialised against THP migration.
2653 if (pmd_protnone(pmd))
2656 if (!gup_huge_pmd(pmd, pmdp, addr, next, flags,
2660 } else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
2662 * architecture have different format for hugetlbfs
2663 * pmd format and THP pmd format
2665 if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
2666 PMD_SHIFT, next, flags, pages, nr))
2668 } else if (!gup_pte_range(pmd, addr, next, flags, pages, nr))
2670 } while (pmdp++, addr = next, addr != end);
2675 static int gup_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr, unsigned long end,
2676 unsigned int flags, struct page **pages, int *nr)
2681 pudp = pud_offset_lockless(p4dp, p4d, addr);
2683 pud_t pud = READ_ONCE(*pudp);
2685 next = pud_addr_end(addr, end);
2686 if (unlikely(!pud_present(pud)))
2688 if (unlikely(pud_huge(pud))) {
2689 if (!gup_huge_pud(pud, pudp, addr, next, flags,
2692 } else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
2693 if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
2694 PUD_SHIFT, next, flags, pages, nr))
2696 } else if (!gup_pmd_range(pudp, pud, addr, next, flags, pages, nr))
2698 } while (pudp++, addr = next, addr != end);
2703 static int gup_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr, unsigned long end,
2704 unsigned int flags, struct page **pages, int *nr)
2709 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
2711 p4d_t p4d = READ_ONCE(*p4dp);
2713 next = p4d_addr_end(addr, end);
2716 BUILD_BUG_ON(p4d_huge(p4d));
2717 if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
2718 if (!gup_huge_pd(__hugepd(p4d_val(p4d)), addr,
2719 P4D_SHIFT, next, flags, pages, nr))
2721 } else if (!gup_pud_range(p4dp, p4d, addr, next, flags, pages, nr))
2723 } while (p4dp++, addr = next, addr != end);
2728 static void gup_pgd_range(unsigned long addr, unsigned long end,
2729 unsigned int flags, struct page **pages, int *nr)
2734 pgdp = pgd_offset(current->mm, addr);
2736 pgd_t pgd = READ_ONCE(*pgdp);
2738 next = pgd_addr_end(addr, end);
2741 if (unlikely(pgd_huge(pgd))) {
2742 if (!gup_huge_pgd(pgd, pgdp, addr, next, flags,
2745 } else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
2746 if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
2747 PGDIR_SHIFT, next, flags, pages, nr))
2749 } else if (!gup_p4d_range(pgdp, pgd, addr, next, flags, pages, nr))
2751 } while (pgdp++, addr = next, addr != end);
2754 static inline void gup_pgd_range(unsigned long addr, unsigned long end,
2755 unsigned int flags, struct page **pages, int *nr)
2758 #endif /* CONFIG_HAVE_FAST_GUP */
2760 #ifndef gup_fast_permitted
2762 * Check if it's allowed to use get_user_pages_fast_only() for the range, or
2763 * we need to fall back to the slow version:
2765 static bool gup_fast_permitted(unsigned long start, unsigned long end)
2771 static int __gup_longterm_unlocked(unsigned long start, int nr_pages,
2772 unsigned int gup_flags, struct page **pages)
2777 * FIXME: FOLL_LONGTERM does not work with
2778 * get_user_pages_unlocked() (see comments in that function)
2780 if (gup_flags & FOLL_LONGTERM) {
2781 mmap_read_lock(current->mm);
2782 ret = __gup_longterm_locked(current->mm,
2784 pages, NULL, gup_flags);
2785 mmap_read_unlock(current->mm);
2787 ret = get_user_pages_unlocked(start, nr_pages,
2794 static unsigned long lockless_pages_from_mm(unsigned long start,
2796 unsigned int gup_flags,
2797 struct page **pages)
2799 unsigned long flags;
2803 if (!IS_ENABLED(CONFIG_HAVE_FAST_GUP) ||
2804 !gup_fast_permitted(start, end))
2807 if (gup_flags & FOLL_PIN) {
2808 seq = raw_read_seqcount(¤t->mm->write_protect_seq);
2814 * Disable interrupts. The nested form is used, in order to allow full,
2815 * general purpose use of this routine.
2817 * With interrupts disabled, we block page table pages from being freed
2818 * from under us. See struct mmu_table_batch comments in
2819 * include/asm-generic/tlb.h for more details.
2821 * We do not adopt an rcu_read_lock() here as we also want to block IPIs
2822 * that come from THPs splitting.
2824 local_irq_save(flags);
2825 gup_pgd_range(start, end, gup_flags, pages, &nr_pinned);
2826 local_irq_restore(flags);
2829 * When pinning pages for DMA there could be a concurrent write protect
2830 * from fork() via copy_page_range(), in this case always fail fast GUP.
2832 if (gup_flags & FOLL_PIN) {
2833 if (read_seqcount_retry(¤t->mm->write_protect_seq, seq)) {
2834 unpin_user_pages(pages, nr_pinned);
2841 static int internal_get_user_pages_fast(unsigned long start,
2842 unsigned long nr_pages,
2843 unsigned int gup_flags,
2844 struct page **pages)
2846 unsigned long len, end;
2847 unsigned long nr_pinned;
2850 if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM |
2851 FOLL_FORCE | FOLL_PIN | FOLL_GET |
2852 FOLL_FAST_ONLY | FOLL_NOFAULT)))
2855 if (gup_flags & FOLL_PIN)
2856 mm_set_has_pinned_flag(¤t->mm->flags);
2858 if (!(gup_flags & FOLL_FAST_ONLY))
2859 might_lock_read(¤t->mm->mmap_lock);
2861 start = untagged_addr(start) & PAGE_MASK;
2862 len = nr_pages << PAGE_SHIFT;
2863 if (check_add_overflow(start, len, &end))
2865 if (unlikely(!access_ok((void __user *)start, len)))
2868 nr_pinned = lockless_pages_from_mm(start, end, gup_flags, pages);
2869 if (nr_pinned == nr_pages || gup_flags & FOLL_FAST_ONLY)
2872 /* Slow path: try to get the remaining pages with get_user_pages */
2873 start += nr_pinned << PAGE_SHIFT;
2875 ret = __gup_longterm_unlocked(start, nr_pages - nr_pinned, gup_flags,
2879 * The caller has to unpin the pages we already pinned so
2880 * returning -errno is not an option
2886 return ret + nr_pinned;
2890 * get_user_pages_fast_only() - pin user pages in memory
2891 * @start: starting user address
2892 * @nr_pages: number of pages from start to pin
2893 * @gup_flags: flags modifying pin behaviour
2894 * @pages: array that receives pointers to the pages pinned.
2895 * Should be at least nr_pages long.
2897 * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
2899 * Note a difference with get_user_pages_fast: this always returns the
2900 * number of pages pinned, 0 if no pages were pinned.
2902 * If the architecture does not support this function, simply return with no
2905 * Careful, careful! COW breaking can go either way, so a non-write
2906 * access can get ambiguous page results. If you call this function without
2907 * 'write' set, you'd better be sure that you're ok with that ambiguity.
2909 int get_user_pages_fast_only(unsigned long start, int nr_pages,
2910 unsigned int gup_flags, struct page **pages)
2914 * Internally (within mm/gup.c), gup fast variants must set FOLL_GET,
2915 * because gup fast is always a "pin with a +1 page refcount" request.
2917 * FOLL_FAST_ONLY is required in order to match the API description of
2918 * this routine: no fall back to regular ("slow") GUP.
2920 gup_flags |= FOLL_GET | FOLL_FAST_ONLY;
2922 nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
2926 * As specified in the API description above, this routine is not
2927 * allowed to return negative values. However, the common core
2928 * routine internal_get_user_pages_fast() *can* return -errno.
2929 * Therefore, correct for that here:
2936 EXPORT_SYMBOL_GPL(get_user_pages_fast_only);
2939 * get_user_pages_fast() - pin user pages in memory
2940 * @start: starting user address
2941 * @nr_pages: number of pages from start to pin
2942 * @gup_flags: flags modifying pin behaviour
2943 * @pages: array that receives pointers to the pages pinned.
2944 * Should be at least nr_pages long.
2946 * Attempt to pin user pages in memory without taking mm->mmap_lock.
2947 * If not successful, it will fall back to taking the lock and
2948 * calling get_user_pages().
2950 * Returns number of pages pinned. This may be fewer than the number requested.
2951 * If nr_pages is 0 or negative, returns 0. If no pages were pinned, returns
2954 int get_user_pages_fast(unsigned long start, int nr_pages,
2955 unsigned int gup_flags, struct page **pages)
2957 if (!is_valid_gup_flags(gup_flags))
2961 * The caller may or may not have explicitly set FOLL_GET; either way is
2962 * OK. However, internally (within mm/gup.c), gup fast variants must set
2963 * FOLL_GET, because gup fast is always a "pin with a +1 page refcount"
2966 gup_flags |= FOLL_GET;
2967 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
2969 EXPORT_SYMBOL_GPL(get_user_pages_fast);
2972 * pin_user_pages_fast() - pin user pages in memory without taking locks
2974 * @start: starting user address
2975 * @nr_pages: number of pages from start to pin
2976 * @gup_flags: flags modifying pin behaviour
2977 * @pages: array that receives pointers to the pages pinned.
2978 * Should be at least nr_pages long.
2980 * Nearly the same as get_user_pages_fast(), except that FOLL_PIN is set. See
2981 * get_user_pages_fast() for documentation on the function arguments, because
2982 * the arguments here are identical.
2984 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
2985 * see Documentation/core-api/pin_user_pages.rst for further details.
2987 int pin_user_pages_fast(unsigned long start, int nr_pages,
2988 unsigned int gup_flags, struct page **pages)
2990 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2991 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2994 gup_flags |= FOLL_PIN;
2995 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
2997 EXPORT_SYMBOL_GPL(pin_user_pages_fast);
3000 * This is the FOLL_PIN equivalent of get_user_pages_fast_only(). Behavior
3001 * is the same, except that this one sets FOLL_PIN instead of FOLL_GET.
3003 * The API rules are the same, too: no negative values may be returned.
3005 int pin_user_pages_fast_only(unsigned long start, int nr_pages,
3006 unsigned int gup_flags, struct page **pages)
3011 * FOLL_GET and FOLL_PIN are mutually exclusive. Note that the API
3012 * rules require returning 0, rather than -errno:
3014 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3017 * FOLL_FAST_ONLY is required in order to match the API description of
3018 * this routine: no fall back to regular ("slow") GUP.
3020 gup_flags |= (FOLL_PIN | FOLL_FAST_ONLY);
3021 nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
3024 * This routine is not allowed to return negative values. However,
3025 * internal_get_user_pages_fast() *can* return -errno. Therefore,
3026 * correct for that here:
3033 EXPORT_SYMBOL_GPL(pin_user_pages_fast_only);
3036 * pin_user_pages_remote() - pin pages of a remote process
3038 * @mm: mm_struct of target mm
3039 * @start: starting user address
3040 * @nr_pages: number of pages from start to pin
3041 * @gup_flags: flags modifying lookup behaviour
3042 * @pages: array that receives pointers to the pages pinned.
3043 * Should be at least nr_pages long. Or NULL, if caller
3044 * only intends to ensure the pages are faulted in.
3045 * @vmas: array of pointers to vmas corresponding to each page.
3046 * Or NULL if the caller does not require them.
3047 * @locked: pointer to lock flag indicating whether lock is held and
3048 * subsequently whether VM_FAULT_RETRY functionality can be
3049 * utilised. Lock must initially be held.
3051 * Nearly the same as get_user_pages_remote(), except that FOLL_PIN is set. See
3052 * get_user_pages_remote() for documentation on the function arguments, because
3053 * the arguments here are identical.
3055 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3056 * see Documentation/core-api/pin_user_pages.rst for details.
3058 long pin_user_pages_remote(struct mm_struct *mm,
3059 unsigned long start, unsigned long nr_pages,
3060 unsigned int gup_flags, struct page **pages,
3061 struct vm_area_struct **vmas, int *locked)
3063 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3064 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3067 gup_flags |= FOLL_PIN;
3068 return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
3069 pages, vmas, locked);
3071 EXPORT_SYMBOL(pin_user_pages_remote);
3074 * pin_user_pages() - pin user pages in memory for use by other devices
3076 * @start: starting user address
3077 * @nr_pages: number of pages from start to pin
3078 * @gup_flags: flags modifying lookup behaviour
3079 * @pages: array that receives pointers to the pages pinned.
3080 * Should be at least nr_pages long. Or NULL, if caller
3081 * only intends to ensure the pages are faulted in.
3082 * @vmas: array of pointers to vmas corresponding to each page.
3083 * Or NULL if the caller does not require them.
3085 * Nearly the same as get_user_pages(), except that FOLL_TOUCH is not set, and
3088 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3089 * see Documentation/core-api/pin_user_pages.rst for details.
3091 long pin_user_pages(unsigned long start, unsigned long nr_pages,
3092 unsigned int gup_flags, struct page **pages,
3093 struct vm_area_struct **vmas)
3095 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3096 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3099 gup_flags |= FOLL_PIN;
3100 return __gup_longterm_locked(current->mm, start, nr_pages,
3101 pages, vmas, gup_flags);
3103 EXPORT_SYMBOL(pin_user_pages);
3106 * pin_user_pages_unlocked() is the FOLL_PIN variant of
3107 * get_user_pages_unlocked(). Behavior is the same, except that this one sets
3108 * FOLL_PIN and rejects FOLL_GET.
3110 long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
3111 struct page **pages, unsigned int gup_flags)
3113 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3114 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3117 gup_flags |= FOLL_PIN;
3118 return get_user_pages_unlocked(start, nr_pages, pages, gup_flags);
3120 EXPORT_SYMBOL(pin_user_pages_unlocked);
3123 * pin_user_pages_locked() is the FOLL_PIN variant of get_user_pages_locked().
3124 * Behavior is the same, except that this one sets FOLL_PIN and rejects
3127 long pin_user_pages_locked(unsigned long start, unsigned long nr_pages,
3128 unsigned int gup_flags, struct page **pages,
3132 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
3133 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
3134 * vmas. As there are no users of this flag in this call we simply
3135 * disallow this option for now.
3137 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
3140 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3141 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3144 gup_flags |= FOLL_PIN;
3145 return __get_user_pages_locked(current->mm, start, nr_pages,
3146 pages, NULL, locked,
3147 gup_flags | FOLL_TOUCH);
3149 EXPORT_SYMBOL(pin_user_pages_locked);