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>
14 #include <linux/sched/signal.h>
15 #include <linux/rwsem.h>
16 #include <linux/hugetlb.h>
17 #include <linux/migrate.h>
18 #include <linux/mm_inline.h>
19 #include <linux/sched/mm.h>
21 #include <asm/mmu_context.h>
22 #include <asm/tlbflush.h>
26 struct follow_page_context {
27 struct dev_pagemap *pgmap;
28 unsigned int page_mask;
31 static void hpage_pincount_add(struct page *page, int refs)
33 VM_BUG_ON_PAGE(!hpage_pincount_available(page), page);
34 VM_BUG_ON_PAGE(page != compound_head(page), page);
36 atomic_add(refs, compound_pincount_ptr(page));
39 static void hpage_pincount_sub(struct page *page, int refs)
41 VM_BUG_ON_PAGE(!hpage_pincount_available(page), page);
42 VM_BUG_ON_PAGE(page != compound_head(page), page);
44 atomic_sub(refs, compound_pincount_ptr(page));
47 /* Equivalent to calling put_page() @refs times. */
48 static void put_page_refs(struct page *page, int refs)
50 #ifdef CONFIG_DEBUG_VM
51 if (VM_WARN_ON_ONCE_PAGE(page_ref_count(page) < refs, page))
56 * Calling put_page() for each ref is unnecessarily slow. Only the last
57 * ref needs a put_page().
60 page_ref_sub(page, refs - 1);
65 * Return the compound head page with ref appropriately incremented,
66 * or NULL if that failed.
68 static inline struct page *try_get_compound_head(struct page *page, int refs)
70 struct page *head = compound_head(page);
72 if (WARN_ON_ONCE(page_ref_count(head) < 0))
74 if (unlikely(!page_cache_add_speculative(head, refs)))
78 * At this point we have a stable reference to the head page; but it
79 * could be that between the compound_head() lookup and the refcount
80 * increment, the compound page was split, in which case we'd end up
81 * holding a reference on a page that has nothing to do with the page
82 * we were given anymore.
83 * So now that the head page is stable, recheck that the pages still
86 if (unlikely(compound_head(page) != head)) {
87 put_page_refs(head, refs);
95 * try_grab_compound_head() - attempt to elevate a page's refcount, by a
96 * flags-dependent amount.
98 * "grab" names in this file mean, "look at flags to decide whether to use
99 * FOLL_PIN or FOLL_GET behavior, when incrementing the page's refcount.
101 * Either FOLL_PIN or FOLL_GET (or neither) must be set, but not both at the
102 * same time. (That's true throughout the get_user_pages*() and
103 * pin_user_pages*() APIs.) Cases:
105 * FOLL_GET: page's refcount will be incremented by 1.
106 * FOLL_PIN: page's refcount will be incremented by GUP_PIN_COUNTING_BIAS.
108 * Return: head page (with refcount appropriately incremented) for success, or
109 * NULL upon failure. If neither FOLL_GET nor FOLL_PIN was set, that's
110 * considered failure, and furthermore, a likely bug in the caller, so a warning
113 __maybe_unused struct page *try_grab_compound_head(struct page *page,
114 int refs, unsigned int flags)
116 if (flags & FOLL_GET)
117 return try_get_compound_head(page, refs);
118 else if (flags & FOLL_PIN) {
119 int orig_refs = refs;
122 * Can't do FOLL_LONGTERM + FOLL_PIN gup fast path if not in a
123 * right zone, so fail and let the caller fall back to the slow
126 if (unlikely((flags & FOLL_LONGTERM) &&
127 !is_pinnable_page(page)))
131 * CAUTION: Don't use compound_head() on the page before this
132 * point, the result won't be stable.
134 page = try_get_compound_head(page, refs);
139 * When pinning a compound page of order > 1 (which is what
140 * hpage_pincount_available() checks for), use an exact count to
141 * track it, via hpage_pincount_add/_sub().
143 * However, be sure to *also* increment the normal page refcount
144 * field at least once, so that the page really is pinned.
146 if (hpage_pincount_available(page))
147 hpage_pincount_add(page, refs);
149 page_ref_add(page, refs * (GUP_PIN_COUNTING_BIAS - 1));
151 mod_node_page_state(page_pgdat(page), NR_FOLL_PIN_ACQUIRED,
161 static void put_compound_head(struct page *page, int refs, unsigned int flags)
163 if (flags & FOLL_PIN) {
164 mod_node_page_state(page_pgdat(page), NR_FOLL_PIN_RELEASED,
167 if (hpage_pincount_available(page))
168 hpage_pincount_sub(page, refs);
170 refs *= GUP_PIN_COUNTING_BIAS;
173 put_page_refs(page, refs);
177 * try_grab_page() - elevate a page's refcount by a flag-dependent amount
179 * This might not do anything at all, depending on the flags argument.
181 * "grab" names in this file mean, "look at flags to decide whether to use
182 * FOLL_PIN or FOLL_GET behavior, when incrementing the page's refcount.
184 * @page: pointer to page to be grabbed
185 * @flags: gup flags: these are the FOLL_* flag values.
187 * Either FOLL_PIN or FOLL_GET (or neither) may be set, but not both at the same
190 * FOLL_GET: page's refcount will be incremented by 1.
191 * FOLL_PIN: page's refcount will be incremented by GUP_PIN_COUNTING_BIAS.
193 * Return: true for success, or if no action was required (if neither FOLL_PIN
194 * nor FOLL_GET was set, nothing is done). False for failure: FOLL_GET or
195 * FOLL_PIN was set, but the page could not be grabbed.
197 bool __must_check try_grab_page(struct page *page, unsigned int flags)
199 WARN_ON_ONCE((flags & (FOLL_GET | FOLL_PIN)) == (FOLL_GET | FOLL_PIN));
201 if (flags & FOLL_GET)
202 return try_get_page(page);
203 else if (flags & FOLL_PIN) {
206 page = compound_head(page);
208 if (WARN_ON_ONCE(page_ref_count(page) <= 0))
211 if (hpage_pincount_available(page))
212 hpage_pincount_add(page, 1);
214 refs = GUP_PIN_COUNTING_BIAS;
217 * Similar to try_grab_compound_head(): even if using the
218 * hpage_pincount_add/_sub() routines, be sure to
219 * *also* increment the normal page refcount field at least
220 * once, so that the page really is pinned.
222 page_ref_add(page, refs);
224 mod_node_page_state(page_pgdat(page), NR_FOLL_PIN_ACQUIRED, 1);
231 * unpin_user_page() - release a dma-pinned page
232 * @page: pointer to page to be released
234 * Pages that were pinned via pin_user_pages*() must be released via either
235 * unpin_user_page(), or one of the unpin_user_pages*() routines. This is so
236 * that such pages can be separately tracked and uniquely handled. In
237 * particular, interactions with RDMA and filesystems need special handling.
239 void unpin_user_page(struct page *page)
241 put_compound_head(compound_head(page), 1, FOLL_PIN);
243 EXPORT_SYMBOL(unpin_user_page);
245 static inline void compound_range_next(unsigned long i, unsigned long npages,
246 struct page **list, struct page **head,
247 unsigned int *ntails)
249 struct page *next, *page;
256 page = compound_head(next);
257 if (PageCompound(page) && compound_order(page) >= 1)
258 nr = min_t(unsigned int,
259 page + compound_nr(page) - next, npages - i);
265 #define for_each_compound_range(__i, __list, __npages, __head, __ntails) \
267 compound_range_next(__i, __npages, __list, &(__head), &(__ntails)); \
268 __i < __npages; __i += __ntails, \
269 compound_range_next(__i, __npages, __list, &(__head), &(__ntails)))
271 static inline void compound_next(unsigned long i, unsigned long npages,
272 struct page **list, struct page **head,
273 unsigned int *ntails)
281 page = compound_head(list[i]);
282 for (nr = i + 1; nr < npages; nr++) {
283 if (compound_head(list[nr]) != page)
291 #define for_each_compound_head(__i, __list, __npages, __head, __ntails) \
293 compound_next(__i, __npages, __list, &(__head), &(__ntails)); \
294 __i < __npages; __i += __ntails, \
295 compound_next(__i, __npages, __list, &(__head), &(__ntails)))
298 * unpin_user_pages_dirty_lock() - release and optionally dirty gup-pinned pages
299 * @pages: array of pages to be maybe marked dirty, and definitely released.
300 * @npages: number of pages in the @pages array.
301 * @make_dirty: whether to mark the pages dirty
303 * "gup-pinned page" refers to a page that has had one of the get_user_pages()
304 * variants called on that page.
306 * For each page in the @pages array, make that page (or its head page, if a
307 * compound page) dirty, if @make_dirty is true, and if the page was previously
308 * listed as clean. In any case, releases all pages using unpin_user_page(),
309 * possibly via unpin_user_pages(), for the non-dirty case.
311 * Please see the unpin_user_page() documentation for details.
313 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
314 * required, then the caller should a) verify that this is really correct,
315 * because _lock() is usually required, and b) hand code it:
316 * set_page_dirty_lock(), unpin_user_page().
319 void unpin_user_pages_dirty_lock(struct page **pages, unsigned long npages,
327 unpin_user_pages(pages, npages);
331 for_each_compound_head(index, pages, npages, head, ntails) {
333 * Checking PageDirty at this point may race with
334 * clear_page_dirty_for_io(), but that's OK. Two key
337 * 1) This code sees the page as already dirty, so it
338 * skips the call to set_page_dirty(). That could happen
339 * because clear_page_dirty_for_io() called
340 * page_mkclean(), followed by set_page_dirty().
341 * However, now the page is going to get written back,
342 * which meets the original intention of setting it
343 * dirty, so all is well: clear_page_dirty_for_io() goes
344 * on to call TestClearPageDirty(), and write the page
347 * 2) This code sees the page as clean, so it calls
348 * set_page_dirty(). The page stays dirty, despite being
349 * written back, so it gets written back again in the
350 * next writeback cycle. This is harmless.
352 if (!PageDirty(head))
353 set_page_dirty_lock(head);
354 put_compound_head(head, ntails, FOLL_PIN);
357 EXPORT_SYMBOL(unpin_user_pages_dirty_lock);
360 * unpin_user_page_range_dirty_lock() - release and optionally dirty
361 * gup-pinned page range
363 * @page: the starting page of a range maybe marked dirty, and definitely released.
364 * @npages: number of consecutive pages to release.
365 * @make_dirty: whether to mark the pages dirty
367 * "gup-pinned page range" refers to a range of pages that has had one of the
368 * pin_user_pages() variants called on that page.
370 * For the page ranges defined by [page .. page+npages], make that range (or
371 * its head pages, if a compound page) dirty, if @make_dirty is true, and if the
372 * page range was previously listed as clean.
374 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
375 * required, then the caller should a) verify that this is really correct,
376 * because _lock() is usually required, and b) hand code it:
377 * set_page_dirty_lock(), unpin_user_page().
380 void unpin_user_page_range_dirty_lock(struct page *page, unsigned long npages,
387 for_each_compound_range(index, &page, npages, head, ntails) {
388 if (make_dirty && !PageDirty(head))
389 set_page_dirty_lock(head);
390 put_compound_head(head, ntails, FOLL_PIN);
393 EXPORT_SYMBOL(unpin_user_page_range_dirty_lock);
396 * unpin_user_pages() - release an array of gup-pinned pages.
397 * @pages: array of pages to be marked dirty and released.
398 * @npages: number of pages in the @pages array.
400 * For each page in the @pages array, release the page using unpin_user_page().
402 * Please see the unpin_user_page() documentation for details.
404 void unpin_user_pages(struct page **pages, unsigned long npages)
411 * If this WARN_ON() fires, then the system *might* be leaking pages (by
412 * leaving them pinned), but probably not. More likely, gup/pup returned
413 * a hard -ERRNO error to the caller, who erroneously passed it here.
415 if (WARN_ON(IS_ERR_VALUE(npages)))
418 for_each_compound_head(index, pages, npages, head, ntails)
419 put_compound_head(head, ntails, FOLL_PIN);
421 EXPORT_SYMBOL(unpin_user_pages);
424 static struct page *no_page_table(struct vm_area_struct *vma,
428 * When core dumping an enormous anonymous area that nobody
429 * has touched so far, we don't want to allocate unnecessary pages or
430 * page tables. Return error instead of NULL to skip handle_mm_fault,
431 * then get_dump_page() will return NULL to leave a hole in the dump.
432 * But we can only make this optimization where a hole would surely
433 * be zero-filled if handle_mm_fault() actually did handle it.
435 if ((flags & FOLL_DUMP) &&
436 (vma_is_anonymous(vma) || !vma->vm_ops->fault))
437 return ERR_PTR(-EFAULT);
441 static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
442 pte_t *pte, unsigned int flags)
444 /* No page to get reference */
445 if (flags & FOLL_GET)
448 if (flags & FOLL_TOUCH) {
451 if (flags & FOLL_WRITE)
452 entry = pte_mkdirty(entry);
453 entry = pte_mkyoung(entry);
455 if (!pte_same(*pte, entry)) {
456 set_pte_at(vma->vm_mm, address, pte, entry);
457 update_mmu_cache(vma, address, pte);
461 /* Proper page table entry exists, but no corresponding struct page */
466 * FOLL_FORCE can write to even unwritable pte's, but only
467 * after we've gone through a COW cycle and they are dirty.
469 static inline bool can_follow_write_pte(pte_t pte, unsigned int flags)
471 return pte_write(pte) ||
472 ((flags & FOLL_FORCE) && (flags & FOLL_COW) && pte_dirty(pte));
475 static struct page *follow_page_pte(struct vm_area_struct *vma,
476 unsigned long address, pmd_t *pmd, unsigned int flags,
477 struct dev_pagemap **pgmap)
479 struct mm_struct *mm = vma->vm_mm;
485 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
486 if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
487 (FOLL_PIN | FOLL_GET)))
488 return ERR_PTR(-EINVAL);
490 if (unlikely(pmd_bad(*pmd)))
491 return no_page_table(vma, flags);
493 ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
495 if (!pte_present(pte)) {
498 * KSM's break_ksm() relies upon recognizing a ksm page
499 * even while it is being migrated, so for that case we
500 * need migration_entry_wait().
502 if (likely(!(flags & FOLL_MIGRATION)))
506 entry = pte_to_swp_entry(pte);
507 if (!is_migration_entry(entry))
509 pte_unmap_unlock(ptep, ptl);
510 migration_entry_wait(mm, pmd, address);
513 if ((flags & FOLL_NUMA) && pte_protnone(pte))
515 if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
516 pte_unmap_unlock(ptep, ptl);
520 page = vm_normal_page(vma, address, pte);
521 if (!page && pte_devmap(pte) && (flags & (FOLL_GET | FOLL_PIN))) {
523 * Only return device mapping pages in the FOLL_GET or FOLL_PIN
524 * case since they are only valid while holding the pgmap
527 *pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
529 page = pte_page(pte);
532 } else if (unlikely(!page)) {
533 if (flags & FOLL_DUMP) {
534 /* Avoid special (like zero) pages in core dumps */
535 page = ERR_PTR(-EFAULT);
539 if (is_zero_pfn(pte_pfn(pte))) {
540 page = pte_page(pte);
542 ret = follow_pfn_pte(vma, address, ptep, flags);
548 /* try_grab_page() does nothing unless FOLL_GET or FOLL_PIN is set. */
549 if (unlikely(!try_grab_page(page, flags))) {
550 page = ERR_PTR(-ENOMEM);
554 * We need to make the page accessible if and only if we are going
555 * to access its content (the FOLL_PIN case). Please see
556 * Documentation/core-api/pin_user_pages.rst for details.
558 if (flags & FOLL_PIN) {
559 ret = arch_make_page_accessible(page);
561 unpin_user_page(page);
566 if (flags & FOLL_TOUCH) {
567 if ((flags & FOLL_WRITE) &&
568 !pte_dirty(pte) && !PageDirty(page))
569 set_page_dirty(page);
571 * pte_mkyoung() would be more correct here, but atomic care
572 * is needed to avoid losing the dirty bit: it is easier to use
573 * mark_page_accessed().
575 mark_page_accessed(page);
577 if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
578 /* Do not mlock pte-mapped THP */
579 if (PageTransCompound(page))
583 * The preliminary mapping check is mainly to avoid the
584 * pointless overhead of lock_page on the ZERO_PAGE
585 * which might bounce very badly if there is contention.
587 * If the page is already locked, we don't need to
588 * handle it now - vmscan will handle it later if and
589 * when it attempts to reclaim the page.
591 if (page->mapping && trylock_page(page)) {
592 lru_add_drain(); /* push cached pages to LRU */
594 * Because we lock page here, and migration is
595 * blocked by the pte's page reference, and we
596 * know the page is still mapped, we don't even
597 * need to check for file-cache page truncation.
599 mlock_vma_page(page);
604 pte_unmap_unlock(ptep, ptl);
607 pte_unmap_unlock(ptep, ptl);
610 return no_page_table(vma, flags);
613 static struct page *follow_pmd_mask(struct vm_area_struct *vma,
614 unsigned long address, pud_t *pudp,
616 struct follow_page_context *ctx)
621 struct mm_struct *mm = vma->vm_mm;
623 pmd = pmd_offset(pudp, address);
625 * The READ_ONCE() will stabilize the pmdval in a register or
626 * on the stack so that it will stop changing under the code.
628 pmdval = READ_ONCE(*pmd);
629 if (pmd_none(pmdval))
630 return no_page_table(vma, flags);
631 if (pmd_huge(pmdval) && is_vm_hugetlb_page(vma)) {
632 page = follow_huge_pmd(mm, address, pmd, flags);
635 return no_page_table(vma, flags);
637 if (is_hugepd(__hugepd(pmd_val(pmdval)))) {
638 page = follow_huge_pd(vma, address,
639 __hugepd(pmd_val(pmdval)), flags,
643 return no_page_table(vma, flags);
646 if (!pmd_present(pmdval)) {
647 if (likely(!(flags & FOLL_MIGRATION)))
648 return no_page_table(vma, flags);
649 VM_BUG_ON(thp_migration_supported() &&
650 !is_pmd_migration_entry(pmdval));
651 if (is_pmd_migration_entry(pmdval))
652 pmd_migration_entry_wait(mm, pmd);
653 pmdval = READ_ONCE(*pmd);
655 * MADV_DONTNEED may convert the pmd to null because
656 * mmap_lock is held in read mode
658 if (pmd_none(pmdval))
659 return no_page_table(vma, flags);
662 if (pmd_devmap(pmdval)) {
663 ptl = pmd_lock(mm, pmd);
664 page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
669 if (likely(!pmd_trans_huge(pmdval)))
670 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
672 if ((flags & FOLL_NUMA) && pmd_protnone(pmdval))
673 return no_page_table(vma, flags);
676 ptl = pmd_lock(mm, pmd);
677 if (unlikely(pmd_none(*pmd))) {
679 return no_page_table(vma, flags);
681 if (unlikely(!pmd_present(*pmd))) {
683 if (likely(!(flags & FOLL_MIGRATION)))
684 return no_page_table(vma, flags);
685 pmd_migration_entry_wait(mm, pmd);
688 if (unlikely(!pmd_trans_huge(*pmd))) {
690 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
692 if (flags & FOLL_SPLIT_PMD) {
694 page = pmd_page(*pmd);
695 if (is_huge_zero_page(page)) {
698 split_huge_pmd(vma, pmd, address);
699 if (pmd_trans_unstable(pmd))
703 split_huge_pmd(vma, pmd, address);
704 ret = pte_alloc(mm, pmd) ? -ENOMEM : 0;
707 return ret ? ERR_PTR(ret) :
708 follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
710 page = follow_trans_huge_pmd(vma, address, pmd, flags);
712 ctx->page_mask = HPAGE_PMD_NR - 1;
716 static struct page *follow_pud_mask(struct vm_area_struct *vma,
717 unsigned long address, p4d_t *p4dp,
719 struct follow_page_context *ctx)
724 struct mm_struct *mm = vma->vm_mm;
726 pud = pud_offset(p4dp, address);
728 return no_page_table(vma, flags);
729 if (pud_huge(*pud) && is_vm_hugetlb_page(vma)) {
730 page = follow_huge_pud(mm, address, pud, flags);
733 return no_page_table(vma, flags);
735 if (is_hugepd(__hugepd(pud_val(*pud)))) {
736 page = follow_huge_pd(vma, address,
737 __hugepd(pud_val(*pud)), flags,
741 return no_page_table(vma, flags);
743 if (pud_devmap(*pud)) {
744 ptl = pud_lock(mm, pud);
745 page = follow_devmap_pud(vma, address, pud, flags, &ctx->pgmap);
750 if (unlikely(pud_bad(*pud)))
751 return no_page_table(vma, flags);
753 return follow_pmd_mask(vma, address, pud, flags, ctx);
756 static struct page *follow_p4d_mask(struct vm_area_struct *vma,
757 unsigned long address, pgd_t *pgdp,
759 struct follow_page_context *ctx)
764 p4d = p4d_offset(pgdp, address);
766 return no_page_table(vma, flags);
767 BUILD_BUG_ON(p4d_huge(*p4d));
768 if (unlikely(p4d_bad(*p4d)))
769 return no_page_table(vma, flags);
771 if (is_hugepd(__hugepd(p4d_val(*p4d)))) {
772 page = follow_huge_pd(vma, address,
773 __hugepd(p4d_val(*p4d)), flags,
777 return no_page_table(vma, flags);
779 return follow_pud_mask(vma, address, p4d, flags, ctx);
783 * follow_page_mask - look up a page descriptor from a user-virtual address
784 * @vma: vm_area_struct mapping @address
785 * @address: virtual address to look up
786 * @flags: flags modifying lookup behaviour
787 * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
788 * pointer to output page_mask
790 * @flags can have FOLL_ flags set, defined in <linux/mm.h>
792 * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
793 * the device's dev_pagemap metadata to avoid repeating expensive lookups.
795 * On output, the @ctx->page_mask is set according to the size of the page.
797 * Return: the mapped (struct page *), %NULL if no mapping exists, or
798 * an error pointer if there is a mapping to something not represented
799 * by a page descriptor (see also vm_normal_page()).
801 static struct page *follow_page_mask(struct vm_area_struct *vma,
802 unsigned long address, unsigned int flags,
803 struct follow_page_context *ctx)
807 struct mm_struct *mm = vma->vm_mm;
811 /* make this handle hugepd */
812 page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
814 WARN_ON_ONCE(flags & (FOLL_GET | FOLL_PIN));
818 pgd = pgd_offset(mm, address);
820 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
821 return no_page_table(vma, flags);
823 if (pgd_huge(*pgd)) {
824 page = follow_huge_pgd(mm, address, pgd, flags);
827 return no_page_table(vma, flags);
829 if (is_hugepd(__hugepd(pgd_val(*pgd)))) {
830 page = follow_huge_pd(vma, address,
831 __hugepd(pgd_val(*pgd)), flags,
835 return no_page_table(vma, flags);
838 return follow_p4d_mask(vma, address, pgd, flags, ctx);
841 struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
842 unsigned int foll_flags)
844 struct follow_page_context ctx = { NULL };
847 page = follow_page_mask(vma, address, foll_flags, &ctx);
849 put_dev_pagemap(ctx.pgmap);
853 static int get_gate_page(struct mm_struct *mm, unsigned long address,
854 unsigned int gup_flags, struct vm_area_struct **vma,
864 /* user gate pages are read-only */
865 if (gup_flags & FOLL_WRITE)
867 if (address > TASK_SIZE)
868 pgd = pgd_offset_k(address);
870 pgd = pgd_offset_gate(mm, address);
873 p4d = p4d_offset(pgd, address);
876 pud = pud_offset(p4d, address);
879 pmd = pmd_offset(pud, address);
880 if (!pmd_present(*pmd))
882 VM_BUG_ON(pmd_trans_huge(*pmd));
883 pte = pte_offset_map(pmd, address);
886 *vma = get_gate_vma(mm);
889 *page = vm_normal_page(*vma, address, *pte);
891 if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
893 *page = pte_page(*pte);
895 if (unlikely(!try_grab_page(*page, gup_flags))) {
907 * mmap_lock must be held on entry. If @locked != NULL and *@flags
908 * does not include FOLL_NOWAIT, the mmap_lock may be released. If it
909 * is, *@locked will be set to 0 and -EBUSY returned.
911 static int faultin_page(struct vm_area_struct *vma,
912 unsigned long address, unsigned int *flags, int *locked)
914 unsigned int fault_flags = 0;
917 /* mlock all present pages, but do not fault in new pages */
918 if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)
920 if (*flags & FOLL_WRITE)
921 fault_flags |= FAULT_FLAG_WRITE;
922 if (*flags & FOLL_REMOTE)
923 fault_flags |= FAULT_FLAG_REMOTE;
925 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
926 if (*flags & FOLL_NOWAIT)
927 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
928 if (*flags & FOLL_TRIED) {
930 * Note: FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_TRIED
933 fault_flags |= FAULT_FLAG_TRIED;
936 ret = handle_mm_fault(vma, address, fault_flags, NULL);
937 if (ret & VM_FAULT_ERROR) {
938 int err = vm_fault_to_errno(ret, *flags);
945 if (ret & VM_FAULT_RETRY) {
946 if (locked && !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
952 * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
953 * necessary, even if maybe_mkwrite decided not to set pte_write. We
954 * can thus safely do subsequent page lookups as if they were reads.
955 * But only do so when looping for pte_write is futile: in some cases
956 * userspace may also be wanting to write to the gotten user page,
957 * which a read fault here might prevent (a readonly page might get
958 * reCOWed by userspace write).
960 if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
965 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
967 vm_flags_t vm_flags = vma->vm_flags;
968 int write = (gup_flags & FOLL_WRITE);
969 int foreign = (gup_flags & FOLL_REMOTE);
971 if (vm_flags & (VM_IO | VM_PFNMAP))
974 if (gup_flags & FOLL_ANON && !vma_is_anonymous(vma))
977 if ((gup_flags & FOLL_LONGTERM) && vma_is_fsdax(vma))
981 if (!(vm_flags & VM_WRITE)) {
982 if (!(gup_flags & FOLL_FORCE))
985 * We used to let the write,force case do COW in a
986 * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
987 * set a breakpoint in a read-only mapping of an
988 * executable, without corrupting the file (yet only
989 * when that file had been opened for writing!).
990 * Anon pages in shared mappings are surprising: now
993 if (!is_cow_mapping(vm_flags))
996 } else if (!(vm_flags & VM_READ)) {
997 if (!(gup_flags & FOLL_FORCE))
1000 * Is there actually any vma we can reach here which does not
1001 * have VM_MAYREAD set?
1003 if (!(vm_flags & VM_MAYREAD))
1007 * gups are always data accesses, not instruction
1008 * fetches, so execute=false here
1010 if (!arch_vma_access_permitted(vma, write, false, foreign))
1016 * __get_user_pages() - pin user pages in memory
1017 * @mm: mm_struct of target mm
1018 * @start: starting user address
1019 * @nr_pages: number of pages from start to pin
1020 * @gup_flags: flags modifying pin behaviour
1021 * @pages: array that receives pointers to the pages pinned.
1022 * Should be at least nr_pages long. Or NULL, if caller
1023 * only intends to ensure the pages are faulted in.
1024 * @vmas: array of pointers to vmas corresponding to each page.
1025 * Or NULL if the caller does not require them.
1026 * @locked: whether we're still with the mmap_lock held
1028 * Returns either number of pages pinned (which may be less than the
1029 * number requested), or an error. Details about the return value:
1031 * -- If nr_pages is 0, returns 0.
1032 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
1033 * -- If nr_pages is >0, and some pages were pinned, returns the number of
1034 * pages pinned. Again, this may be less than nr_pages.
1035 * -- 0 return value is possible when the fault would need to be retried.
1037 * The caller is responsible for releasing returned @pages, via put_page().
1039 * @vmas are valid only as long as mmap_lock is held.
1041 * Must be called with mmap_lock held. It may be released. See below.
1043 * __get_user_pages walks a process's page tables and takes a reference to
1044 * each struct page that each user address corresponds to at a given
1045 * instant. That is, it takes the page that would be accessed if a user
1046 * thread accesses the given user virtual address at that instant.
1048 * This does not guarantee that the page exists in the user mappings when
1049 * __get_user_pages returns, and there may even be a completely different
1050 * page there in some cases (eg. if mmapped pagecache has been invalidated
1051 * and subsequently re faulted). However it does guarantee that the page
1052 * won't be freed completely. And mostly callers simply care that the page
1053 * contains data that was valid *at some point in time*. Typically, an IO
1054 * or similar operation cannot guarantee anything stronger anyway because
1055 * locks can't be held over the syscall boundary.
1057 * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
1058 * the page is written to, set_page_dirty (or set_page_dirty_lock, as
1059 * appropriate) must be called after the page is finished with, and
1060 * before put_page is called.
1062 * If @locked != NULL, *@locked will be set to 0 when mmap_lock is
1063 * released by an up_read(). That can happen if @gup_flags does not
1066 * A caller using such a combination of @locked and @gup_flags
1067 * must therefore hold the mmap_lock for reading only, and recognize
1068 * when it's been released. Otherwise, it must be held for either
1069 * reading or writing and will not be released.
1071 * In most cases, get_user_pages or get_user_pages_fast should be used
1072 * instead of __get_user_pages. __get_user_pages should be used only if
1073 * you need some special @gup_flags.
1075 static long __get_user_pages(struct mm_struct *mm,
1076 unsigned long start, unsigned long nr_pages,
1077 unsigned int gup_flags, struct page **pages,
1078 struct vm_area_struct **vmas, int *locked)
1080 long ret = 0, i = 0;
1081 struct vm_area_struct *vma = NULL;
1082 struct follow_page_context ctx = { NULL };
1087 start = untagged_addr(start);
1089 VM_BUG_ON(!!pages != !!(gup_flags & (FOLL_GET | FOLL_PIN)));
1092 * If FOLL_FORCE is set then do not force a full fault as the hinting
1093 * fault information is unrelated to the reference behaviour of a task
1094 * using the address space
1096 if (!(gup_flags & FOLL_FORCE))
1097 gup_flags |= FOLL_NUMA;
1101 unsigned int foll_flags = gup_flags;
1102 unsigned int page_increm;
1104 /* first iteration or cross vma bound */
1105 if (!vma || start >= vma->vm_end) {
1106 vma = find_extend_vma(mm, start);
1107 if (!vma && in_gate_area(mm, start)) {
1108 ret = get_gate_page(mm, start & PAGE_MASK,
1110 pages ? &pages[i] : NULL);
1121 ret = check_vma_flags(vma, gup_flags);
1125 if (is_vm_hugetlb_page(vma)) {
1126 i = follow_hugetlb_page(mm, vma, pages, vmas,
1127 &start, &nr_pages, i,
1129 if (locked && *locked == 0) {
1131 * We've got a VM_FAULT_RETRY
1132 * and we've lost mmap_lock.
1133 * We must stop here.
1135 BUG_ON(gup_flags & FOLL_NOWAIT);
1144 * If we have a pending SIGKILL, don't keep faulting pages and
1145 * potentially allocating memory.
1147 if (fatal_signal_pending(current)) {
1153 page = follow_page_mask(vma, start, foll_flags, &ctx);
1155 ret = faultin_page(vma, start, &foll_flags, locked);
1170 } else if (PTR_ERR(page) == -EEXIST) {
1172 * Proper page table entry exists, but no corresponding
1176 } else if (IS_ERR(page)) {
1177 ret = PTR_ERR(page);
1182 flush_anon_page(vma, page, start);
1183 flush_dcache_page(page);
1191 page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
1192 if (page_increm > nr_pages)
1193 page_increm = nr_pages;
1195 start += page_increm * PAGE_SIZE;
1196 nr_pages -= page_increm;
1200 put_dev_pagemap(ctx.pgmap);
1204 static bool vma_permits_fault(struct vm_area_struct *vma,
1205 unsigned int fault_flags)
1207 bool write = !!(fault_flags & FAULT_FLAG_WRITE);
1208 bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
1209 vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
1211 if (!(vm_flags & vma->vm_flags))
1215 * The architecture might have a hardware protection
1216 * mechanism other than read/write that can deny access.
1218 * gup always represents data access, not instruction
1219 * fetches, so execute=false here:
1221 if (!arch_vma_access_permitted(vma, write, false, foreign))
1228 * fixup_user_fault() - manually resolve a user page fault
1229 * @mm: mm_struct of target mm
1230 * @address: user address
1231 * @fault_flags:flags to pass down to handle_mm_fault()
1232 * @unlocked: did we unlock the mmap_lock while retrying, maybe NULL if caller
1233 * does not allow retry. If NULL, the caller must guarantee
1234 * that fault_flags does not contain FAULT_FLAG_ALLOW_RETRY.
1236 * This is meant to be called in the specific scenario where for locking reasons
1237 * we try to access user memory in atomic context (within a pagefault_disable()
1238 * section), this returns -EFAULT, and we want to resolve the user fault before
1241 * Typically this is meant to be used by the futex code.
1243 * The main difference with get_user_pages() is that this function will
1244 * unconditionally call handle_mm_fault() which will in turn perform all the
1245 * necessary SW fixup of the dirty and young bits in the PTE, while
1246 * get_user_pages() only guarantees to update these in the struct page.
1248 * This is important for some architectures where those bits also gate the
1249 * access permission to the page because they are maintained in software. On
1250 * such architectures, gup() will not be enough to make a subsequent access
1253 * This function will not return with an unlocked mmap_lock. So it has not the
1254 * same semantics wrt the @mm->mmap_lock as does filemap_fault().
1256 int fixup_user_fault(struct mm_struct *mm,
1257 unsigned long address, unsigned int fault_flags,
1260 struct vm_area_struct *vma;
1261 vm_fault_t ret, major = 0;
1263 address = untagged_addr(address);
1266 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1269 vma = find_extend_vma(mm, address);
1270 if (!vma || address < vma->vm_start)
1273 if (!vma_permits_fault(vma, fault_flags))
1276 if ((fault_flags & FAULT_FLAG_KILLABLE) &&
1277 fatal_signal_pending(current))
1280 ret = handle_mm_fault(vma, address, fault_flags, NULL);
1281 major |= ret & VM_FAULT_MAJOR;
1282 if (ret & VM_FAULT_ERROR) {
1283 int err = vm_fault_to_errno(ret, 0);
1290 if (ret & VM_FAULT_RETRY) {
1293 fault_flags |= FAULT_FLAG_TRIED;
1299 EXPORT_SYMBOL_GPL(fixup_user_fault);
1302 * Please note that this function, unlike __get_user_pages will not
1303 * return 0 for nr_pages > 0 without FOLL_NOWAIT
1305 static __always_inline long __get_user_pages_locked(struct mm_struct *mm,
1306 unsigned long start,
1307 unsigned long nr_pages,
1308 struct page **pages,
1309 struct vm_area_struct **vmas,
1313 long ret, pages_done;
1317 /* if VM_FAULT_RETRY can be returned, vmas become invalid */
1319 /* check caller initialized locked */
1320 BUG_ON(*locked != 1);
1323 if (flags & FOLL_PIN)
1324 atomic_set(&mm->has_pinned, 1);
1327 * FOLL_PIN and FOLL_GET are mutually exclusive. Traditional behavior
1328 * is to set FOLL_GET if the caller wants pages[] filled in (but has
1329 * carelessly failed to specify FOLL_GET), so keep doing that, but only
1330 * for FOLL_GET, not for the newer FOLL_PIN.
1332 * FOLL_PIN always expects pages to be non-null, but no need to assert
1333 * that here, as any failures will be obvious enough.
1335 if (pages && !(flags & FOLL_PIN))
1339 lock_dropped = false;
1341 ret = __get_user_pages(mm, start, nr_pages, flags, pages,
1344 /* VM_FAULT_RETRY couldn't trigger, bypass */
1347 /* VM_FAULT_RETRY cannot return errors */
1350 BUG_ON(ret >= nr_pages);
1361 * VM_FAULT_RETRY didn't trigger or it was a
1369 * VM_FAULT_RETRY triggered, so seek to the faulting offset.
1370 * For the prefault case (!pages) we only update counts.
1374 start += ret << PAGE_SHIFT;
1375 lock_dropped = true;
1379 * Repeat on the address that fired VM_FAULT_RETRY
1380 * with both FAULT_FLAG_ALLOW_RETRY and
1381 * FAULT_FLAG_TRIED. Note that GUP can be interrupted
1382 * by fatal signals, so we need to check it before we
1383 * start trying again otherwise it can loop forever.
1386 if (fatal_signal_pending(current)) {
1388 pages_done = -EINTR;
1392 ret = mmap_read_lock_killable(mm);
1401 ret = __get_user_pages(mm, start, 1, flags | FOLL_TRIED,
1402 pages, NULL, locked);
1404 /* Continue to retry until we succeeded */
1422 if (lock_dropped && *locked) {
1424 * We must let the caller know we temporarily dropped the lock
1425 * and so the critical section protected by it was lost.
1427 mmap_read_unlock(mm);
1434 * populate_vma_page_range() - populate a range of pages in the vma.
1436 * @start: start address
1438 * @locked: whether the mmap_lock is still held
1440 * This takes care of mlocking the pages too if VM_LOCKED is set.
1442 * Return either number of pages pinned in the vma, or a negative error
1445 * vma->vm_mm->mmap_lock must be held.
1447 * If @locked is NULL, it may be held for read or write and will
1450 * If @locked is non-NULL, it must held for read only and may be
1451 * released. If it's released, *@locked will be set to 0.
1453 long populate_vma_page_range(struct vm_area_struct *vma,
1454 unsigned long start, unsigned long end, int *locked)
1456 struct mm_struct *mm = vma->vm_mm;
1457 unsigned long nr_pages = (end - start) / PAGE_SIZE;
1460 VM_BUG_ON(start & ~PAGE_MASK);
1461 VM_BUG_ON(end & ~PAGE_MASK);
1462 VM_BUG_ON_VMA(start < vma->vm_start, vma);
1463 VM_BUG_ON_VMA(end > vma->vm_end, vma);
1464 mmap_assert_locked(mm);
1466 gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK;
1467 if (vma->vm_flags & VM_LOCKONFAULT)
1468 gup_flags &= ~FOLL_POPULATE;
1470 * We want to touch writable mappings with a write fault in order
1471 * to break COW, except for shared mappings because these don't COW
1472 * and we would not want to dirty them for nothing.
1474 if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
1475 gup_flags |= FOLL_WRITE;
1478 * We want mlock to succeed for regions that have any permissions
1479 * other than PROT_NONE.
1481 if (vma_is_accessible(vma))
1482 gup_flags |= FOLL_FORCE;
1485 * We made sure addr is within a VMA, so the following will
1486 * not result in a stack expansion that recurses back here.
1488 return __get_user_pages(mm, start, nr_pages, gup_flags,
1489 NULL, NULL, locked);
1493 * __mm_populate - populate and/or mlock pages within a range of address space.
1495 * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
1496 * flags. VMAs must be already marked with the desired vm_flags, and
1497 * mmap_lock must not be held.
1499 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
1501 struct mm_struct *mm = current->mm;
1502 unsigned long end, nstart, nend;
1503 struct vm_area_struct *vma = NULL;
1509 for (nstart = start; nstart < end; nstart = nend) {
1511 * We want to fault in pages for [nstart; end) address range.
1512 * Find first corresponding VMA.
1517 vma = find_vma(mm, nstart);
1518 } else if (nstart >= vma->vm_end)
1520 if (!vma || vma->vm_start >= end)
1523 * Set [nstart; nend) to intersection of desired address
1524 * range with the first VMA. Also, skip undesirable VMA types.
1526 nend = min(end, vma->vm_end);
1527 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1529 if (nstart < vma->vm_start)
1530 nstart = vma->vm_start;
1532 * Now fault in a range of pages. populate_vma_page_range()
1533 * double checks the vma flags, so that it won't mlock pages
1534 * if the vma was already munlocked.
1536 ret = populate_vma_page_range(vma, nstart, nend, &locked);
1538 if (ignore_errors) {
1540 continue; /* continue at next VMA */
1544 nend = nstart + ret * PAGE_SIZE;
1548 mmap_read_unlock(mm);
1549 return ret; /* 0 or negative error code */
1551 #else /* CONFIG_MMU */
1552 static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start,
1553 unsigned long nr_pages, struct page **pages,
1554 struct vm_area_struct **vmas, int *locked,
1555 unsigned int foll_flags)
1557 struct vm_area_struct *vma;
1558 unsigned long vm_flags;
1561 /* calculate required read or write permissions.
1562 * If FOLL_FORCE is set, we only require the "MAY" flags.
1564 vm_flags = (foll_flags & FOLL_WRITE) ?
1565 (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
1566 vm_flags &= (foll_flags & FOLL_FORCE) ?
1567 (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
1569 for (i = 0; i < nr_pages; i++) {
1570 vma = find_vma(mm, start);
1572 goto finish_or_fault;
1574 /* protect what we can, including chardevs */
1575 if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
1576 !(vm_flags & vma->vm_flags))
1577 goto finish_or_fault;
1580 pages[i] = virt_to_page(start);
1586 start = (start + PAGE_SIZE) & PAGE_MASK;
1592 return i ? : -EFAULT;
1594 #endif /* !CONFIG_MMU */
1597 * get_dump_page() - pin user page in memory while writing it to core dump
1598 * @addr: user address
1600 * Returns struct page pointer of user page pinned for dump,
1601 * to be freed afterwards by put_page().
1603 * Returns NULL on any kind of failure - a hole must then be inserted into
1604 * the corefile, to preserve alignment with its headers; and also returns
1605 * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
1606 * allowing a hole to be left in the corefile to save disk space.
1608 * Called without mmap_lock (takes and releases the mmap_lock by itself).
1610 #ifdef CONFIG_ELF_CORE
1611 struct page *get_dump_page(unsigned long addr)
1613 struct mm_struct *mm = current->mm;
1618 if (mmap_read_lock_killable(mm))
1620 ret = __get_user_pages_locked(mm, addr, 1, &page, NULL, &locked,
1621 FOLL_FORCE | FOLL_DUMP | FOLL_GET);
1623 mmap_read_unlock(mm);
1624 return (ret == 1) ? page : NULL;
1626 #endif /* CONFIG_ELF_CORE */
1628 #ifdef CONFIG_MIGRATION
1630 * Check whether all pages are pinnable, if so return number of pages. If some
1631 * pages are not pinnable, migrate them, and unpin all pages. Return zero if
1632 * pages were migrated, or if some pages were not successfully isolated.
1633 * Return negative error if migration fails.
1635 static long check_and_migrate_movable_pages(unsigned long nr_pages,
1636 struct page **pages,
1637 unsigned int gup_flags)
1640 unsigned long isolation_error_count = 0;
1641 bool drain_allow = true;
1642 LIST_HEAD(movable_page_list);
1644 struct page *prev_head = NULL;
1646 struct migration_target_control mtc = {
1647 .nid = NUMA_NO_NODE,
1648 .gfp_mask = GFP_USER | __GFP_NOWARN,
1651 for (i = 0; i < nr_pages; i++) {
1652 head = compound_head(pages[i]);
1653 if (head == prev_head)
1657 * If we get a movable page, since we are going to be pinning
1658 * these entries, try to move them out if possible.
1660 if (!is_pinnable_page(head)) {
1661 if (PageHuge(head)) {
1662 if (!isolate_huge_page(head, &movable_page_list))
1663 isolation_error_count++;
1665 if (!PageLRU(head) && drain_allow) {
1666 lru_add_drain_all();
1667 drain_allow = false;
1670 if (isolate_lru_page(head)) {
1671 isolation_error_count++;
1674 list_add_tail(&head->lru, &movable_page_list);
1675 mod_node_page_state(page_pgdat(head),
1677 page_is_file_lru(head),
1678 thp_nr_pages(head));
1684 * If list is empty, and no isolation errors, means that all pages are
1685 * in the correct zone.
1687 if (list_empty(&movable_page_list) && !isolation_error_count)
1690 if (gup_flags & FOLL_PIN) {
1691 unpin_user_pages(pages, nr_pages);
1693 for (i = 0; i < nr_pages; i++)
1696 if (!list_empty(&movable_page_list)) {
1697 ret = migrate_pages(&movable_page_list, alloc_migration_target,
1698 NULL, (unsigned long)&mtc, MIGRATE_SYNC,
1700 if (ret && !list_empty(&movable_page_list))
1701 putback_movable_pages(&movable_page_list);
1704 return ret > 0 ? -ENOMEM : ret;
1707 static long check_and_migrate_movable_pages(unsigned long nr_pages,
1708 struct page **pages,
1709 unsigned int gup_flags)
1713 #endif /* CONFIG_MIGRATION */
1716 * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
1717 * allows us to process the FOLL_LONGTERM flag.
1719 static long __gup_longterm_locked(struct mm_struct *mm,
1720 unsigned long start,
1721 unsigned long nr_pages,
1722 struct page **pages,
1723 struct vm_area_struct **vmas,
1724 unsigned int gup_flags)
1729 if (!(gup_flags & FOLL_LONGTERM))
1730 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1732 flags = memalloc_pin_save();
1734 rc = __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1738 rc = check_and_migrate_movable_pages(rc, pages, gup_flags);
1740 memalloc_pin_restore(flags);
1745 static bool is_valid_gup_flags(unsigned int gup_flags)
1748 * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
1749 * never directly by the caller, so enforce that with an assertion:
1751 if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
1754 * FOLL_PIN is a prerequisite to FOLL_LONGTERM. Another way of saying
1755 * that is, FOLL_LONGTERM is a specific case, more restrictive case of
1758 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1765 static long __get_user_pages_remote(struct mm_struct *mm,
1766 unsigned long start, unsigned long nr_pages,
1767 unsigned int gup_flags, struct page **pages,
1768 struct vm_area_struct **vmas, int *locked)
1771 * Parts of FOLL_LONGTERM behavior are incompatible with
1772 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1773 * vmas. However, this only comes up if locked is set, and there are
1774 * callers that do request FOLL_LONGTERM, but do not set locked. So,
1775 * allow what we can.
1777 if (gup_flags & FOLL_LONGTERM) {
1778 if (WARN_ON_ONCE(locked))
1781 * This will check the vmas (even if our vmas arg is NULL)
1782 * and return -ENOTSUPP if DAX isn't allowed in this case:
1784 return __gup_longterm_locked(mm, start, nr_pages, pages,
1785 vmas, gup_flags | FOLL_TOUCH |
1789 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1791 gup_flags | FOLL_TOUCH | FOLL_REMOTE);
1795 * get_user_pages_remote() - pin user pages in memory
1796 * @mm: mm_struct of target mm
1797 * @start: starting user address
1798 * @nr_pages: number of pages from start to pin
1799 * @gup_flags: flags modifying lookup behaviour
1800 * @pages: array that receives pointers to the pages pinned.
1801 * Should be at least nr_pages long. Or NULL, if caller
1802 * only intends to ensure the pages are faulted in.
1803 * @vmas: array of pointers to vmas corresponding to each page.
1804 * Or NULL if the caller does not require them.
1805 * @locked: pointer to lock flag indicating whether lock is held and
1806 * subsequently whether VM_FAULT_RETRY functionality can be
1807 * utilised. Lock must initially be held.
1809 * Returns either number of pages pinned (which may be less than the
1810 * number requested), or an error. Details about the return value:
1812 * -- If nr_pages is 0, returns 0.
1813 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
1814 * -- If nr_pages is >0, and some pages were pinned, returns the number of
1815 * pages pinned. Again, this may be less than nr_pages.
1817 * The caller is responsible for releasing returned @pages, via put_page().
1819 * @vmas are valid only as long as mmap_lock is held.
1821 * Must be called with mmap_lock held for read or write.
1823 * get_user_pages_remote walks a process's page tables and takes a reference
1824 * to each struct page that each user address corresponds to at a given
1825 * instant. That is, it takes the page that would be accessed if a user
1826 * thread accesses the given user virtual address at that instant.
1828 * This does not guarantee that the page exists in the user mappings when
1829 * get_user_pages_remote returns, and there may even be a completely different
1830 * page there in some cases (eg. if mmapped pagecache has been invalidated
1831 * and subsequently re faulted). However it does guarantee that the page
1832 * won't be freed completely. And mostly callers simply care that the page
1833 * contains data that was valid *at some point in time*. Typically, an IO
1834 * or similar operation cannot guarantee anything stronger anyway because
1835 * locks can't be held over the syscall boundary.
1837 * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
1838 * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
1839 * be called after the page is finished with, and before put_page is called.
1841 * get_user_pages_remote is typically used for fewer-copy IO operations,
1842 * to get a handle on the memory by some means other than accesses
1843 * via the user virtual addresses. The pages may be submitted for
1844 * DMA to devices or accessed via their kernel linear mapping (via the
1845 * kmap APIs). Care should be taken to use the correct cache flushing APIs.
1847 * See also get_user_pages_fast, for performance critical applications.
1849 * get_user_pages_remote should be phased out in favor of
1850 * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
1851 * should use get_user_pages_remote because it cannot pass
1852 * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
1854 long get_user_pages_remote(struct mm_struct *mm,
1855 unsigned long start, unsigned long nr_pages,
1856 unsigned int gup_flags, struct page **pages,
1857 struct vm_area_struct **vmas, int *locked)
1859 if (!is_valid_gup_flags(gup_flags))
1862 return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
1863 pages, vmas, locked);
1865 EXPORT_SYMBOL(get_user_pages_remote);
1867 #else /* CONFIG_MMU */
1868 long get_user_pages_remote(struct mm_struct *mm,
1869 unsigned long start, unsigned long nr_pages,
1870 unsigned int gup_flags, struct page **pages,
1871 struct vm_area_struct **vmas, int *locked)
1876 static long __get_user_pages_remote(struct mm_struct *mm,
1877 unsigned long start, unsigned long nr_pages,
1878 unsigned int gup_flags, struct page **pages,
1879 struct vm_area_struct **vmas, int *locked)
1883 #endif /* !CONFIG_MMU */
1886 * get_user_pages() - pin user pages in memory
1887 * @start: starting user address
1888 * @nr_pages: number of pages from start to pin
1889 * @gup_flags: flags modifying lookup behaviour
1890 * @pages: array that receives pointers to the pages pinned.
1891 * Should be at least nr_pages long. Or NULL, if caller
1892 * only intends to ensure the pages are faulted in.
1893 * @vmas: array of pointers to vmas corresponding to each page.
1894 * Or NULL if the caller does not require them.
1896 * This is the same as get_user_pages_remote(), just with a less-flexible
1897 * calling convention where we assume that the mm being operated on belongs to
1898 * the current task, and doesn't allow passing of a locked parameter. We also
1899 * obviously don't pass FOLL_REMOTE in here.
1901 long get_user_pages(unsigned long start, unsigned long nr_pages,
1902 unsigned int gup_flags, struct page **pages,
1903 struct vm_area_struct **vmas)
1905 if (!is_valid_gup_flags(gup_flags))
1908 return __gup_longterm_locked(current->mm, start, nr_pages,
1909 pages, vmas, gup_flags | FOLL_TOUCH);
1911 EXPORT_SYMBOL(get_user_pages);
1914 * get_user_pages_locked() - variant of get_user_pages()
1916 * @start: starting user address
1917 * @nr_pages: number of pages from start to pin
1918 * @gup_flags: flags modifying lookup behaviour
1919 * @pages: array that receives pointers to the pages pinned.
1920 * Should be at least nr_pages long. Or NULL, if caller
1921 * only intends to ensure the pages are faulted in.
1922 * @locked: pointer to lock flag indicating whether lock is held and
1923 * subsequently whether VM_FAULT_RETRY functionality can be
1924 * utilised. Lock must initially be held.
1926 * It is suitable to replace the form:
1928 * mmap_read_lock(mm);
1930 * get_user_pages(mm, ..., pages, NULL);
1931 * mmap_read_unlock(mm);
1936 * mmap_read_lock(mm);
1938 * get_user_pages_locked(mm, ..., pages, &locked);
1940 * mmap_read_unlock(mm);
1942 * We can leverage the VM_FAULT_RETRY functionality in the page fault
1943 * paths better by using either get_user_pages_locked() or
1944 * get_user_pages_unlocked().
1947 long get_user_pages_locked(unsigned long start, unsigned long nr_pages,
1948 unsigned int gup_flags, struct page **pages,
1952 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
1953 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1954 * vmas. As there are no users of this flag in this call we simply
1955 * disallow this option for now.
1957 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1960 * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
1961 * never directly by the caller, so enforce that:
1963 if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
1966 return __get_user_pages_locked(current->mm, start, nr_pages,
1967 pages, NULL, locked,
1968 gup_flags | FOLL_TOUCH);
1970 EXPORT_SYMBOL(get_user_pages_locked);
1973 * get_user_pages_unlocked() is suitable to replace the form:
1975 * mmap_read_lock(mm);
1976 * get_user_pages(mm, ..., pages, NULL);
1977 * mmap_read_unlock(mm);
1981 * get_user_pages_unlocked(mm, ..., pages);
1983 * It is functionally equivalent to get_user_pages_fast so
1984 * get_user_pages_fast should be used instead if specific gup_flags
1985 * (e.g. FOLL_FORCE) are not required.
1987 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
1988 struct page **pages, unsigned int gup_flags)
1990 struct mm_struct *mm = current->mm;
1995 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
1996 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1997 * vmas. As there are no users of this flag in this call we simply
1998 * disallow this option for now.
2000 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
2004 ret = __get_user_pages_locked(mm, start, nr_pages, pages, NULL,
2005 &locked, gup_flags | FOLL_TOUCH);
2007 mmap_read_unlock(mm);
2010 EXPORT_SYMBOL(get_user_pages_unlocked);
2015 * get_user_pages_fast attempts to pin user pages by walking the page
2016 * tables directly and avoids taking locks. Thus the walker needs to be
2017 * protected from page table pages being freed from under it, and should
2018 * block any THP splits.
2020 * One way to achieve this is to have the walker disable interrupts, and
2021 * rely on IPIs from the TLB flushing code blocking before the page table
2022 * pages are freed. This is unsuitable for architectures that do not need
2023 * to broadcast an IPI when invalidating TLBs.
2025 * Another way to achieve this is to batch up page table containing pages
2026 * belonging to more than one mm_user, then rcu_sched a callback to free those
2027 * pages. Disabling interrupts will allow the fast_gup walker to both block
2028 * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
2029 * (which is a relatively rare event). The code below adopts this strategy.
2031 * Before activating this code, please be aware that the following assumptions
2032 * are currently made:
2034 * *) Either MMU_GATHER_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
2035 * free pages containing page tables or TLB flushing requires IPI broadcast.
2037 * *) ptes can be read atomically by the architecture.
2039 * *) access_ok is sufficient to validate userspace address ranges.
2041 * The last two assumptions can be relaxed by the addition of helper functions.
2043 * This code is based heavily on the PowerPC implementation by Nick Piggin.
2045 #ifdef CONFIG_HAVE_FAST_GUP
2047 static void __maybe_unused undo_dev_pagemap(int *nr, int nr_start,
2049 struct page **pages)
2051 while ((*nr) - nr_start) {
2052 struct page *page = pages[--(*nr)];
2054 ClearPageReferenced(page);
2055 if (flags & FOLL_PIN)
2056 unpin_user_page(page);
2062 #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
2063 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2064 unsigned int flags, struct page **pages, int *nr)
2066 struct dev_pagemap *pgmap = NULL;
2067 int nr_start = *nr, ret = 0;
2070 ptem = ptep = pte_offset_map(&pmd, addr);
2072 pte_t pte = ptep_get_lockless(ptep);
2073 struct page *head, *page;
2076 * Similar to the PMD case below, NUMA hinting must take slow
2077 * path using the pte_protnone check.
2079 if (pte_protnone(pte))
2082 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2085 if (pte_devmap(pte)) {
2086 if (unlikely(flags & FOLL_LONGTERM))
2089 pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
2090 if (unlikely(!pgmap)) {
2091 undo_dev_pagemap(nr, nr_start, flags, pages);
2094 } else if (pte_special(pte))
2097 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2098 page = pte_page(pte);
2100 head = try_grab_compound_head(page, 1, flags);
2104 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2105 put_compound_head(head, 1, flags);
2109 VM_BUG_ON_PAGE(compound_head(page) != head, page);
2112 * We need to make the page accessible if and only if we are
2113 * going to access its content (the FOLL_PIN case). Please
2114 * see Documentation/core-api/pin_user_pages.rst for
2117 if (flags & FOLL_PIN) {
2118 ret = arch_make_page_accessible(page);
2120 unpin_user_page(page);
2124 SetPageReferenced(page);
2128 } while (ptep++, addr += PAGE_SIZE, addr != end);
2134 put_dev_pagemap(pgmap);
2141 * If we can't determine whether or not a pte is special, then fail immediately
2142 * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
2145 * For a futex to be placed on a THP tail page, get_futex_key requires a
2146 * get_user_pages_fast_only implementation that can pin pages. Thus it's still
2147 * useful to have gup_huge_pmd even if we can't operate on ptes.
2149 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2150 unsigned int flags, struct page **pages, int *nr)
2154 #endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
2156 #if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
2157 static int __gup_device_huge(unsigned long pfn, unsigned long addr,
2158 unsigned long end, unsigned int flags,
2159 struct page **pages, int *nr)
2162 struct dev_pagemap *pgmap = NULL;
2165 struct page *page = pfn_to_page(pfn);
2167 pgmap = get_dev_pagemap(pfn, pgmap);
2168 if (unlikely(!pgmap)) {
2169 undo_dev_pagemap(nr, nr_start, flags, pages);
2172 SetPageReferenced(page);
2174 if (unlikely(!try_grab_page(page, flags))) {
2175 undo_dev_pagemap(nr, nr_start, flags, pages);
2180 } while (addr += PAGE_SIZE, addr != end);
2183 put_dev_pagemap(pgmap);
2187 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2188 unsigned long end, unsigned int flags,
2189 struct page **pages, int *nr)
2191 unsigned long fault_pfn;
2194 fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2195 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2198 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2199 undo_dev_pagemap(nr, nr_start, flags, pages);
2205 static int __gup_device_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2206 unsigned long end, unsigned int flags,
2207 struct page **pages, int *nr)
2209 unsigned long fault_pfn;
2212 fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2213 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2216 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2217 undo_dev_pagemap(nr, nr_start, flags, pages);
2223 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2224 unsigned long end, unsigned int flags,
2225 struct page **pages, int *nr)
2231 static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr,
2232 unsigned long end, unsigned int flags,
2233 struct page **pages, int *nr)
2240 static int record_subpages(struct page *page, unsigned long addr,
2241 unsigned long end, struct page **pages)
2245 for (nr = 0; addr != end; addr += PAGE_SIZE)
2246 pages[nr++] = page++;
2251 #ifdef CONFIG_ARCH_HAS_HUGEPD
2252 static unsigned long hugepte_addr_end(unsigned long addr, unsigned long end,
2255 unsigned long __boundary = (addr + sz) & ~(sz-1);
2256 return (__boundary - 1 < end - 1) ? __boundary : end;
2259 static int gup_hugepte(pte_t *ptep, unsigned long sz, unsigned long addr,
2260 unsigned long end, unsigned int flags,
2261 struct page **pages, int *nr)
2263 unsigned long pte_end;
2264 struct page *head, *page;
2268 pte_end = (addr + sz) & ~(sz-1);
2272 pte = huge_ptep_get(ptep);
2274 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2277 /* hugepages are never "special" */
2278 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2280 head = pte_page(pte);
2281 page = head + ((addr & (sz-1)) >> PAGE_SHIFT);
2282 refs = record_subpages(page, addr, end, pages + *nr);
2284 head = try_grab_compound_head(head, refs, flags);
2288 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2289 put_compound_head(head, refs, flags);
2294 SetPageReferenced(head);
2298 static int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2299 unsigned int pdshift, unsigned long end, unsigned int flags,
2300 struct page **pages, int *nr)
2303 unsigned long sz = 1UL << hugepd_shift(hugepd);
2306 ptep = hugepte_offset(hugepd, addr, pdshift);
2308 next = hugepte_addr_end(addr, end, sz);
2309 if (!gup_hugepte(ptep, sz, addr, end, flags, pages, nr))
2311 } while (ptep++, addr = next, addr != end);
2316 static inline int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2317 unsigned int pdshift, unsigned long end, unsigned int flags,
2318 struct page **pages, int *nr)
2322 #endif /* CONFIG_ARCH_HAS_HUGEPD */
2324 static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2325 unsigned long end, unsigned int flags,
2326 struct page **pages, int *nr)
2328 struct page *head, *page;
2331 if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
2334 if (pmd_devmap(orig)) {
2335 if (unlikely(flags & FOLL_LONGTERM))
2337 return __gup_device_huge_pmd(orig, pmdp, addr, end, flags,
2341 page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2342 refs = record_subpages(page, addr, end, pages + *nr);
2344 head = try_grab_compound_head(pmd_page(orig), refs, flags);
2348 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2349 put_compound_head(head, refs, flags);
2354 SetPageReferenced(head);
2358 static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2359 unsigned long end, unsigned int flags,
2360 struct page **pages, int *nr)
2362 struct page *head, *page;
2365 if (!pud_access_permitted(orig, flags & FOLL_WRITE))
2368 if (pud_devmap(orig)) {
2369 if (unlikely(flags & FOLL_LONGTERM))
2371 return __gup_device_huge_pud(orig, pudp, addr, end, flags,
2375 page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2376 refs = record_subpages(page, addr, end, pages + *nr);
2378 head = try_grab_compound_head(pud_page(orig), refs, flags);
2382 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2383 put_compound_head(head, refs, flags);
2388 SetPageReferenced(head);
2392 static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
2393 unsigned long end, unsigned int flags,
2394 struct page **pages, int *nr)
2397 struct page *head, *page;
2399 if (!pgd_access_permitted(orig, flags & FOLL_WRITE))
2402 BUILD_BUG_ON(pgd_devmap(orig));
2404 page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT);
2405 refs = record_subpages(page, addr, end, pages + *nr);
2407 head = try_grab_compound_head(pgd_page(orig), refs, flags);
2411 if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
2412 put_compound_head(head, refs, flags);
2417 SetPageReferenced(head);
2421 static int gup_pmd_range(pud_t *pudp, pud_t pud, unsigned long addr, unsigned long end,
2422 unsigned int flags, struct page **pages, int *nr)
2427 pmdp = pmd_offset_lockless(pudp, pud, addr);
2429 pmd_t pmd = READ_ONCE(*pmdp);
2431 next = pmd_addr_end(addr, end);
2432 if (!pmd_present(pmd))
2435 if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd) ||
2438 * NUMA hinting faults need to be handled in the GUP
2439 * slowpath for accounting purposes and so that they
2440 * can be serialised against THP migration.
2442 if (pmd_protnone(pmd))
2445 if (!gup_huge_pmd(pmd, pmdp, addr, next, flags,
2449 } else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
2451 * architecture have different format for hugetlbfs
2452 * pmd format and THP pmd format
2454 if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
2455 PMD_SHIFT, next, flags, pages, nr))
2457 } else if (!gup_pte_range(pmd, addr, next, flags, pages, nr))
2459 } while (pmdp++, addr = next, addr != end);
2464 static int gup_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr, unsigned long end,
2465 unsigned int flags, struct page **pages, int *nr)
2470 pudp = pud_offset_lockless(p4dp, p4d, addr);
2472 pud_t pud = READ_ONCE(*pudp);
2474 next = pud_addr_end(addr, end);
2475 if (unlikely(!pud_present(pud)))
2477 if (unlikely(pud_huge(pud))) {
2478 if (!gup_huge_pud(pud, pudp, addr, next, flags,
2481 } else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
2482 if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
2483 PUD_SHIFT, next, flags, pages, nr))
2485 } else if (!gup_pmd_range(pudp, pud, addr, next, flags, pages, nr))
2487 } while (pudp++, addr = next, addr != end);
2492 static int gup_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr, unsigned long end,
2493 unsigned int flags, struct page **pages, int *nr)
2498 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
2500 p4d_t p4d = READ_ONCE(*p4dp);
2502 next = p4d_addr_end(addr, end);
2505 BUILD_BUG_ON(p4d_huge(p4d));
2506 if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
2507 if (!gup_huge_pd(__hugepd(p4d_val(p4d)), addr,
2508 P4D_SHIFT, next, flags, pages, nr))
2510 } else if (!gup_pud_range(p4dp, p4d, addr, next, flags, pages, nr))
2512 } while (p4dp++, addr = next, addr != end);
2517 static void gup_pgd_range(unsigned long addr, unsigned long end,
2518 unsigned int flags, struct page **pages, int *nr)
2523 pgdp = pgd_offset(current->mm, addr);
2525 pgd_t pgd = READ_ONCE(*pgdp);
2527 next = pgd_addr_end(addr, end);
2530 if (unlikely(pgd_huge(pgd))) {
2531 if (!gup_huge_pgd(pgd, pgdp, addr, next, flags,
2534 } else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
2535 if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
2536 PGDIR_SHIFT, next, flags, pages, nr))
2538 } else if (!gup_p4d_range(pgdp, pgd, addr, next, flags, pages, nr))
2540 } while (pgdp++, addr = next, addr != end);
2543 static inline void gup_pgd_range(unsigned long addr, unsigned long end,
2544 unsigned int flags, struct page **pages, int *nr)
2547 #endif /* CONFIG_HAVE_FAST_GUP */
2549 #ifndef gup_fast_permitted
2551 * Check if it's allowed to use get_user_pages_fast_only() for the range, or
2552 * we need to fall back to the slow version:
2554 static bool gup_fast_permitted(unsigned long start, unsigned long end)
2560 static int __gup_longterm_unlocked(unsigned long start, int nr_pages,
2561 unsigned int gup_flags, struct page **pages)
2566 * FIXME: FOLL_LONGTERM does not work with
2567 * get_user_pages_unlocked() (see comments in that function)
2569 if (gup_flags & FOLL_LONGTERM) {
2570 mmap_read_lock(current->mm);
2571 ret = __gup_longterm_locked(current->mm,
2573 pages, NULL, gup_flags);
2574 mmap_read_unlock(current->mm);
2576 ret = get_user_pages_unlocked(start, nr_pages,
2583 static unsigned long lockless_pages_from_mm(unsigned long start,
2585 unsigned int gup_flags,
2586 struct page **pages)
2588 unsigned long flags;
2592 if (!IS_ENABLED(CONFIG_HAVE_FAST_GUP) ||
2593 !gup_fast_permitted(start, end))
2596 if (gup_flags & FOLL_PIN) {
2597 seq = raw_read_seqcount(¤t->mm->write_protect_seq);
2603 * Disable interrupts. The nested form is used, in order to allow full,
2604 * general purpose use of this routine.
2606 * With interrupts disabled, we block page table pages from being freed
2607 * from under us. See struct mmu_table_batch comments in
2608 * include/asm-generic/tlb.h for more details.
2610 * We do not adopt an rcu_read_lock() here as we also want to block IPIs
2611 * that come from THPs splitting.
2613 local_irq_save(flags);
2614 gup_pgd_range(start, end, gup_flags, pages, &nr_pinned);
2615 local_irq_restore(flags);
2618 * When pinning pages for DMA there could be a concurrent write protect
2619 * from fork() via copy_page_range(), in this case always fail fast GUP.
2621 if (gup_flags & FOLL_PIN) {
2622 if (read_seqcount_retry(¤t->mm->write_protect_seq, seq)) {
2623 unpin_user_pages(pages, nr_pinned);
2630 static int internal_get_user_pages_fast(unsigned long start,
2631 unsigned long nr_pages,
2632 unsigned int gup_flags,
2633 struct page **pages)
2635 unsigned long len, end;
2636 unsigned long nr_pinned;
2639 if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM |
2640 FOLL_FORCE | FOLL_PIN | FOLL_GET |
2644 if (gup_flags & FOLL_PIN)
2645 atomic_set(¤t->mm->has_pinned, 1);
2647 if (!(gup_flags & FOLL_FAST_ONLY))
2648 might_lock_read(¤t->mm->mmap_lock);
2650 start = untagged_addr(start) & PAGE_MASK;
2651 len = nr_pages << PAGE_SHIFT;
2652 if (check_add_overflow(start, len, &end))
2654 if (unlikely(!access_ok((void __user *)start, len)))
2657 nr_pinned = lockless_pages_from_mm(start, end, gup_flags, pages);
2658 if (nr_pinned == nr_pages || gup_flags & FOLL_FAST_ONLY)
2661 /* Slow path: try to get the remaining pages with get_user_pages */
2662 start += nr_pinned << PAGE_SHIFT;
2664 ret = __gup_longterm_unlocked(start, nr_pages - nr_pinned, gup_flags,
2668 * The caller has to unpin the pages we already pinned so
2669 * returning -errno is not an option
2675 return ret + nr_pinned;
2679 * get_user_pages_fast_only() - pin user pages in memory
2680 * @start: starting user address
2681 * @nr_pages: number of pages from start to pin
2682 * @gup_flags: flags modifying pin behaviour
2683 * @pages: array that receives pointers to the pages pinned.
2684 * Should be at least nr_pages long.
2686 * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
2688 * Note a difference with get_user_pages_fast: this always returns the
2689 * number of pages pinned, 0 if no pages were pinned.
2691 * If the architecture does not support this function, simply return with no
2694 * Careful, careful! COW breaking can go either way, so a non-write
2695 * access can get ambiguous page results. If you call this function without
2696 * 'write' set, you'd better be sure that you're ok with that ambiguity.
2698 int get_user_pages_fast_only(unsigned long start, int nr_pages,
2699 unsigned int gup_flags, struct page **pages)
2703 * Internally (within mm/gup.c), gup fast variants must set FOLL_GET,
2704 * because gup fast is always a "pin with a +1 page refcount" request.
2706 * FOLL_FAST_ONLY is required in order to match the API description of
2707 * this routine: no fall back to regular ("slow") GUP.
2709 gup_flags |= FOLL_GET | FOLL_FAST_ONLY;
2711 nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
2715 * As specified in the API description above, this routine is not
2716 * allowed to return negative values. However, the common core
2717 * routine internal_get_user_pages_fast() *can* return -errno.
2718 * Therefore, correct for that here:
2725 EXPORT_SYMBOL_GPL(get_user_pages_fast_only);
2728 * get_user_pages_fast() - pin user pages in memory
2729 * @start: starting user address
2730 * @nr_pages: number of pages from start to pin
2731 * @gup_flags: flags modifying pin behaviour
2732 * @pages: array that receives pointers to the pages pinned.
2733 * Should be at least nr_pages long.
2735 * Attempt to pin user pages in memory without taking mm->mmap_lock.
2736 * If not successful, it will fall back to taking the lock and
2737 * calling get_user_pages().
2739 * Returns number of pages pinned. This may be fewer than the number requested.
2740 * If nr_pages is 0 or negative, returns 0. If no pages were pinned, returns
2743 int get_user_pages_fast(unsigned long start, int nr_pages,
2744 unsigned int gup_flags, struct page **pages)
2746 if (!is_valid_gup_flags(gup_flags))
2750 * The caller may or may not have explicitly set FOLL_GET; either way is
2751 * OK. However, internally (within mm/gup.c), gup fast variants must set
2752 * FOLL_GET, because gup fast is always a "pin with a +1 page refcount"
2755 gup_flags |= FOLL_GET;
2756 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
2758 EXPORT_SYMBOL_GPL(get_user_pages_fast);
2761 * pin_user_pages_fast() - pin user pages in memory without taking locks
2763 * @start: starting user address
2764 * @nr_pages: number of pages from start to pin
2765 * @gup_flags: flags modifying pin behaviour
2766 * @pages: array that receives pointers to the pages pinned.
2767 * Should be at least nr_pages long.
2769 * Nearly the same as get_user_pages_fast(), except that FOLL_PIN is set. See
2770 * get_user_pages_fast() for documentation on the function arguments, because
2771 * the arguments here are identical.
2773 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
2774 * see Documentation/core-api/pin_user_pages.rst for further details.
2776 int pin_user_pages_fast(unsigned long start, int nr_pages,
2777 unsigned int gup_flags, struct page **pages)
2779 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2780 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2783 gup_flags |= FOLL_PIN;
2784 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
2786 EXPORT_SYMBOL_GPL(pin_user_pages_fast);
2789 * This is the FOLL_PIN equivalent of get_user_pages_fast_only(). Behavior
2790 * is the same, except that this one sets FOLL_PIN instead of FOLL_GET.
2792 * The API rules are the same, too: no negative values may be returned.
2794 int pin_user_pages_fast_only(unsigned long start, int nr_pages,
2795 unsigned int gup_flags, struct page **pages)
2800 * FOLL_GET and FOLL_PIN are mutually exclusive. Note that the API
2801 * rules require returning 0, rather than -errno:
2803 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2806 * FOLL_FAST_ONLY is required in order to match the API description of
2807 * this routine: no fall back to regular ("slow") GUP.
2809 gup_flags |= (FOLL_PIN | FOLL_FAST_ONLY);
2810 nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
2813 * This routine is not allowed to return negative values. However,
2814 * internal_get_user_pages_fast() *can* return -errno. Therefore,
2815 * correct for that here:
2822 EXPORT_SYMBOL_GPL(pin_user_pages_fast_only);
2825 * pin_user_pages_remote() - pin pages of a remote process
2827 * @mm: mm_struct of target mm
2828 * @start: starting user address
2829 * @nr_pages: number of pages from start to pin
2830 * @gup_flags: flags modifying lookup behaviour
2831 * @pages: array that receives pointers to the pages pinned.
2832 * Should be at least nr_pages long. Or NULL, if caller
2833 * only intends to ensure the pages are faulted in.
2834 * @vmas: array of pointers to vmas corresponding to each page.
2835 * Or NULL if the caller does not require them.
2836 * @locked: pointer to lock flag indicating whether lock is held and
2837 * subsequently whether VM_FAULT_RETRY functionality can be
2838 * utilised. Lock must initially be held.
2840 * Nearly the same as get_user_pages_remote(), except that FOLL_PIN is set. See
2841 * get_user_pages_remote() for documentation on the function arguments, because
2842 * the arguments here are identical.
2844 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
2845 * see Documentation/core-api/pin_user_pages.rst for details.
2847 long pin_user_pages_remote(struct mm_struct *mm,
2848 unsigned long start, unsigned long nr_pages,
2849 unsigned int gup_flags, struct page **pages,
2850 struct vm_area_struct **vmas, int *locked)
2852 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2853 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2856 gup_flags |= FOLL_PIN;
2857 return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
2858 pages, vmas, locked);
2860 EXPORT_SYMBOL(pin_user_pages_remote);
2863 * pin_user_pages() - pin user pages in memory for use by other devices
2865 * @start: starting user address
2866 * @nr_pages: number of pages from start to pin
2867 * @gup_flags: flags modifying lookup behaviour
2868 * @pages: array that receives pointers to the pages pinned.
2869 * Should be at least nr_pages long. Or NULL, if caller
2870 * only intends to ensure the pages are faulted in.
2871 * @vmas: array of pointers to vmas corresponding to each page.
2872 * Or NULL if the caller does not require them.
2874 * Nearly the same as get_user_pages(), except that FOLL_TOUCH is not set, and
2877 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
2878 * see Documentation/core-api/pin_user_pages.rst for details.
2880 long pin_user_pages(unsigned long start, unsigned long nr_pages,
2881 unsigned int gup_flags, struct page **pages,
2882 struct vm_area_struct **vmas)
2884 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2885 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2888 gup_flags |= FOLL_PIN;
2889 return __gup_longterm_locked(current->mm, start, nr_pages,
2890 pages, vmas, gup_flags);
2892 EXPORT_SYMBOL(pin_user_pages);
2895 * pin_user_pages_unlocked() is the FOLL_PIN variant of
2896 * get_user_pages_unlocked(). Behavior is the same, except that this one sets
2897 * FOLL_PIN and rejects FOLL_GET.
2899 long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
2900 struct page **pages, unsigned int gup_flags)
2902 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2903 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2906 gup_flags |= FOLL_PIN;
2907 return get_user_pages_unlocked(start, nr_pages, pages, gup_flags);
2909 EXPORT_SYMBOL(pin_user_pages_unlocked);
2912 * pin_user_pages_locked() is the FOLL_PIN variant of get_user_pages_locked().
2913 * Behavior is the same, except that this one sets FOLL_PIN and rejects
2916 long pin_user_pages_locked(unsigned long start, unsigned long nr_pages,
2917 unsigned int gup_flags, struct page **pages,
2921 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
2922 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2923 * vmas. As there are no users of this flag in this call we simply
2924 * disallow this option for now.
2926 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
2929 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2930 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2933 gup_flags |= FOLL_PIN;
2934 return __get_user_pages_locked(current->mm, start, nr_pages,
2935 pages, NULL, locked,
2936 gup_flags | FOLL_TOUCH);
2938 EXPORT_SYMBOL(pin_user_pages_locked);