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 static __maybe_unused struct page *try_grab_compound_head(struct page *page,
117 if (flags & FOLL_GET)
118 return try_get_compound_head(page, refs);
119 else if (flags & FOLL_PIN) {
120 int orig_refs = refs;
123 * Can't do FOLL_LONGTERM + FOLL_PIN with CMA in the gup fast
124 * path, so fail and let the caller fall back to the slow path.
126 if (unlikely(flags & FOLL_LONGTERM) &&
127 is_migrate_cma_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);
246 * unpin_user_pages_dirty_lock() - release and optionally dirty gup-pinned pages
247 * @pages: array of pages to be maybe marked dirty, and definitely released.
248 * @npages: number of pages in the @pages array.
249 * @make_dirty: whether to mark the pages dirty
251 * "gup-pinned page" refers to a page that has had one of the get_user_pages()
252 * variants called on that page.
254 * For each page in the @pages array, make that page (or its head page, if a
255 * compound page) dirty, if @make_dirty is true, and if the page was previously
256 * listed as clean. In any case, releases all pages using unpin_user_page(),
257 * possibly via unpin_user_pages(), for the non-dirty case.
259 * Please see the unpin_user_page() documentation for details.
261 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
262 * required, then the caller should a) verify that this is really correct,
263 * because _lock() is usually required, and b) hand code it:
264 * set_page_dirty_lock(), unpin_user_page().
267 void unpin_user_pages_dirty_lock(struct page **pages, unsigned long npages,
273 * TODO: this can be optimized for huge pages: if a series of pages is
274 * physically contiguous and part of the same compound page, then a
275 * single operation to the head page should suffice.
279 unpin_user_pages(pages, npages);
283 for (index = 0; index < npages; index++) {
284 struct page *page = compound_head(pages[index]);
286 * Checking PageDirty at this point may race with
287 * clear_page_dirty_for_io(), but that's OK. Two key
290 * 1) This code sees the page as already dirty, so it
291 * skips the call to set_page_dirty(). That could happen
292 * because clear_page_dirty_for_io() called
293 * page_mkclean(), followed by set_page_dirty().
294 * However, now the page is going to get written back,
295 * which meets the original intention of setting it
296 * dirty, so all is well: clear_page_dirty_for_io() goes
297 * on to call TestClearPageDirty(), and write the page
300 * 2) This code sees the page as clean, so it calls
301 * set_page_dirty(). The page stays dirty, despite being
302 * written back, so it gets written back again in the
303 * next writeback cycle. This is harmless.
305 if (!PageDirty(page))
306 set_page_dirty_lock(page);
307 unpin_user_page(page);
310 EXPORT_SYMBOL(unpin_user_pages_dirty_lock);
313 * unpin_user_pages() - release an array of gup-pinned pages.
314 * @pages: array of pages to be marked dirty and released.
315 * @npages: number of pages in the @pages array.
317 * For each page in the @pages array, release the page using unpin_user_page().
319 * Please see the unpin_user_page() documentation for details.
321 void unpin_user_pages(struct page **pages, unsigned long npages)
326 * If this WARN_ON() fires, then the system *might* be leaking pages (by
327 * leaving them pinned), but probably not. More likely, gup/pup returned
328 * a hard -ERRNO error to the caller, who erroneously passed it here.
330 if (WARN_ON(IS_ERR_VALUE(npages)))
333 * TODO: this can be optimized for huge pages: if a series of pages is
334 * physically contiguous and part of the same compound page, then a
335 * single operation to the head page should suffice.
337 for (index = 0; index < npages; index++)
338 unpin_user_page(pages[index]);
340 EXPORT_SYMBOL(unpin_user_pages);
343 static struct page *no_page_table(struct vm_area_struct *vma,
347 * When core dumping an enormous anonymous area that nobody
348 * has touched so far, we don't want to allocate unnecessary pages or
349 * page tables. Return error instead of NULL to skip handle_mm_fault,
350 * then get_dump_page() will return NULL to leave a hole in the dump.
351 * But we can only make this optimization where a hole would surely
352 * be zero-filled if handle_mm_fault() actually did handle it.
354 if ((flags & FOLL_DUMP) &&
355 (vma_is_anonymous(vma) || !vma->vm_ops->fault))
356 return ERR_PTR(-EFAULT);
360 static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
361 pte_t *pte, unsigned int flags)
363 /* No page to get reference */
364 if (flags & FOLL_GET)
367 if (flags & FOLL_TOUCH) {
370 if (flags & FOLL_WRITE)
371 entry = pte_mkdirty(entry);
372 entry = pte_mkyoung(entry);
374 if (!pte_same(*pte, entry)) {
375 set_pte_at(vma->vm_mm, address, pte, entry);
376 update_mmu_cache(vma, address, pte);
380 /* Proper page table entry exists, but no corresponding struct page */
385 * FOLL_FORCE can write to even unwritable pte's, but only
386 * after we've gone through a COW cycle and they are dirty.
388 static inline bool can_follow_write_pte(pte_t pte, unsigned int flags)
390 return pte_write(pte) ||
391 ((flags & FOLL_FORCE) && (flags & FOLL_COW) && pte_dirty(pte));
394 static struct page *follow_page_pte(struct vm_area_struct *vma,
395 unsigned long address, pmd_t *pmd, unsigned int flags,
396 struct dev_pagemap **pgmap)
398 struct mm_struct *mm = vma->vm_mm;
404 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
405 if (WARN_ON_ONCE((flags & (FOLL_PIN | FOLL_GET)) ==
406 (FOLL_PIN | FOLL_GET)))
407 return ERR_PTR(-EINVAL);
409 if (unlikely(pmd_bad(*pmd)))
410 return no_page_table(vma, flags);
412 ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
414 if (!pte_present(pte)) {
417 * KSM's break_ksm() relies upon recognizing a ksm page
418 * even while it is being migrated, so for that case we
419 * need migration_entry_wait().
421 if (likely(!(flags & FOLL_MIGRATION)))
425 entry = pte_to_swp_entry(pte);
426 if (!is_migration_entry(entry))
428 pte_unmap_unlock(ptep, ptl);
429 migration_entry_wait(mm, pmd, address);
432 if ((flags & FOLL_NUMA) && pte_protnone(pte))
434 if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
435 pte_unmap_unlock(ptep, ptl);
439 page = vm_normal_page(vma, address, pte);
440 if (!page && pte_devmap(pte) && (flags & (FOLL_GET | FOLL_PIN))) {
442 * Only return device mapping pages in the FOLL_GET or FOLL_PIN
443 * case since they are only valid while holding the pgmap
446 *pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
448 page = pte_page(pte);
451 } else if (unlikely(!page)) {
452 if (flags & FOLL_DUMP) {
453 /* Avoid special (like zero) pages in core dumps */
454 page = ERR_PTR(-EFAULT);
458 if (is_zero_pfn(pte_pfn(pte))) {
459 page = pte_page(pte);
461 ret = follow_pfn_pte(vma, address, ptep, flags);
467 if (flags & FOLL_SPLIT && PageTransCompound(page)) {
469 pte_unmap_unlock(ptep, ptl);
471 ret = split_huge_page(page);
479 /* try_grab_page() does nothing unless FOLL_GET or FOLL_PIN is set. */
480 if (unlikely(!try_grab_page(page, flags))) {
481 page = ERR_PTR(-ENOMEM);
485 * We need to make the page accessible if and only if we are going
486 * to access its content (the FOLL_PIN case). Please see
487 * Documentation/core-api/pin_user_pages.rst for details.
489 if (flags & FOLL_PIN) {
490 ret = arch_make_page_accessible(page);
492 unpin_user_page(page);
497 if (flags & FOLL_TOUCH) {
498 if ((flags & FOLL_WRITE) &&
499 !pte_dirty(pte) && !PageDirty(page))
500 set_page_dirty(page);
502 * pte_mkyoung() would be more correct here, but atomic care
503 * is needed to avoid losing the dirty bit: it is easier to use
504 * mark_page_accessed().
506 mark_page_accessed(page);
508 if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
509 /* Do not mlock pte-mapped THP */
510 if (PageTransCompound(page))
514 * The preliminary mapping check is mainly to avoid the
515 * pointless overhead of lock_page on the ZERO_PAGE
516 * which might bounce very badly if there is contention.
518 * If the page is already locked, we don't need to
519 * handle it now - vmscan will handle it later if and
520 * when it attempts to reclaim the page.
522 if (page->mapping && trylock_page(page)) {
523 lru_add_drain(); /* push cached pages to LRU */
525 * Because we lock page here, and migration is
526 * blocked by the pte's page reference, and we
527 * know the page is still mapped, we don't even
528 * need to check for file-cache page truncation.
530 mlock_vma_page(page);
535 pte_unmap_unlock(ptep, ptl);
538 pte_unmap_unlock(ptep, ptl);
541 return no_page_table(vma, flags);
544 static struct page *follow_pmd_mask(struct vm_area_struct *vma,
545 unsigned long address, pud_t *pudp,
547 struct follow_page_context *ctx)
552 struct mm_struct *mm = vma->vm_mm;
554 pmd = pmd_offset(pudp, address);
556 * The READ_ONCE() will stabilize the pmdval in a register or
557 * on the stack so that it will stop changing under the code.
559 pmdval = READ_ONCE(*pmd);
560 if (pmd_none(pmdval))
561 return no_page_table(vma, flags);
562 if (pmd_huge(pmdval) && is_vm_hugetlb_page(vma)) {
563 page = follow_huge_pmd(mm, address, pmd, flags);
566 return no_page_table(vma, flags);
568 if (is_hugepd(__hugepd(pmd_val(pmdval)))) {
569 page = follow_huge_pd(vma, address,
570 __hugepd(pmd_val(pmdval)), flags,
574 return no_page_table(vma, flags);
577 if (!pmd_present(pmdval)) {
578 if (likely(!(flags & FOLL_MIGRATION)))
579 return no_page_table(vma, flags);
580 VM_BUG_ON(thp_migration_supported() &&
581 !is_pmd_migration_entry(pmdval));
582 if (is_pmd_migration_entry(pmdval))
583 pmd_migration_entry_wait(mm, pmd);
584 pmdval = READ_ONCE(*pmd);
586 * MADV_DONTNEED may convert the pmd to null because
587 * mmap_lock is held in read mode
589 if (pmd_none(pmdval))
590 return no_page_table(vma, flags);
593 if (pmd_devmap(pmdval)) {
594 ptl = pmd_lock(mm, pmd);
595 page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
600 if (likely(!pmd_trans_huge(pmdval)))
601 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
603 if ((flags & FOLL_NUMA) && pmd_protnone(pmdval))
604 return no_page_table(vma, flags);
607 ptl = pmd_lock(mm, pmd);
608 if (unlikely(pmd_none(*pmd))) {
610 return no_page_table(vma, flags);
612 if (unlikely(!pmd_present(*pmd))) {
614 if (likely(!(flags & FOLL_MIGRATION)))
615 return no_page_table(vma, flags);
616 pmd_migration_entry_wait(mm, pmd);
619 if (unlikely(!pmd_trans_huge(*pmd))) {
621 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
623 if (flags & (FOLL_SPLIT | FOLL_SPLIT_PMD)) {
625 page = pmd_page(*pmd);
626 if (is_huge_zero_page(page)) {
629 split_huge_pmd(vma, pmd, address);
630 if (pmd_trans_unstable(pmd))
632 } else if (flags & FOLL_SPLIT) {
633 if (unlikely(!try_get_page(page))) {
635 return ERR_PTR(-ENOMEM);
639 ret = split_huge_page(page);
643 return no_page_table(vma, flags);
644 } else { /* flags & FOLL_SPLIT_PMD */
646 split_huge_pmd(vma, pmd, address);
647 ret = pte_alloc(mm, pmd) ? -ENOMEM : 0;
650 return ret ? ERR_PTR(ret) :
651 follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
653 page = follow_trans_huge_pmd(vma, address, pmd, flags);
655 ctx->page_mask = HPAGE_PMD_NR - 1;
659 static struct page *follow_pud_mask(struct vm_area_struct *vma,
660 unsigned long address, p4d_t *p4dp,
662 struct follow_page_context *ctx)
667 struct mm_struct *mm = vma->vm_mm;
669 pud = pud_offset(p4dp, address);
671 return no_page_table(vma, flags);
672 if (pud_huge(*pud) && is_vm_hugetlb_page(vma)) {
673 page = follow_huge_pud(mm, address, pud, flags);
676 return no_page_table(vma, flags);
678 if (is_hugepd(__hugepd(pud_val(*pud)))) {
679 page = follow_huge_pd(vma, address,
680 __hugepd(pud_val(*pud)), flags,
684 return no_page_table(vma, flags);
686 if (pud_devmap(*pud)) {
687 ptl = pud_lock(mm, pud);
688 page = follow_devmap_pud(vma, address, pud, flags, &ctx->pgmap);
693 if (unlikely(pud_bad(*pud)))
694 return no_page_table(vma, flags);
696 return follow_pmd_mask(vma, address, pud, flags, ctx);
699 static struct page *follow_p4d_mask(struct vm_area_struct *vma,
700 unsigned long address, pgd_t *pgdp,
702 struct follow_page_context *ctx)
707 p4d = p4d_offset(pgdp, address);
709 return no_page_table(vma, flags);
710 BUILD_BUG_ON(p4d_huge(*p4d));
711 if (unlikely(p4d_bad(*p4d)))
712 return no_page_table(vma, flags);
714 if (is_hugepd(__hugepd(p4d_val(*p4d)))) {
715 page = follow_huge_pd(vma, address,
716 __hugepd(p4d_val(*p4d)), flags,
720 return no_page_table(vma, flags);
722 return follow_pud_mask(vma, address, p4d, flags, ctx);
726 * follow_page_mask - look up a page descriptor from a user-virtual address
727 * @vma: vm_area_struct mapping @address
728 * @address: virtual address to look up
729 * @flags: flags modifying lookup behaviour
730 * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
731 * pointer to output page_mask
733 * @flags can have FOLL_ flags set, defined in <linux/mm.h>
735 * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
736 * the device's dev_pagemap metadata to avoid repeating expensive lookups.
738 * On output, the @ctx->page_mask is set according to the size of the page.
740 * Return: the mapped (struct page *), %NULL if no mapping exists, or
741 * an error pointer if there is a mapping to something not represented
742 * by a page descriptor (see also vm_normal_page()).
744 static struct page *follow_page_mask(struct vm_area_struct *vma,
745 unsigned long address, unsigned int flags,
746 struct follow_page_context *ctx)
750 struct mm_struct *mm = vma->vm_mm;
754 /* make this handle hugepd */
755 page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
757 WARN_ON_ONCE(flags & (FOLL_GET | FOLL_PIN));
761 pgd = pgd_offset(mm, address);
763 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
764 return no_page_table(vma, flags);
766 if (pgd_huge(*pgd)) {
767 page = follow_huge_pgd(mm, address, pgd, flags);
770 return no_page_table(vma, flags);
772 if (is_hugepd(__hugepd(pgd_val(*pgd)))) {
773 page = follow_huge_pd(vma, address,
774 __hugepd(pgd_val(*pgd)), flags,
778 return no_page_table(vma, flags);
781 return follow_p4d_mask(vma, address, pgd, flags, ctx);
784 struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
785 unsigned int foll_flags)
787 struct follow_page_context ctx = { NULL };
790 page = follow_page_mask(vma, address, foll_flags, &ctx);
792 put_dev_pagemap(ctx.pgmap);
796 static int get_gate_page(struct mm_struct *mm, unsigned long address,
797 unsigned int gup_flags, struct vm_area_struct **vma,
807 /* user gate pages are read-only */
808 if (gup_flags & FOLL_WRITE)
810 if (address > TASK_SIZE)
811 pgd = pgd_offset_k(address);
813 pgd = pgd_offset_gate(mm, address);
816 p4d = p4d_offset(pgd, address);
819 pud = pud_offset(p4d, address);
822 pmd = pmd_offset(pud, address);
823 if (!pmd_present(*pmd))
825 VM_BUG_ON(pmd_trans_huge(*pmd));
826 pte = pte_offset_map(pmd, address);
829 *vma = get_gate_vma(mm);
832 *page = vm_normal_page(*vma, address, *pte);
834 if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
836 *page = pte_page(*pte);
838 if (unlikely(!try_grab_page(*page, gup_flags))) {
850 * mmap_lock must be held on entry. If @locked != NULL and *@flags
851 * does not include FOLL_NOWAIT, the mmap_lock may be released. If it
852 * is, *@locked will be set to 0 and -EBUSY returned.
854 static int faultin_page(struct vm_area_struct *vma,
855 unsigned long address, unsigned int *flags, int *locked)
857 unsigned int fault_flags = 0;
860 /* mlock all present pages, but do not fault in new pages */
861 if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)
863 if (*flags & FOLL_WRITE)
864 fault_flags |= FAULT_FLAG_WRITE;
865 if (*flags & FOLL_REMOTE)
866 fault_flags |= FAULT_FLAG_REMOTE;
868 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
869 if (*flags & FOLL_NOWAIT)
870 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
871 if (*flags & FOLL_TRIED) {
873 * Note: FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_TRIED
876 fault_flags |= FAULT_FLAG_TRIED;
879 ret = handle_mm_fault(vma, address, fault_flags, NULL);
880 if (ret & VM_FAULT_ERROR) {
881 int err = vm_fault_to_errno(ret, *flags);
888 if (ret & VM_FAULT_RETRY) {
889 if (locked && !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
895 * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
896 * necessary, even if maybe_mkwrite decided not to set pte_write. We
897 * can thus safely do subsequent page lookups as if they were reads.
898 * But only do so when looping for pte_write is futile: in some cases
899 * userspace may also be wanting to write to the gotten user page,
900 * which a read fault here might prevent (a readonly page might get
901 * reCOWed by userspace write).
903 if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
908 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
910 vm_flags_t vm_flags = vma->vm_flags;
911 int write = (gup_flags & FOLL_WRITE);
912 int foreign = (gup_flags & FOLL_REMOTE);
914 if (vm_flags & (VM_IO | VM_PFNMAP))
917 if (gup_flags & FOLL_ANON && !vma_is_anonymous(vma))
921 if (!(vm_flags & VM_WRITE)) {
922 if (!(gup_flags & FOLL_FORCE))
925 * We used to let the write,force case do COW in a
926 * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
927 * set a breakpoint in a read-only mapping of an
928 * executable, without corrupting the file (yet only
929 * when that file had been opened for writing!).
930 * Anon pages in shared mappings are surprising: now
933 if (!is_cow_mapping(vm_flags))
936 } else if (!(vm_flags & VM_READ)) {
937 if (!(gup_flags & FOLL_FORCE))
940 * Is there actually any vma we can reach here which does not
941 * have VM_MAYREAD set?
943 if (!(vm_flags & VM_MAYREAD))
947 * gups are always data accesses, not instruction
948 * fetches, so execute=false here
950 if (!arch_vma_access_permitted(vma, write, false, foreign))
956 * __get_user_pages() - pin user pages in memory
957 * @mm: mm_struct of target mm
958 * @start: starting user address
959 * @nr_pages: number of pages from start to pin
960 * @gup_flags: flags modifying pin behaviour
961 * @pages: array that receives pointers to the pages pinned.
962 * Should be at least nr_pages long. Or NULL, if caller
963 * only intends to ensure the pages are faulted in.
964 * @vmas: array of pointers to vmas corresponding to each page.
965 * Or NULL if the caller does not require them.
966 * @locked: whether we're still with the mmap_lock held
968 * Returns either number of pages pinned (which may be less than the
969 * number requested), or an error. Details about the return value:
971 * -- If nr_pages is 0, returns 0.
972 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
973 * -- If nr_pages is >0, and some pages were pinned, returns the number of
974 * pages pinned. Again, this may be less than nr_pages.
975 * -- 0 return value is possible when the fault would need to be retried.
977 * The caller is responsible for releasing returned @pages, via put_page().
979 * @vmas are valid only as long as mmap_lock is held.
981 * Must be called with mmap_lock held. It may be released. See below.
983 * __get_user_pages walks a process's page tables and takes a reference to
984 * each struct page that each user address corresponds to at a given
985 * instant. That is, it takes the page that would be accessed if a user
986 * thread accesses the given user virtual address at that instant.
988 * This does not guarantee that the page exists in the user mappings when
989 * __get_user_pages returns, and there may even be a completely different
990 * page there in some cases (eg. if mmapped pagecache has been invalidated
991 * and subsequently re faulted). However it does guarantee that the page
992 * won't be freed completely. And mostly callers simply care that the page
993 * contains data that was valid *at some point in time*. Typically, an IO
994 * or similar operation cannot guarantee anything stronger anyway because
995 * locks can't be held over the syscall boundary.
997 * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
998 * the page is written to, set_page_dirty (or set_page_dirty_lock, as
999 * appropriate) must be called after the page is finished with, and
1000 * before put_page is called.
1002 * If @locked != NULL, *@locked will be set to 0 when mmap_lock is
1003 * released by an up_read(). That can happen if @gup_flags does not
1006 * A caller using such a combination of @locked and @gup_flags
1007 * must therefore hold the mmap_lock for reading only, and recognize
1008 * when it's been released. Otherwise, it must be held for either
1009 * reading or writing and will not be released.
1011 * In most cases, get_user_pages or get_user_pages_fast should be used
1012 * instead of __get_user_pages. __get_user_pages should be used only if
1013 * you need some special @gup_flags.
1015 static long __get_user_pages(struct mm_struct *mm,
1016 unsigned long start, unsigned long nr_pages,
1017 unsigned int gup_flags, struct page **pages,
1018 struct vm_area_struct **vmas, int *locked)
1020 long ret = 0, i = 0;
1021 struct vm_area_struct *vma = NULL;
1022 struct follow_page_context ctx = { NULL };
1027 start = untagged_addr(start);
1029 VM_BUG_ON(!!pages != !!(gup_flags & (FOLL_GET | FOLL_PIN)));
1032 * If FOLL_FORCE is set then do not force a full fault as the hinting
1033 * fault information is unrelated to the reference behaviour of a task
1034 * using the address space
1036 if (!(gup_flags & FOLL_FORCE))
1037 gup_flags |= FOLL_NUMA;
1041 unsigned int foll_flags = gup_flags;
1042 unsigned int page_increm;
1044 /* first iteration or cross vma bound */
1045 if (!vma || start >= vma->vm_end) {
1046 vma = find_extend_vma(mm, start);
1047 if (!vma && in_gate_area(mm, start)) {
1048 ret = get_gate_page(mm, start & PAGE_MASK,
1050 pages ? &pages[i] : NULL);
1057 if (!vma || check_vma_flags(vma, gup_flags)) {
1061 if (is_vm_hugetlb_page(vma)) {
1062 i = follow_hugetlb_page(mm, vma, pages, vmas,
1063 &start, &nr_pages, i,
1065 if (locked && *locked == 0) {
1067 * We've got a VM_FAULT_RETRY
1068 * and we've lost mmap_lock.
1069 * We must stop here.
1071 BUG_ON(gup_flags & FOLL_NOWAIT);
1080 * If we have a pending SIGKILL, don't keep faulting pages and
1081 * potentially allocating memory.
1083 if (fatal_signal_pending(current)) {
1089 page = follow_page_mask(vma, start, foll_flags, &ctx);
1091 ret = faultin_page(vma, start, &foll_flags, locked);
1106 } else if (PTR_ERR(page) == -EEXIST) {
1108 * Proper page table entry exists, but no corresponding
1112 } else if (IS_ERR(page)) {
1113 ret = PTR_ERR(page);
1118 flush_anon_page(vma, page, start);
1119 flush_dcache_page(page);
1127 page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
1128 if (page_increm > nr_pages)
1129 page_increm = nr_pages;
1131 start += page_increm * PAGE_SIZE;
1132 nr_pages -= page_increm;
1136 put_dev_pagemap(ctx.pgmap);
1140 static bool vma_permits_fault(struct vm_area_struct *vma,
1141 unsigned int fault_flags)
1143 bool write = !!(fault_flags & FAULT_FLAG_WRITE);
1144 bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
1145 vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
1147 if (!(vm_flags & vma->vm_flags))
1151 * The architecture might have a hardware protection
1152 * mechanism other than read/write that can deny access.
1154 * gup always represents data access, not instruction
1155 * fetches, so execute=false here:
1157 if (!arch_vma_access_permitted(vma, write, false, foreign))
1164 * fixup_user_fault() - manually resolve a user page fault
1165 * @mm: mm_struct of target mm
1166 * @address: user address
1167 * @fault_flags:flags to pass down to handle_mm_fault()
1168 * @unlocked: did we unlock the mmap_lock while retrying, maybe NULL if caller
1169 * does not allow retry. If NULL, the caller must guarantee
1170 * that fault_flags does not contain FAULT_FLAG_ALLOW_RETRY.
1172 * This is meant to be called in the specific scenario where for locking reasons
1173 * we try to access user memory in atomic context (within a pagefault_disable()
1174 * section), this returns -EFAULT, and we want to resolve the user fault before
1177 * Typically this is meant to be used by the futex code.
1179 * The main difference with get_user_pages() is that this function will
1180 * unconditionally call handle_mm_fault() which will in turn perform all the
1181 * necessary SW fixup of the dirty and young bits in the PTE, while
1182 * get_user_pages() only guarantees to update these in the struct page.
1184 * This is important for some architectures where those bits also gate the
1185 * access permission to the page because they are maintained in software. On
1186 * such architectures, gup() will not be enough to make a subsequent access
1189 * This function will not return with an unlocked mmap_lock. So it has not the
1190 * same semantics wrt the @mm->mmap_lock as does filemap_fault().
1192 int fixup_user_fault(struct mm_struct *mm,
1193 unsigned long address, unsigned int fault_flags,
1196 struct vm_area_struct *vma;
1197 vm_fault_t ret, major = 0;
1199 address = untagged_addr(address);
1202 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1205 vma = find_extend_vma(mm, address);
1206 if (!vma || address < vma->vm_start)
1209 if (!vma_permits_fault(vma, fault_flags))
1212 if ((fault_flags & FAULT_FLAG_KILLABLE) &&
1213 fatal_signal_pending(current))
1216 ret = handle_mm_fault(vma, address, fault_flags, NULL);
1217 major |= ret & VM_FAULT_MAJOR;
1218 if (ret & VM_FAULT_ERROR) {
1219 int err = vm_fault_to_errno(ret, 0);
1226 if (ret & VM_FAULT_RETRY) {
1229 fault_flags |= FAULT_FLAG_TRIED;
1235 EXPORT_SYMBOL_GPL(fixup_user_fault);
1238 * Please note that this function, unlike __get_user_pages will not
1239 * return 0 for nr_pages > 0 without FOLL_NOWAIT
1241 static __always_inline long __get_user_pages_locked(struct mm_struct *mm,
1242 unsigned long start,
1243 unsigned long nr_pages,
1244 struct page **pages,
1245 struct vm_area_struct **vmas,
1249 long ret, pages_done;
1253 /* if VM_FAULT_RETRY can be returned, vmas become invalid */
1255 /* check caller initialized locked */
1256 BUG_ON(*locked != 1);
1259 if (flags & FOLL_PIN)
1260 atomic_set(&mm->has_pinned, 1);
1263 * FOLL_PIN and FOLL_GET are mutually exclusive. Traditional behavior
1264 * is to set FOLL_GET if the caller wants pages[] filled in (but has
1265 * carelessly failed to specify FOLL_GET), so keep doing that, but only
1266 * for FOLL_GET, not for the newer FOLL_PIN.
1268 * FOLL_PIN always expects pages to be non-null, but no need to assert
1269 * that here, as any failures will be obvious enough.
1271 if (pages && !(flags & FOLL_PIN))
1275 lock_dropped = false;
1277 ret = __get_user_pages(mm, start, nr_pages, flags, pages,
1280 /* VM_FAULT_RETRY couldn't trigger, bypass */
1283 /* VM_FAULT_RETRY cannot return errors */
1286 BUG_ON(ret >= nr_pages);
1297 * VM_FAULT_RETRY didn't trigger or it was a
1305 * VM_FAULT_RETRY triggered, so seek to the faulting offset.
1306 * For the prefault case (!pages) we only update counts.
1310 start += ret << PAGE_SHIFT;
1311 lock_dropped = true;
1315 * Repeat on the address that fired VM_FAULT_RETRY
1316 * with both FAULT_FLAG_ALLOW_RETRY and
1317 * FAULT_FLAG_TRIED. Note that GUP can be interrupted
1318 * by fatal signals, so we need to check it before we
1319 * start trying again otherwise it can loop forever.
1322 if (fatal_signal_pending(current)) {
1324 pages_done = -EINTR;
1328 ret = mmap_read_lock_killable(mm);
1337 ret = __get_user_pages(mm, start, 1, flags | FOLL_TRIED,
1338 pages, NULL, locked);
1340 /* Continue to retry until we succeeded */
1358 if (lock_dropped && *locked) {
1360 * We must let the caller know we temporarily dropped the lock
1361 * and so the critical section protected by it was lost.
1363 mmap_read_unlock(mm);
1370 * populate_vma_page_range() - populate a range of pages in the vma.
1372 * @start: start address
1374 * @locked: whether the mmap_lock is still held
1376 * This takes care of mlocking the pages too if VM_LOCKED is set.
1378 * Return either number of pages pinned in the vma, or a negative error
1381 * vma->vm_mm->mmap_lock must be held.
1383 * If @locked is NULL, it may be held for read or write and will
1386 * If @locked is non-NULL, it must held for read only and may be
1387 * released. If it's released, *@locked will be set to 0.
1389 long populate_vma_page_range(struct vm_area_struct *vma,
1390 unsigned long start, unsigned long end, int *locked)
1392 struct mm_struct *mm = vma->vm_mm;
1393 unsigned long nr_pages = (end - start) / PAGE_SIZE;
1396 VM_BUG_ON(start & ~PAGE_MASK);
1397 VM_BUG_ON(end & ~PAGE_MASK);
1398 VM_BUG_ON_VMA(start < vma->vm_start, vma);
1399 VM_BUG_ON_VMA(end > vma->vm_end, vma);
1400 mmap_assert_locked(mm);
1402 gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK;
1403 if (vma->vm_flags & VM_LOCKONFAULT)
1404 gup_flags &= ~FOLL_POPULATE;
1406 * We want to touch writable mappings with a write fault in order
1407 * to break COW, except for shared mappings because these don't COW
1408 * and we would not want to dirty them for nothing.
1410 if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
1411 gup_flags |= FOLL_WRITE;
1414 * We want mlock to succeed for regions that have any permissions
1415 * other than PROT_NONE.
1417 if (vma_is_accessible(vma))
1418 gup_flags |= FOLL_FORCE;
1421 * We made sure addr is within a VMA, so the following will
1422 * not result in a stack expansion that recurses back here.
1424 return __get_user_pages(mm, start, nr_pages, gup_flags,
1425 NULL, NULL, locked);
1429 * __mm_populate - populate and/or mlock pages within a range of address space.
1431 * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
1432 * flags. VMAs must be already marked with the desired vm_flags, and
1433 * mmap_lock must not be held.
1435 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
1437 struct mm_struct *mm = current->mm;
1438 unsigned long end, nstart, nend;
1439 struct vm_area_struct *vma = NULL;
1445 for (nstart = start; nstart < end; nstart = nend) {
1447 * We want to fault in pages for [nstart; end) address range.
1448 * Find first corresponding VMA.
1453 vma = find_vma(mm, nstart);
1454 } else if (nstart >= vma->vm_end)
1456 if (!vma || vma->vm_start >= end)
1459 * Set [nstart; nend) to intersection of desired address
1460 * range with the first VMA. Also, skip undesirable VMA types.
1462 nend = min(end, vma->vm_end);
1463 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1465 if (nstart < vma->vm_start)
1466 nstart = vma->vm_start;
1468 * Now fault in a range of pages. populate_vma_page_range()
1469 * double checks the vma flags, so that it won't mlock pages
1470 * if the vma was already munlocked.
1472 ret = populate_vma_page_range(vma, nstart, nend, &locked);
1474 if (ignore_errors) {
1476 continue; /* continue at next VMA */
1480 nend = nstart + ret * PAGE_SIZE;
1484 mmap_read_unlock(mm);
1485 return ret; /* 0 or negative error code */
1487 #else /* CONFIG_MMU */
1488 static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start,
1489 unsigned long nr_pages, struct page **pages,
1490 struct vm_area_struct **vmas, int *locked,
1491 unsigned int foll_flags)
1493 struct vm_area_struct *vma;
1494 unsigned long vm_flags;
1497 /* calculate required read or write permissions.
1498 * If FOLL_FORCE is set, we only require the "MAY" flags.
1500 vm_flags = (foll_flags & FOLL_WRITE) ?
1501 (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
1502 vm_flags &= (foll_flags & FOLL_FORCE) ?
1503 (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
1505 for (i = 0; i < nr_pages; i++) {
1506 vma = find_vma(mm, start);
1508 goto finish_or_fault;
1510 /* protect what we can, including chardevs */
1511 if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
1512 !(vm_flags & vma->vm_flags))
1513 goto finish_or_fault;
1516 pages[i] = virt_to_page(start);
1522 start = (start + PAGE_SIZE) & PAGE_MASK;
1528 return i ? : -EFAULT;
1530 #endif /* !CONFIG_MMU */
1533 * get_dump_page() - pin user page in memory while writing it to core dump
1534 * @addr: user address
1536 * Returns struct page pointer of user page pinned for dump,
1537 * to be freed afterwards by put_page().
1539 * Returns NULL on any kind of failure - a hole must then be inserted into
1540 * the corefile, to preserve alignment with its headers; and also returns
1541 * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
1542 * allowing a hole to be left in the corefile to save diskspace.
1544 * Called without mmap_lock (takes and releases the mmap_lock by itself).
1546 #ifdef CONFIG_ELF_CORE
1547 struct page *get_dump_page(unsigned long addr)
1549 struct mm_struct *mm = current->mm;
1554 if (mmap_read_lock_killable(mm))
1556 ret = __get_user_pages_locked(mm, addr, 1, &page, NULL, &locked,
1557 FOLL_FORCE | FOLL_DUMP | FOLL_GET);
1559 mmap_read_unlock(mm);
1560 return (ret == 1) ? page : NULL;
1562 #endif /* CONFIG_ELF_CORE */
1564 #if defined(CONFIG_FS_DAX) || defined (CONFIG_CMA)
1565 static bool check_dax_vmas(struct vm_area_struct **vmas, long nr_pages)
1568 struct vm_area_struct *vma_prev = NULL;
1570 for (i = 0; i < nr_pages; i++) {
1571 struct vm_area_struct *vma = vmas[i];
1573 if (vma == vma_prev)
1578 if (vma_is_fsdax(vma))
1585 static long check_and_migrate_cma_pages(struct mm_struct *mm,
1586 unsigned long start,
1587 unsigned long nr_pages,
1588 struct page **pages,
1589 struct vm_area_struct **vmas,
1590 unsigned int gup_flags)
1592 unsigned long i, isolation_error_count;
1594 LIST_HEAD(cma_page_list);
1595 long ret = nr_pages;
1596 struct page *prev_head, *head;
1597 struct migration_target_control mtc = {
1598 .nid = NUMA_NO_NODE,
1599 .gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_NOWARN,
1604 isolation_error_count = 0;
1606 for (i = 0; i < nr_pages; i++) {
1607 head = compound_head(pages[i]);
1608 if (head == prev_head)
1612 * If we get a page from the CMA zone, since we are going to
1613 * be pinning these entries, we might as well move them out
1614 * of the CMA zone if possible.
1616 if (is_migrate_cma_page(head)) {
1617 if (PageHuge(head)) {
1618 if (!isolate_huge_page(head, &cma_page_list))
1619 isolation_error_count++;
1621 if (!PageLRU(head) && drain_allow) {
1622 lru_add_drain_all();
1623 drain_allow = false;
1626 if (isolate_lru_page(head)) {
1627 isolation_error_count++;
1630 list_add_tail(&head->lru, &cma_page_list);
1631 mod_node_page_state(page_pgdat(head),
1633 page_is_file_lru(head),
1634 thp_nr_pages(head));
1640 * If list is empty, and no isolation errors, means that all pages are
1641 * in the correct zone.
1643 if (list_empty(&cma_page_list) && !isolation_error_count)
1646 if (!list_empty(&cma_page_list)) {
1648 * drop the above get_user_pages reference.
1650 if (gup_flags & FOLL_PIN)
1651 unpin_user_pages(pages, nr_pages);
1653 for (i = 0; i < nr_pages; i++)
1656 ret = migrate_pages(&cma_page_list, alloc_migration_target,
1657 NULL, (unsigned long)&mtc, MIGRATE_SYNC,
1660 if (!list_empty(&cma_page_list))
1661 putback_movable_pages(&cma_page_list);
1662 return ret > 0 ? -ENOMEM : ret;
1665 /* We unpinned pages before migration, pin them again */
1666 ret = __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1674 * check again because pages were unpinned, and we also might have
1675 * had isolation errors and need more pages to migrate.
1680 static long check_and_migrate_cma_pages(struct mm_struct *mm,
1681 unsigned long start,
1682 unsigned long nr_pages,
1683 struct page **pages,
1684 struct vm_area_struct **vmas,
1685 unsigned int gup_flags)
1689 #endif /* CONFIG_CMA */
1692 * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
1693 * allows us to process the FOLL_LONGTERM flag.
1695 static long __gup_longterm_locked(struct mm_struct *mm,
1696 unsigned long start,
1697 unsigned long nr_pages,
1698 struct page **pages,
1699 struct vm_area_struct **vmas,
1700 unsigned int gup_flags)
1702 struct vm_area_struct **vmas_tmp = vmas;
1703 unsigned long flags = 0;
1706 if (gup_flags & FOLL_LONGTERM) {
1711 vmas_tmp = kcalloc(nr_pages,
1712 sizeof(struct vm_area_struct *),
1717 flags = memalloc_nocma_save();
1720 rc = __get_user_pages_locked(mm, start, nr_pages, pages,
1721 vmas_tmp, NULL, gup_flags);
1723 if (gup_flags & FOLL_LONGTERM) {
1727 if (check_dax_vmas(vmas_tmp, rc)) {
1728 if (gup_flags & FOLL_PIN)
1729 unpin_user_pages(pages, rc);
1731 for (i = 0; i < rc; i++)
1737 rc = check_and_migrate_cma_pages(mm, start, rc, pages,
1738 vmas_tmp, gup_flags);
1740 memalloc_nocma_restore(flags);
1743 if (vmas_tmp != vmas)
1747 #else /* !CONFIG_FS_DAX && !CONFIG_CMA */
1748 static __always_inline long __gup_longterm_locked(struct mm_struct *mm,
1749 unsigned long start,
1750 unsigned long nr_pages,
1751 struct page **pages,
1752 struct vm_area_struct **vmas,
1755 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1758 #endif /* CONFIG_FS_DAX || CONFIG_CMA */
1760 static bool is_valid_gup_flags(unsigned int gup_flags)
1763 * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
1764 * never directly by the caller, so enforce that with an assertion:
1766 if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
1769 * FOLL_PIN is a prerequisite to FOLL_LONGTERM. Another way of saying
1770 * that is, FOLL_LONGTERM is a specific case, more restrictive case of
1773 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1780 static long __get_user_pages_remote(struct mm_struct *mm,
1781 unsigned long start, unsigned long nr_pages,
1782 unsigned int gup_flags, struct page **pages,
1783 struct vm_area_struct **vmas, int *locked)
1786 * Parts of FOLL_LONGTERM behavior are incompatible with
1787 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1788 * vmas. However, this only comes up if locked is set, and there are
1789 * callers that do request FOLL_LONGTERM, but do not set locked. So,
1790 * allow what we can.
1792 if (gup_flags & FOLL_LONGTERM) {
1793 if (WARN_ON_ONCE(locked))
1796 * This will check the vmas (even if our vmas arg is NULL)
1797 * and return -ENOTSUPP if DAX isn't allowed in this case:
1799 return __gup_longterm_locked(mm, start, nr_pages, pages,
1800 vmas, gup_flags | FOLL_TOUCH |
1804 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1806 gup_flags | FOLL_TOUCH | FOLL_REMOTE);
1810 * get_user_pages_remote() - pin user pages in memory
1811 * @mm: mm_struct of target mm
1812 * @start: starting user address
1813 * @nr_pages: number of pages from start to pin
1814 * @gup_flags: flags modifying lookup behaviour
1815 * @pages: array that receives pointers to the pages pinned.
1816 * Should be at least nr_pages long. Or NULL, if caller
1817 * only intends to ensure the pages are faulted in.
1818 * @vmas: array of pointers to vmas corresponding to each page.
1819 * Or NULL if the caller does not require them.
1820 * @locked: pointer to lock flag indicating whether lock is held and
1821 * subsequently whether VM_FAULT_RETRY functionality can be
1822 * utilised. Lock must initially be held.
1824 * Returns either number of pages pinned (which may be less than the
1825 * number requested), or an error. Details about the return value:
1827 * -- If nr_pages is 0, returns 0.
1828 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
1829 * -- If nr_pages is >0, and some pages were pinned, returns the number of
1830 * pages pinned. Again, this may be less than nr_pages.
1832 * The caller is responsible for releasing returned @pages, via put_page().
1834 * @vmas are valid only as long as mmap_lock is held.
1836 * Must be called with mmap_lock held for read or write.
1838 * get_user_pages_remote walks a process's page tables and takes a reference
1839 * to each struct page that each user address corresponds to at a given
1840 * instant. That is, it takes the page that would be accessed if a user
1841 * thread accesses the given user virtual address at that instant.
1843 * This does not guarantee that the page exists in the user mappings when
1844 * get_user_pages_remote returns, and there may even be a completely different
1845 * page there in some cases (eg. if mmapped pagecache has been invalidated
1846 * and subsequently re faulted). However it does guarantee that the page
1847 * won't be freed completely. And mostly callers simply care that the page
1848 * contains data that was valid *at some point in time*. Typically, an IO
1849 * or similar operation cannot guarantee anything stronger anyway because
1850 * locks can't be held over the syscall boundary.
1852 * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
1853 * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
1854 * be called after the page is finished with, and before put_page is called.
1856 * get_user_pages_remote is typically used for fewer-copy IO operations,
1857 * to get a handle on the memory by some means other than accesses
1858 * via the user virtual addresses. The pages may be submitted for
1859 * DMA to devices or accessed via their kernel linear mapping (via the
1860 * kmap APIs). Care should be taken to use the correct cache flushing APIs.
1862 * See also get_user_pages_fast, for performance critical applications.
1864 * get_user_pages_remote should be phased out in favor of
1865 * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
1866 * should use get_user_pages_remote because it cannot pass
1867 * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
1869 long get_user_pages_remote(struct mm_struct *mm,
1870 unsigned long start, unsigned long nr_pages,
1871 unsigned int gup_flags, struct page **pages,
1872 struct vm_area_struct **vmas, int *locked)
1874 if (!is_valid_gup_flags(gup_flags))
1877 return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
1878 pages, vmas, locked);
1880 EXPORT_SYMBOL(get_user_pages_remote);
1882 #else /* CONFIG_MMU */
1883 long get_user_pages_remote(struct mm_struct *mm,
1884 unsigned long start, unsigned long nr_pages,
1885 unsigned int gup_flags, struct page **pages,
1886 struct vm_area_struct **vmas, int *locked)
1891 static long __get_user_pages_remote(struct mm_struct *mm,
1892 unsigned long start, unsigned long nr_pages,
1893 unsigned int gup_flags, struct page **pages,
1894 struct vm_area_struct **vmas, int *locked)
1898 #endif /* !CONFIG_MMU */
1901 * get_user_pages() - pin user pages in memory
1902 * @start: starting user address
1903 * @nr_pages: number of pages from start to pin
1904 * @gup_flags: flags modifying lookup behaviour
1905 * @pages: array that receives pointers to the pages pinned.
1906 * Should be at least nr_pages long. Or NULL, if caller
1907 * only intends to ensure the pages are faulted in.
1908 * @vmas: array of pointers to vmas corresponding to each page.
1909 * Or NULL if the caller does not require them.
1911 * This is the same as get_user_pages_remote(), just with a less-flexible
1912 * calling convention where we assume that the mm being operated on belongs to
1913 * the current task, and doesn't allow passing of a locked parameter. We also
1914 * obviously don't pass FOLL_REMOTE in here.
1916 long get_user_pages(unsigned long start, unsigned long nr_pages,
1917 unsigned int gup_flags, struct page **pages,
1918 struct vm_area_struct **vmas)
1920 if (!is_valid_gup_flags(gup_flags))
1923 return __gup_longterm_locked(current->mm, start, nr_pages,
1924 pages, vmas, gup_flags | FOLL_TOUCH);
1926 EXPORT_SYMBOL(get_user_pages);
1929 * get_user_pages_locked() is suitable to replace the form:
1931 * mmap_read_lock(mm);
1933 * get_user_pages(mm, ..., pages, NULL);
1934 * mmap_read_unlock(mm);
1939 * mmap_read_lock(mm);
1941 * get_user_pages_locked(mm, ..., pages, &locked);
1943 * mmap_read_unlock(mm);
1945 * @start: starting user address
1946 * @nr_pages: number of pages from start to pin
1947 * @gup_flags: flags modifying lookup behaviour
1948 * @pages: array that receives pointers to the pages pinned.
1949 * Should be at least nr_pages long. Or NULL, if caller
1950 * only intends to ensure the pages are faulted in.
1951 * @locked: pointer to lock flag indicating whether lock is held and
1952 * subsequently whether VM_FAULT_RETRY functionality can be
1953 * utilised. Lock must initially be held.
1955 * We can leverage the VM_FAULT_RETRY functionality in the page fault
1956 * paths better by using either get_user_pages_locked() or
1957 * get_user_pages_unlocked().
1960 long get_user_pages_locked(unsigned long start, unsigned long nr_pages,
1961 unsigned int gup_flags, struct page **pages,
1965 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
1966 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1967 * vmas. As there are no users of this flag in this call we simply
1968 * disallow this option for now.
1970 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1973 * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
1974 * never directly by the caller, so enforce that:
1976 if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
1979 return __get_user_pages_locked(current->mm, start, nr_pages,
1980 pages, NULL, locked,
1981 gup_flags | FOLL_TOUCH);
1983 EXPORT_SYMBOL(get_user_pages_locked);
1986 * get_user_pages_unlocked() is suitable to replace the form:
1988 * mmap_read_lock(mm);
1989 * get_user_pages(mm, ..., pages, NULL);
1990 * mmap_read_unlock(mm);
1994 * get_user_pages_unlocked(mm, ..., pages);
1996 * It is functionally equivalent to get_user_pages_fast so
1997 * get_user_pages_fast should be used instead if specific gup_flags
1998 * (e.g. FOLL_FORCE) are not required.
2000 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
2001 struct page **pages, unsigned int gup_flags)
2003 struct mm_struct *mm = current->mm;
2008 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
2009 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2010 * vmas. As there are no users of this flag in this call we simply
2011 * disallow this option for now.
2013 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
2017 ret = __get_user_pages_locked(mm, start, nr_pages, pages, NULL,
2018 &locked, gup_flags | FOLL_TOUCH);
2020 mmap_read_unlock(mm);
2023 EXPORT_SYMBOL(get_user_pages_unlocked);
2028 * get_user_pages_fast attempts to pin user pages by walking the page
2029 * tables directly and avoids taking locks. Thus the walker needs to be
2030 * protected from page table pages being freed from under it, and should
2031 * block any THP splits.
2033 * One way to achieve this is to have the walker disable interrupts, and
2034 * rely on IPIs from the TLB flushing code blocking before the page table
2035 * pages are freed. This is unsuitable for architectures that do not need
2036 * to broadcast an IPI when invalidating TLBs.
2038 * Another way to achieve this is to batch up page table containing pages
2039 * belonging to more than one mm_user, then rcu_sched a callback to free those
2040 * pages. Disabling interrupts will allow the fast_gup walker to both block
2041 * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
2042 * (which is a relatively rare event). The code below adopts this strategy.
2044 * Before activating this code, please be aware that the following assumptions
2045 * are currently made:
2047 * *) Either MMU_GATHER_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
2048 * free pages containing page tables or TLB flushing requires IPI broadcast.
2050 * *) ptes can be read atomically by the architecture.
2052 * *) access_ok is sufficient to validate userspace address ranges.
2054 * The last two assumptions can be relaxed by the addition of helper functions.
2056 * This code is based heavily on the PowerPC implementation by Nick Piggin.
2058 #ifdef CONFIG_HAVE_FAST_GUP
2059 #ifdef CONFIG_GUP_GET_PTE_LOW_HIGH
2062 * WARNING: only to be used in the get_user_pages_fast() implementation.
2064 * With get_user_pages_fast(), we walk down the pagetables without taking any
2065 * locks. For this we would like to load the pointers atomically, but sometimes
2066 * that is not possible (e.g. without expensive cmpxchg8b on x86_32 PAE). What
2067 * we do have is the guarantee that a PTE will only either go from not present
2068 * to present, or present to not present or both -- it will not switch to a
2069 * completely different present page without a TLB flush in between; something
2070 * that we are blocking by holding interrupts off.
2072 * Setting ptes from not present to present goes:
2074 * ptep->pte_high = h;
2076 * ptep->pte_low = l;
2078 * And present to not present goes:
2080 * ptep->pte_low = 0;
2082 * ptep->pte_high = 0;
2084 * We must ensure here that the load of pte_low sees 'l' IFF pte_high sees 'h'.
2085 * We load pte_high *after* loading pte_low, which ensures we don't see an older
2086 * value of pte_high. *Then* we recheck pte_low, which ensures that we haven't
2087 * picked up a changed pte high. We might have gotten rubbish values from
2088 * pte_low and pte_high, but we are guaranteed that pte_low will not have the
2089 * present bit set *unless* it is 'l'. Because get_user_pages_fast() only
2090 * operates on present ptes we're safe.
2092 static inline pte_t gup_get_pte(pte_t *ptep)
2097 pte.pte_low = ptep->pte_low;
2099 pte.pte_high = ptep->pte_high;
2101 } while (unlikely(pte.pte_low != ptep->pte_low));
2105 #else /* CONFIG_GUP_GET_PTE_LOW_HIGH */
2107 * We require that the PTE can be read atomically.
2109 static inline pte_t gup_get_pte(pte_t *ptep)
2111 return ptep_get(ptep);
2113 #endif /* CONFIG_GUP_GET_PTE_LOW_HIGH */
2115 static void __maybe_unused undo_dev_pagemap(int *nr, int nr_start,
2117 struct page **pages)
2119 while ((*nr) - nr_start) {
2120 struct page *page = pages[--(*nr)];
2122 ClearPageReferenced(page);
2123 if (flags & FOLL_PIN)
2124 unpin_user_page(page);
2130 #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
2131 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2132 unsigned int flags, struct page **pages, int *nr)
2134 struct dev_pagemap *pgmap = NULL;
2135 int nr_start = *nr, ret = 0;
2138 ptem = ptep = pte_offset_map(&pmd, addr);
2140 pte_t pte = gup_get_pte(ptep);
2141 struct page *head, *page;
2144 * Similar to the PMD case below, NUMA hinting must take slow
2145 * path using the pte_protnone check.
2147 if (pte_protnone(pte))
2150 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2153 if (pte_devmap(pte)) {
2154 if (unlikely(flags & FOLL_LONGTERM))
2157 pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
2158 if (unlikely(!pgmap)) {
2159 undo_dev_pagemap(nr, nr_start, flags, pages);
2162 } else if (pte_special(pte))
2165 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2166 page = pte_page(pte);
2168 head = try_grab_compound_head(page, 1, flags);
2172 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2173 put_compound_head(head, 1, flags);
2177 VM_BUG_ON_PAGE(compound_head(page) != head, page);
2180 * We need to make the page accessible if and only if we are
2181 * going to access its content (the FOLL_PIN case). Please
2182 * see Documentation/core-api/pin_user_pages.rst for
2185 if (flags & FOLL_PIN) {
2186 ret = arch_make_page_accessible(page);
2188 unpin_user_page(page);
2192 SetPageReferenced(page);
2196 } while (ptep++, addr += PAGE_SIZE, addr != end);
2202 put_dev_pagemap(pgmap);
2209 * If we can't determine whether or not a pte is special, then fail immediately
2210 * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
2213 * For a futex to be placed on a THP tail page, get_futex_key requires a
2214 * get_user_pages_fast_only implementation that can pin pages. Thus it's still
2215 * useful to have gup_huge_pmd even if we can't operate on ptes.
2217 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2218 unsigned int flags, struct page **pages, int *nr)
2222 #endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
2224 #if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
2225 static int __gup_device_huge(unsigned long pfn, unsigned long addr,
2226 unsigned long end, unsigned int flags,
2227 struct page **pages, int *nr)
2230 struct dev_pagemap *pgmap = NULL;
2233 struct page *page = pfn_to_page(pfn);
2235 pgmap = get_dev_pagemap(pfn, pgmap);
2236 if (unlikely(!pgmap)) {
2237 undo_dev_pagemap(nr, nr_start, flags, pages);
2240 SetPageReferenced(page);
2242 if (unlikely(!try_grab_page(page, flags))) {
2243 undo_dev_pagemap(nr, nr_start, flags, pages);
2248 } while (addr += PAGE_SIZE, addr != end);
2251 put_dev_pagemap(pgmap);
2255 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2256 unsigned long end, unsigned int flags,
2257 struct page **pages, int *nr)
2259 unsigned long fault_pfn;
2262 fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2263 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2266 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2267 undo_dev_pagemap(nr, nr_start, flags, pages);
2273 static int __gup_device_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2274 unsigned long end, unsigned int flags,
2275 struct page **pages, int *nr)
2277 unsigned long fault_pfn;
2280 fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2281 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2284 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2285 undo_dev_pagemap(nr, nr_start, flags, pages);
2291 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2292 unsigned long end, unsigned int flags,
2293 struct page **pages, int *nr)
2299 static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr,
2300 unsigned long end, unsigned int flags,
2301 struct page **pages, int *nr)
2308 static int record_subpages(struct page *page, unsigned long addr,
2309 unsigned long end, struct page **pages)
2313 for (nr = 0; addr != end; addr += PAGE_SIZE)
2314 pages[nr++] = page++;
2319 #ifdef CONFIG_ARCH_HAS_HUGEPD
2320 static unsigned long hugepte_addr_end(unsigned long addr, unsigned long end,
2323 unsigned long __boundary = (addr + sz) & ~(sz-1);
2324 return (__boundary - 1 < end - 1) ? __boundary : end;
2327 static int gup_hugepte(pte_t *ptep, unsigned long sz, unsigned long addr,
2328 unsigned long end, unsigned int flags,
2329 struct page **pages, int *nr)
2331 unsigned long pte_end;
2332 struct page *head, *page;
2336 pte_end = (addr + sz) & ~(sz-1);
2340 pte = huge_ptep_get(ptep);
2342 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2345 /* hugepages are never "special" */
2346 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2348 head = pte_page(pte);
2349 page = head + ((addr & (sz-1)) >> PAGE_SHIFT);
2350 refs = record_subpages(page, addr, end, pages + *nr);
2352 head = try_grab_compound_head(head, refs, flags);
2356 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2357 put_compound_head(head, refs, flags);
2362 SetPageReferenced(head);
2366 static int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2367 unsigned int pdshift, unsigned long end, unsigned int flags,
2368 struct page **pages, int *nr)
2371 unsigned long sz = 1UL << hugepd_shift(hugepd);
2374 ptep = hugepte_offset(hugepd, addr, pdshift);
2376 next = hugepte_addr_end(addr, end, sz);
2377 if (!gup_hugepte(ptep, sz, addr, end, flags, pages, nr))
2379 } while (ptep++, addr = next, addr != end);
2384 static inline int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2385 unsigned int pdshift, unsigned long end, unsigned int flags,
2386 struct page **pages, int *nr)
2390 #endif /* CONFIG_ARCH_HAS_HUGEPD */
2392 static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2393 unsigned long end, unsigned int flags,
2394 struct page **pages, int *nr)
2396 struct page *head, *page;
2399 if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
2402 if (pmd_devmap(orig)) {
2403 if (unlikely(flags & FOLL_LONGTERM))
2405 return __gup_device_huge_pmd(orig, pmdp, addr, end, flags,
2409 page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2410 refs = record_subpages(page, addr, end, pages + *nr);
2412 head = try_grab_compound_head(pmd_page(orig), refs, flags);
2416 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2417 put_compound_head(head, refs, flags);
2422 SetPageReferenced(head);
2426 static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2427 unsigned long end, unsigned int flags,
2428 struct page **pages, int *nr)
2430 struct page *head, *page;
2433 if (!pud_access_permitted(orig, flags & FOLL_WRITE))
2436 if (pud_devmap(orig)) {
2437 if (unlikely(flags & FOLL_LONGTERM))
2439 return __gup_device_huge_pud(orig, pudp, addr, end, flags,
2443 page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2444 refs = record_subpages(page, addr, end, pages + *nr);
2446 head = try_grab_compound_head(pud_page(orig), refs, flags);
2450 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2451 put_compound_head(head, refs, flags);
2456 SetPageReferenced(head);
2460 static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
2461 unsigned long end, unsigned int flags,
2462 struct page **pages, int *nr)
2465 struct page *head, *page;
2467 if (!pgd_access_permitted(orig, flags & FOLL_WRITE))
2470 BUILD_BUG_ON(pgd_devmap(orig));
2472 page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT);
2473 refs = record_subpages(page, addr, end, pages + *nr);
2475 head = try_grab_compound_head(pgd_page(orig), refs, flags);
2479 if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
2480 put_compound_head(head, refs, flags);
2485 SetPageReferenced(head);
2489 static int gup_pmd_range(pud_t *pudp, pud_t pud, unsigned long addr, unsigned long end,
2490 unsigned int flags, struct page **pages, int *nr)
2495 pmdp = pmd_offset_lockless(pudp, pud, addr);
2497 pmd_t pmd = READ_ONCE(*pmdp);
2499 next = pmd_addr_end(addr, end);
2500 if (!pmd_present(pmd))
2503 if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd) ||
2506 * NUMA hinting faults need to be handled in the GUP
2507 * slowpath for accounting purposes and so that they
2508 * can be serialised against THP migration.
2510 if (pmd_protnone(pmd))
2513 if (!gup_huge_pmd(pmd, pmdp, addr, next, flags,
2517 } else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
2519 * architecture have different format for hugetlbfs
2520 * pmd format and THP pmd format
2522 if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
2523 PMD_SHIFT, next, flags, pages, nr))
2525 } else if (!gup_pte_range(pmd, addr, next, flags, pages, nr))
2527 } while (pmdp++, addr = next, addr != end);
2532 static int gup_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr, unsigned long end,
2533 unsigned int flags, struct page **pages, int *nr)
2538 pudp = pud_offset_lockless(p4dp, p4d, addr);
2540 pud_t pud = READ_ONCE(*pudp);
2542 next = pud_addr_end(addr, end);
2543 if (unlikely(!pud_present(pud)))
2545 if (unlikely(pud_huge(pud))) {
2546 if (!gup_huge_pud(pud, pudp, addr, next, flags,
2549 } else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
2550 if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
2551 PUD_SHIFT, next, flags, pages, nr))
2553 } else if (!gup_pmd_range(pudp, pud, addr, next, flags, pages, nr))
2555 } while (pudp++, addr = next, addr != end);
2560 static int gup_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr, unsigned long end,
2561 unsigned int flags, struct page **pages, int *nr)
2566 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
2568 p4d_t p4d = READ_ONCE(*p4dp);
2570 next = p4d_addr_end(addr, end);
2573 BUILD_BUG_ON(p4d_huge(p4d));
2574 if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
2575 if (!gup_huge_pd(__hugepd(p4d_val(p4d)), addr,
2576 P4D_SHIFT, next, flags, pages, nr))
2578 } else if (!gup_pud_range(p4dp, p4d, addr, next, flags, pages, nr))
2580 } while (p4dp++, addr = next, addr != end);
2585 static void gup_pgd_range(unsigned long addr, unsigned long end,
2586 unsigned int flags, struct page **pages, int *nr)
2591 pgdp = pgd_offset(current->mm, addr);
2593 pgd_t pgd = READ_ONCE(*pgdp);
2595 next = pgd_addr_end(addr, end);
2598 if (unlikely(pgd_huge(pgd))) {
2599 if (!gup_huge_pgd(pgd, pgdp, addr, next, flags,
2602 } else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
2603 if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
2604 PGDIR_SHIFT, next, flags, pages, nr))
2606 } else if (!gup_p4d_range(pgdp, pgd, addr, next, flags, pages, nr))
2608 } while (pgdp++, addr = next, addr != end);
2611 static inline void gup_pgd_range(unsigned long addr, unsigned long end,
2612 unsigned int flags, struct page **pages, int *nr)
2615 #endif /* CONFIG_HAVE_FAST_GUP */
2617 #ifndef gup_fast_permitted
2619 * Check if it's allowed to use get_user_pages_fast_only() for the range, or
2620 * we need to fall back to the slow version:
2622 static bool gup_fast_permitted(unsigned long start, unsigned long end)
2628 static int __gup_longterm_unlocked(unsigned long start, int nr_pages,
2629 unsigned int gup_flags, struct page **pages)
2634 * FIXME: FOLL_LONGTERM does not work with
2635 * get_user_pages_unlocked() (see comments in that function)
2637 if (gup_flags & FOLL_LONGTERM) {
2638 mmap_read_lock(current->mm);
2639 ret = __gup_longterm_locked(current->mm,
2641 pages, NULL, gup_flags);
2642 mmap_read_unlock(current->mm);
2644 ret = get_user_pages_unlocked(start, nr_pages,
2651 static unsigned long lockless_pages_from_mm(unsigned long start,
2653 unsigned int gup_flags,
2654 struct page **pages)
2656 unsigned long flags;
2660 if (!IS_ENABLED(CONFIG_HAVE_FAST_GUP) ||
2661 !gup_fast_permitted(start, end))
2664 if (gup_flags & FOLL_PIN) {
2665 seq = raw_read_seqcount(¤t->mm->write_protect_seq);
2671 * Disable interrupts. The nested form is used, in order to allow full,
2672 * general purpose use of this routine.
2674 * With interrupts disabled, we block page table pages from being freed
2675 * from under us. See struct mmu_table_batch comments in
2676 * include/asm-generic/tlb.h for more details.
2678 * We do not adopt an rcu_read_lock() here as we also want to block IPIs
2679 * that come from THPs splitting.
2681 local_irq_save(flags);
2682 gup_pgd_range(start, end, gup_flags, pages, &nr_pinned);
2683 local_irq_restore(flags);
2686 * When pinning pages for DMA there could be a concurrent write protect
2687 * from fork() via copy_page_range(), in this case always fail fast GUP.
2689 if (gup_flags & FOLL_PIN) {
2690 if (read_seqcount_retry(¤t->mm->write_protect_seq, seq)) {
2691 unpin_user_pages(pages, nr_pinned);
2698 static int internal_get_user_pages_fast(unsigned long start,
2699 unsigned long nr_pages,
2700 unsigned int gup_flags,
2701 struct page **pages)
2703 unsigned long len, end;
2704 unsigned long nr_pinned;
2707 if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM |
2708 FOLL_FORCE | FOLL_PIN | FOLL_GET |
2712 if (gup_flags & FOLL_PIN)
2713 atomic_set(¤t->mm->has_pinned, 1);
2715 if (!(gup_flags & FOLL_FAST_ONLY))
2716 might_lock_read(¤t->mm->mmap_lock);
2718 start = untagged_addr(start) & PAGE_MASK;
2719 len = nr_pages << PAGE_SHIFT;
2720 if (check_add_overflow(start, len, &end))
2722 if (unlikely(!access_ok((void __user *)start, len)))
2725 nr_pinned = lockless_pages_from_mm(start, end, gup_flags, pages);
2726 if (nr_pinned == nr_pages || gup_flags & FOLL_FAST_ONLY)
2729 /* Slow path: try to get the remaining pages with get_user_pages */
2730 start += nr_pinned << PAGE_SHIFT;
2732 ret = __gup_longterm_unlocked(start, nr_pages - nr_pinned, gup_flags,
2736 * The caller has to unpin the pages we already pinned so
2737 * returning -errno is not an option
2743 return ret + nr_pinned;
2747 * get_user_pages_fast_only() - pin user pages in memory
2748 * @start: starting user address
2749 * @nr_pages: number of pages from start to pin
2750 * @gup_flags: flags modifying pin behaviour
2751 * @pages: array that receives pointers to the pages pinned.
2752 * Should be at least nr_pages long.
2754 * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
2756 * Note a difference with get_user_pages_fast: this always returns the
2757 * number of pages pinned, 0 if no pages were pinned.
2759 * If the architecture does not support this function, simply return with no
2762 * Careful, careful! COW breaking can go either way, so a non-write
2763 * access can get ambiguous page results. If you call this function without
2764 * 'write' set, you'd better be sure that you're ok with that ambiguity.
2766 int get_user_pages_fast_only(unsigned long start, int nr_pages,
2767 unsigned int gup_flags, struct page **pages)
2771 * Internally (within mm/gup.c), gup fast variants must set FOLL_GET,
2772 * because gup fast is always a "pin with a +1 page refcount" request.
2774 * FOLL_FAST_ONLY is required in order to match the API description of
2775 * this routine: no fall back to regular ("slow") GUP.
2777 gup_flags |= FOLL_GET | FOLL_FAST_ONLY;
2779 nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
2783 * As specified in the API description above, this routine is not
2784 * allowed to return negative values. However, the common core
2785 * routine internal_get_user_pages_fast() *can* return -errno.
2786 * Therefore, correct for that here:
2793 EXPORT_SYMBOL_GPL(get_user_pages_fast_only);
2796 * get_user_pages_fast() - pin user pages in memory
2797 * @start: starting user address
2798 * @nr_pages: number of pages from start to pin
2799 * @gup_flags: flags modifying pin behaviour
2800 * @pages: array that receives pointers to the pages pinned.
2801 * Should be at least nr_pages long.
2803 * Attempt to pin user pages in memory without taking mm->mmap_lock.
2804 * If not successful, it will fall back to taking the lock and
2805 * calling get_user_pages().
2807 * Returns number of pages pinned. This may be fewer than the number requested.
2808 * If nr_pages is 0 or negative, returns 0. If no pages were pinned, returns
2811 int get_user_pages_fast(unsigned long start, int nr_pages,
2812 unsigned int gup_flags, struct page **pages)
2814 if (!is_valid_gup_flags(gup_flags))
2818 * The caller may or may not have explicitly set FOLL_GET; either way is
2819 * OK. However, internally (within mm/gup.c), gup fast variants must set
2820 * FOLL_GET, because gup fast is always a "pin with a +1 page refcount"
2823 gup_flags |= FOLL_GET;
2824 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
2826 EXPORT_SYMBOL_GPL(get_user_pages_fast);
2829 * pin_user_pages_fast() - pin user pages in memory without taking locks
2831 * @start: starting user address
2832 * @nr_pages: number of pages from start to pin
2833 * @gup_flags: flags modifying pin behaviour
2834 * @pages: array that receives pointers to the pages pinned.
2835 * Should be at least nr_pages long.
2837 * Nearly the same as get_user_pages_fast(), except that FOLL_PIN is set. See
2838 * get_user_pages_fast() for documentation on the function arguments, because
2839 * the arguments here are identical.
2841 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
2842 * see Documentation/core-api/pin_user_pages.rst for further details.
2844 int pin_user_pages_fast(unsigned long start, int nr_pages,
2845 unsigned int gup_flags, struct page **pages)
2847 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2848 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2851 gup_flags |= FOLL_PIN;
2852 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
2854 EXPORT_SYMBOL_GPL(pin_user_pages_fast);
2857 * This is the FOLL_PIN equivalent of get_user_pages_fast_only(). Behavior
2858 * is the same, except that this one sets FOLL_PIN instead of FOLL_GET.
2860 * The API rules are the same, too: no negative values may be returned.
2862 int pin_user_pages_fast_only(unsigned long start, int nr_pages,
2863 unsigned int gup_flags, struct page **pages)
2868 * FOLL_GET and FOLL_PIN are mutually exclusive. Note that the API
2869 * rules require returning 0, rather than -errno:
2871 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2874 * FOLL_FAST_ONLY is required in order to match the API description of
2875 * this routine: no fall back to regular ("slow") GUP.
2877 gup_flags |= (FOLL_PIN | FOLL_FAST_ONLY);
2878 nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
2881 * This routine is not allowed to return negative values. However,
2882 * internal_get_user_pages_fast() *can* return -errno. Therefore,
2883 * correct for that here:
2890 EXPORT_SYMBOL_GPL(pin_user_pages_fast_only);
2893 * pin_user_pages_remote() - pin pages of a remote process
2895 * @mm: mm_struct of target mm
2896 * @start: starting user address
2897 * @nr_pages: number of pages from start to pin
2898 * @gup_flags: flags modifying lookup behaviour
2899 * @pages: array that receives pointers to the pages pinned.
2900 * Should be at least nr_pages long. Or NULL, if caller
2901 * only intends to ensure the pages are faulted in.
2902 * @vmas: array of pointers to vmas corresponding to each page.
2903 * Or NULL if the caller does not require them.
2904 * @locked: pointer to lock flag indicating whether lock is held and
2905 * subsequently whether VM_FAULT_RETRY functionality can be
2906 * utilised. Lock must initially be held.
2908 * Nearly the same as get_user_pages_remote(), except that FOLL_PIN is set. See
2909 * get_user_pages_remote() for documentation on the function arguments, because
2910 * the arguments here are identical.
2912 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
2913 * see Documentation/core-api/pin_user_pages.rst for details.
2915 long pin_user_pages_remote(struct mm_struct *mm,
2916 unsigned long start, unsigned long nr_pages,
2917 unsigned int gup_flags, struct page **pages,
2918 struct vm_area_struct **vmas, int *locked)
2920 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2921 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2924 gup_flags |= FOLL_PIN;
2925 return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
2926 pages, vmas, locked);
2928 EXPORT_SYMBOL(pin_user_pages_remote);
2931 * pin_user_pages() - pin user pages in memory for use by other devices
2933 * @start: starting user address
2934 * @nr_pages: number of pages from start to pin
2935 * @gup_flags: flags modifying lookup behaviour
2936 * @pages: array that receives pointers to the pages pinned.
2937 * Should be at least nr_pages long. Or NULL, if caller
2938 * only intends to ensure the pages are faulted in.
2939 * @vmas: array of pointers to vmas corresponding to each page.
2940 * Or NULL if the caller does not require them.
2942 * Nearly the same as get_user_pages(), except that FOLL_TOUCH is not set, and
2945 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
2946 * see Documentation/core-api/pin_user_pages.rst for details.
2948 long pin_user_pages(unsigned long start, unsigned long nr_pages,
2949 unsigned int gup_flags, struct page **pages,
2950 struct vm_area_struct **vmas)
2952 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2953 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2956 gup_flags |= FOLL_PIN;
2957 return __gup_longterm_locked(current->mm, start, nr_pages,
2958 pages, vmas, gup_flags);
2960 EXPORT_SYMBOL(pin_user_pages);
2963 * pin_user_pages_unlocked() is the FOLL_PIN variant of
2964 * get_user_pages_unlocked(). Behavior is the same, except that this one sets
2965 * FOLL_PIN and rejects FOLL_GET.
2967 long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
2968 struct page **pages, unsigned int gup_flags)
2970 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2971 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2974 gup_flags |= FOLL_PIN;
2975 return get_user_pages_unlocked(start, nr_pages, pages, gup_flags);
2977 EXPORT_SYMBOL(pin_user_pages_unlocked);
2980 * pin_user_pages_locked() is the FOLL_PIN variant of get_user_pages_locked().
2981 * Behavior is the same, except that this one sets FOLL_PIN and rejects
2984 long pin_user_pages_locked(unsigned long start, unsigned long nr_pages,
2985 unsigned int gup_flags, struct page **pages,
2989 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
2990 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2991 * vmas. As there are no users of this flag in this call we simply
2992 * disallow this option for now.
2994 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
2997 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2998 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3001 gup_flags |= FOLL_PIN;
3002 return __get_user_pages_locked(current->mm, start, nr_pages,
3003 pages, NULL, locked,
3004 gup_flags | FOLL_TOUCH);
3006 EXPORT_SYMBOL(pin_user_pages_locked);