1 // SPDX-License-Identifier: GPL-2.0-only
2 #include <linux/kernel.h>
3 #include <linux/errno.h>
5 #include <linux/spinlock.h>
8 #include <linux/memremap.h>
9 #include <linux/pagemap.h>
10 #include <linux/rmap.h>
11 #include <linux/swap.h>
12 #include <linux/swapops.h>
13 #include <linux/secretmem.h>
15 #include <linux/sched/signal.h>
16 #include <linux/rwsem.h>
17 #include <linux/hugetlb.h>
18 #include <linux/migrate.h>
19 #include <linux/mm_inline.h>
20 #include <linux/sched/mm.h>
22 #include <asm/mmu_context.h>
23 #include <asm/tlbflush.h>
27 struct follow_page_context {
28 struct dev_pagemap *pgmap;
29 unsigned int page_mask;
32 static void hpage_pincount_add(struct page *page, int refs)
34 VM_BUG_ON_PAGE(!hpage_pincount_available(page), page);
35 VM_BUG_ON_PAGE(page != compound_head(page), page);
37 atomic_add(refs, compound_pincount_ptr(page));
40 static void hpage_pincount_sub(struct page *page, int refs)
42 VM_BUG_ON_PAGE(!hpage_pincount_available(page), page);
43 VM_BUG_ON_PAGE(page != compound_head(page), page);
45 atomic_sub(refs, compound_pincount_ptr(page));
48 /* Equivalent to calling put_page() @refs times. */
49 static void put_page_refs(struct page *page, int refs)
51 #ifdef CONFIG_DEBUG_VM
52 if (VM_WARN_ON_ONCE_PAGE(page_ref_count(page) < refs, page))
57 * Calling put_page() for each ref is unnecessarily slow. Only the last
58 * ref needs a put_page().
61 page_ref_sub(page, refs - 1);
66 * Return the compound head page with ref appropriately incremented,
67 * or NULL if that failed.
69 static inline struct page *try_get_compound_head(struct page *page, int refs)
71 struct page *head = compound_head(page);
73 if (WARN_ON_ONCE(page_ref_count(head) < 0))
75 if (unlikely(!page_cache_add_speculative(head, refs)))
79 * At this point we have a stable reference to the head page; but it
80 * could be that between the compound_head() lookup and the refcount
81 * increment, the compound page was split, in which case we'd end up
82 * holding a reference on a page that has nothing to do with the page
83 * we were given anymore.
84 * So now that the head page is stable, recheck that the pages still
87 if (unlikely(compound_head(page) != head)) {
88 put_page_refs(head, refs);
96 * try_grab_compound_head() - attempt to elevate a page's refcount, by a
97 * flags-dependent amount.
99 * Even though the name includes "compound_head", this function is still
100 * appropriate for callers that have a non-compound @page to get.
102 * @page: pointer to page to be grabbed
103 * @refs: the value to (effectively) add to the page's refcount
104 * @flags: gup flags: these are the FOLL_* flag values.
106 * "grab" names in this file mean, "look at flags to decide whether to use
107 * FOLL_PIN or FOLL_GET behavior, when incrementing the page's refcount.
109 * Either FOLL_PIN or FOLL_GET (or neither) must be set, but not both at the
110 * same time. (That's true throughout the get_user_pages*() and
111 * pin_user_pages*() APIs.) Cases:
113 * FOLL_GET: page's refcount will be incremented by @refs.
115 * FOLL_PIN on compound pages that are > two pages long: page's refcount will
116 * be incremented by @refs, and page[2].hpage_pinned_refcount will be
117 * incremented by @refs * GUP_PIN_COUNTING_BIAS.
119 * FOLL_PIN on normal pages, or compound pages that are two pages long:
120 * page's refcount will be incremented by @refs * GUP_PIN_COUNTING_BIAS.
122 * Return: head page (with refcount appropriately incremented) for success, or
123 * NULL upon failure. If neither FOLL_GET nor FOLL_PIN was set, that's
124 * considered failure, and furthermore, a likely bug in the caller, so a warning
127 __maybe_unused struct page *try_grab_compound_head(struct page *page,
128 int refs, unsigned int flags)
130 if (flags & FOLL_GET)
131 return try_get_compound_head(page, refs);
132 else if (flags & FOLL_PIN) {
134 * Can't do FOLL_LONGTERM + FOLL_PIN gup fast path if not in a
135 * right zone, so fail and let the caller fall back to the slow
138 if (unlikely((flags & FOLL_LONGTERM) &&
139 !is_pinnable_page(page)))
143 * CAUTION: Don't use compound_head() on the page before this
144 * point, the result won't be stable.
146 page = try_get_compound_head(page, refs);
151 * When pinning a compound page of order > 1 (which is what
152 * hpage_pincount_available() checks for), use an exact count to
153 * track it, via hpage_pincount_add/_sub().
155 * However, be sure to *also* increment the normal page refcount
156 * field at least once, so that the page really is pinned.
157 * That's why the refcount from the earlier
158 * try_get_compound_head() is left intact.
160 if (hpage_pincount_available(page))
161 hpage_pincount_add(page, refs);
163 page_ref_add(page, refs * (GUP_PIN_COUNTING_BIAS - 1));
165 mod_node_page_state(page_pgdat(page), NR_FOLL_PIN_ACQUIRED,
175 static void put_compound_head(struct page *page, int refs, unsigned int flags)
177 if (flags & FOLL_PIN) {
178 mod_node_page_state(page_pgdat(page), NR_FOLL_PIN_RELEASED,
181 if (hpage_pincount_available(page))
182 hpage_pincount_sub(page, refs);
184 refs *= GUP_PIN_COUNTING_BIAS;
187 put_page_refs(page, refs);
191 * try_grab_page() - elevate a page's refcount by a flag-dependent amount
193 * This might not do anything at all, depending on the flags argument.
195 * "grab" names in this file mean, "look at flags to decide whether to use
196 * FOLL_PIN or FOLL_GET behavior, when incrementing the page's refcount.
198 * @page: pointer to page to be grabbed
199 * @flags: gup flags: these are the FOLL_* flag values.
201 * Either FOLL_PIN or FOLL_GET (or neither) may be set, but not both at the same
202 * time. Cases: please see the try_grab_compound_head() documentation, with
205 * Return: true for success, or if no action was required (if neither FOLL_PIN
206 * nor FOLL_GET was set, nothing is done). False for failure: FOLL_GET or
207 * FOLL_PIN was set, but the page could not be grabbed.
209 bool __must_check try_grab_page(struct page *page, unsigned int flags)
211 WARN_ON_ONCE((flags & (FOLL_GET | FOLL_PIN)) == (FOLL_GET | FOLL_PIN));
213 if (flags & FOLL_GET)
214 return try_get_page(page);
215 else if (flags & FOLL_PIN) {
218 page = compound_head(page);
220 if (WARN_ON_ONCE(page_ref_count(page) <= 0))
223 if (hpage_pincount_available(page))
224 hpage_pincount_add(page, 1);
226 refs = GUP_PIN_COUNTING_BIAS;
229 * Similar to try_grab_compound_head(): even if using the
230 * hpage_pincount_add/_sub() routines, be sure to
231 * *also* increment the normal page refcount field at least
232 * once, so that the page really is pinned.
234 page_ref_add(page, refs);
236 mod_node_page_state(page_pgdat(page), NR_FOLL_PIN_ACQUIRED, 1);
243 * unpin_user_page() - release a dma-pinned page
244 * @page: pointer to page to be released
246 * Pages that were pinned via pin_user_pages*() must be released via either
247 * unpin_user_page(), or one of the unpin_user_pages*() routines. This is so
248 * that such pages can be separately tracked and uniquely handled. In
249 * particular, interactions with RDMA and filesystems need special handling.
251 void unpin_user_page(struct page *page)
253 put_compound_head(compound_head(page), 1, FOLL_PIN);
255 EXPORT_SYMBOL(unpin_user_page);
257 static inline void compound_range_next(unsigned long i, unsigned long npages,
258 struct page **list, struct page **head,
259 unsigned int *ntails)
261 struct page *next, *page;
268 page = compound_head(next);
269 if (PageCompound(page) && compound_order(page) >= 1)
270 nr = min_t(unsigned int,
271 page + compound_nr(page) - next, npages - i);
277 #define for_each_compound_range(__i, __list, __npages, __head, __ntails) \
279 compound_range_next(__i, __npages, __list, &(__head), &(__ntails)); \
280 __i < __npages; __i += __ntails, \
281 compound_range_next(__i, __npages, __list, &(__head), &(__ntails)))
283 static inline void compound_next(unsigned long i, unsigned long npages,
284 struct page **list, struct page **head,
285 unsigned int *ntails)
293 page = compound_head(list[i]);
294 for (nr = i + 1; nr < npages; nr++) {
295 if (compound_head(list[nr]) != page)
303 #define for_each_compound_head(__i, __list, __npages, __head, __ntails) \
305 compound_next(__i, __npages, __list, &(__head), &(__ntails)); \
306 __i < __npages; __i += __ntails, \
307 compound_next(__i, __npages, __list, &(__head), &(__ntails)))
310 * unpin_user_pages_dirty_lock() - release and optionally dirty gup-pinned pages
311 * @pages: array of pages to be maybe marked dirty, and definitely released.
312 * @npages: number of pages in the @pages array.
313 * @make_dirty: whether to mark the pages dirty
315 * "gup-pinned page" refers to a page that has had one of the get_user_pages()
316 * variants called on that page.
318 * For each page in the @pages array, make that page (or its head page, if a
319 * compound page) dirty, if @make_dirty is true, and if the page was previously
320 * listed as clean. In any case, releases all pages using unpin_user_page(),
321 * possibly via unpin_user_pages(), for the non-dirty case.
323 * Please see the unpin_user_page() documentation for details.
325 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
326 * required, then the caller should a) verify that this is really correct,
327 * because _lock() is usually required, and b) hand code it:
328 * set_page_dirty_lock(), unpin_user_page().
331 void unpin_user_pages_dirty_lock(struct page **pages, unsigned long npages,
339 unpin_user_pages(pages, npages);
343 for_each_compound_head(index, pages, npages, head, ntails) {
345 * Checking PageDirty at this point may race with
346 * clear_page_dirty_for_io(), but that's OK. Two key
349 * 1) This code sees the page as already dirty, so it
350 * skips the call to set_page_dirty(). That could happen
351 * because clear_page_dirty_for_io() called
352 * page_mkclean(), followed by set_page_dirty().
353 * However, now the page is going to get written back,
354 * which meets the original intention of setting it
355 * dirty, so all is well: clear_page_dirty_for_io() goes
356 * on to call TestClearPageDirty(), and write the page
359 * 2) This code sees the page as clean, so it calls
360 * set_page_dirty(). The page stays dirty, despite being
361 * written back, so it gets written back again in the
362 * next writeback cycle. This is harmless.
364 if (!PageDirty(head))
365 set_page_dirty_lock(head);
366 put_compound_head(head, ntails, FOLL_PIN);
369 EXPORT_SYMBOL(unpin_user_pages_dirty_lock);
372 * unpin_user_page_range_dirty_lock() - release and optionally dirty
373 * gup-pinned page range
375 * @page: the starting page of a range maybe marked dirty, and definitely released.
376 * @npages: number of consecutive pages to release.
377 * @make_dirty: whether to mark the pages dirty
379 * "gup-pinned page range" refers to a range of pages that has had one of the
380 * pin_user_pages() variants called on that page.
382 * For the page ranges defined by [page .. page+npages], make that range (or
383 * its head pages, if a compound page) dirty, if @make_dirty is true, and if the
384 * page range was previously listed as clean.
386 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
387 * required, then the caller should a) verify that this is really correct,
388 * because _lock() is usually required, and b) hand code it:
389 * set_page_dirty_lock(), unpin_user_page().
392 void unpin_user_page_range_dirty_lock(struct page *page, unsigned long npages,
399 for_each_compound_range(index, &page, npages, head, ntails) {
400 if (make_dirty && !PageDirty(head))
401 set_page_dirty_lock(head);
402 put_compound_head(head, ntails, FOLL_PIN);
405 EXPORT_SYMBOL(unpin_user_page_range_dirty_lock);
408 * unpin_user_pages() - release an array of gup-pinned pages.
409 * @pages: array of pages to be marked dirty and released.
410 * @npages: number of pages in the @pages array.
412 * For each page in the @pages array, release the page using unpin_user_page().
414 * Please see the unpin_user_page() documentation for details.
416 void unpin_user_pages(struct page **pages, unsigned long npages)
423 * If this WARN_ON() fires, then the system *might* be leaking pages (by
424 * leaving them pinned), but probably not. More likely, gup/pup returned
425 * a hard -ERRNO error to the caller, who erroneously passed it here.
427 if (WARN_ON(IS_ERR_VALUE(npages)))
430 for_each_compound_head(index, pages, npages, head, ntails)
431 put_compound_head(head, ntails, FOLL_PIN);
433 EXPORT_SYMBOL(unpin_user_pages);
436 * Set the MMF_HAS_PINNED if not set yet; after set it'll be there for the mm's
437 * lifecycle. Avoid setting the bit unless necessary, or it might cause write
438 * cache bouncing on large SMP machines for concurrent pinned gups.
440 static inline void mm_set_has_pinned_flag(unsigned long *mm_flags)
442 if (!test_bit(MMF_HAS_PINNED, mm_flags))
443 set_bit(MMF_HAS_PINNED, mm_flags);
447 static struct page *no_page_table(struct vm_area_struct *vma,
451 * When core dumping an enormous anonymous area that nobody
452 * has touched so far, we don't want to allocate unnecessary pages or
453 * page tables. Return error instead of NULL to skip handle_mm_fault,
454 * then get_dump_page() will return NULL to leave a hole in the dump.
455 * But we can only make this optimization where a hole would surely
456 * be zero-filled if handle_mm_fault() actually did handle it.
458 if ((flags & FOLL_DUMP) &&
459 (vma_is_anonymous(vma) || !vma->vm_ops->fault))
460 return ERR_PTR(-EFAULT);
464 static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
465 pte_t *pte, unsigned int flags)
467 /* No page to get reference */
468 if (flags & FOLL_GET)
471 if (flags & FOLL_TOUCH) {
474 if (flags & FOLL_WRITE)
475 entry = pte_mkdirty(entry);
476 entry = pte_mkyoung(entry);
478 if (!pte_same(*pte, entry)) {
479 set_pte_at(vma->vm_mm, address, pte, entry);
480 update_mmu_cache(vma, address, pte);
484 /* Proper page table entry exists, but no corresponding struct page */
489 * FOLL_FORCE can write to even unwritable pte's, but only
490 * after we've gone through a COW cycle and they are dirty.
492 static inline bool can_follow_write_pte(pte_t pte, unsigned int flags)
494 return pte_write(pte) ||
495 ((flags & FOLL_FORCE) && (flags & FOLL_COW) && pte_dirty(pte));
498 static struct page *follow_page_pte(struct vm_area_struct *vma,
499 unsigned long address, pmd_t *pmd, unsigned int flags,
500 struct dev_pagemap **pgmap)
502 struct mm_struct *mm = vma->vm_mm;
508 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
509 if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
510 (FOLL_PIN | FOLL_GET)))
511 return ERR_PTR(-EINVAL);
513 if (unlikely(pmd_bad(*pmd)))
514 return no_page_table(vma, flags);
516 ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
518 if (!pte_present(pte)) {
521 * KSM's break_ksm() relies upon recognizing a ksm page
522 * even while it is being migrated, so for that case we
523 * need migration_entry_wait().
525 if (likely(!(flags & FOLL_MIGRATION)))
529 entry = pte_to_swp_entry(pte);
530 if (!is_migration_entry(entry))
532 pte_unmap_unlock(ptep, ptl);
533 migration_entry_wait(mm, pmd, address);
536 if ((flags & FOLL_NUMA) && pte_protnone(pte))
538 if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
539 pte_unmap_unlock(ptep, ptl);
543 page = vm_normal_page(vma, address, pte);
544 if (!page && pte_devmap(pte) && (flags & (FOLL_GET | FOLL_PIN))) {
546 * Only return device mapping pages in the FOLL_GET or FOLL_PIN
547 * case since they are only valid while holding the pgmap
550 *pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
552 page = pte_page(pte);
555 } else if (unlikely(!page)) {
556 if (flags & FOLL_DUMP) {
557 /* Avoid special (like zero) pages in core dumps */
558 page = ERR_PTR(-EFAULT);
562 if (is_zero_pfn(pte_pfn(pte))) {
563 page = pte_page(pte);
565 ret = follow_pfn_pte(vma, address, ptep, flags);
571 /* try_grab_page() does nothing unless FOLL_GET or FOLL_PIN is set. */
572 if (unlikely(!try_grab_page(page, flags))) {
573 page = ERR_PTR(-ENOMEM);
577 * We need to make the page accessible if and only if we are going
578 * to access its content (the FOLL_PIN case). Please see
579 * Documentation/core-api/pin_user_pages.rst for details.
581 if (flags & FOLL_PIN) {
582 ret = arch_make_page_accessible(page);
584 unpin_user_page(page);
589 if (flags & FOLL_TOUCH) {
590 if ((flags & FOLL_WRITE) &&
591 !pte_dirty(pte) && !PageDirty(page))
592 set_page_dirty(page);
594 * pte_mkyoung() would be more correct here, but atomic care
595 * is needed to avoid losing the dirty bit: it is easier to use
596 * mark_page_accessed().
598 mark_page_accessed(page);
600 if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
601 /* Do not mlock pte-mapped THP */
602 if (PageTransCompound(page))
606 * The preliminary mapping check is mainly to avoid the
607 * pointless overhead of lock_page on the ZERO_PAGE
608 * which might bounce very badly if there is contention.
610 * If the page is already locked, we don't need to
611 * handle it now - vmscan will handle it later if and
612 * when it attempts to reclaim the page.
614 if (page->mapping && trylock_page(page)) {
615 lru_add_drain(); /* push cached pages to LRU */
617 * Because we lock page here, and migration is
618 * blocked by the pte's page reference, and we
619 * know the page is still mapped, we don't even
620 * need to check for file-cache page truncation.
622 mlock_vma_page(page);
627 pte_unmap_unlock(ptep, ptl);
630 pte_unmap_unlock(ptep, ptl);
633 return no_page_table(vma, flags);
636 static struct page *follow_pmd_mask(struct vm_area_struct *vma,
637 unsigned long address, pud_t *pudp,
639 struct follow_page_context *ctx)
644 struct mm_struct *mm = vma->vm_mm;
646 pmd = pmd_offset(pudp, address);
648 * The READ_ONCE() will stabilize the pmdval in a register or
649 * on the stack so that it will stop changing under the code.
651 pmdval = READ_ONCE(*pmd);
652 if (pmd_none(pmdval))
653 return no_page_table(vma, flags);
654 if (pmd_huge(pmdval) && is_vm_hugetlb_page(vma)) {
655 page = follow_huge_pmd(mm, address, pmd, flags);
658 return no_page_table(vma, flags);
660 if (is_hugepd(__hugepd(pmd_val(pmdval)))) {
661 page = follow_huge_pd(vma, address,
662 __hugepd(pmd_val(pmdval)), flags,
666 return no_page_table(vma, flags);
669 if (!pmd_present(pmdval)) {
671 * Should never reach here, if thp migration is not supported;
672 * Otherwise, it must be a thp migration entry.
674 VM_BUG_ON(!thp_migration_supported() ||
675 !is_pmd_migration_entry(pmdval));
677 if (likely(!(flags & FOLL_MIGRATION)))
678 return no_page_table(vma, flags);
680 pmd_migration_entry_wait(mm, pmd);
681 pmdval = READ_ONCE(*pmd);
683 * MADV_DONTNEED may convert the pmd to null because
684 * mmap_lock is held in read mode
686 if (pmd_none(pmdval))
687 return no_page_table(vma, flags);
690 if (pmd_devmap(pmdval)) {
691 ptl = pmd_lock(mm, pmd);
692 page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
697 if (likely(!pmd_trans_huge(pmdval)))
698 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
700 if ((flags & FOLL_NUMA) && pmd_protnone(pmdval))
701 return no_page_table(vma, flags);
704 ptl = pmd_lock(mm, pmd);
705 if (unlikely(pmd_none(*pmd))) {
707 return no_page_table(vma, flags);
709 if (unlikely(!pmd_present(*pmd))) {
711 if (likely(!(flags & FOLL_MIGRATION)))
712 return no_page_table(vma, flags);
713 pmd_migration_entry_wait(mm, pmd);
716 if (unlikely(!pmd_trans_huge(*pmd))) {
718 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
720 if (flags & FOLL_SPLIT_PMD) {
722 page = pmd_page(*pmd);
723 if (is_huge_zero_page(page)) {
726 split_huge_pmd(vma, pmd, address);
727 if (pmd_trans_unstable(pmd))
731 split_huge_pmd(vma, pmd, address);
732 ret = pte_alloc(mm, pmd) ? -ENOMEM : 0;
735 return ret ? ERR_PTR(ret) :
736 follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
738 page = follow_trans_huge_pmd(vma, address, pmd, flags);
740 ctx->page_mask = HPAGE_PMD_NR - 1;
744 static struct page *follow_pud_mask(struct vm_area_struct *vma,
745 unsigned long address, p4d_t *p4dp,
747 struct follow_page_context *ctx)
752 struct mm_struct *mm = vma->vm_mm;
754 pud = pud_offset(p4dp, address);
756 return no_page_table(vma, flags);
757 if (pud_huge(*pud) && is_vm_hugetlb_page(vma)) {
758 page = follow_huge_pud(mm, address, pud, flags);
761 return no_page_table(vma, flags);
763 if (is_hugepd(__hugepd(pud_val(*pud)))) {
764 page = follow_huge_pd(vma, address,
765 __hugepd(pud_val(*pud)), flags,
769 return no_page_table(vma, flags);
771 if (pud_devmap(*pud)) {
772 ptl = pud_lock(mm, pud);
773 page = follow_devmap_pud(vma, address, pud, flags, &ctx->pgmap);
778 if (unlikely(pud_bad(*pud)))
779 return no_page_table(vma, flags);
781 return follow_pmd_mask(vma, address, pud, flags, ctx);
784 static struct page *follow_p4d_mask(struct vm_area_struct *vma,
785 unsigned long address, pgd_t *pgdp,
787 struct follow_page_context *ctx)
792 p4d = p4d_offset(pgdp, address);
794 return no_page_table(vma, flags);
795 BUILD_BUG_ON(p4d_huge(*p4d));
796 if (unlikely(p4d_bad(*p4d)))
797 return no_page_table(vma, flags);
799 if (is_hugepd(__hugepd(p4d_val(*p4d)))) {
800 page = follow_huge_pd(vma, address,
801 __hugepd(p4d_val(*p4d)), flags,
805 return no_page_table(vma, flags);
807 return follow_pud_mask(vma, address, p4d, flags, ctx);
811 * follow_page_mask - look up a page descriptor from a user-virtual address
812 * @vma: vm_area_struct mapping @address
813 * @address: virtual address to look up
814 * @flags: flags modifying lookup behaviour
815 * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
816 * pointer to output page_mask
818 * @flags can have FOLL_ flags set, defined in <linux/mm.h>
820 * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
821 * the device's dev_pagemap metadata to avoid repeating expensive lookups.
823 * On output, the @ctx->page_mask is set according to the size of the page.
825 * Return: the mapped (struct page *), %NULL if no mapping exists, or
826 * an error pointer if there is a mapping to something not represented
827 * by a page descriptor (see also vm_normal_page()).
829 static struct page *follow_page_mask(struct vm_area_struct *vma,
830 unsigned long address, unsigned int flags,
831 struct follow_page_context *ctx)
835 struct mm_struct *mm = vma->vm_mm;
839 /* make this handle hugepd */
840 page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
842 WARN_ON_ONCE(flags & (FOLL_GET | FOLL_PIN));
846 pgd = pgd_offset(mm, address);
848 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
849 return no_page_table(vma, flags);
851 if (pgd_huge(*pgd)) {
852 page = follow_huge_pgd(mm, address, pgd, flags);
855 return no_page_table(vma, flags);
857 if (is_hugepd(__hugepd(pgd_val(*pgd)))) {
858 page = follow_huge_pd(vma, address,
859 __hugepd(pgd_val(*pgd)), flags,
863 return no_page_table(vma, flags);
866 return follow_p4d_mask(vma, address, pgd, flags, ctx);
869 struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
870 unsigned int foll_flags)
872 struct follow_page_context ctx = { NULL };
875 if (vma_is_secretmem(vma))
878 page = follow_page_mask(vma, address, foll_flags, &ctx);
880 put_dev_pagemap(ctx.pgmap);
884 static int get_gate_page(struct mm_struct *mm, unsigned long address,
885 unsigned int gup_flags, struct vm_area_struct **vma,
895 /* user gate pages are read-only */
896 if (gup_flags & FOLL_WRITE)
898 if (address > TASK_SIZE)
899 pgd = pgd_offset_k(address);
901 pgd = pgd_offset_gate(mm, address);
904 p4d = p4d_offset(pgd, address);
907 pud = pud_offset(p4d, address);
910 pmd = pmd_offset(pud, address);
911 if (!pmd_present(*pmd))
913 VM_BUG_ON(pmd_trans_huge(*pmd));
914 pte = pte_offset_map(pmd, address);
917 *vma = get_gate_vma(mm);
920 *page = vm_normal_page(*vma, address, *pte);
922 if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
924 *page = pte_page(*pte);
926 if (unlikely(!try_grab_page(*page, gup_flags))) {
938 * mmap_lock must be held on entry. If @locked != NULL and *@flags
939 * does not include FOLL_NOWAIT, the mmap_lock may be released. If it
940 * is, *@locked will be set to 0 and -EBUSY returned.
942 static int faultin_page(struct vm_area_struct *vma,
943 unsigned long address, unsigned int *flags, int *locked)
945 unsigned int fault_flags = 0;
948 /* mlock all present pages, but do not fault in new pages */
949 if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)
951 if (*flags & FOLL_NOFAULT)
953 if (*flags & FOLL_WRITE)
954 fault_flags |= FAULT_FLAG_WRITE;
955 if (*flags & FOLL_REMOTE)
956 fault_flags |= FAULT_FLAG_REMOTE;
958 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
959 if (*flags & FOLL_NOWAIT)
960 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
961 if (*flags & FOLL_TRIED) {
963 * Note: FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_TRIED
966 fault_flags |= FAULT_FLAG_TRIED;
969 ret = handle_mm_fault(vma, address, fault_flags, NULL);
970 if (ret & VM_FAULT_ERROR) {
971 int err = vm_fault_to_errno(ret, *flags);
978 if (ret & VM_FAULT_RETRY) {
979 if (locked && !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
985 * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
986 * necessary, even if maybe_mkwrite decided not to set pte_write. We
987 * can thus safely do subsequent page lookups as if they were reads.
988 * But only do so when looping for pte_write is futile: in some cases
989 * userspace may also be wanting to write to the gotten user page,
990 * which a read fault here might prevent (a readonly page might get
991 * reCOWed by userspace write).
993 if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
998 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
1000 vm_flags_t vm_flags = vma->vm_flags;
1001 int write = (gup_flags & FOLL_WRITE);
1002 int foreign = (gup_flags & FOLL_REMOTE);
1004 if (vm_flags & (VM_IO | VM_PFNMAP))
1007 if (gup_flags & FOLL_ANON && !vma_is_anonymous(vma))
1010 if ((gup_flags & FOLL_LONGTERM) && vma_is_fsdax(vma))
1013 if (vma_is_secretmem(vma))
1017 if (!(vm_flags & VM_WRITE)) {
1018 if (!(gup_flags & FOLL_FORCE))
1021 * We used to let the write,force case do COW in a
1022 * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
1023 * set a breakpoint in a read-only mapping of an
1024 * executable, without corrupting the file (yet only
1025 * when that file had been opened for writing!).
1026 * Anon pages in shared mappings are surprising: now
1029 if (!is_cow_mapping(vm_flags))
1032 } else if (!(vm_flags & VM_READ)) {
1033 if (!(gup_flags & FOLL_FORCE))
1036 * Is there actually any vma we can reach here which does not
1037 * have VM_MAYREAD set?
1039 if (!(vm_flags & VM_MAYREAD))
1043 * gups are always data accesses, not instruction
1044 * fetches, so execute=false here
1046 if (!arch_vma_access_permitted(vma, write, false, foreign))
1052 * __get_user_pages() - pin user pages in memory
1053 * @mm: mm_struct of target mm
1054 * @start: starting user address
1055 * @nr_pages: number of pages from start to pin
1056 * @gup_flags: flags modifying pin behaviour
1057 * @pages: array that receives pointers to the pages pinned.
1058 * Should be at least nr_pages long. Or NULL, if caller
1059 * only intends to ensure the pages are faulted in.
1060 * @vmas: array of pointers to vmas corresponding to each page.
1061 * Or NULL if the caller does not require them.
1062 * @locked: whether we're still with the mmap_lock held
1064 * Returns either number of pages pinned (which may be less than the
1065 * number requested), or an error. Details about the return value:
1067 * -- If nr_pages is 0, returns 0.
1068 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
1069 * -- If nr_pages is >0, and some pages were pinned, returns the number of
1070 * pages pinned. Again, this may be less than nr_pages.
1071 * -- 0 return value is possible when the fault would need to be retried.
1073 * The caller is responsible for releasing returned @pages, via put_page().
1075 * @vmas are valid only as long as mmap_lock is held.
1077 * Must be called with mmap_lock held. It may be released. See below.
1079 * __get_user_pages walks a process's page tables and takes a reference to
1080 * each struct page that each user address corresponds to at a given
1081 * instant. That is, it takes the page that would be accessed if a user
1082 * thread accesses the given user virtual address at that instant.
1084 * This does not guarantee that the page exists in the user mappings when
1085 * __get_user_pages returns, and there may even be a completely different
1086 * page there in some cases (eg. if mmapped pagecache has been invalidated
1087 * and subsequently re faulted). However it does guarantee that the page
1088 * won't be freed completely. And mostly callers simply care that the page
1089 * contains data that was valid *at some point in time*. Typically, an IO
1090 * or similar operation cannot guarantee anything stronger anyway because
1091 * locks can't be held over the syscall boundary.
1093 * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
1094 * the page is written to, set_page_dirty (or set_page_dirty_lock, as
1095 * appropriate) must be called after the page is finished with, and
1096 * before put_page is called.
1098 * If @locked != NULL, *@locked will be set to 0 when mmap_lock is
1099 * released by an up_read(). That can happen if @gup_flags does not
1102 * A caller using such a combination of @locked and @gup_flags
1103 * must therefore hold the mmap_lock for reading only, and recognize
1104 * when it's been released. Otherwise, it must be held for either
1105 * reading or writing and will not be released.
1107 * In most cases, get_user_pages or get_user_pages_fast should be used
1108 * instead of __get_user_pages. __get_user_pages should be used only if
1109 * you need some special @gup_flags.
1111 static long __get_user_pages(struct mm_struct *mm,
1112 unsigned long start, unsigned long nr_pages,
1113 unsigned int gup_flags, struct page **pages,
1114 struct vm_area_struct **vmas, int *locked)
1116 long ret = 0, i = 0;
1117 struct vm_area_struct *vma = NULL;
1118 struct follow_page_context ctx = { NULL };
1123 start = untagged_addr(start);
1125 VM_BUG_ON(!!pages != !!(gup_flags & (FOLL_GET | FOLL_PIN)));
1128 * If FOLL_FORCE is set then do not force a full fault as the hinting
1129 * fault information is unrelated to the reference behaviour of a task
1130 * using the address space
1132 if (!(gup_flags & FOLL_FORCE))
1133 gup_flags |= FOLL_NUMA;
1137 unsigned int foll_flags = gup_flags;
1138 unsigned int page_increm;
1140 /* first iteration or cross vma bound */
1141 if (!vma || start >= vma->vm_end) {
1142 vma = find_extend_vma(mm, start);
1143 if (!vma && in_gate_area(mm, start)) {
1144 ret = get_gate_page(mm, start & PAGE_MASK,
1146 pages ? &pages[i] : NULL);
1157 ret = check_vma_flags(vma, gup_flags);
1161 if (is_vm_hugetlb_page(vma)) {
1162 i = follow_hugetlb_page(mm, vma, pages, vmas,
1163 &start, &nr_pages, i,
1165 if (locked && *locked == 0) {
1167 * We've got a VM_FAULT_RETRY
1168 * and we've lost mmap_lock.
1169 * We must stop here.
1171 BUG_ON(gup_flags & FOLL_NOWAIT);
1179 * If we have a pending SIGKILL, don't keep faulting pages and
1180 * potentially allocating memory.
1182 if (fatal_signal_pending(current)) {
1188 page = follow_page_mask(vma, start, foll_flags, &ctx);
1190 ret = faultin_page(vma, start, &foll_flags, locked);
1205 } else if (PTR_ERR(page) == -EEXIST) {
1207 * Proper page table entry exists, but no corresponding
1211 } else if (IS_ERR(page)) {
1212 ret = PTR_ERR(page);
1217 flush_anon_page(vma, page, start);
1218 flush_dcache_page(page);
1226 page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
1227 if (page_increm > nr_pages)
1228 page_increm = nr_pages;
1230 start += page_increm * PAGE_SIZE;
1231 nr_pages -= page_increm;
1235 put_dev_pagemap(ctx.pgmap);
1239 static bool vma_permits_fault(struct vm_area_struct *vma,
1240 unsigned int fault_flags)
1242 bool write = !!(fault_flags & FAULT_FLAG_WRITE);
1243 bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
1244 vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
1246 if (!(vm_flags & vma->vm_flags))
1250 * The architecture might have a hardware protection
1251 * mechanism other than read/write that can deny access.
1253 * gup always represents data access, not instruction
1254 * fetches, so execute=false here:
1256 if (!arch_vma_access_permitted(vma, write, false, foreign))
1263 * fixup_user_fault() - manually resolve a user page fault
1264 * @mm: mm_struct of target mm
1265 * @address: user address
1266 * @fault_flags:flags to pass down to handle_mm_fault()
1267 * @unlocked: did we unlock the mmap_lock while retrying, maybe NULL if caller
1268 * does not allow retry. If NULL, the caller must guarantee
1269 * that fault_flags does not contain FAULT_FLAG_ALLOW_RETRY.
1271 * This is meant to be called in the specific scenario where for locking reasons
1272 * we try to access user memory in atomic context (within a pagefault_disable()
1273 * section), this returns -EFAULT, and we want to resolve the user fault before
1276 * Typically this is meant to be used by the futex code.
1278 * The main difference with get_user_pages() is that this function will
1279 * unconditionally call handle_mm_fault() which will in turn perform all the
1280 * necessary SW fixup of the dirty and young bits in the PTE, while
1281 * get_user_pages() only guarantees to update these in the struct page.
1283 * This is important for some architectures where those bits also gate the
1284 * access permission to the page because they are maintained in software. On
1285 * such architectures, gup() will not be enough to make a subsequent access
1288 * This function will not return with an unlocked mmap_lock. So it has not the
1289 * same semantics wrt the @mm->mmap_lock as does filemap_fault().
1291 int fixup_user_fault(struct mm_struct *mm,
1292 unsigned long address, unsigned int fault_flags,
1295 struct vm_area_struct *vma;
1298 address = untagged_addr(address);
1301 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1304 vma = find_extend_vma(mm, address);
1305 if (!vma || address < vma->vm_start)
1308 if (!vma_permits_fault(vma, fault_flags))
1311 if ((fault_flags & FAULT_FLAG_KILLABLE) &&
1312 fatal_signal_pending(current))
1315 ret = handle_mm_fault(vma, address, fault_flags, NULL);
1316 if (ret & VM_FAULT_ERROR) {
1317 int err = vm_fault_to_errno(ret, 0);
1324 if (ret & VM_FAULT_RETRY) {
1327 fault_flags |= FAULT_FLAG_TRIED;
1333 EXPORT_SYMBOL_GPL(fixup_user_fault);
1336 * Please note that this function, unlike __get_user_pages will not
1337 * return 0 for nr_pages > 0 without FOLL_NOWAIT
1339 static __always_inline long __get_user_pages_locked(struct mm_struct *mm,
1340 unsigned long start,
1341 unsigned long nr_pages,
1342 struct page **pages,
1343 struct vm_area_struct **vmas,
1347 long ret, pages_done;
1351 /* if VM_FAULT_RETRY can be returned, vmas become invalid */
1353 /* check caller initialized locked */
1354 BUG_ON(*locked != 1);
1357 if (flags & FOLL_PIN)
1358 mm_set_has_pinned_flag(&mm->flags);
1361 * FOLL_PIN and FOLL_GET are mutually exclusive. Traditional behavior
1362 * is to set FOLL_GET if the caller wants pages[] filled in (but has
1363 * carelessly failed to specify FOLL_GET), so keep doing that, but only
1364 * for FOLL_GET, not for the newer FOLL_PIN.
1366 * FOLL_PIN always expects pages to be non-null, but no need to assert
1367 * that here, as any failures will be obvious enough.
1369 if (pages && !(flags & FOLL_PIN))
1373 lock_dropped = false;
1375 ret = __get_user_pages(mm, start, nr_pages, flags, pages,
1378 /* VM_FAULT_RETRY couldn't trigger, bypass */
1381 /* VM_FAULT_RETRY cannot return errors */
1384 BUG_ON(ret >= nr_pages);
1395 * VM_FAULT_RETRY didn't trigger or it was a
1403 * VM_FAULT_RETRY triggered, so seek to the faulting offset.
1404 * For the prefault case (!pages) we only update counts.
1408 start += ret << PAGE_SHIFT;
1409 lock_dropped = true;
1413 * Repeat on the address that fired VM_FAULT_RETRY
1414 * with both FAULT_FLAG_ALLOW_RETRY and
1415 * FAULT_FLAG_TRIED. Note that GUP can be interrupted
1416 * by fatal signals, so we need to check it before we
1417 * start trying again otherwise it can loop forever.
1420 if (fatal_signal_pending(current)) {
1422 pages_done = -EINTR;
1426 ret = mmap_read_lock_killable(mm);
1435 ret = __get_user_pages(mm, start, 1, flags | FOLL_TRIED,
1436 pages, NULL, locked);
1438 /* Continue to retry until we succeeded */
1456 if (lock_dropped && *locked) {
1458 * We must let the caller know we temporarily dropped the lock
1459 * and so the critical section protected by it was lost.
1461 mmap_read_unlock(mm);
1468 * populate_vma_page_range() - populate a range of pages in the vma.
1470 * @start: start address
1472 * @locked: whether the mmap_lock is still held
1474 * This takes care of mlocking the pages too if VM_LOCKED is set.
1476 * Return either number of pages pinned in the vma, or a negative error
1479 * vma->vm_mm->mmap_lock must be held.
1481 * If @locked is NULL, it may be held for read or write and will
1484 * If @locked is non-NULL, it must held for read only and may be
1485 * released. If it's released, *@locked will be set to 0.
1487 long populate_vma_page_range(struct vm_area_struct *vma,
1488 unsigned long start, unsigned long end, int *locked)
1490 struct mm_struct *mm = vma->vm_mm;
1491 unsigned long nr_pages = (end - start) / PAGE_SIZE;
1494 VM_BUG_ON(!PAGE_ALIGNED(start));
1495 VM_BUG_ON(!PAGE_ALIGNED(end));
1496 VM_BUG_ON_VMA(start < vma->vm_start, vma);
1497 VM_BUG_ON_VMA(end > vma->vm_end, vma);
1498 mmap_assert_locked(mm);
1500 gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK;
1501 if (vma->vm_flags & VM_LOCKONFAULT)
1502 gup_flags &= ~FOLL_POPULATE;
1504 * We want to touch writable mappings with a write fault in order
1505 * to break COW, except for shared mappings because these don't COW
1506 * and we would not want to dirty them for nothing.
1508 if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
1509 gup_flags |= FOLL_WRITE;
1512 * We want mlock to succeed for regions that have any permissions
1513 * other than PROT_NONE.
1515 if (vma_is_accessible(vma))
1516 gup_flags |= FOLL_FORCE;
1519 * We made sure addr is within a VMA, so the following will
1520 * not result in a stack expansion that recurses back here.
1522 return __get_user_pages(mm, start, nr_pages, gup_flags,
1523 NULL, NULL, locked);
1527 * faultin_vma_page_range() - populate (prefault) page tables inside the
1528 * given VMA range readable/writable
1530 * This takes care of mlocking the pages, too, if VM_LOCKED is set.
1533 * @start: start address
1535 * @write: whether to prefault readable or writable
1536 * @locked: whether the mmap_lock is still held
1538 * Returns either number of processed pages in the vma, or a negative error
1539 * code on error (see __get_user_pages()).
1541 * vma->vm_mm->mmap_lock must be held. The range must be page-aligned and
1542 * covered by the VMA.
1544 * If @locked is NULL, it may be held for read or write and will be unperturbed.
1546 * If @locked is non-NULL, it must held for read only and may be released. If
1547 * it's released, *@locked will be set to 0.
1549 long faultin_vma_page_range(struct vm_area_struct *vma, unsigned long start,
1550 unsigned long end, bool write, int *locked)
1552 struct mm_struct *mm = vma->vm_mm;
1553 unsigned long nr_pages = (end - start) / PAGE_SIZE;
1556 VM_BUG_ON(!PAGE_ALIGNED(start));
1557 VM_BUG_ON(!PAGE_ALIGNED(end));
1558 VM_BUG_ON_VMA(start < vma->vm_start, vma);
1559 VM_BUG_ON_VMA(end > vma->vm_end, vma);
1560 mmap_assert_locked(mm);
1563 * FOLL_TOUCH: Mark page accessed and thereby young; will also mark
1564 * the page dirty with FOLL_WRITE -- which doesn't make a
1565 * difference with !FOLL_FORCE, because the page is writable
1566 * in the page table.
1567 * FOLL_HWPOISON: Return -EHWPOISON instead of -EFAULT when we hit
1569 * FOLL_POPULATE: Always populate memory with VM_LOCKONFAULT.
1570 * !FOLL_FORCE: Require proper access permissions.
1572 gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK | FOLL_HWPOISON;
1574 gup_flags |= FOLL_WRITE;
1577 * We want to report -EINVAL instead of -EFAULT for any permission
1578 * problems or incompatible mappings.
1580 if (check_vma_flags(vma, gup_flags))
1583 return __get_user_pages(mm, start, nr_pages, gup_flags,
1584 NULL, NULL, locked);
1588 * __mm_populate - populate and/or mlock pages within a range of address space.
1590 * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
1591 * flags. VMAs must be already marked with the desired vm_flags, and
1592 * mmap_lock must not be held.
1594 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
1596 struct mm_struct *mm = current->mm;
1597 unsigned long end, nstart, nend;
1598 struct vm_area_struct *vma = NULL;
1604 for (nstart = start; nstart < end; nstart = nend) {
1606 * We want to fault in pages for [nstart; end) address range.
1607 * Find first corresponding VMA.
1612 vma = find_vma(mm, nstart);
1613 } else if (nstart >= vma->vm_end)
1615 if (!vma || vma->vm_start >= end)
1618 * Set [nstart; nend) to intersection of desired address
1619 * range with the first VMA. Also, skip undesirable VMA types.
1621 nend = min(end, vma->vm_end);
1622 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1624 if (nstart < vma->vm_start)
1625 nstart = vma->vm_start;
1627 * Now fault in a range of pages. populate_vma_page_range()
1628 * double checks the vma flags, so that it won't mlock pages
1629 * if the vma was already munlocked.
1631 ret = populate_vma_page_range(vma, nstart, nend, &locked);
1633 if (ignore_errors) {
1635 continue; /* continue at next VMA */
1639 nend = nstart + ret * PAGE_SIZE;
1643 mmap_read_unlock(mm);
1644 return ret; /* 0 or negative error code */
1646 #else /* CONFIG_MMU */
1647 static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start,
1648 unsigned long nr_pages, struct page **pages,
1649 struct vm_area_struct **vmas, int *locked,
1650 unsigned int foll_flags)
1652 struct vm_area_struct *vma;
1653 unsigned long vm_flags;
1656 /* calculate required read or write permissions.
1657 * If FOLL_FORCE is set, we only require the "MAY" flags.
1659 vm_flags = (foll_flags & FOLL_WRITE) ?
1660 (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
1661 vm_flags &= (foll_flags & FOLL_FORCE) ?
1662 (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
1664 for (i = 0; i < nr_pages; i++) {
1665 vma = find_vma(mm, start);
1667 goto finish_or_fault;
1669 /* protect what we can, including chardevs */
1670 if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
1671 !(vm_flags & vma->vm_flags))
1672 goto finish_or_fault;
1675 pages[i] = virt_to_page(start);
1681 start = (start + PAGE_SIZE) & PAGE_MASK;
1687 return i ? : -EFAULT;
1689 #endif /* !CONFIG_MMU */
1692 * fault_in_writeable - fault in userspace address range for writing
1693 * @uaddr: start of address range
1694 * @size: size of address range
1696 * Returns the number of bytes not faulted in (like copy_to_user() and
1697 * copy_from_user()).
1699 size_t fault_in_writeable(char __user *uaddr, size_t size)
1701 char __user *start = uaddr, *end;
1703 if (unlikely(size == 0))
1705 if (!user_write_access_begin(uaddr, size))
1707 if (!PAGE_ALIGNED(uaddr)) {
1708 unsafe_put_user(0, uaddr, out);
1709 uaddr = (char __user *)PAGE_ALIGN((unsigned long)uaddr);
1711 end = (char __user *)PAGE_ALIGN((unsigned long)start + size);
1712 if (unlikely(end < start))
1714 while (uaddr != end) {
1715 unsafe_put_user(0, uaddr, out);
1720 user_write_access_end();
1721 if (size > uaddr - start)
1722 return size - (uaddr - start);
1725 EXPORT_SYMBOL(fault_in_writeable);
1728 * fault_in_safe_writeable - fault in an address range for writing
1729 * @uaddr: start of address range
1730 * @size: length of address range
1732 * Faults in an address range using get_user_pages, i.e., without triggering
1733 * hardware page faults. This is primarily useful when we already know that
1734 * some or all of the pages in the address range aren't in memory.
1736 * Other than fault_in_writeable(), this function is non-destructive.
1738 * Note that we don't pin or otherwise hold the pages referenced that we fault
1739 * in. There's no guarantee that they'll stay in memory for any duration of
1742 * Returns the number of bytes not faulted in, like copy_to_user() and
1745 size_t fault_in_safe_writeable(const char __user *uaddr, size_t size)
1747 unsigned long start = (unsigned long)untagged_addr(uaddr);
1748 unsigned long end, nstart, nend;
1749 struct mm_struct *mm = current->mm;
1750 struct vm_area_struct *vma = NULL;
1753 nstart = start & PAGE_MASK;
1754 end = PAGE_ALIGN(start + size);
1757 for (; nstart != end; nstart = nend) {
1758 unsigned long nr_pages;
1764 vma = find_vma(mm, nstart);
1765 } else if (nstart >= vma->vm_end)
1767 if (!vma || vma->vm_start >= end)
1769 nend = end ? min(end, vma->vm_end) : vma->vm_end;
1770 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1772 if (nstart < vma->vm_start)
1773 nstart = vma->vm_start;
1774 nr_pages = (nend - nstart) / PAGE_SIZE;
1775 ret = __get_user_pages_locked(mm, nstart, nr_pages,
1776 NULL, NULL, &locked,
1777 FOLL_TOUCH | FOLL_WRITE);
1780 nend = nstart + ret * PAGE_SIZE;
1783 mmap_read_unlock(mm);
1786 return size - min_t(size_t, nstart - start, size);
1788 EXPORT_SYMBOL(fault_in_safe_writeable);
1791 * fault_in_readable - fault in userspace address range for reading
1792 * @uaddr: start of user address range
1793 * @size: size of user address range
1795 * Returns the number of bytes not faulted in (like copy_to_user() and
1796 * copy_from_user()).
1798 size_t fault_in_readable(const char __user *uaddr, size_t size)
1800 const char __user *start = uaddr, *end;
1803 if (unlikely(size == 0))
1805 if (!user_read_access_begin(uaddr, size))
1807 if (!PAGE_ALIGNED(uaddr)) {
1808 unsafe_get_user(c, uaddr, out);
1809 uaddr = (const char __user *)PAGE_ALIGN((unsigned long)uaddr);
1811 end = (const char __user *)PAGE_ALIGN((unsigned long)start + size);
1812 if (unlikely(end < start))
1814 while (uaddr != end) {
1815 unsafe_get_user(c, uaddr, out);
1820 user_read_access_end();
1822 if (size > uaddr - start)
1823 return size - (uaddr - start);
1826 EXPORT_SYMBOL(fault_in_readable);
1829 * get_dump_page() - pin user page in memory while writing it to core dump
1830 * @addr: user address
1832 * Returns struct page pointer of user page pinned for dump,
1833 * to be freed afterwards by put_page().
1835 * Returns NULL on any kind of failure - a hole must then be inserted into
1836 * the corefile, to preserve alignment with its headers; and also returns
1837 * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
1838 * allowing a hole to be left in the corefile to save disk space.
1840 * Called without mmap_lock (takes and releases the mmap_lock by itself).
1842 #ifdef CONFIG_ELF_CORE
1843 struct page *get_dump_page(unsigned long addr)
1845 struct mm_struct *mm = current->mm;
1850 if (mmap_read_lock_killable(mm))
1852 ret = __get_user_pages_locked(mm, addr, 1, &page, NULL, &locked,
1853 FOLL_FORCE | FOLL_DUMP | FOLL_GET);
1855 mmap_read_unlock(mm);
1856 return (ret == 1) ? page : NULL;
1858 #endif /* CONFIG_ELF_CORE */
1860 #ifdef CONFIG_MIGRATION
1862 * Check whether all pages are pinnable, if so return number of pages. If some
1863 * pages are not pinnable, migrate them, and unpin all pages. Return zero if
1864 * pages were migrated, or if some pages were not successfully isolated.
1865 * Return negative error if migration fails.
1867 static long check_and_migrate_movable_pages(unsigned long nr_pages,
1868 struct page **pages,
1869 unsigned int gup_flags)
1872 unsigned long isolation_error_count = 0;
1873 bool drain_allow = true;
1874 LIST_HEAD(movable_page_list);
1876 struct page *prev_head = NULL;
1878 struct migration_target_control mtc = {
1879 .nid = NUMA_NO_NODE,
1880 .gfp_mask = GFP_USER | __GFP_NOWARN,
1883 for (i = 0; i < nr_pages; i++) {
1884 head = compound_head(pages[i]);
1885 if (head == prev_head)
1889 * If we get a movable page, since we are going to be pinning
1890 * these entries, try to move them out if possible.
1892 if (!is_pinnable_page(head)) {
1893 if (PageHuge(head)) {
1894 if (!isolate_huge_page(head, &movable_page_list))
1895 isolation_error_count++;
1897 if (!PageLRU(head) && drain_allow) {
1898 lru_add_drain_all();
1899 drain_allow = false;
1902 if (isolate_lru_page(head)) {
1903 isolation_error_count++;
1906 list_add_tail(&head->lru, &movable_page_list);
1907 mod_node_page_state(page_pgdat(head),
1909 page_is_file_lru(head),
1910 thp_nr_pages(head));
1916 * If list is empty, and no isolation errors, means that all pages are
1917 * in the correct zone.
1919 if (list_empty(&movable_page_list) && !isolation_error_count)
1922 if (gup_flags & FOLL_PIN) {
1923 unpin_user_pages(pages, nr_pages);
1925 for (i = 0; i < nr_pages; i++)
1928 if (!list_empty(&movable_page_list)) {
1929 ret = migrate_pages(&movable_page_list, alloc_migration_target,
1930 NULL, (unsigned long)&mtc, MIGRATE_SYNC,
1931 MR_LONGTERM_PIN, NULL);
1932 if (ret && !list_empty(&movable_page_list))
1933 putback_movable_pages(&movable_page_list);
1936 return ret > 0 ? -ENOMEM : ret;
1939 static long check_and_migrate_movable_pages(unsigned long nr_pages,
1940 struct page **pages,
1941 unsigned int gup_flags)
1945 #endif /* CONFIG_MIGRATION */
1948 * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
1949 * allows us to process the FOLL_LONGTERM flag.
1951 static long __gup_longterm_locked(struct mm_struct *mm,
1952 unsigned long start,
1953 unsigned long nr_pages,
1954 struct page **pages,
1955 struct vm_area_struct **vmas,
1956 unsigned int gup_flags)
1961 if (!(gup_flags & FOLL_LONGTERM))
1962 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1964 flags = memalloc_pin_save();
1966 rc = __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1970 rc = check_and_migrate_movable_pages(rc, pages, gup_flags);
1972 memalloc_pin_restore(flags);
1977 static bool is_valid_gup_flags(unsigned int gup_flags)
1980 * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
1981 * never directly by the caller, so enforce that with an assertion:
1983 if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
1986 * FOLL_PIN is a prerequisite to FOLL_LONGTERM. Another way of saying
1987 * that is, FOLL_LONGTERM is a specific case, more restrictive case of
1990 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1997 static long __get_user_pages_remote(struct mm_struct *mm,
1998 unsigned long start, unsigned long nr_pages,
1999 unsigned int gup_flags, struct page **pages,
2000 struct vm_area_struct **vmas, int *locked)
2003 * Parts of FOLL_LONGTERM behavior are incompatible with
2004 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2005 * vmas. However, this only comes up if locked is set, and there are
2006 * callers that do request FOLL_LONGTERM, but do not set locked. So,
2007 * allow what we can.
2009 if (gup_flags & FOLL_LONGTERM) {
2010 if (WARN_ON_ONCE(locked))
2013 * This will check the vmas (even if our vmas arg is NULL)
2014 * and return -ENOTSUPP if DAX isn't allowed in this case:
2016 return __gup_longterm_locked(mm, start, nr_pages, pages,
2017 vmas, gup_flags | FOLL_TOUCH |
2021 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
2023 gup_flags | FOLL_TOUCH | FOLL_REMOTE);
2027 * get_user_pages_remote() - pin user pages in memory
2028 * @mm: mm_struct of target mm
2029 * @start: starting user address
2030 * @nr_pages: number of pages from start to pin
2031 * @gup_flags: flags modifying lookup behaviour
2032 * @pages: array that receives pointers to the pages pinned.
2033 * Should be at least nr_pages long. Or NULL, if caller
2034 * only intends to ensure the pages are faulted in.
2035 * @vmas: array of pointers to vmas corresponding to each page.
2036 * Or NULL if the caller does not require them.
2037 * @locked: pointer to lock flag indicating whether lock is held and
2038 * subsequently whether VM_FAULT_RETRY functionality can be
2039 * utilised. Lock must initially be held.
2041 * Returns either number of pages pinned (which may be less than the
2042 * number requested), or an error. Details about the return value:
2044 * -- If nr_pages is 0, returns 0.
2045 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
2046 * -- If nr_pages is >0, and some pages were pinned, returns the number of
2047 * pages pinned. Again, this may be less than nr_pages.
2049 * The caller is responsible for releasing returned @pages, via put_page().
2051 * @vmas are valid only as long as mmap_lock is held.
2053 * Must be called with mmap_lock held for read or write.
2055 * get_user_pages_remote walks a process's page tables and takes a reference
2056 * to each struct page that each user address corresponds to at a given
2057 * instant. That is, it takes the page that would be accessed if a user
2058 * thread accesses the given user virtual address at that instant.
2060 * This does not guarantee that the page exists in the user mappings when
2061 * get_user_pages_remote returns, and there may even be a completely different
2062 * page there in some cases (eg. if mmapped pagecache has been invalidated
2063 * and subsequently re faulted). However it does guarantee that the page
2064 * won't be freed completely. And mostly callers simply care that the page
2065 * contains data that was valid *at some point in time*. Typically, an IO
2066 * or similar operation cannot guarantee anything stronger anyway because
2067 * locks can't be held over the syscall boundary.
2069 * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
2070 * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
2071 * be called after the page is finished with, and before put_page is called.
2073 * get_user_pages_remote is typically used for fewer-copy IO operations,
2074 * to get a handle on the memory by some means other than accesses
2075 * via the user virtual addresses. The pages may be submitted for
2076 * DMA to devices or accessed via their kernel linear mapping (via the
2077 * kmap APIs). Care should be taken to use the correct cache flushing APIs.
2079 * See also get_user_pages_fast, for performance critical applications.
2081 * get_user_pages_remote should be phased out in favor of
2082 * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
2083 * should use get_user_pages_remote because it cannot pass
2084 * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
2086 long get_user_pages_remote(struct mm_struct *mm,
2087 unsigned long start, unsigned long nr_pages,
2088 unsigned int gup_flags, struct page **pages,
2089 struct vm_area_struct **vmas, int *locked)
2091 if (!is_valid_gup_flags(gup_flags))
2094 return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
2095 pages, vmas, locked);
2097 EXPORT_SYMBOL(get_user_pages_remote);
2099 #else /* CONFIG_MMU */
2100 long get_user_pages_remote(struct mm_struct *mm,
2101 unsigned long start, unsigned long nr_pages,
2102 unsigned int gup_flags, struct page **pages,
2103 struct vm_area_struct **vmas, int *locked)
2108 static long __get_user_pages_remote(struct mm_struct *mm,
2109 unsigned long start, unsigned long nr_pages,
2110 unsigned int gup_flags, struct page **pages,
2111 struct vm_area_struct **vmas, int *locked)
2115 #endif /* !CONFIG_MMU */
2118 * get_user_pages() - pin user pages in memory
2119 * @start: starting user address
2120 * @nr_pages: number of pages from start to pin
2121 * @gup_flags: flags modifying lookup behaviour
2122 * @pages: array that receives pointers to the pages pinned.
2123 * Should be at least nr_pages long. Or NULL, if caller
2124 * only intends to ensure the pages are faulted in.
2125 * @vmas: array of pointers to vmas corresponding to each page.
2126 * Or NULL if the caller does not require them.
2128 * This is the same as get_user_pages_remote(), just with a less-flexible
2129 * calling convention where we assume that the mm being operated on belongs to
2130 * the current task, and doesn't allow passing of a locked parameter. We also
2131 * obviously don't pass FOLL_REMOTE in here.
2133 long get_user_pages(unsigned long start, unsigned long nr_pages,
2134 unsigned int gup_flags, struct page **pages,
2135 struct vm_area_struct **vmas)
2137 if (!is_valid_gup_flags(gup_flags))
2140 return __gup_longterm_locked(current->mm, start, nr_pages,
2141 pages, vmas, gup_flags | FOLL_TOUCH);
2143 EXPORT_SYMBOL(get_user_pages);
2146 * get_user_pages_locked() - variant of get_user_pages()
2148 * @start: starting user address
2149 * @nr_pages: number of pages from start to pin
2150 * @gup_flags: flags modifying lookup behaviour
2151 * @pages: array that receives pointers to the pages pinned.
2152 * Should be at least nr_pages long. Or NULL, if caller
2153 * only intends to ensure the pages are faulted in.
2154 * @locked: pointer to lock flag indicating whether lock is held and
2155 * subsequently whether VM_FAULT_RETRY functionality can be
2156 * utilised. Lock must initially be held.
2158 * It is suitable to replace the form:
2160 * mmap_read_lock(mm);
2162 * get_user_pages(mm, ..., pages, NULL);
2163 * mmap_read_unlock(mm);
2168 * mmap_read_lock(mm);
2170 * get_user_pages_locked(mm, ..., pages, &locked);
2172 * mmap_read_unlock(mm);
2174 * We can leverage the VM_FAULT_RETRY functionality in the page fault
2175 * paths better by using either get_user_pages_locked() or
2176 * get_user_pages_unlocked().
2179 long get_user_pages_locked(unsigned long start, unsigned long nr_pages,
2180 unsigned int gup_flags, struct page **pages,
2184 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
2185 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2186 * vmas. As there are no users of this flag in this call we simply
2187 * disallow this option for now.
2189 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
2192 * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
2193 * never directly by the caller, so enforce that:
2195 if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
2198 return __get_user_pages_locked(current->mm, start, nr_pages,
2199 pages, NULL, locked,
2200 gup_flags | FOLL_TOUCH);
2202 EXPORT_SYMBOL(get_user_pages_locked);
2205 * get_user_pages_unlocked() is suitable to replace the form:
2207 * mmap_read_lock(mm);
2208 * get_user_pages(mm, ..., pages, NULL);
2209 * mmap_read_unlock(mm);
2213 * get_user_pages_unlocked(mm, ..., pages);
2215 * It is functionally equivalent to get_user_pages_fast so
2216 * get_user_pages_fast should be used instead if specific gup_flags
2217 * (e.g. FOLL_FORCE) are not required.
2219 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
2220 struct page **pages, unsigned int gup_flags)
2222 struct mm_struct *mm = current->mm;
2227 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
2228 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2229 * vmas. As there are no users of this flag in this call we simply
2230 * disallow this option for now.
2232 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
2236 ret = __get_user_pages_locked(mm, start, nr_pages, pages, NULL,
2237 &locked, gup_flags | FOLL_TOUCH);
2239 mmap_read_unlock(mm);
2242 EXPORT_SYMBOL(get_user_pages_unlocked);
2247 * get_user_pages_fast attempts to pin user pages by walking the page
2248 * tables directly and avoids taking locks. Thus the walker needs to be
2249 * protected from page table pages being freed from under it, and should
2250 * block any THP splits.
2252 * One way to achieve this is to have the walker disable interrupts, and
2253 * rely on IPIs from the TLB flushing code blocking before the page table
2254 * pages are freed. This is unsuitable for architectures that do not need
2255 * to broadcast an IPI when invalidating TLBs.
2257 * Another way to achieve this is to batch up page table containing pages
2258 * belonging to more than one mm_user, then rcu_sched a callback to free those
2259 * pages. Disabling interrupts will allow the fast_gup walker to both block
2260 * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
2261 * (which is a relatively rare event). The code below adopts this strategy.
2263 * Before activating this code, please be aware that the following assumptions
2264 * are currently made:
2266 * *) Either MMU_GATHER_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
2267 * free pages containing page tables or TLB flushing requires IPI broadcast.
2269 * *) ptes can be read atomically by the architecture.
2271 * *) access_ok is sufficient to validate userspace address ranges.
2273 * The last two assumptions can be relaxed by the addition of helper functions.
2275 * This code is based heavily on the PowerPC implementation by Nick Piggin.
2277 #ifdef CONFIG_HAVE_FAST_GUP
2279 static void __maybe_unused undo_dev_pagemap(int *nr, int nr_start,
2281 struct page **pages)
2283 while ((*nr) - nr_start) {
2284 struct page *page = pages[--(*nr)];
2286 ClearPageReferenced(page);
2287 if (flags & FOLL_PIN)
2288 unpin_user_page(page);
2294 #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
2295 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2296 unsigned int flags, struct page **pages, int *nr)
2298 struct dev_pagemap *pgmap = NULL;
2299 int nr_start = *nr, ret = 0;
2302 ptem = ptep = pte_offset_map(&pmd, addr);
2304 pte_t pte = ptep_get_lockless(ptep);
2305 struct page *head, *page;
2308 * Similar to the PMD case below, NUMA hinting must take slow
2309 * path using the pte_protnone check.
2311 if (pte_protnone(pte))
2314 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2317 if (pte_devmap(pte)) {
2318 if (unlikely(flags & FOLL_LONGTERM))
2321 pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
2322 if (unlikely(!pgmap)) {
2323 undo_dev_pagemap(nr, nr_start, flags, pages);
2326 } else if (pte_special(pte))
2329 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2330 page = pte_page(pte);
2332 head = try_grab_compound_head(page, 1, flags);
2336 if (unlikely(page_is_secretmem(page))) {
2337 put_compound_head(head, 1, flags);
2341 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2342 put_compound_head(head, 1, flags);
2346 VM_BUG_ON_PAGE(compound_head(page) != head, page);
2349 * We need to make the page accessible if and only if we are
2350 * going to access its content (the FOLL_PIN case). Please
2351 * see Documentation/core-api/pin_user_pages.rst for
2354 if (flags & FOLL_PIN) {
2355 ret = arch_make_page_accessible(page);
2357 unpin_user_page(page);
2361 SetPageReferenced(page);
2365 } while (ptep++, addr += PAGE_SIZE, addr != end);
2371 put_dev_pagemap(pgmap);
2378 * If we can't determine whether or not a pte is special, then fail immediately
2379 * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
2382 * For a futex to be placed on a THP tail page, get_futex_key requires a
2383 * get_user_pages_fast_only implementation that can pin pages. Thus it's still
2384 * useful to have gup_huge_pmd even if we can't operate on ptes.
2386 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2387 unsigned int flags, struct page **pages, int *nr)
2391 #endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
2393 #if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
2394 static int __gup_device_huge(unsigned long pfn, unsigned long addr,
2395 unsigned long end, unsigned int flags,
2396 struct page **pages, int *nr)
2399 struct dev_pagemap *pgmap = NULL;
2402 struct page *page = pfn_to_page(pfn);
2404 pgmap = get_dev_pagemap(pfn, pgmap);
2405 if (unlikely(!pgmap)) {
2406 undo_dev_pagemap(nr, nr_start, flags, pages);
2409 SetPageReferenced(page);
2411 if (unlikely(!try_grab_page(page, flags))) {
2412 undo_dev_pagemap(nr, nr_start, flags, pages);
2417 } while (addr += PAGE_SIZE, addr != end);
2419 put_dev_pagemap(pgmap);
2423 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2424 unsigned long end, unsigned int flags,
2425 struct page **pages, int *nr)
2427 unsigned long fault_pfn;
2430 fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2431 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2434 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2435 undo_dev_pagemap(nr, nr_start, flags, pages);
2441 static int __gup_device_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2442 unsigned long end, unsigned int flags,
2443 struct page **pages, int *nr)
2445 unsigned long fault_pfn;
2448 fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2449 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2452 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2453 undo_dev_pagemap(nr, nr_start, flags, pages);
2459 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2460 unsigned long end, unsigned int flags,
2461 struct page **pages, int *nr)
2467 static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr,
2468 unsigned long end, unsigned int flags,
2469 struct page **pages, int *nr)
2476 static int record_subpages(struct page *page, unsigned long addr,
2477 unsigned long end, struct page **pages)
2481 for (nr = 0; addr != end; addr += PAGE_SIZE)
2482 pages[nr++] = page++;
2487 #ifdef CONFIG_ARCH_HAS_HUGEPD
2488 static unsigned long hugepte_addr_end(unsigned long addr, unsigned long end,
2491 unsigned long __boundary = (addr + sz) & ~(sz-1);
2492 return (__boundary - 1 < end - 1) ? __boundary : end;
2495 static int gup_hugepte(pte_t *ptep, unsigned long sz, unsigned long addr,
2496 unsigned long end, unsigned int flags,
2497 struct page **pages, int *nr)
2499 unsigned long pte_end;
2500 struct page *head, *page;
2504 pte_end = (addr + sz) & ~(sz-1);
2508 pte = huge_ptep_get(ptep);
2510 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2513 /* hugepages are never "special" */
2514 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2516 head = pte_page(pte);
2517 page = head + ((addr & (sz-1)) >> PAGE_SHIFT);
2518 refs = record_subpages(page, addr, end, pages + *nr);
2520 head = try_grab_compound_head(head, refs, flags);
2524 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2525 put_compound_head(head, refs, flags);
2530 SetPageReferenced(head);
2534 static int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2535 unsigned int pdshift, unsigned long end, unsigned int flags,
2536 struct page **pages, int *nr)
2539 unsigned long sz = 1UL << hugepd_shift(hugepd);
2542 ptep = hugepte_offset(hugepd, addr, pdshift);
2544 next = hugepte_addr_end(addr, end, sz);
2545 if (!gup_hugepte(ptep, sz, addr, end, flags, pages, nr))
2547 } while (ptep++, addr = next, addr != end);
2552 static inline int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2553 unsigned int pdshift, unsigned long end, unsigned int flags,
2554 struct page **pages, int *nr)
2558 #endif /* CONFIG_ARCH_HAS_HUGEPD */
2560 static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2561 unsigned long end, unsigned int flags,
2562 struct page **pages, int *nr)
2564 struct page *head, *page;
2567 if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
2570 if (pmd_devmap(orig)) {
2571 if (unlikely(flags & FOLL_LONGTERM))
2573 return __gup_device_huge_pmd(orig, pmdp, addr, end, flags,
2577 page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2578 refs = record_subpages(page, addr, end, pages + *nr);
2580 head = try_grab_compound_head(pmd_page(orig), refs, flags);
2584 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2585 put_compound_head(head, refs, flags);
2590 SetPageReferenced(head);
2594 static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2595 unsigned long end, unsigned int flags,
2596 struct page **pages, int *nr)
2598 struct page *head, *page;
2601 if (!pud_access_permitted(orig, flags & FOLL_WRITE))
2604 if (pud_devmap(orig)) {
2605 if (unlikely(flags & FOLL_LONGTERM))
2607 return __gup_device_huge_pud(orig, pudp, addr, end, flags,
2611 page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2612 refs = record_subpages(page, addr, end, pages + *nr);
2614 head = try_grab_compound_head(pud_page(orig), refs, flags);
2618 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2619 put_compound_head(head, refs, flags);
2624 SetPageReferenced(head);
2628 static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
2629 unsigned long end, unsigned int flags,
2630 struct page **pages, int *nr)
2633 struct page *head, *page;
2635 if (!pgd_access_permitted(orig, flags & FOLL_WRITE))
2638 BUILD_BUG_ON(pgd_devmap(orig));
2640 page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT);
2641 refs = record_subpages(page, addr, end, pages + *nr);
2643 head = try_grab_compound_head(pgd_page(orig), refs, flags);
2647 if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
2648 put_compound_head(head, refs, flags);
2653 SetPageReferenced(head);
2657 static int gup_pmd_range(pud_t *pudp, pud_t pud, unsigned long addr, unsigned long end,
2658 unsigned int flags, struct page **pages, int *nr)
2663 pmdp = pmd_offset_lockless(pudp, pud, addr);
2665 pmd_t pmd = READ_ONCE(*pmdp);
2667 next = pmd_addr_end(addr, end);
2668 if (!pmd_present(pmd))
2671 if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd) ||
2674 * NUMA hinting faults need to be handled in the GUP
2675 * slowpath for accounting purposes and so that they
2676 * can be serialised against THP migration.
2678 if (pmd_protnone(pmd))
2681 if (!gup_huge_pmd(pmd, pmdp, addr, next, flags,
2685 } else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
2687 * architecture have different format for hugetlbfs
2688 * pmd format and THP pmd format
2690 if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
2691 PMD_SHIFT, next, flags, pages, nr))
2693 } else if (!gup_pte_range(pmd, addr, next, flags, pages, nr))
2695 } while (pmdp++, addr = next, addr != end);
2700 static int gup_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr, unsigned long end,
2701 unsigned int flags, struct page **pages, int *nr)
2706 pudp = pud_offset_lockless(p4dp, p4d, addr);
2708 pud_t pud = READ_ONCE(*pudp);
2710 next = pud_addr_end(addr, end);
2711 if (unlikely(!pud_present(pud)))
2713 if (unlikely(pud_huge(pud))) {
2714 if (!gup_huge_pud(pud, pudp, addr, next, flags,
2717 } else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
2718 if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
2719 PUD_SHIFT, next, flags, pages, nr))
2721 } else if (!gup_pmd_range(pudp, pud, addr, next, flags, pages, nr))
2723 } while (pudp++, addr = next, addr != end);
2728 static int gup_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr, unsigned long end,
2729 unsigned int flags, struct page **pages, int *nr)
2734 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
2736 p4d_t p4d = READ_ONCE(*p4dp);
2738 next = p4d_addr_end(addr, end);
2741 BUILD_BUG_ON(p4d_huge(p4d));
2742 if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
2743 if (!gup_huge_pd(__hugepd(p4d_val(p4d)), addr,
2744 P4D_SHIFT, next, flags, pages, nr))
2746 } else if (!gup_pud_range(p4dp, p4d, addr, next, flags, pages, nr))
2748 } while (p4dp++, addr = next, addr != end);
2753 static void gup_pgd_range(unsigned long addr, unsigned long end,
2754 unsigned int flags, struct page **pages, int *nr)
2759 pgdp = pgd_offset(current->mm, addr);
2761 pgd_t pgd = READ_ONCE(*pgdp);
2763 next = pgd_addr_end(addr, end);
2766 if (unlikely(pgd_huge(pgd))) {
2767 if (!gup_huge_pgd(pgd, pgdp, addr, next, flags,
2770 } else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
2771 if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
2772 PGDIR_SHIFT, next, flags, pages, nr))
2774 } else if (!gup_p4d_range(pgdp, pgd, addr, next, flags, pages, nr))
2776 } while (pgdp++, addr = next, addr != end);
2779 static inline void gup_pgd_range(unsigned long addr, unsigned long end,
2780 unsigned int flags, struct page **pages, int *nr)
2783 #endif /* CONFIG_HAVE_FAST_GUP */
2785 #ifndef gup_fast_permitted
2787 * Check if it's allowed to use get_user_pages_fast_only() for the range, or
2788 * we need to fall back to the slow version:
2790 static bool gup_fast_permitted(unsigned long start, unsigned long end)
2796 static int __gup_longterm_unlocked(unsigned long start, int nr_pages,
2797 unsigned int gup_flags, struct page **pages)
2802 * FIXME: FOLL_LONGTERM does not work with
2803 * get_user_pages_unlocked() (see comments in that function)
2805 if (gup_flags & FOLL_LONGTERM) {
2806 mmap_read_lock(current->mm);
2807 ret = __gup_longterm_locked(current->mm,
2809 pages, NULL, gup_flags);
2810 mmap_read_unlock(current->mm);
2812 ret = get_user_pages_unlocked(start, nr_pages,
2819 static unsigned long lockless_pages_from_mm(unsigned long start,
2821 unsigned int gup_flags,
2822 struct page **pages)
2824 unsigned long flags;
2828 if (!IS_ENABLED(CONFIG_HAVE_FAST_GUP) ||
2829 !gup_fast_permitted(start, end))
2832 if (gup_flags & FOLL_PIN) {
2833 seq = raw_read_seqcount(¤t->mm->write_protect_seq);
2839 * Disable interrupts. The nested form is used, in order to allow full,
2840 * general purpose use of this routine.
2842 * With interrupts disabled, we block page table pages from being freed
2843 * from under us. See struct mmu_table_batch comments in
2844 * include/asm-generic/tlb.h for more details.
2846 * We do not adopt an rcu_read_lock() here as we also want to block IPIs
2847 * that come from THPs splitting.
2849 local_irq_save(flags);
2850 gup_pgd_range(start, end, gup_flags, pages, &nr_pinned);
2851 local_irq_restore(flags);
2854 * When pinning pages for DMA there could be a concurrent write protect
2855 * from fork() via copy_page_range(), in this case always fail fast GUP.
2857 if (gup_flags & FOLL_PIN) {
2858 if (read_seqcount_retry(¤t->mm->write_protect_seq, seq)) {
2859 unpin_user_pages(pages, nr_pinned);
2866 static int internal_get_user_pages_fast(unsigned long start,
2867 unsigned long nr_pages,
2868 unsigned int gup_flags,
2869 struct page **pages)
2871 unsigned long len, end;
2872 unsigned long nr_pinned;
2875 if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM |
2876 FOLL_FORCE | FOLL_PIN | FOLL_GET |
2877 FOLL_FAST_ONLY | FOLL_NOFAULT)))
2880 if (gup_flags & FOLL_PIN)
2881 mm_set_has_pinned_flag(¤t->mm->flags);
2883 if (!(gup_flags & FOLL_FAST_ONLY))
2884 might_lock_read(¤t->mm->mmap_lock);
2886 start = untagged_addr(start) & PAGE_MASK;
2887 len = nr_pages << PAGE_SHIFT;
2888 if (check_add_overflow(start, len, &end))
2890 if (unlikely(!access_ok((void __user *)start, len)))
2893 nr_pinned = lockless_pages_from_mm(start, end, gup_flags, pages);
2894 if (nr_pinned == nr_pages || gup_flags & FOLL_FAST_ONLY)
2897 /* Slow path: try to get the remaining pages with get_user_pages */
2898 start += nr_pinned << PAGE_SHIFT;
2900 ret = __gup_longterm_unlocked(start, nr_pages - nr_pinned, gup_flags,
2904 * The caller has to unpin the pages we already pinned so
2905 * returning -errno is not an option
2911 return ret + nr_pinned;
2915 * get_user_pages_fast_only() - pin user pages in memory
2916 * @start: starting user address
2917 * @nr_pages: number of pages from start to pin
2918 * @gup_flags: flags modifying pin behaviour
2919 * @pages: array that receives pointers to the pages pinned.
2920 * Should be at least nr_pages long.
2922 * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
2924 * Note a difference with get_user_pages_fast: this always returns the
2925 * number of pages pinned, 0 if no pages were pinned.
2927 * If the architecture does not support this function, simply return with no
2930 * Careful, careful! COW breaking can go either way, so a non-write
2931 * access can get ambiguous page results. If you call this function without
2932 * 'write' set, you'd better be sure that you're ok with that ambiguity.
2934 int get_user_pages_fast_only(unsigned long start, int nr_pages,
2935 unsigned int gup_flags, struct page **pages)
2939 * Internally (within mm/gup.c), gup fast variants must set FOLL_GET,
2940 * because gup fast is always a "pin with a +1 page refcount" request.
2942 * FOLL_FAST_ONLY is required in order to match the API description of
2943 * this routine: no fall back to regular ("slow") GUP.
2945 gup_flags |= FOLL_GET | FOLL_FAST_ONLY;
2947 nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
2951 * As specified in the API description above, this routine is not
2952 * allowed to return negative values. However, the common core
2953 * routine internal_get_user_pages_fast() *can* return -errno.
2954 * Therefore, correct for that here:
2961 EXPORT_SYMBOL_GPL(get_user_pages_fast_only);
2964 * get_user_pages_fast() - pin user pages in memory
2965 * @start: starting user address
2966 * @nr_pages: number of pages from start to pin
2967 * @gup_flags: flags modifying pin behaviour
2968 * @pages: array that receives pointers to the pages pinned.
2969 * Should be at least nr_pages long.
2971 * Attempt to pin user pages in memory without taking mm->mmap_lock.
2972 * If not successful, it will fall back to taking the lock and
2973 * calling get_user_pages().
2975 * Returns number of pages pinned. This may be fewer than the number requested.
2976 * If nr_pages is 0 or negative, returns 0. If no pages were pinned, returns
2979 int get_user_pages_fast(unsigned long start, int nr_pages,
2980 unsigned int gup_flags, struct page **pages)
2982 if (!is_valid_gup_flags(gup_flags))
2986 * The caller may or may not have explicitly set FOLL_GET; either way is
2987 * OK. However, internally (within mm/gup.c), gup fast variants must set
2988 * FOLL_GET, because gup fast is always a "pin with a +1 page refcount"
2991 gup_flags |= FOLL_GET;
2992 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
2994 EXPORT_SYMBOL_GPL(get_user_pages_fast);
2997 * pin_user_pages_fast() - pin user pages in memory without taking locks
2999 * @start: starting user address
3000 * @nr_pages: number of pages from start to pin
3001 * @gup_flags: flags modifying pin behaviour
3002 * @pages: array that receives pointers to the pages pinned.
3003 * Should be at least nr_pages long.
3005 * Nearly the same as get_user_pages_fast(), except that FOLL_PIN is set. See
3006 * get_user_pages_fast() for documentation on the function arguments, because
3007 * the arguments here are identical.
3009 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3010 * see Documentation/core-api/pin_user_pages.rst for further details.
3012 int pin_user_pages_fast(unsigned long start, int nr_pages,
3013 unsigned int gup_flags, struct page **pages)
3015 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3016 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3019 gup_flags |= FOLL_PIN;
3020 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
3022 EXPORT_SYMBOL_GPL(pin_user_pages_fast);
3025 * This is the FOLL_PIN equivalent of get_user_pages_fast_only(). Behavior
3026 * is the same, except that this one sets FOLL_PIN instead of FOLL_GET.
3028 * The API rules are the same, too: no negative values may be returned.
3030 int pin_user_pages_fast_only(unsigned long start, int nr_pages,
3031 unsigned int gup_flags, struct page **pages)
3036 * FOLL_GET and FOLL_PIN are mutually exclusive. Note that the API
3037 * rules require returning 0, rather than -errno:
3039 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3042 * FOLL_FAST_ONLY is required in order to match the API description of
3043 * this routine: no fall back to regular ("slow") GUP.
3045 gup_flags |= (FOLL_PIN | FOLL_FAST_ONLY);
3046 nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
3049 * This routine is not allowed to return negative values. However,
3050 * internal_get_user_pages_fast() *can* return -errno. Therefore,
3051 * correct for that here:
3058 EXPORT_SYMBOL_GPL(pin_user_pages_fast_only);
3061 * pin_user_pages_remote() - pin pages of a remote process
3063 * @mm: mm_struct of target mm
3064 * @start: starting user address
3065 * @nr_pages: number of pages from start to pin
3066 * @gup_flags: flags modifying lookup behaviour
3067 * @pages: array that receives pointers to the pages pinned.
3068 * Should be at least nr_pages long. Or NULL, if caller
3069 * only intends to ensure the pages are faulted in.
3070 * @vmas: array of pointers to vmas corresponding to each page.
3071 * Or NULL if the caller does not require them.
3072 * @locked: pointer to lock flag indicating whether lock is held and
3073 * subsequently whether VM_FAULT_RETRY functionality can be
3074 * utilised. Lock must initially be held.
3076 * Nearly the same as get_user_pages_remote(), except that FOLL_PIN is set. See
3077 * get_user_pages_remote() for documentation on the function arguments, because
3078 * the arguments here are identical.
3080 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3081 * see Documentation/core-api/pin_user_pages.rst for details.
3083 long pin_user_pages_remote(struct mm_struct *mm,
3084 unsigned long start, unsigned long nr_pages,
3085 unsigned int gup_flags, struct page **pages,
3086 struct vm_area_struct **vmas, int *locked)
3088 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3089 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3092 gup_flags |= FOLL_PIN;
3093 return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
3094 pages, vmas, locked);
3096 EXPORT_SYMBOL(pin_user_pages_remote);
3099 * pin_user_pages() - pin user pages in memory for use by other devices
3101 * @start: starting user address
3102 * @nr_pages: number of pages from start to pin
3103 * @gup_flags: flags modifying lookup behaviour
3104 * @pages: array that receives pointers to the pages pinned.
3105 * Should be at least nr_pages long. Or NULL, if caller
3106 * only intends to ensure the pages are faulted in.
3107 * @vmas: array of pointers to vmas corresponding to each page.
3108 * Or NULL if the caller does not require them.
3110 * Nearly the same as get_user_pages(), except that FOLL_TOUCH is not set, and
3113 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
3114 * see Documentation/core-api/pin_user_pages.rst for details.
3116 long pin_user_pages(unsigned long start, unsigned long nr_pages,
3117 unsigned int gup_flags, struct page **pages,
3118 struct vm_area_struct **vmas)
3120 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3121 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3124 gup_flags |= FOLL_PIN;
3125 return __gup_longterm_locked(current->mm, start, nr_pages,
3126 pages, vmas, gup_flags);
3128 EXPORT_SYMBOL(pin_user_pages);
3131 * pin_user_pages_unlocked() is the FOLL_PIN variant of
3132 * get_user_pages_unlocked(). Behavior is the same, except that this one sets
3133 * FOLL_PIN and rejects FOLL_GET.
3135 long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
3136 struct page **pages, unsigned int gup_flags)
3138 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3139 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3142 gup_flags |= FOLL_PIN;
3143 return get_user_pages_unlocked(start, nr_pages, pages, gup_flags);
3145 EXPORT_SYMBOL(pin_user_pages_unlocked);
3148 * pin_user_pages_locked() is the FOLL_PIN variant of get_user_pages_locked().
3149 * Behavior is the same, except that this one sets FOLL_PIN and rejects
3152 long pin_user_pages_locked(unsigned long start, unsigned long nr_pages,
3153 unsigned int gup_flags, struct page **pages,
3157 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
3158 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
3159 * vmas. As there are no users of this flag in this call we simply
3160 * disallow this option for now.
3162 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
3165 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3166 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3169 gup_flags |= FOLL_PIN;
3170 return __get_user_pages_locked(current->mm, start, nr_pages,
3171 pages, NULL, locked,
3172 gup_flags | FOLL_TOUCH);
3174 EXPORT_SYMBOL(pin_user_pages_locked);