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 if (flags & FOLL_TOUCH) {
470 if (flags & FOLL_WRITE)
471 entry = pte_mkdirty(entry);
472 entry = pte_mkyoung(entry);
474 if (!pte_same(*pte, entry)) {
475 set_pte_at(vma->vm_mm, address, pte, entry);
476 update_mmu_cache(vma, address, pte);
480 /* Proper page table entry exists, but no corresponding struct page */
485 * FOLL_FORCE can write to even unwritable pte's, but only
486 * after we've gone through a COW cycle and they are dirty.
488 static inline bool can_follow_write_pte(pte_t pte, unsigned int flags)
490 return pte_write(pte) ||
491 ((flags & FOLL_FORCE) && (flags & FOLL_COW) && pte_dirty(pte));
494 static struct page *follow_page_pte(struct vm_area_struct *vma,
495 unsigned long address, pmd_t *pmd, unsigned int flags,
496 struct dev_pagemap **pgmap)
498 struct mm_struct *mm = vma->vm_mm;
504 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
505 if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
506 (FOLL_PIN | FOLL_GET)))
507 return ERR_PTR(-EINVAL);
509 if (unlikely(pmd_bad(*pmd)))
510 return no_page_table(vma, flags);
512 ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
514 if (!pte_present(pte)) {
517 * KSM's break_ksm() relies upon recognizing a ksm page
518 * even while it is being migrated, so for that case we
519 * need migration_entry_wait().
521 if (likely(!(flags & FOLL_MIGRATION)))
525 entry = pte_to_swp_entry(pte);
526 if (!is_migration_entry(entry))
528 pte_unmap_unlock(ptep, ptl);
529 migration_entry_wait(mm, pmd, address);
532 if ((flags & FOLL_NUMA) && pte_protnone(pte))
534 if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
535 pte_unmap_unlock(ptep, ptl);
539 page = vm_normal_page(vma, address, pte);
540 if (!page && pte_devmap(pte) && (flags & (FOLL_GET | FOLL_PIN))) {
542 * Only return device mapping pages in the FOLL_GET or FOLL_PIN
543 * case since they are only valid while holding the pgmap
546 *pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
548 page = pte_page(pte);
551 } else if (unlikely(!page)) {
552 if (flags & FOLL_DUMP) {
553 /* Avoid special (like zero) pages in core dumps */
554 page = ERR_PTR(-EFAULT);
558 if (is_zero_pfn(pte_pfn(pte))) {
559 page = pte_page(pte);
561 ret = follow_pfn_pte(vma, address, ptep, flags);
567 /* try_grab_page() does nothing unless FOLL_GET or FOLL_PIN is set. */
568 if (unlikely(!try_grab_page(page, flags))) {
569 page = ERR_PTR(-ENOMEM);
573 * We need to make the page accessible if and only if we are going
574 * to access its content (the FOLL_PIN case). Please see
575 * Documentation/core-api/pin_user_pages.rst for details.
577 if (flags & FOLL_PIN) {
578 ret = arch_make_page_accessible(page);
580 unpin_user_page(page);
585 if (flags & FOLL_TOUCH) {
586 if ((flags & FOLL_WRITE) &&
587 !pte_dirty(pte) && !PageDirty(page))
588 set_page_dirty(page);
590 * pte_mkyoung() would be more correct here, but atomic care
591 * is needed to avoid losing the dirty bit: it is easier to use
592 * mark_page_accessed().
594 mark_page_accessed(page);
596 if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
597 /* Do not mlock pte-mapped THP */
598 if (PageTransCompound(page))
602 * The preliminary mapping check is mainly to avoid the
603 * pointless overhead of lock_page on the ZERO_PAGE
604 * which might bounce very badly if there is contention.
606 * If the page is already locked, we don't need to
607 * handle it now - vmscan will handle it later if and
608 * when it attempts to reclaim the page.
610 if (page->mapping && trylock_page(page)) {
611 lru_add_drain(); /* push cached pages to LRU */
613 * Because we lock page here, and migration is
614 * blocked by the pte's page reference, and we
615 * know the page is still mapped, we don't even
616 * need to check for file-cache page truncation.
618 mlock_vma_page(page);
623 pte_unmap_unlock(ptep, ptl);
626 pte_unmap_unlock(ptep, ptl);
629 return no_page_table(vma, flags);
632 static struct page *follow_pmd_mask(struct vm_area_struct *vma,
633 unsigned long address, pud_t *pudp,
635 struct follow_page_context *ctx)
640 struct mm_struct *mm = vma->vm_mm;
642 pmd = pmd_offset(pudp, address);
644 * The READ_ONCE() will stabilize the pmdval in a register or
645 * on the stack so that it will stop changing under the code.
647 pmdval = READ_ONCE(*pmd);
648 if (pmd_none(pmdval))
649 return no_page_table(vma, flags);
650 if (pmd_huge(pmdval) && is_vm_hugetlb_page(vma)) {
651 page = follow_huge_pmd(mm, address, pmd, flags);
654 return no_page_table(vma, flags);
656 if (is_hugepd(__hugepd(pmd_val(pmdval)))) {
657 page = follow_huge_pd(vma, address,
658 __hugepd(pmd_val(pmdval)), flags,
662 return no_page_table(vma, flags);
665 if (!pmd_present(pmdval)) {
667 * Should never reach here, if thp migration is not supported;
668 * Otherwise, it must be a thp migration entry.
670 VM_BUG_ON(!thp_migration_supported() ||
671 !is_pmd_migration_entry(pmdval));
673 if (likely(!(flags & FOLL_MIGRATION)))
674 return no_page_table(vma, flags);
676 pmd_migration_entry_wait(mm, pmd);
677 pmdval = READ_ONCE(*pmd);
679 * MADV_DONTNEED may convert the pmd to null because
680 * mmap_lock is held in read mode
682 if (pmd_none(pmdval))
683 return no_page_table(vma, flags);
686 if (pmd_devmap(pmdval)) {
687 ptl = pmd_lock(mm, pmd);
688 page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
693 if (likely(!pmd_trans_huge(pmdval)))
694 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
696 if ((flags & FOLL_NUMA) && pmd_protnone(pmdval))
697 return no_page_table(vma, flags);
700 ptl = pmd_lock(mm, pmd);
701 if (unlikely(pmd_none(*pmd))) {
703 return no_page_table(vma, flags);
705 if (unlikely(!pmd_present(*pmd))) {
707 if (likely(!(flags & FOLL_MIGRATION)))
708 return no_page_table(vma, flags);
709 pmd_migration_entry_wait(mm, pmd);
712 if (unlikely(!pmd_trans_huge(*pmd))) {
714 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
716 if (flags & FOLL_SPLIT_PMD) {
718 page = pmd_page(*pmd);
719 if (is_huge_zero_page(page)) {
722 split_huge_pmd(vma, pmd, address);
723 if (pmd_trans_unstable(pmd))
727 split_huge_pmd(vma, pmd, address);
728 ret = pte_alloc(mm, pmd) ? -ENOMEM : 0;
731 return ret ? ERR_PTR(ret) :
732 follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
734 page = follow_trans_huge_pmd(vma, address, pmd, flags);
736 ctx->page_mask = HPAGE_PMD_NR - 1;
740 static struct page *follow_pud_mask(struct vm_area_struct *vma,
741 unsigned long address, p4d_t *p4dp,
743 struct follow_page_context *ctx)
748 struct mm_struct *mm = vma->vm_mm;
750 pud = pud_offset(p4dp, address);
752 return no_page_table(vma, flags);
753 if (pud_huge(*pud) && is_vm_hugetlb_page(vma)) {
754 page = follow_huge_pud(mm, address, pud, flags);
757 return no_page_table(vma, flags);
759 if (is_hugepd(__hugepd(pud_val(*pud)))) {
760 page = follow_huge_pd(vma, address,
761 __hugepd(pud_val(*pud)), flags,
765 return no_page_table(vma, flags);
767 if (pud_devmap(*pud)) {
768 ptl = pud_lock(mm, pud);
769 page = follow_devmap_pud(vma, address, pud, flags, &ctx->pgmap);
774 if (unlikely(pud_bad(*pud)))
775 return no_page_table(vma, flags);
777 return follow_pmd_mask(vma, address, pud, flags, ctx);
780 static struct page *follow_p4d_mask(struct vm_area_struct *vma,
781 unsigned long address, pgd_t *pgdp,
783 struct follow_page_context *ctx)
788 p4d = p4d_offset(pgdp, address);
790 return no_page_table(vma, flags);
791 BUILD_BUG_ON(p4d_huge(*p4d));
792 if (unlikely(p4d_bad(*p4d)))
793 return no_page_table(vma, flags);
795 if (is_hugepd(__hugepd(p4d_val(*p4d)))) {
796 page = follow_huge_pd(vma, address,
797 __hugepd(p4d_val(*p4d)), flags,
801 return no_page_table(vma, flags);
803 return follow_pud_mask(vma, address, p4d, flags, ctx);
807 * follow_page_mask - look up a page descriptor from a user-virtual address
808 * @vma: vm_area_struct mapping @address
809 * @address: virtual address to look up
810 * @flags: flags modifying lookup behaviour
811 * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
812 * pointer to output page_mask
814 * @flags can have FOLL_ flags set, defined in <linux/mm.h>
816 * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
817 * the device's dev_pagemap metadata to avoid repeating expensive lookups.
819 * On output, the @ctx->page_mask is set according to the size of the page.
821 * Return: the mapped (struct page *), %NULL if no mapping exists, or
822 * an error pointer if there is a mapping to something not represented
823 * by a page descriptor (see also vm_normal_page()).
825 static struct page *follow_page_mask(struct vm_area_struct *vma,
826 unsigned long address, unsigned int flags,
827 struct follow_page_context *ctx)
831 struct mm_struct *mm = vma->vm_mm;
835 /* make this handle hugepd */
836 page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
838 WARN_ON_ONCE(flags & (FOLL_GET | FOLL_PIN));
842 pgd = pgd_offset(mm, address);
844 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
845 return no_page_table(vma, flags);
847 if (pgd_huge(*pgd)) {
848 page = follow_huge_pgd(mm, address, pgd, flags);
851 return no_page_table(vma, flags);
853 if (is_hugepd(__hugepd(pgd_val(*pgd)))) {
854 page = follow_huge_pd(vma, address,
855 __hugepd(pgd_val(*pgd)), flags,
859 return no_page_table(vma, flags);
862 return follow_p4d_mask(vma, address, pgd, flags, ctx);
865 struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
866 unsigned int foll_flags)
868 struct follow_page_context ctx = { NULL };
871 if (vma_is_secretmem(vma))
874 page = follow_page_mask(vma, address, foll_flags, &ctx);
876 put_dev_pagemap(ctx.pgmap);
880 static int get_gate_page(struct mm_struct *mm, unsigned long address,
881 unsigned int gup_flags, struct vm_area_struct **vma,
891 /* user gate pages are read-only */
892 if (gup_flags & FOLL_WRITE)
894 if (address > TASK_SIZE)
895 pgd = pgd_offset_k(address);
897 pgd = pgd_offset_gate(mm, address);
900 p4d = p4d_offset(pgd, address);
903 pud = pud_offset(p4d, address);
906 pmd = pmd_offset(pud, address);
907 if (!pmd_present(*pmd))
909 VM_BUG_ON(pmd_trans_huge(*pmd));
910 pte = pte_offset_map(pmd, address);
913 *vma = get_gate_vma(mm);
916 *page = vm_normal_page(*vma, address, *pte);
918 if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
920 *page = pte_page(*pte);
922 if (unlikely(!try_grab_page(*page, gup_flags))) {
934 * mmap_lock must be held on entry. If @locked != NULL and *@flags
935 * does not include FOLL_NOWAIT, the mmap_lock may be released. If it
936 * is, *@locked will be set to 0 and -EBUSY returned.
938 static int faultin_page(struct vm_area_struct *vma,
939 unsigned long address, unsigned int *flags, int *locked)
941 unsigned int fault_flags = 0;
944 /* mlock all present pages, but do not fault in new pages */
945 if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)
947 if (*flags & FOLL_NOFAULT)
949 if (*flags & FOLL_WRITE)
950 fault_flags |= FAULT_FLAG_WRITE;
951 if (*flags & FOLL_REMOTE)
952 fault_flags |= FAULT_FLAG_REMOTE;
954 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
955 if (*flags & FOLL_NOWAIT)
956 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
957 if (*flags & FOLL_TRIED) {
959 * Note: FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_TRIED
962 fault_flags |= FAULT_FLAG_TRIED;
965 ret = handle_mm_fault(vma, address, fault_flags, NULL);
966 if (ret & VM_FAULT_ERROR) {
967 int err = vm_fault_to_errno(ret, *flags);
974 if (ret & VM_FAULT_RETRY) {
975 if (locked && !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
981 * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
982 * necessary, even if maybe_mkwrite decided not to set pte_write. We
983 * can thus safely do subsequent page lookups as if they were reads.
984 * But only do so when looping for pte_write is futile: in some cases
985 * userspace may also be wanting to write to the gotten user page,
986 * which a read fault here might prevent (a readonly page might get
987 * reCOWed by userspace write).
989 if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
994 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
996 vm_flags_t vm_flags = vma->vm_flags;
997 int write = (gup_flags & FOLL_WRITE);
998 int foreign = (gup_flags & FOLL_REMOTE);
1000 if (vm_flags & (VM_IO | VM_PFNMAP))
1003 if (gup_flags & FOLL_ANON && !vma_is_anonymous(vma))
1006 if ((gup_flags & FOLL_LONGTERM) && vma_is_fsdax(vma))
1009 if (vma_is_secretmem(vma))
1013 if (!(vm_flags & VM_WRITE)) {
1014 if (!(gup_flags & FOLL_FORCE))
1017 * We used to let the write,force case do COW in a
1018 * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
1019 * set a breakpoint in a read-only mapping of an
1020 * executable, without corrupting the file (yet only
1021 * when that file had been opened for writing!).
1022 * Anon pages in shared mappings are surprising: now
1025 if (!is_cow_mapping(vm_flags))
1028 } else if (!(vm_flags & VM_READ)) {
1029 if (!(gup_flags & FOLL_FORCE))
1032 * Is there actually any vma we can reach here which does not
1033 * have VM_MAYREAD set?
1035 if (!(vm_flags & VM_MAYREAD))
1039 * gups are always data accesses, not instruction
1040 * fetches, so execute=false here
1042 if (!arch_vma_access_permitted(vma, write, false, foreign))
1048 * __get_user_pages() - pin user pages in memory
1049 * @mm: mm_struct of target mm
1050 * @start: starting user address
1051 * @nr_pages: number of pages from start to pin
1052 * @gup_flags: flags modifying pin behaviour
1053 * @pages: array that receives pointers to the pages pinned.
1054 * Should be at least nr_pages long. Or NULL, if caller
1055 * only intends to ensure the pages are faulted in.
1056 * @vmas: array of pointers to vmas corresponding to each page.
1057 * Or NULL if the caller does not require them.
1058 * @locked: whether we're still with the mmap_lock held
1060 * Returns either number of pages pinned (which may be less than the
1061 * number requested), or an error. Details about the return value:
1063 * -- If nr_pages is 0, returns 0.
1064 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
1065 * -- If nr_pages is >0, and some pages were pinned, returns the number of
1066 * pages pinned. Again, this may be less than nr_pages.
1067 * -- 0 return value is possible when the fault would need to be retried.
1069 * The caller is responsible for releasing returned @pages, via put_page().
1071 * @vmas are valid only as long as mmap_lock is held.
1073 * Must be called with mmap_lock held. It may be released. See below.
1075 * __get_user_pages walks a process's page tables and takes a reference to
1076 * each struct page that each user address corresponds to at a given
1077 * instant. That is, it takes the page that would be accessed if a user
1078 * thread accesses the given user virtual address at that instant.
1080 * This does not guarantee that the page exists in the user mappings when
1081 * __get_user_pages returns, and there may even be a completely different
1082 * page there in some cases (eg. if mmapped pagecache has been invalidated
1083 * and subsequently re faulted). However it does guarantee that the page
1084 * won't be freed completely. And mostly callers simply care that the page
1085 * contains data that was valid *at some point in time*. Typically, an IO
1086 * or similar operation cannot guarantee anything stronger anyway because
1087 * locks can't be held over the syscall boundary.
1089 * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
1090 * the page is written to, set_page_dirty (or set_page_dirty_lock, as
1091 * appropriate) must be called after the page is finished with, and
1092 * before put_page is called.
1094 * If @locked != NULL, *@locked will be set to 0 when mmap_lock is
1095 * released by an up_read(). That can happen if @gup_flags does not
1098 * A caller using such a combination of @locked and @gup_flags
1099 * must therefore hold the mmap_lock for reading only, and recognize
1100 * when it's been released. Otherwise, it must be held for either
1101 * reading or writing and will not be released.
1103 * In most cases, get_user_pages or get_user_pages_fast should be used
1104 * instead of __get_user_pages. __get_user_pages should be used only if
1105 * you need some special @gup_flags.
1107 static long __get_user_pages(struct mm_struct *mm,
1108 unsigned long start, unsigned long nr_pages,
1109 unsigned int gup_flags, struct page **pages,
1110 struct vm_area_struct **vmas, int *locked)
1112 long ret = 0, i = 0;
1113 struct vm_area_struct *vma = NULL;
1114 struct follow_page_context ctx = { NULL };
1119 start = untagged_addr(start);
1121 VM_BUG_ON(!!pages != !!(gup_flags & (FOLL_GET | FOLL_PIN)));
1124 * If FOLL_FORCE is set then do not force a full fault as the hinting
1125 * fault information is unrelated to the reference behaviour of a task
1126 * using the address space
1128 if (!(gup_flags & FOLL_FORCE))
1129 gup_flags |= FOLL_NUMA;
1133 unsigned int foll_flags = gup_flags;
1134 unsigned int page_increm;
1136 /* first iteration or cross vma bound */
1137 if (!vma || start >= vma->vm_end) {
1138 vma = find_extend_vma(mm, start);
1139 if (!vma && in_gate_area(mm, start)) {
1140 ret = get_gate_page(mm, start & PAGE_MASK,
1142 pages ? &pages[i] : NULL);
1153 ret = check_vma_flags(vma, gup_flags);
1157 if (is_vm_hugetlb_page(vma)) {
1158 i = follow_hugetlb_page(mm, vma, pages, vmas,
1159 &start, &nr_pages, i,
1161 if (locked && *locked == 0) {
1163 * We've got a VM_FAULT_RETRY
1164 * and we've lost mmap_lock.
1165 * We must stop here.
1167 BUG_ON(gup_flags & FOLL_NOWAIT);
1175 * If we have a pending SIGKILL, don't keep faulting pages and
1176 * potentially allocating memory.
1178 if (fatal_signal_pending(current)) {
1184 page = follow_page_mask(vma, start, foll_flags, &ctx);
1186 ret = faultin_page(vma, start, &foll_flags, locked);
1201 } else if (PTR_ERR(page) == -EEXIST) {
1203 * Proper page table entry exists, but no corresponding
1204 * struct page. If the caller expects **pages to be
1205 * filled in, bail out now, because that can't be done
1209 ret = PTR_ERR(page);
1214 } else if (IS_ERR(page)) {
1215 ret = PTR_ERR(page);
1220 flush_anon_page(vma, page, start);
1221 flush_dcache_page(page);
1229 page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
1230 if (page_increm > nr_pages)
1231 page_increm = nr_pages;
1233 start += page_increm * PAGE_SIZE;
1234 nr_pages -= page_increm;
1238 put_dev_pagemap(ctx.pgmap);
1242 static bool vma_permits_fault(struct vm_area_struct *vma,
1243 unsigned int fault_flags)
1245 bool write = !!(fault_flags & FAULT_FLAG_WRITE);
1246 bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
1247 vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
1249 if (!(vm_flags & vma->vm_flags))
1253 * The architecture might have a hardware protection
1254 * mechanism other than read/write that can deny access.
1256 * gup always represents data access, not instruction
1257 * fetches, so execute=false here:
1259 if (!arch_vma_access_permitted(vma, write, false, foreign))
1266 * fixup_user_fault() - manually resolve a user page fault
1267 * @mm: mm_struct of target mm
1268 * @address: user address
1269 * @fault_flags:flags to pass down to handle_mm_fault()
1270 * @unlocked: did we unlock the mmap_lock while retrying, maybe NULL if caller
1271 * does not allow retry. If NULL, the caller must guarantee
1272 * that fault_flags does not contain FAULT_FLAG_ALLOW_RETRY.
1274 * This is meant to be called in the specific scenario where for locking reasons
1275 * we try to access user memory in atomic context (within a pagefault_disable()
1276 * section), this returns -EFAULT, and we want to resolve the user fault before
1279 * Typically this is meant to be used by the futex code.
1281 * The main difference with get_user_pages() is that this function will
1282 * unconditionally call handle_mm_fault() which will in turn perform all the
1283 * necessary SW fixup of the dirty and young bits in the PTE, while
1284 * get_user_pages() only guarantees to update these in the struct page.
1286 * This is important for some architectures where those bits also gate the
1287 * access permission to the page because they are maintained in software. On
1288 * such architectures, gup() will not be enough to make a subsequent access
1291 * This function will not return with an unlocked mmap_lock. So it has not the
1292 * same semantics wrt the @mm->mmap_lock as does filemap_fault().
1294 int fixup_user_fault(struct mm_struct *mm,
1295 unsigned long address, unsigned int fault_flags,
1298 struct vm_area_struct *vma;
1301 address = untagged_addr(address);
1304 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1307 vma = find_extend_vma(mm, address);
1308 if (!vma || address < vma->vm_start)
1311 if (!vma_permits_fault(vma, fault_flags))
1314 if ((fault_flags & FAULT_FLAG_KILLABLE) &&
1315 fatal_signal_pending(current))
1318 ret = handle_mm_fault(vma, address, fault_flags, NULL);
1319 if (ret & VM_FAULT_ERROR) {
1320 int err = vm_fault_to_errno(ret, 0);
1327 if (ret & VM_FAULT_RETRY) {
1330 fault_flags |= FAULT_FLAG_TRIED;
1336 EXPORT_SYMBOL_GPL(fixup_user_fault);
1339 * Please note that this function, unlike __get_user_pages will not
1340 * return 0 for nr_pages > 0 without FOLL_NOWAIT
1342 static __always_inline long __get_user_pages_locked(struct mm_struct *mm,
1343 unsigned long start,
1344 unsigned long nr_pages,
1345 struct page **pages,
1346 struct vm_area_struct **vmas,
1350 long ret, pages_done;
1354 /* if VM_FAULT_RETRY can be returned, vmas become invalid */
1356 /* check caller initialized locked */
1357 BUG_ON(*locked != 1);
1360 if (flags & FOLL_PIN)
1361 mm_set_has_pinned_flag(&mm->flags);
1364 * FOLL_PIN and FOLL_GET are mutually exclusive. Traditional behavior
1365 * is to set FOLL_GET if the caller wants pages[] filled in (but has
1366 * carelessly failed to specify FOLL_GET), so keep doing that, but only
1367 * for FOLL_GET, not for the newer FOLL_PIN.
1369 * FOLL_PIN always expects pages to be non-null, but no need to assert
1370 * that here, as any failures will be obvious enough.
1372 if (pages && !(flags & FOLL_PIN))
1376 lock_dropped = false;
1378 ret = __get_user_pages(mm, start, nr_pages, flags, pages,
1381 /* VM_FAULT_RETRY couldn't trigger, bypass */
1384 /* VM_FAULT_RETRY cannot return errors */
1387 BUG_ON(ret >= nr_pages);
1398 * VM_FAULT_RETRY didn't trigger or it was a
1406 * VM_FAULT_RETRY triggered, so seek to the faulting offset.
1407 * For the prefault case (!pages) we only update counts.
1411 start += ret << PAGE_SHIFT;
1412 lock_dropped = true;
1416 * Repeat on the address that fired VM_FAULT_RETRY
1417 * with both FAULT_FLAG_ALLOW_RETRY and
1418 * FAULT_FLAG_TRIED. Note that GUP can be interrupted
1419 * by fatal signals, so we need to check it before we
1420 * start trying again otherwise it can loop forever.
1423 if (fatal_signal_pending(current)) {
1425 pages_done = -EINTR;
1429 ret = mmap_read_lock_killable(mm);
1438 ret = __get_user_pages(mm, start, 1, flags | FOLL_TRIED,
1439 pages, NULL, locked);
1441 /* Continue to retry until we succeeded */
1459 if (lock_dropped && *locked) {
1461 * We must let the caller know we temporarily dropped the lock
1462 * and so the critical section protected by it was lost.
1464 mmap_read_unlock(mm);
1471 * populate_vma_page_range() - populate a range of pages in the vma.
1473 * @start: start address
1475 * @locked: whether the mmap_lock is still held
1477 * This takes care of mlocking the pages too if VM_LOCKED is set.
1479 * Return either number of pages pinned in the vma, or a negative error
1482 * vma->vm_mm->mmap_lock must be held.
1484 * If @locked is NULL, it may be held for read or write and will
1487 * If @locked is non-NULL, it must held for read only and may be
1488 * released. If it's released, *@locked will be set to 0.
1490 long populate_vma_page_range(struct vm_area_struct *vma,
1491 unsigned long start, unsigned long end, int *locked)
1493 struct mm_struct *mm = vma->vm_mm;
1494 unsigned long nr_pages = (end - start) / PAGE_SIZE;
1497 VM_BUG_ON(!PAGE_ALIGNED(start));
1498 VM_BUG_ON(!PAGE_ALIGNED(end));
1499 VM_BUG_ON_VMA(start < vma->vm_start, vma);
1500 VM_BUG_ON_VMA(end > vma->vm_end, vma);
1501 mmap_assert_locked(mm);
1503 gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK;
1504 if (vma->vm_flags & VM_LOCKONFAULT)
1505 gup_flags &= ~FOLL_POPULATE;
1507 * We want to touch writable mappings with a write fault in order
1508 * to break COW, except for shared mappings because these don't COW
1509 * and we would not want to dirty them for nothing.
1511 if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
1512 gup_flags |= FOLL_WRITE;
1515 * We want mlock to succeed for regions that have any permissions
1516 * other than PROT_NONE.
1518 if (vma_is_accessible(vma))
1519 gup_flags |= FOLL_FORCE;
1522 * We made sure addr is within a VMA, so the following will
1523 * not result in a stack expansion that recurses back here.
1525 return __get_user_pages(mm, start, nr_pages, gup_flags,
1526 NULL, NULL, locked);
1530 * faultin_vma_page_range() - populate (prefault) page tables inside the
1531 * given VMA range readable/writable
1533 * This takes care of mlocking the pages, too, if VM_LOCKED is set.
1536 * @start: start address
1538 * @write: whether to prefault readable or writable
1539 * @locked: whether the mmap_lock is still held
1541 * Returns either number of processed pages in the vma, or a negative error
1542 * code on error (see __get_user_pages()).
1544 * vma->vm_mm->mmap_lock must be held. The range must be page-aligned and
1545 * covered by the VMA.
1547 * If @locked is NULL, it may be held for read or write and will be unperturbed.
1549 * If @locked is non-NULL, it must held for read only and may be released. If
1550 * it's released, *@locked will be set to 0.
1552 long faultin_vma_page_range(struct vm_area_struct *vma, unsigned long start,
1553 unsigned long end, bool write, int *locked)
1555 struct mm_struct *mm = vma->vm_mm;
1556 unsigned long nr_pages = (end - start) / PAGE_SIZE;
1559 VM_BUG_ON(!PAGE_ALIGNED(start));
1560 VM_BUG_ON(!PAGE_ALIGNED(end));
1561 VM_BUG_ON_VMA(start < vma->vm_start, vma);
1562 VM_BUG_ON_VMA(end > vma->vm_end, vma);
1563 mmap_assert_locked(mm);
1566 * FOLL_TOUCH: Mark page accessed and thereby young; will also mark
1567 * the page dirty with FOLL_WRITE -- which doesn't make a
1568 * difference with !FOLL_FORCE, because the page is writable
1569 * in the page table.
1570 * FOLL_HWPOISON: Return -EHWPOISON instead of -EFAULT when we hit
1572 * FOLL_POPULATE: Always populate memory with VM_LOCKONFAULT.
1573 * !FOLL_FORCE: Require proper access permissions.
1575 gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK | FOLL_HWPOISON;
1577 gup_flags |= FOLL_WRITE;
1580 * We want to report -EINVAL instead of -EFAULT for any permission
1581 * problems or incompatible mappings.
1583 if (check_vma_flags(vma, gup_flags))
1586 return __get_user_pages(mm, start, nr_pages, gup_flags,
1587 NULL, NULL, locked);
1591 * __mm_populate - populate and/or mlock pages within a range of address space.
1593 * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
1594 * flags. VMAs must be already marked with the desired vm_flags, and
1595 * mmap_lock must not be held.
1597 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
1599 struct mm_struct *mm = current->mm;
1600 unsigned long end, nstart, nend;
1601 struct vm_area_struct *vma = NULL;
1607 for (nstart = start; nstart < end; nstart = nend) {
1609 * We want to fault in pages for [nstart; end) address range.
1610 * Find first corresponding VMA.
1615 vma = find_vma(mm, nstart);
1616 } else if (nstart >= vma->vm_end)
1618 if (!vma || vma->vm_start >= end)
1621 * Set [nstart; nend) to intersection of desired address
1622 * range with the first VMA. Also, skip undesirable VMA types.
1624 nend = min(end, vma->vm_end);
1625 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1627 if (nstart < vma->vm_start)
1628 nstart = vma->vm_start;
1630 * Now fault in a range of pages. populate_vma_page_range()
1631 * double checks the vma flags, so that it won't mlock pages
1632 * if the vma was already munlocked.
1634 ret = populate_vma_page_range(vma, nstart, nend, &locked);
1636 if (ignore_errors) {
1638 continue; /* continue at next VMA */
1642 nend = nstart + ret * PAGE_SIZE;
1646 mmap_read_unlock(mm);
1647 return ret; /* 0 or negative error code */
1649 #else /* CONFIG_MMU */
1650 static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start,
1651 unsigned long nr_pages, struct page **pages,
1652 struct vm_area_struct **vmas, int *locked,
1653 unsigned int foll_flags)
1655 struct vm_area_struct *vma;
1656 unsigned long vm_flags;
1659 /* calculate required read or write permissions.
1660 * If FOLL_FORCE is set, we only require the "MAY" flags.
1662 vm_flags = (foll_flags & FOLL_WRITE) ?
1663 (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
1664 vm_flags &= (foll_flags & FOLL_FORCE) ?
1665 (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
1667 for (i = 0; i < nr_pages; i++) {
1668 vma = find_vma(mm, start);
1670 goto finish_or_fault;
1672 /* protect what we can, including chardevs */
1673 if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
1674 !(vm_flags & vma->vm_flags))
1675 goto finish_or_fault;
1678 pages[i] = virt_to_page(start);
1684 start = (start + PAGE_SIZE) & PAGE_MASK;
1690 return i ? : -EFAULT;
1692 #endif /* !CONFIG_MMU */
1695 * fault_in_writeable - fault in userspace address range for writing
1696 * @uaddr: start of address range
1697 * @size: size of address range
1699 * Returns the number of bytes not faulted in (like copy_to_user() and
1700 * copy_from_user()).
1702 size_t fault_in_writeable(char __user *uaddr, size_t size)
1704 char __user *start = uaddr, *end;
1706 if (unlikely(size == 0))
1708 if (!user_write_access_begin(uaddr, size))
1710 if (!PAGE_ALIGNED(uaddr)) {
1711 unsafe_put_user(0, uaddr, out);
1712 uaddr = (char __user *)PAGE_ALIGN((unsigned long)uaddr);
1714 end = (char __user *)PAGE_ALIGN((unsigned long)start + size);
1715 if (unlikely(end < start))
1717 while (uaddr != end) {
1718 unsafe_put_user(0, uaddr, out);
1723 user_write_access_end();
1724 if (size > uaddr - start)
1725 return size - (uaddr - start);
1728 EXPORT_SYMBOL(fault_in_writeable);
1731 * fault_in_safe_writeable - fault in an address range for writing
1732 * @uaddr: start of address range
1733 * @size: length of address range
1735 * Faults in an address range for writing. This is primarily useful when we
1736 * already know that some or all of the pages in the address range aren't in
1739 * Unlike fault_in_writeable(), this function is non-destructive.
1741 * Note that we don't pin or otherwise hold the pages referenced that we fault
1742 * in. There's no guarantee that they'll stay in memory for any duration of
1745 * Returns the number of bytes not faulted in, like copy_to_user() and
1748 size_t fault_in_safe_writeable(const char __user *uaddr, size_t size)
1750 unsigned long start = (unsigned long)uaddr, end;
1751 struct mm_struct *mm = current->mm;
1752 bool unlocked = false;
1754 if (unlikely(size == 0))
1756 end = PAGE_ALIGN(start + size);
1762 if (fixup_user_fault(mm, start, FAULT_FLAG_WRITE, &unlocked))
1764 start = (start + PAGE_SIZE) & PAGE_MASK;
1765 } while (start != end);
1766 mmap_read_unlock(mm);
1768 if (size > (unsigned long)uaddr - start)
1769 return size - ((unsigned long)uaddr - start);
1772 EXPORT_SYMBOL(fault_in_safe_writeable);
1775 * fault_in_readable - fault in userspace address range for reading
1776 * @uaddr: start of user address range
1777 * @size: size of user address range
1779 * Returns the number of bytes not faulted in (like copy_to_user() and
1780 * copy_from_user()).
1782 size_t fault_in_readable(const char __user *uaddr, size_t size)
1784 const char __user *start = uaddr, *end;
1787 if (unlikely(size == 0))
1789 if (!user_read_access_begin(uaddr, size))
1791 if (!PAGE_ALIGNED(uaddr)) {
1792 unsafe_get_user(c, uaddr, out);
1793 uaddr = (const char __user *)PAGE_ALIGN((unsigned long)uaddr);
1795 end = (const char __user *)PAGE_ALIGN((unsigned long)start + size);
1796 if (unlikely(end < start))
1798 while (uaddr != end) {
1799 unsafe_get_user(c, uaddr, out);
1804 user_read_access_end();
1806 if (size > uaddr - start)
1807 return size - (uaddr - start);
1810 EXPORT_SYMBOL(fault_in_readable);
1813 * get_dump_page() - pin user page in memory while writing it to core dump
1814 * @addr: user address
1816 * Returns struct page pointer of user page pinned for dump,
1817 * to be freed afterwards by put_page().
1819 * Returns NULL on any kind of failure - a hole must then be inserted into
1820 * the corefile, to preserve alignment with its headers; and also returns
1821 * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
1822 * allowing a hole to be left in the corefile to save disk space.
1824 * Called without mmap_lock (takes and releases the mmap_lock by itself).
1826 #ifdef CONFIG_ELF_CORE
1827 struct page *get_dump_page(unsigned long addr)
1829 struct mm_struct *mm = current->mm;
1834 if (mmap_read_lock_killable(mm))
1836 ret = __get_user_pages_locked(mm, addr, 1, &page, NULL, &locked,
1837 FOLL_FORCE | FOLL_DUMP | FOLL_GET);
1839 mmap_read_unlock(mm);
1840 return (ret == 1) ? page : NULL;
1842 #endif /* CONFIG_ELF_CORE */
1844 #ifdef CONFIG_MIGRATION
1846 * Check whether all pages are pinnable, if so return number of pages. If some
1847 * pages are not pinnable, migrate them, and unpin all pages. Return zero if
1848 * pages were migrated, or if some pages were not successfully isolated.
1849 * Return negative error if migration fails.
1851 static long check_and_migrate_movable_pages(unsigned long nr_pages,
1852 struct page **pages,
1853 unsigned int gup_flags)
1856 unsigned long isolation_error_count = 0;
1857 bool drain_allow = true;
1858 LIST_HEAD(movable_page_list);
1860 struct page *prev_head = NULL;
1862 struct migration_target_control mtc = {
1863 .nid = NUMA_NO_NODE,
1864 .gfp_mask = GFP_USER | __GFP_NOWARN,
1867 for (i = 0; i < nr_pages; i++) {
1868 head = compound_head(pages[i]);
1869 if (head == prev_head)
1873 * If we get a movable page, since we are going to be pinning
1874 * these entries, try to move them out if possible.
1876 if (!is_pinnable_page(head)) {
1877 if (PageHuge(head)) {
1878 if (!isolate_huge_page(head, &movable_page_list))
1879 isolation_error_count++;
1881 if (!PageLRU(head) && drain_allow) {
1882 lru_add_drain_all();
1883 drain_allow = false;
1886 if (isolate_lru_page(head)) {
1887 isolation_error_count++;
1890 list_add_tail(&head->lru, &movable_page_list);
1891 mod_node_page_state(page_pgdat(head),
1893 page_is_file_lru(head),
1894 thp_nr_pages(head));
1900 * If list is empty, and no isolation errors, means that all pages are
1901 * in the correct zone.
1903 if (list_empty(&movable_page_list) && !isolation_error_count)
1906 if (gup_flags & FOLL_PIN) {
1907 unpin_user_pages(pages, nr_pages);
1909 for (i = 0; i < nr_pages; i++)
1912 if (!list_empty(&movable_page_list)) {
1913 ret = migrate_pages(&movable_page_list, alloc_migration_target,
1914 NULL, (unsigned long)&mtc, MIGRATE_SYNC,
1915 MR_LONGTERM_PIN, NULL);
1916 if (ret && !list_empty(&movable_page_list))
1917 putback_movable_pages(&movable_page_list);
1920 return ret > 0 ? -ENOMEM : ret;
1923 static long check_and_migrate_movable_pages(unsigned long nr_pages,
1924 struct page **pages,
1925 unsigned int gup_flags)
1929 #endif /* CONFIG_MIGRATION */
1932 * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
1933 * allows us to process the FOLL_LONGTERM flag.
1935 static long __gup_longterm_locked(struct mm_struct *mm,
1936 unsigned long start,
1937 unsigned long nr_pages,
1938 struct page **pages,
1939 struct vm_area_struct **vmas,
1940 unsigned int gup_flags)
1945 if (!(gup_flags & FOLL_LONGTERM))
1946 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1948 flags = memalloc_pin_save();
1950 rc = __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1954 rc = check_and_migrate_movable_pages(rc, pages, gup_flags);
1956 memalloc_pin_restore(flags);
1961 static bool is_valid_gup_flags(unsigned int gup_flags)
1964 * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
1965 * never directly by the caller, so enforce that with an assertion:
1967 if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
1970 * FOLL_PIN is a prerequisite to FOLL_LONGTERM. Another way of saying
1971 * that is, FOLL_LONGTERM is a specific case, more restrictive case of
1974 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1981 static long __get_user_pages_remote(struct mm_struct *mm,
1982 unsigned long start, unsigned long nr_pages,
1983 unsigned int gup_flags, struct page **pages,
1984 struct vm_area_struct **vmas, int *locked)
1987 * Parts of FOLL_LONGTERM behavior are incompatible with
1988 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1989 * vmas. However, this only comes up if locked is set, and there are
1990 * callers that do request FOLL_LONGTERM, but do not set locked. So,
1991 * allow what we can.
1993 if (gup_flags & FOLL_LONGTERM) {
1994 if (WARN_ON_ONCE(locked))
1997 * This will check the vmas (even if our vmas arg is NULL)
1998 * and return -ENOTSUPP if DAX isn't allowed in this case:
2000 return __gup_longterm_locked(mm, start, nr_pages, pages,
2001 vmas, gup_flags | FOLL_TOUCH |
2005 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
2007 gup_flags | FOLL_TOUCH | FOLL_REMOTE);
2011 * get_user_pages_remote() - pin user pages in memory
2012 * @mm: mm_struct of target mm
2013 * @start: starting user address
2014 * @nr_pages: number of pages from start to pin
2015 * @gup_flags: flags modifying lookup behaviour
2016 * @pages: array that receives pointers to the pages pinned.
2017 * Should be at least nr_pages long. Or NULL, if caller
2018 * only intends to ensure the pages are faulted in.
2019 * @vmas: array of pointers to vmas corresponding to each page.
2020 * Or NULL if the caller does not require them.
2021 * @locked: pointer to lock flag indicating whether lock is held and
2022 * subsequently whether VM_FAULT_RETRY functionality can be
2023 * utilised. Lock must initially be held.
2025 * Returns either number of pages pinned (which may be less than the
2026 * number requested), or an error. Details about the return value:
2028 * -- If nr_pages is 0, returns 0.
2029 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
2030 * -- If nr_pages is >0, and some pages were pinned, returns the number of
2031 * pages pinned. Again, this may be less than nr_pages.
2033 * The caller is responsible for releasing returned @pages, via put_page().
2035 * @vmas are valid only as long as mmap_lock is held.
2037 * Must be called with mmap_lock held for read or write.
2039 * get_user_pages_remote walks a process's page tables and takes a reference
2040 * to each struct page that each user address corresponds to at a given
2041 * instant. That is, it takes the page that would be accessed if a user
2042 * thread accesses the given user virtual address at that instant.
2044 * This does not guarantee that the page exists in the user mappings when
2045 * get_user_pages_remote returns, and there may even be a completely different
2046 * page there in some cases (eg. if mmapped pagecache has been invalidated
2047 * and subsequently re faulted). However it does guarantee that the page
2048 * won't be freed completely. And mostly callers simply care that the page
2049 * contains data that was valid *at some point in time*. Typically, an IO
2050 * or similar operation cannot guarantee anything stronger anyway because
2051 * locks can't be held over the syscall boundary.
2053 * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
2054 * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
2055 * be called after the page is finished with, and before put_page is called.
2057 * get_user_pages_remote is typically used for fewer-copy IO operations,
2058 * to get a handle on the memory by some means other than accesses
2059 * via the user virtual addresses. The pages may be submitted for
2060 * DMA to devices or accessed via their kernel linear mapping (via the
2061 * kmap APIs). Care should be taken to use the correct cache flushing APIs.
2063 * See also get_user_pages_fast, for performance critical applications.
2065 * get_user_pages_remote should be phased out in favor of
2066 * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
2067 * should use get_user_pages_remote because it cannot pass
2068 * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
2070 long get_user_pages_remote(struct mm_struct *mm,
2071 unsigned long start, unsigned long nr_pages,
2072 unsigned int gup_flags, struct page **pages,
2073 struct vm_area_struct **vmas, int *locked)
2075 if (!is_valid_gup_flags(gup_flags))
2078 return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
2079 pages, vmas, locked);
2081 EXPORT_SYMBOL(get_user_pages_remote);
2083 #else /* CONFIG_MMU */
2084 long get_user_pages_remote(struct mm_struct *mm,
2085 unsigned long start, unsigned long nr_pages,
2086 unsigned int gup_flags, struct page **pages,
2087 struct vm_area_struct **vmas, int *locked)
2092 static long __get_user_pages_remote(struct mm_struct *mm,
2093 unsigned long start, unsigned long nr_pages,
2094 unsigned int gup_flags, struct page **pages,
2095 struct vm_area_struct **vmas, int *locked)
2099 #endif /* !CONFIG_MMU */
2102 * get_user_pages() - pin user pages in memory
2103 * @start: starting user address
2104 * @nr_pages: number of pages from start to pin
2105 * @gup_flags: flags modifying lookup behaviour
2106 * @pages: array that receives pointers to the pages pinned.
2107 * Should be at least nr_pages long. Or NULL, if caller
2108 * only intends to ensure the pages are faulted in.
2109 * @vmas: array of pointers to vmas corresponding to each page.
2110 * Or NULL if the caller does not require them.
2112 * This is the same as get_user_pages_remote(), just with a less-flexible
2113 * calling convention where we assume that the mm being operated on belongs to
2114 * the current task, and doesn't allow passing of a locked parameter. We also
2115 * obviously don't pass FOLL_REMOTE in here.
2117 long get_user_pages(unsigned long start, unsigned long nr_pages,
2118 unsigned int gup_flags, struct page **pages,
2119 struct vm_area_struct **vmas)
2121 if (!is_valid_gup_flags(gup_flags))
2124 return __gup_longterm_locked(current->mm, start, nr_pages,
2125 pages, vmas, gup_flags | FOLL_TOUCH);
2127 EXPORT_SYMBOL(get_user_pages);
2130 * get_user_pages_locked() - variant of get_user_pages()
2132 * @start: starting user address
2133 * @nr_pages: number of pages from start to pin
2134 * @gup_flags: flags modifying lookup behaviour
2135 * @pages: array that receives pointers to the pages pinned.
2136 * Should be at least nr_pages long. Or NULL, if caller
2137 * only intends to ensure the pages are faulted in.
2138 * @locked: pointer to lock flag indicating whether lock is held and
2139 * subsequently whether VM_FAULT_RETRY functionality can be
2140 * utilised. Lock must initially be held.
2142 * It is suitable to replace the form:
2144 * mmap_read_lock(mm);
2146 * get_user_pages(mm, ..., pages, NULL);
2147 * mmap_read_unlock(mm);
2152 * mmap_read_lock(mm);
2154 * get_user_pages_locked(mm, ..., pages, &locked);
2156 * mmap_read_unlock(mm);
2158 * We can leverage the VM_FAULT_RETRY functionality in the page fault
2159 * paths better by using either get_user_pages_locked() or
2160 * get_user_pages_unlocked().
2163 long get_user_pages_locked(unsigned long start, unsigned long nr_pages,
2164 unsigned int gup_flags, struct page **pages,
2168 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
2169 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2170 * vmas. As there are no users of this flag in this call we simply
2171 * disallow this option for now.
2173 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
2176 * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
2177 * never directly by the caller, so enforce that:
2179 if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
2182 return __get_user_pages_locked(current->mm, start, nr_pages,
2183 pages, NULL, locked,
2184 gup_flags | FOLL_TOUCH);
2186 EXPORT_SYMBOL(get_user_pages_locked);
2189 * get_user_pages_unlocked() is suitable to replace the form:
2191 * mmap_read_lock(mm);
2192 * get_user_pages(mm, ..., pages, NULL);
2193 * mmap_read_unlock(mm);
2197 * get_user_pages_unlocked(mm, ..., pages);
2199 * It is functionally equivalent to get_user_pages_fast so
2200 * get_user_pages_fast should be used instead if specific gup_flags
2201 * (e.g. FOLL_FORCE) are not required.
2203 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
2204 struct page **pages, unsigned int gup_flags)
2206 struct mm_struct *mm = current->mm;
2211 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
2212 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2213 * vmas. As there are no users of this flag in this call we simply
2214 * disallow this option for now.
2216 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
2220 ret = __get_user_pages_locked(mm, start, nr_pages, pages, NULL,
2221 &locked, gup_flags | FOLL_TOUCH);
2223 mmap_read_unlock(mm);
2226 EXPORT_SYMBOL(get_user_pages_unlocked);
2231 * get_user_pages_fast attempts to pin user pages by walking the page
2232 * tables directly and avoids taking locks. Thus the walker needs to be
2233 * protected from page table pages being freed from under it, and should
2234 * block any THP splits.
2236 * One way to achieve this is to have the walker disable interrupts, and
2237 * rely on IPIs from the TLB flushing code blocking before the page table
2238 * pages are freed. This is unsuitable for architectures that do not need
2239 * to broadcast an IPI when invalidating TLBs.
2241 * Another way to achieve this is to batch up page table containing pages
2242 * belonging to more than one mm_user, then rcu_sched a callback to free those
2243 * pages. Disabling interrupts will allow the fast_gup walker to both block
2244 * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
2245 * (which is a relatively rare event). The code below adopts this strategy.
2247 * Before activating this code, please be aware that the following assumptions
2248 * are currently made:
2250 * *) Either MMU_GATHER_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
2251 * free pages containing page tables or TLB flushing requires IPI broadcast.
2253 * *) ptes can be read atomically by the architecture.
2255 * *) access_ok is sufficient to validate userspace address ranges.
2257 * The last two assumptions can be relaxed by the addition of helper functions.
2259 * This code is based heavily on the PowerPC implementation by Nick Piggin.
2261 #ifdef CONFIG_HAVE_FAST_GUP
2263 static void __maybe_unused undo_dev_pagemap(int *nr, int nr_start,
2265 struct page **pages)
2267 while ((*nr) - nr_start) {
2268 struct page *page = pages[--(*nr)];
2270 ClearPageReferenced(page);
2271 if (flags & FOLL_PIN)
2272 unpin_user_page(page);
2278 #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
2279 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2280 unsigned int flags, struct page **pages, int *nr)
2282 struct dev_pagemap *pgmap = NULL;
2283 int nr_start = *nr, ret = 0;
2286 ptem = ptep = pte_offset_map(&pmd, addr);
2288 pte_t pte = ptep_get_lockless(ptep);
2289 struct page *head, *page;
2292 * Similar to the PMD case below, NUMA hinting must take slow
2293 * path using the pte_protnone check.
2295 if (pte_protnone(pte))
2298 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2301 if (pte_devmap(pte)) {
2302 if (unlikely(flags & FOLL_LONGTERM))
2305 pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
2306 if (unlikely(!pgmap)) {
2307 undo_dev_pagemap(nr, nr_start, flags, pages);
2310 } else if (pte_special(pte))
2313 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2314 page = pte_page(pte);
2316 head = try_grab_compound_head(page, 1, flags);
2320 if (unlikely(page_is_secretmem(page))) {
2321 put_compound_head(head, 1, flags);
2325 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2326 put_compound_head(head, 1, flags);
2330 VM_BUG_ON_PAGE(compound_head(page) != head, page);
2333 * We need to make the page accessible if and only if we are
2334 * going to access its content (the FOLL_PIN case). Please
2335 * see Documentation/core-api/pin_user_pages.rst for
2338 if (flags & FOLL_PIN) {
2339 ret = arch_make_page_accessible(page);
2341 unpin_user_page(page);
2345 SetPageReferenced(page);
2349 } while (ptep++, addr += PAGE_SIZE, addr != end);
2355 put_dev_pagemap(pgmap);
2362 * If we can't determine whether or not a pte is special, then fail immediately
2363 * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
2366 * For a futex to be placed on a THP tail page, get_futex_key requires a
2367 * get_user_pages_fast_only implementation that can pin pages. Thus it's still
2368 * useful to have gup_huge_pmd even if we can't operate on ptes.
2370 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2371 unsigned int flags, struct page **pages, int *nr)
2375 #endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
2377 #if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
2378 static int __gup_device_huge(unsigned long pfn, unsigned long addr,
2379 unsigned long end, unsigned int flags,
2380 struct page **pages, int *nr)
2383 struct dev_pagemap *pgmap = NULL;
2386 struct page *page = pfn_to_page(pfn);
2388 pgmap = get_dev_pagemap(pfn, pgmap);
2389 if (unlikely(!pgmap)) {
2390 undo_dev_pagemap(nr, nr_start, flags, pages);
2393 SetPageReferenced(page);
2395 if (unlikely(!try_grab_page(page, flags))) {
2396 undo_dev_pagemap(nr, nr_start, flags, pages);
2401 } while (addr += PAGE_SIZE, addr != end);
2403 put_dev_pagemap(pgmap);
2407 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2408 unsigned long end, unsigned int flags,
2409 struct page **pages, int *nr)
2411 unsigned long fault_pfn;
2414 fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2415 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2418 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2419 undo_dev_pagemap(nr, nr_start, flags, pages);
2425 static int __gup_device_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2426 unsigned long end, unsigned int flags,
2427 struct page **pages, int *nr)
2429 unsigned long fault_pfn;
2432 fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2433 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2436 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2437 undo_dev_pagemap(nr, nr_start, flags, pages);
2443 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2444 unsigned long end, unsigned int flags,
2445 struct page **pages, int *nr)
2451 static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr,
2452 unsigned long end, unsigned int flags,
2453 struct page **pages, int *nr)
2460 static int record_subpages(struct page *page, unsigned long addr,
2461 unsigned long end, struct page **pages)
2465 for (nr = 0; addr != end; addr += PAGE_SIZE)
2466 pages[nr++] = page++;
2471 #ifdef CONFIG_ARCH_HAS_HUGEPD
2472 static unsigned long hugepte_addr_end(unsigned long addr, unsigned long end,
2475 unsigned long __boundary = (addr + sz) & ~(sz-1);
2476 return (__boundary - 1 < end - 1) ? __boundary : end;
2479 static int gup_hugepte(pte_t *ptep, unsigned long sz, unsigned long addr,
2480 unsigned long end, unsigned int flags,
2481 struct page **pages, int *nr)
2483 unsigned long pte_end;
2484 struct page *head, *page;
2488 pte_end = (addr + sz) & ~(sz-1);
2492 pte = huge_ptep_get(ptep);
2494 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2497 /* hugepages are never "special" */
2498 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2500 head = pte_page(pte);
2501 page = head + ((addr & (sz-1)) >> PAGE_SHIFT);
2502 refs = record_subpages(page, addr, end, pages + *nr);
2504 head = try_grab_compound_head(head, refs, flags);
2508 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2509 put_compound_head(head, refs, flags);
2514 SetPageReferenced(head);
2518 static int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2519 unsigned int pdshift, unsigned long end, unsigned int flags,
2520 struct page **pages, int *nr)
2523 unsigned long sz = 1UL << hugepd_shift(hugepd);
2526 ptep = hugepte_offset(hugepd, addr, pdshift);
2528 next = hugepte_addr_end(addr, end, sz);
2529 if (!gup_hugepte(ptep, sz, addr, end, flags, pages, nr))
2531 } while (ptep++, addr = next, addr != end);
2536 static inline int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2537 unsigned int pdshift, unsigned long end, unsigned int flags,
2538 struct page **pages, int *nr)
2542 #endif /* CONFIG_ARCH_HAS_HUGEPD */
2544 static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2545 unsigned long end, unsigned int flags,
2546 struct page **pages, int *nr)
2548 struct page *head, *page;
2551 if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
2554 if (pmd_devmap(orig)) {
2555 if (unlikely(flags & FOLL_LONGTERM))
2557 return __gup_device_huge_pmd(orig, pmdp, addr, end, flags,
2561 page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2562 refs = record_subpages(page, addr, end, pages + *nr);
2564 head = try_grab_compound_head(pmd_page(orig), refs, flags);
2568 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2569 put_compound_head(head, refs, flags);
2574 SetPageReferenced(head);
2578 static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2579 unsigned long end, unsigned int flags,
2580 struct page **pages, int *nr)
2582 struct page *head, *page;
2585 if (!pud_access_permitted(orig, flags & FOLL_WRITE))
2588 if (pud_devmap(orig)) {
2589 if (unlikely(flags & FOLL_LONGTERM))
2591 return __gup_device_huge_pud(orig, pudp, addr, end, flags,
2595 page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2596 refs = record_subpages(page, addr, end, pages + *nr);
2598 head = try_grab_compound_head(pud_page(orig), refs, flags);
2602 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2603 put_compound_head(head, refs, flags);
2608 SetPageReferenced(head);
2612 static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
2613 unsigned long end, unsigned int flags,
2614 struct page **pages, int *nr)
2617 struct page *head, *page;
2619 if (!pgd_access_permitted(orig, flags & FOLL_WRITE))
2622 BUILD_BUG_ON(pgd_devmap(orig));
2624 page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT);
2625 refs = record_subpages(page, addr, end, pages + *nr);
2627 head = try_grab_compound_head(pgd_page(orig), refs, flags);
2631 if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
2632 put_compound_head(head, refs, flags);
2637 SetPageReferenced(head);
2641 static int gup_pmd_range(pud_t *pudp, pud_t pud, unsigned long addr, unsigned long end,
2642 unsigned int flags, struct page **pages, int *nr)
2647 pmdp = pmd_offset_lockless(pudp, pud, addr);
2649 pmd_t pmd = READ_ONCE(*pmdp);
2651 next = pmd_addr_end(addr, end);
2652 if (!pmd_present(pmd))
2655 if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd) ||
2658 * NUMA hinting faults need to be handled in the GUP
2659 * slowpath for accounting purposes and so that they
2660 * can be serialised against THP migration.
2662 if (pmd_protnone(pmd))
2665 if (!gup_huge_pmd(pmd, pmdp, addr, next, flags,
2669 } else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
2671 * architecture have different format for hugetlbfs
2672 * pmd format and THP pmd format
2674 if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
2675 PMD_SHIFT, next, flags, pages, nr))
2677 } else if (!gup_pte_range(pmd, addr, next, flags, pages, nr))
2679 } while (pmdp++, addr = next, addr != end);
2684 static int gup_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr, unsigned long end,
2685 unsigned int flags, struct page **pages, int *nr)
2690 pudp = pud_offset_lockless(p4dp, p4d, addr);
2692 pud_t pud = READ_ONCE(*pudp);
2694 next = pud_addr_end(addr, end);
2695 if (unlikely(!pud_present(pud)))
2697 if (unlikely(pud_huge(pud))) {
2698 if (!gup_huge_pud(pud, pudp, addr, next, flags,
2701 } else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
2702 if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
2703 PUD_SHIFT, next, flags, pages, nr))
2705 } else if (!gup_pmd_range(pudp, pud, addr, next, flags, pages, nr))
2707 } while (pudp++, addr = next, addr != end);
2712 static int gup_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr, unsigned long end,
2713 unsigned int flags, struct page **pages, int *nr)
2718 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
2720 p4d_t p4d = READ_ONCE(*p4dp);
2722 next = p4d_addr_end(addr, end);
2725 BUILD_BUG_ON(p4d_huge(p4d));
2726 if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
2727 if (!gup_huge_pd(__hugepd(p4d_val(p4d)), addr,
2728 P4D_SHIFT, next, flags, pages, nr))
2730 } else if (!gup_pud_range(p4dp, p4d, addr, next, flags, pages, nr))
2732 } while (p4dp++, addr = next, addr != end);
2737 static void gup_pgd_range(unsigned long addr, unsigned long end,
2738 unsigned int flags, struct page **pages, int *nr)
2743 pgdp = pgd_offset(current->mm, addr);
2745 pgd_t pgd = READ_ONCE(*pgdp);
2747 next = pgd_addr_end(addr, end);
2750 if (unlikely(pgd_huge(pgd))) {
2751 if (!gup_huge_pgd(pgd, pgdp, addr, next, flags,
2754 } else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
2755 if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
2756 PGDIR_SHIFT, next, flags, pages, nr))
2758 } else if (!gup_p4d_range(pgdp, pgd, addr, next, flags, pages, nr))
2760 } while (pgdp++, addr = next, addr != end);
2763 static inline void gup_pgd_range(unsigned long addr, unsigned long end,
2764 unsigned int flags, struct page **pages, int *nr)
2767 #endif /* CONFIG_HAVE_FAST_GUP */
2769 #ifndef gup_fast_permitted
2771 * Check if it's allowed to use get_user_pages_fast_only() for the range, or
2772 * we need to fall back to the slow version:
2774 static bool gup_fast_permitted(unsigned long start, unsigned long end)
2780 static int __gup_longterm_unlocked(unsigned long start, int nr_pages,
2781 unsigned int gup_flags, struct page **pages)
2786 * FIXME: FOLL_LONGTERM does not work with
2787 * get_user_pages_unlocked() (see comments in that function)
2789 if (gup_flags & FOLL_LONGTERM) {
2790 mmap_read_lock(current->mm);
2791 ret = __gup_longterm_locked(current->mm,
2793 pages, NULL, gup_flags);
2794 mmap_read_unlock(current->mm);
2796 ret = get_user_pages_unlocked(start, nr_pages,
2803 static unsigned long lockless_pages_from_mm(unsigned long start,
2805 unsigned int gup_flags,
2806 struct page **pages)
2808 unsigned long flags;
2812 if (!IS_ENABLED(CONFIG_HAVE_FAST_GUP) ||
2813 !gup_fast_permitted(start, end))
2816 if (gup_flags & FOLL_PIN) {
2817 seq = raw_read_seqcount(¤t->mm->write_protect_seq);
2823 * Disable interrupts. The nested form is used, in order to allow full,
2824 * general purpose use of this routine.
2826 * With interrupts disabled, we block page table pages from being freed
2827 * from under us. See struct mmu_table_batch comments in
2828 * include/asm-generic/tlb.h for more details.
2830 * We do not adopt an rcu_read_lock() here as we also want to block IPIs
2831 * that come from THPs splitting.
2833 local_irq_save(flags);
2834 gup_pgd_range(start, end, gup_flags, pages, &nr_pinned);
2835 local_irq_restore(flags);
2838 * When pinning pages for DMA there could be a concurrent write protect
2839 * from fork() via copy_page_range(), in this case always fail fast GUP.
2841 if (gup_flags & FOLL_PIN) {
2842 if (read_seqcount_retry(¤t->mm->write_protect_seq, seq)) {
2843 unpin_user_pages(pages, nr_pinned);
2850 static int internal_get_user_pages_fast(unsigned long start,
2851 unsigned long nr_pages,
2852 unsigned int gup_flags,
2853 struct page **pages)
2855 unsigned long len, end;
2856 unsigned long nr_pinned;
2859 if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM |
2860 FOLL_FORCE | FOLL_PIN | FOLL_GET |
2861 FOLL_FAST_ONLY | FOLL_NOFAULT)))
2864 if (gup_flags & FOLL_PIN)
2865 mm_set_has_pinned_flag(¤t->mm->flags);
2867 if (!(gup_flags & FOLL_FAST_ONLY))
2868 might_lock_read(¤t->mm->mmap_lock);
2870 start = untagged_addr(start) & PAGE_MASK;
2871 len = nr_pages << PAGE_SHIFT;
2872 if (check_add_overflow(start, len, &end))
2874 if (unlikely(!access_ok((void __user *)start, len)))
2877 nr_pinned = lockless_pages_from_mm(start, end, gup_flags, pages);
2878 if (nr_pinned == nr_pages || gup_flags & FOLL_FAST_ONLY)
2881 /* Slow path: try to get the remaining pages with get_user_pages */
2882 start += nr_pinned << PAGE_SHIFT;
2884 ret = __gup_longterm_unlocked(start, nr_pages - nr_pinned, gup_flags,
2888 * The caller has to unpin the pages we already pinned so
2889 * returning -errno is not an option
2895 return ret + nr_pinned;
2899 * get_user_pages_fast_only() - pin user pages in memory
2900 * @start: starting user address
2901 * @nr_pages: number of pages from start to pin
2902 * @gup_flags: flags modifying pin behaviour
2903 * @pages: array that receives pointers to the pages pinned.
2904 * Should be at least nr_pages long.
2906 * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
2908 * Note a difference with get_user_pages_fast: this always returns the
2909 * number of pages pinned, 0 if no pages were pinned.
2911 * If the architecture does not support this function, simply return with no
2914 * Careful, careful! COW breaking can go either way, so a non-write
2915 * access can get ambiguous page results. If you call this function without
2916 * 'write' set, you'd better be sure that you're ok with that ambiguity.
2918 int get_user_pages_fast_only(unsigned long start, int nr_pages,
2919 unsigned int gup_flags, struct page **pages)
2923 * Internally (within mm/gup.c), gup fast variants must set FOLL_GET,
2924 * because gup fast is always a "pin with a +1 page refcount" request.
2926 * FOLL_FAST_ONLY is required in order to match the API description of
2927 * this routine: no fall back to regular ("slow") GUP.
2929 gup_flags |= FOLL_GET | FOLL_FAST_ONLY;
2931 nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
2935 * As specified in the API description above, this routine is not
2936 * allowed to return negative values. However, the common core
2937 * routine internal_get_user_pages_fast() *can* return -errno.
2938 * Therefore, correct for that here:
2945 EXPORT_SYMBOL_GPL(get_user_pages_fast_only);
2948 * get_user_pages_fast() - pin user pages in memory
2949 * @start: starting user address
2950 * @nr_pages: number of pages from start to pin
2951 * @gup_flags: flags modifying pin behaviour
2952 * @pages: array that receives pointers to the pages pinned.
2953 * Should be at least nr_pages long.
2955 * Attempt to pin user pages in memory without taking mm->mmap_lock.
2956 * If not successful, it will fall back to taking the lock and
2957 * calling get_user_pages().
2959 * Returns number of pages pinned. This may be fewer than the number requested.
2960 * If nr_pages is 0 or negative, returns 0. If no pages were pinned, returns
2963 int get_user_pages_fast(unsigned long start, int nr_pages,
2964 unsigned int gup_flags, struct page **pages)
2966 if (!is_valid_gup_flags(gup_flags))
2970 * The caller may or may not have explicitly set FOLL_GET; either way is
2971 * OK. However, internally (within mm/gup.c), gup fast variants must set
2972 * FOLL_GET, because gup fast is always a "pin with a +1 page refcount"
2975 gup_flags |= FOLL_GET;
2976 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
2978 EXPORT_SYMBOL_GPL(get_user_pages_fast);
2981 * pin_user_pages_fast() - pin user pages in memory without taking locks
2983 * @start: starting user address
2984 * @nr_pages: number of pages from start to pin
2985 * @gup_flags: flags modifying pin behaviour
2986 * @pages: array that receives pointers to the pages pinned.
2987 * Should be at least nr_pages long.
2989 * Nearly the same as get_user_pages_fast(), except that FOLL_PIN is set. See
2990 * get_user_pages_fast() for documentation on the function arguments, because
2991 * the arguments here are identical.
2993 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
2994 * see Documentation/core-api/pin_user_pages.rst for further details.
2996 int pin_user_pages_fast(unsigned long start, int nr_pages,
2997 unsigned int gup_flags, struct page **pages)
2999 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3000 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3003 gup_flags |= FOLL_PIN;
3004 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
3006 EXPORT_SYMBOL_GPL(pin_user_pages_fast);
3009 * This is the FOLL_PIN equivalent of get_user_pages_fast_only(). Behavior
3010 * is the same, except that this one sets FOLL_PIN instead of FOLL_GET.
3012 * The API rules are the same, too: no negative values may be returned.
3014 int pin_user_pages_fast_only(unsigned long start, int nr_pages,
3015 unsigned int gup_flags, struct page **pages)
3020 * FOLL_GET and FOLL_PIN are mutually exclusive. Note that the API
3021 * rules require returning 0, rather than -errno:
3023 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3026 * FOLL_FAST_ONLY is required in order to match the API description of
3027 * this routine: no fall back to regular ("slow") GUP.
3029 gup_flags |= (FOLL_PIN | FOLL_FAST_ONLY);
3030 nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
3033 * This routine is not allowed to return negative values. However,
3034 * internal_get_user_pages_fast() *can* return -errno. Therefore,
3035 * correct for that here:
3042 EXPORT_SYMBOL_GPL(pin_user_pages_fast_only);
3045 * pin_user_pages_remote() - pin pages of a remote process
3047 * @mm: mm_struct of target mm
3048 * @start: starting user address
3049 * @nr_pages: number of pages from start to pin
3050 * @gup_flags: flags modifying lookup behaviour
3051 * @pages: array that receives pointers to the pages pinned.
3052 * Should be at least nr_pages long. Or NULL, if caller
3053 * only intends to ensure the pages are faulted in.
3054 * @vmas: array of pointers to vmas corresponding to each page.
3055 * Or NULL if the caller does not require them.
3056 * @locked: pointer to lock flag indicating whether lock is held and
3057 * subsequently whether VM_FAULT_RETRY functionality can be
3058 * utilised. Lock must initially be held.
3060 * Nearly the same as get_user_pages_remote(), except that FOLL_PIN is set. See
3061 * get_user_pages_remote() for documentation on the function arguments, because
3062 * the arguments here are identical.
3064 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3065 * see Documentation/core-api/pin_user_pages.rst for details.
3067 long pin_user_pages_remote(struct mm_struct *mm,
3068 unsigned long start, unsigned long nr_pages,
3069 unsigned int gup_flags, struct page **pages,
3070 struct vm_area_struct **vmas, int *locked)
3072 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3073 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3076 gup_flags |= FOLL_PIN;
3077 return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
3078 pages, vmas, locked);
3080 EXPORT_SYMBOL(pin_user_pages_remote);
3083 * pin_user_pages() - pin user pages in memory for use by other devices
3085 * @start: starting user address
3086 * @nr_pages: number of pages from start to pin
3087 * @gup_flags: flags modifying lookup behaviour
3088 * @pages: array that receives pointers to the pages pinned.
3089 * Should be at least nr_pages long. Or NULL, if caller
3090 * only intends to ensure the pages are faulted in.
3091 * @vmas: array of pointers to vmas corresponding to each page.
3092 * Or NULL if the caller does not require them.
3094 * Nearly the same as get_user_pages(), except that FOLL_TOUCH is not set, and
3097 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3098 * see Documentation/core-api/pin_user_pages.rst for details.
3100 long pin_user_pages(unsigned long start, unsigned long nr_pages,
3101 unsigned int gup_flags, struct page **pages,
3102 struct vm_area_struct **vmas)
3104 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3105 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3108 gup_flags |= FOLL_PIN;
3109 return __gup_longterm_locked(current->mm, start, nr_pages,
3110 pages, vmas, gup_flags);
3112 EXPORT_SYMBOL(pin_user_pages);
3115 * pin_user_pages_unlocked() is the FOLL_PIN variant of
3116 * get_user_pages_unlocked(). Behavior is the same, except that this one sets
3117 * FOLL_PIN and rejects FOLL_GET.
3119 long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
3120 struct page **pages, unsigned int gup_flags)
3122 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3123 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3126 gup_flags |= FOLL_PIN;
3127 return get_user_pages_unlocked(start, nr_pages, pages, gup_flags);
3129 EXPORT_SYMBOL(pin_user_pages_unlocked);
3132 * pin_user_pages_locked() is the FOLL_PIN variant of get_user_pages_locked().
3133 * Behavior is the same, except that this one sets FOLL_PIN and rejects
3136 long pin_user_pages_locked(unsigned long start, unsigned long nr_pages,
3137 unsigned int gup_flags, struct page **pages,
3141 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
3142 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
3143 * vmas. As there are no users of this flag in this call we simply
3144 * disallow this option for now.
3146 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
3149 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3150 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3153 gup_flags |= FOLL_PIN;
3154 return __get_user_pages_locked(current->mm, start, nr_pages,
3155 pages, NULL, locked,
3156 gup_flags | FOLL_TOUCH);
3158 EXPORT_SYMBOL(pin_user_pages_locked);