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);
478 #ifdef CONFIG_FINEGRAINED_THP
479 else if (flags & FOLL_SPLIT_PTE && pte_cont(pte))
480 split_huge_pte(vma, pmd, ptep, address);
481 #endif /* CONFIG_FINEGRAINED_THP */
483 /* try_grab_page() does nothing unless FOLL_GET or FOLL_PIN is set. */
484 if (unlikely(!try_grab_page(page, flags))) {
485 page = ERR_PTR(-ENOMEM);
489 * We need to make the page accessible if and only if we are going
490 * to access its content (the FOLL_PIN case). Please see
491 * Documentation/core-api/pin_user_pages.rst for details.
493 if (flags & FOLL_PIN) {
494 ret = arch_make_page_accessible(page);
496 unpin_user_page(page);
501 if (flags & FOLL_TOUCH) {
502 if ((flags & FOLL_WRITE) &&
503 !pte_dirty(pte) && !PageDirty(page))
504 set_page_dirty(page);
506 * pte_mkyoung() would be more correct here, but atomic care
507 * is needed to avoid losing the dirty bit: it is easier to use
508 * mark_page_accessed().
510 mark_page_accessed(page);
512 if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
513 /* Do not mlock pte-mapped THP */
514 if (PageTransCompound(page))
518 * The preliminary mapping check is mainly to avoid the
519 * pointless overhead of lock_page on the ZERO_PAGE
520 * which might bounce very badly if there is contention.
522 * If the page is already locked, we don't need to
523 * handle it now - vmscan will handle it later if and
524 * when it attempts to reclaim the page.
526 if (page->mapping && trylock_page(page)) {
527 lru_add_drain(); /* push cached pages to LRU */
529 * Because we lock page here, and migration is
530 * blocked by the pte's page reference, and we
531 * know the page is still mapped, we don't even
532 * need to check for file-cache page truncation.
534 mlock_vma_page(page);
539 pte_unmap_unlock(ptep, ptl);
542 pte_unmap_unlock(ptep, ptl);
545 return no_page_table(vma, flags);
548 static struct page *follow_pmd_mask(struct vm_area_struct *vma,
549 unsigned long address, pud_t *pudp,
551 struct follow_page_context *ctx)
556 struct mm_struct *mm = vma->vm_mm;
558 pmd = pmd_offset(pudp, address);
560 * The READ_ONCE() will stabilize the pmdval in a register or
561 * on the stack so that it will stop changing under the code.
563 pmdval = READ_ONCE(*pmd);
564 if (pmd_none(pmdval))
565 return no_page_table(vma, flags);
566 if (pmd_huge(pmdval) && is_vm_hugetlb_page(vma)) {
567 page = follow_huge_pmd(mm, address, pmd, flags);
570 return no_page_table(vma, flags);
572 if (is_hugepd(__hugepd(pmd_val(pmdval)))) {
573 page = follow_huge_pd(vma, address,
574 __hugepd(pmd_val(pmdval)), flags,
578 return no_page_table(vma, flags);
581 if (!pmd_present(pmdval)) {
582 if (likely(!(flags & FOLL_MIGRATION)))
583 return no_page_table(vma, flags);
584 VM_BUG_ON(thp_migration_supported() &&
585 !is_pmd_migration_entry(pmdval));
586 if (is_pmd_migration_entry(pmdval))
587 pmd_migration_entry_wait(mm, pmd);
588 pmdval = READ_ONCE(*pmd);
590 * MADV_DONTNEED may convert the pmd to null because
591 * mmap_lock is held in read mode
593 if (pmd_none(pmdval))
594 return no_page_table(vma, flags);
597 if (pmd_devmap(pmdval)) {
598 ptl = pmd_lock(mm, pmd);
599 page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
604 if (likely(!pmd_trans_huge(pmdval)))
605 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
607 if ((flags & FOLL_NUMA) && pmd_protnone(pmdval))
608 return no_page_table(vma, flags);
611 ptl = pmd_lock(mm, pmd);
612 if (unlikely(pmd_none(*pmd))) {
614 return no_page_table(vma, flags);
616 if (unlikely(!pmd_present(*pmd))) {
618 if (likely(!(flags & FOLL_MIGRATION)))
619 return no_page_table(vma, flags);
620 pmd_migration_entry_wait(mm, pmd);
623 if (unlikely(!pmd_trans_huge(*pmd))) {
625 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
627 if (flags & (FOLL_SPLIT | FOLL_SPLIT_PMD)) {
629 page = pmd_page(*pmd);
630 if (is_huge_zero_page(page)) {
633 split_huge_pmd(vma, pmd, address);
634 if (pmd_trans_unstable(pmd))
636 } else if (flags & FOLL_SPLIT) {
637 if (unlikely(!try_get_page(page))) {
639 return ERR_PTR(-ENOMEM);
643 ret = split_huge_page(page);
647 return no_page_table(vma, flags);
648 } else { /* flags & FOLL_SPLIT_PMD */
650 split_huge_pmd(vma, pmd, address);
651 ret = pte_alloc(mm, pmd) ? -ENOMEM : 0;
654 return ret ? ERR_PTR(ret) :
655 follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
657 page = follow_trans_huge_pmd(vma, address, pmd, flags);
659 ctx->page_mask = HPAGE_PMD_NR - 1;
663 static struct page *follow_pud_mask(struct vm_area_struct *vma,
664 unsigned long address, p4d_t *p4dp,
666 struct follow_page_context *ctx)
671 struct mm_struct *mm = vma->vm_mm;
673 pud = pud_offset(p4dp, address);
675 return no_page_table(vma, flags);
676 if (pud_huge(*pud) && is_vm_hugetlb_page(vma)) {
677 page = follow_huge_pud(mm, address, pud, flags);
680 return no_page_table(vma, flags);
682 if (is_hugepd(__hugepd(pud_val(*pud)))) {
683 page = follow_huge_pd(vma, address,
684 __hugepd(pud_val(*pud)), flags,
688 return no_page_table(vma, flags);
690 if (pud_devmap(*pud)) {
691 ptl = pud_lock(mm, pud);
692 page = follow_devmap_pud(vma, address, pud, flags, &ctx->pgmap);
697 if (unlikely(pud_bad(*pud)))
698 return no_page_table(vma, flags);
700 return follow_pmd_mask(vma, address, pud, flags, ctx);
703 static struct page *follow_p4d_mask(struct vm_area_struct *vma,
704 unsigned long address, pgd_t *pgdp,
706 struct follow_page_context *ctx)
711 p4d = p4d_offset(pgdp, address);
713 return no_page_table(vma, flags);
714 BUILD_BUG_ON(p4d_huge(*p4d));
715 if (unlikely(p4d_bad(*p4d)))
716 return no_page_table(vma, flags);
718 if (is_hugepd(__hugepd(p4d_val(*p4d)))) {
719 page = follow_huge_pd(vma, address,
720 __hugepd(p4d_val(*p4d)), flags,
724 return no_page_table(vma, flags);
726 return follow_pud_mask(vma, address, p4d, flags, ctx);
730 * follow_page_mask - look up a page descriptor from a user-virtual address
731 * @vma: vm_area_struct mapping @address
732 * @address: virtual address to look up
733 * @flags: flags modifying lookup behaviour
734 * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
735 * pointer to output page_mask
737 * @flags can have FOLL_ flags set, defined in <linux/mm.h>
739 * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
740 * the device's dev_pagemap metadata to avoid repeating expensive lookups.
742 * On output, the @ctx->page_mask is set according to the size of the page.
744 * Return: the mapped (struct page *), %NULL if no mapping exists, or
745 * an error pointer if there is a mapping to something not represented
746 * by a page descriptor (see also vm_normal_page()).
748 static struct page *follow_page_mask(struct vm_area_struct *vma,
749 unsigned long address, unsigned int flags,
750 struct follow_page_context *ctx)
754 struct mm_struct *mm = vma->vm_mm;
758 /* make this handle hugepd */
759 page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
761 WARN_ON_ONCE(flags & (FOLL_GET | FOLL_PIN));
765 pgd = pgd_offset(mm, address);
767 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
768 return no_page_table(vma, flags);
770 if (pgd_huge(*pgd)) {
771 page = follow_huge_pgd(mm, address, pgd, flags);
774 return no_page_table(vma, flags);
776 if (is_hugepd(__hugepd(pgd_val(*pgd)))) {
777 page = follow_huge_pd(vma, address,
778 __hugepd(pgd_val(*pgd)), flags,
782 return no_page_table(vma, flags);
785 return follow_p4d_mask(vma, address, pgd, flags, ctx);
788 struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
789 unsigned int foll_flags)
791 struct follow_page_context ctx = { NULL };
794 page = follow_page_mask(vma, address, foll_flags, &ctx);
796 put_dev_pagemap(ctx.pgmap);
800 static int get_gate_page(struct mm_struct *mm, unsigned long address,
801 unsigned int gup_flags, struct vm_area_struct **vma,
811 /* user gate pages are read-only */
812 if (gup_flags & FOLL_WRITE)
814 if (address > TASK_SIZE)
815 pgd = pgd_offset_k(address);
817 pgd = pgd_offset_gate(mm, address);
820 p4d = p4d_offset(pgd, address);
823 pud = pud_offset(p4d, address);
826 pmd = pmd_offset(pud, address);
827 if (!pmd_present(*pmd))
829 VM_BUG_ON(pmd_trans_huge(*pmd));
830 pte = pte_offset_map(pmd, address);
833 *vma = get_gate_vma(mm);
836 *page = vm_normal_page(*vma, address, *pte);
838 if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
840 *page = pte_page(*pte);
842 if (unlikely(!try_grab_page(*page, gup_flags))) {
854 * mmap_lock must be held on entry. If @locked != NULL and *@flags
855 * does not include FOLL_NOWAIT, the mmap_lock may be released. If it
856 * is, *@locked will be set to 0 and -EBUSY returned.
858 static int faultin_page(struct vm_area_struct *vma,
859 unsigned long address, unsigned int *flags, int *locked)
861 unsigned int fault_flags = 0;
864 /* mlock all present pages, but do not fault in new pages */
865 if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)
867 if (*flags & FOLL_WRITE)
868 fault_flags |= FAULT_FLAG_WRITE;
869 if (*flags & FOLL_REMOTE)
870 fault_flags |= FAULT_FLAG_REMOTE;
872 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
873 if (*flags & FOLL_NOWAIT)
874 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
875 if (*flags & FOLL_TRIED) {
877 * Note: FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_TRIED
880 fault_flags |= FAULT_FLAG_TRIED;
883 ret = handle_mm_fault(vma, address, fault_flags, NULL);
884 if (ret & VM_FAULT_ERROR) {
885 int err = vm_fault_to_errno(ret, *flags);
892 if (ret & VM_FAULT_RETRY) {
893 if (locked && !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
899 * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
900 * necessary, even if maybe_mkwrite decided not to set pte_write. We
901 * can thus safely do subsequent page lookups as if they were reads.
902 * But only do so when looping for pte_write is futile: in some cases
903 * userspace may also be wanting to write to the gotten user page,
904 * which a read fault here might prevent (a readonly page might get
905 * reCOWed by userspace write).
907 if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
912 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
914 vm_flags_t vm_flags = vma->vm_flags;
915 int write = (gup_flags & FOLL_WRITE);
916 int foreign = (gup_flags & FOLL_REMOTE);
918 if (vm_flags & (VM_IO | VM_PFNMAP))
921 if (gup_flags & FOLL_ANON && !vma_is_anonymous(vma))
925 if (!(vm_flags & VM_WRITE)) {
926 if (!(gup_flags & FOLL_FORCE))
929 * We used to let the write,force case do COW in a
930 * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
931 * set a breakpoint in a read-only mapping of an
932 * executable, without corrupting the file (yet only
933 * when that file had been opened for writing!).
934 * Anon pages in shared mappings are surprising: now
937 if (!is_cow_mapping(vm_flags))
940 } else if (!(vm_flags & VM_READ)) {
941 if (!(gup_flags & FOLL_FORCE))
944 * Is there actually any vma we can reach here which does not
945 * have VM_MAYREAD set?
947 if (!(vm_flags & VM_MAYREAD))
951 * gups are always data accesses, not instruction
952 * fetches, so execute=false here
954 if (!arch_vma_access_permitted(vma, write, false, foreign))
960 * __get_user_pages() - pin user pages in memory
961 * @mm: mm_struct of target mm
962 * @start: starting user address
963 * @nr_pages: number of pages from start to pin
964 * @gup_flags: flags modifying pin behaviour
965 * @pages: array that receives pointers to the pages pinned.
966 * Should be at least nr_pages long. Or NULL, if caller
967 * only intends to ensure the pages are faulted in.
968 * @vmas: array of pointers to vmas corresponding to each page.
969 * Or NULL if the caller does not require them.
970 * @locked: whether we're still with the mmap_lock held
972 * Returns either number of pages pinned (which may be less than the
973 * number requested), or an error. Details about the return value:
975 * -- If nr_pages is 0, returns 0.
976 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
977 * -- If nr_pages is >0, and some pages were pinned, returns the number of
978 * pages pinned. Again, this may be less than nr_pages.
979 * -- 0 return value is possible when the fault would need to be retried.
981 * The caller is responsible for releasing returned @pages, via put_page().
983 * @vmas are valid only as long as mmap_lock is held.
985 * Must be called with mmap_lock held. It may be released. See below.
987 * __get_user_pages walks a process's page tables and takes a reference to
988 * each struct page that each user address corresponds to at a given
989 * instant. That is, it takes the page that would be accessed if a user
990 * thread accesses the given user virtual address at that instant.
992 * This does not guarantee that the page exists in the user mappings when
993 * __get_user_pages returns, and there may even be a completely different
994 * page there in some cases (eg. if mmapped pagecache has been invalidated
995 * and subsequently re faulted). However it does guarantee that the page
996 * won't be freed completely. And mostly callers simply care that the page
997 * contains data that was valid *at some point in time*. Typically, an IO
998 * or similar operation cannot guarantee anything stronger anyway because
999 * locks can't be held over the syscall boundary.
1001 * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
1002 * the page is written to, set_page_dirty (or set_page_dirty_lock, as
1003 * appropriate) must be called after the page is finished with, and
1004 * before put_page is called.
1006 * If @locked != NULL, *@locked will be set to 0 when mmap_lock is
1007 * released by an up_read(). That can happen if @gup_flags does not
1010 * A caller using such a combination of @locked and @gup_flags
1011 * must therefore hold the mmap_lock for reading only, and recognize
1012 * when it's been released. Otherwise, it must be held for either
1013 * reading or writing and will not be released.
1015 * In most cases, get_user_pages or get_user_pages_fast should be used
1016 * instead of __get_user_pages. __get_user_pages should be used only if
1017 * you need some special @gup_flags.
1019 static long __get_user_pages(struct mm_struct *mm,
1020 unsigned long start, unsigned long nr_pages,
1021 unsigned int gup_flags, struct page **pages,
1022 struct vm_area_struct **vmas, int *locked)
1024 long ret = 0, i = 0;
1025 struct vm_area_struct *vma = NULL;
1026 struct follow_page_context ctx = { NULL };
1031 start = untagged_addr(start);
1033 VM_BUG_ON(!!pages != !!(gup_flags & (FOLL_GET | FOLL_PIN)));
1036 * If FOLL_FORCE is set then do not force a full fault as the hinting
1037 * fault information is unrelated to the reference behaviour of a task
1038 * using the address space
1040 if (!(gup_flags & FOLL_FORCE))
1041 gup_flags |= FOLL_NUMA;
1045 unsigned int foll_flags = gup_flags;
1046 unsigned int page_increm;
1048 /* first iteration or cross vma bound */
1049 if (!vma || start >= vma->vm_end) {
1050 vma = find_extend_vma(mm, start);
1051 if (!vma && in_gate_area(mm, start)) {
1052 ret = get_gate_page(mm, start & PAGE_MASK,
1054 pages ? &pages[i] : NULL);
1061 if (!vma || check_vma_flags(vma, gup_flags)) {
1065 if (is_vm_hugetlb_page(vma)) {
1066 i = follow_hugetlb_page(mm, vma, pages, vmas,
1067 &start, &nr_pages, i,
1069 if (locked && *locked == 0) {
1071 * We've got a VM_FAULT_RETRY
1072 * and we've lost mmap_lock.
1073 * We must stop here.
1075 BUG_ON(gup_flags & FOLL_NOWAIT);
1084 * If we have a pending SIGKILL, don't keep faulting pages and
1085 * potentially allocating memory.
1087 if (fatal_signal_pending(current)) {
1093 page = follow_page_mask(vma, start, foll_flags, &ctx);
1095 ret = faultin_page(vma, start, &foll_flags, locked);
1110 } else if (PTR_ERR(page) == -EEXIST) {
1112 * Proper page table entry exists, but no corresponding
1116 } else if (IS_ERR(page)) {
1117 ret = PTR_ERR(page);
1122 flush_anon_page(vma, page, start);
1123 flush_dcache_page(page);
1131 page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
1132 if (page_increm > nr_pages)
1133 page_increm = nr_pages;
1135 start += page_increm * PAGE_SIZE;
1136 nr_pages -= page_increm;
1140 put_dev_pagemap(ctx.pgmap);
1144 static bool vma_permits_fault(struct vm_area_struct *vma,
1145 unsigned int fault_flags)
1147 bool write = !!(fault_flags & FAULT_FLAG_WRITE);
1148 bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
1149 vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
1151 if (!(vm_flags & vma->vm_flags))
1155 * The architecture might have a hardware protection
1156 * mechanism other than read/write that can deny access.
1158 * gup always represents data access, not instruction
1159 * fetches, so execute=false here:
1161 if (!arch_vma_access_permitted(vma, write, false, foreign))
1168 * fixup_user_fault() - manually resolve a user page fault
1169 * @mm: mm_struct of target mm
1170 * @address: user address
1171 * @fault_flags:flags to pass down to handle_mm_fault()
1172 * @unlocked: did we unlock the mmap_lock while retrying, maybe NULL if caller
1173 * does not allow retry. If NULL, the caller must guarantee
1174 * that fault_flags does not contain FAULT_FLAG_ALLOW_RETRY.
1176 * This is meant to be called in the specific scenario where for locking reasons
1177 * we try to access user memory in atomic context (within a pagefault_disable()
1178 * section), this returns -EFAULT, and we want to resolve the user fault before
1181 * Typically this is meant to be used by the futex code.
1183 * The main difference with get_user_pages() is that this function will
1184 * unconditionally call handle_mm_fault() which will in turn perform all the
1185 * necessary SW fixup of the dirty and young bits in the PTE, while
1186 * get_user_pages() only guarantees to update these in the struct page.
1188 * This is important for some architectures where those bits also gate the
1189 * access permission to the page because they are maintained in software. On
1190 * such architectures, gup() will not be enough to make a subsequent access
1193 * This function will not return with an unlocked mmap_lock. So it has not the
1194 * same semantics wrt the @mm->mmap_lock as does filemap_fault().
1196 int fixup_user_fault(struct mm_struct *mm,
1197 unsigned long address, unsigned int fault_flags,
1200 struct vm_area_struct *vma;
1201 vm_fault_t ret, major = 0;
1203 address = untagged_addr(address);
1206 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1209 vma = find_extend_vma(mm, address);
1210 if (!vma || address < vma->vm_start)
1213 if (!vma_permits_fault(vma, fault_flags))
1216 if ((fault_flags & FAULT_FLAG_KILLABLE) &&
1217 fatal_signal_pending(current))
1220 ret = handle_mm_fault(vma, address, fault_flags, NULL);
1221 major |= ret & VM_FAULT_MAJOR;
1222 if (ret & VM_FAULT_ERROR) {
1223 int err = vm_fault_to_errno(ret, 0);
1230 if (ret & VM_FAULT_RETRY) {
1233 fault_flags |= FAULT_FLAG_TRIED;
1239 EXPORT_SYMBOL_GPL(fixup_user_fault);
1242 * Please note that this function, unlike __get_user_pages will not
1243 * return 0 for nr_pages > 0 without FOLL_NOWAIT
1245 static __always_inline long __get_user_pages_locked(struct mm_struct *mm,
1246 unsigned long start,
1247 unsigned long nr_pages,
1248 struct page **pages,
1249 struct vm_area_struct **vmas,
1253 long ret, pages_done;
1257 /* if VM_FAULT_RETRY can be returned, vmas become invalid */
1259 /* check caller initialized locked */
1260 BUG_ON(*locked != 1);
1263 if (flags & FOLL_PIN)
1264 atomic_set(&mm->has_pinned, 1);
1267 * FOLL_PIN and FOLL_GET are mutually exclusive. Traditional behavior
1268 * is to set FOLL_GET if the caller wants pages[] filled in (but has
1269 * carelessly failed to specify FOLL_GET), so keep doing that, but only
1270 * for FOLL_GET, not for the newer FOLL_PIN.
1272 * FOLL_PIN always expects pages to be non-null, but no need to assert
1273 * that here, as any failures will be obvious enough.
1275 if (pages && !(flags & FOLL_PIN))
1279 lock_dropped = false;
1281 ret = __get_user_pages(mm, start, nr_pages, flags, pages,
1284 /* VM_FAULT_RETRY couldn't trigger, bypass */
1287 /* VM_FAULT_RETRY cannot return errors */
1290 BUG_ON(ret >= nr_pages);
1301 * VM_FAULT_RETRY didn't trigger or it was a
1309 * VM_FAULT_RETRY triggered, so seek to the faulting offset.
1310 * For the prefault case (!pages) we only update counts.
1314 start += ret << PAGE_SHIFT;
1315 lock_dropped = true;
1319 * Repeat on the address that fired VM_FAULT_RETRY
1320 * with both FAULT_FLAG_ALLOW_RETRY and
1321 * FAULT_FLAG_TRIED. Note that GUP can be interrupted
1322 * by fatal signals, so we need to check it before we
1323 * start trying again otherwise it can loop forever.
1326 if (fatal_signal_pending(current)) {
1328 pages_done = -EINTR;
1332 ret = mmap_read_lock_killable(mm);
1341 ret = __get_user_pages(mm, start, 1, flags | FOLL_TRIED,
1342 pages, NULL, locked);
1344 /* Continue to retry until we succeeded */
1362 if (lock_dropped && *locked) {
1364 * We must let the caller know we temporarily dropped the lock
1365 * and so the critical section protected by it was lost.
1367 mmap_read_unlock(mm);
1374 * populate_vma_page_range() - populate a range of pages in the vma.
1376 * @start: start address
1378 * @locked: whether the mmap_lock is still held
1380 * This takes care of mlocking the pages too if VM_LOCKED is set.
1382 * Return either number of pages pinned in the vma, or a negative error
1385 * vma->vm_mm->mmap_lock must be held.
1387 * If @locked is NULL, it may be held for read or write and will
1390 * If @locked is non-NULL, it must held for read only and may be
1391 * released. If it's released, *@locked will be set to 0.
1393 long populate_vma_page_range(struct vm_area_struct *vma,
1394 unsigned long start, unsigned long end, int *locked)
1396 struct mm_struct *mm = vma->vm_mm;
1397 unsigned long nr_pages = (end - start) / PAGE_SIZE;
1400 VM_BUG_ON(start & ~PAGE_MASK);
1401 VM_BUG_ON(end & ~PAGE_MASK);
1402 VM_BUG_ON_VMA(start < vma->vm_start, vma);
1403 VM_BUG_ON_VMA(end > vma->vm_end, vma);
1404 mmap_assert_locked(mm);
1406 gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK;
1407 if (vma->vm_flags & VM_LOCKONFAULT)
1408 gup_flags &= ~FOLL_POPULATE;
1410 * We want to touch writable mappings with a write fault in order
1411 * to break COW, except for shared mappings because these don't COW
1412 * and we would not want to dirty them for nothing.
1414 if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
1415 gup_flags |= FOLL_WRITE;
1418 * We want mlock to succeed for regions that have any permissions
1419 * other than PROT_NONE.
1421 if (vma_is_accessible(vma))
1422 gup_flags |= FOLL_FORCE;
1425 * We made sure addr is within a VMA, so the following will
1426 * not result in a stack expansion that recurses back here.
1428 return __get_user_pages(mm, start, nr_pages, gup_flags,
1429 NULL, NULL, locked);
1433 * __mm_populate - populate and/or mlock pages within a range of address space.
1435 * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
1436 * flags. VMAs must be already marked with the desired vm_flags, and
1437 * mmap_lock must not be held.
1439 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
1441 struct mm_struct *mm = current->mm;
1442 unsigned long end, nstart, nend;
1443 struct vm_area_struct *vma = NULL;
1449 for (nstart = start; nstart < end; nstart = nend) {
1451 * We want to fault in pages for [nstart; end) address range.
1452 * Find first corresponding VMA.
1457 vma = find_vma(mm, nstart);
1458 } else if (nstart >= vma->vm_end)
1460 if (!vma || vma->vm_start >= end)
1463 * Set [nstart; nend) to intersection of desired address
1464 * range with the first VMA. Also, skip undesirable VMA types.
1466 nend = min(end, vma->vm_end);
1467 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1469 if (nstart < vma->vm_start)
1470 nstart = vma->vm_start;
1472 * Now fault in a range of pages. populate_vma_page_range()
1473 * double checks the vma flags, so that it won't mlock pages
1474 * if the vma was already munlocked.
1476 ret = populate_vma_page_range(vma, nstart, nend, &locked);
1478 if (ignore_errors) {
1480 continue; /* continue at next VMA */
1484 nend = nstart + ret * PAGE_SIZE;
1488 mmap_read_unlock(mm);
1489 return ret; /* 0 or negative error code */
1491 #else /* CONFIG_MMU */
1492 static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start,
1493 unsigned long nr_pages, struct page **pages,
1494 struct vm_area_struct **vmas, int *locked,
1495 unsigned int foll_flags)
1497 struct vm_area_struct *vma;
1498 unsigned long vm_flags;
1501 /* calculate required read or write permissions.
1502 * If FOLL_FORCE is set, we only require the "MAY" flags.
1504 vm_flags = (foll_flags & FOLL_WRITE) ?
1505 (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
1506 vm_flags &= (foll_flags & FOLL_FORCE) ?
1507 (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
1509 for (i = 0; i < nr_pages; i++) {
1510 vma = find_vma(mm, start);
1512 goto finish_or_fault;
1514 /* protect what we can, including chardevs */
1515 if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
1516 !(vm_flags & vma->vm_flags))
1517 goto finish_or_fault;
1520 pages[i] = virt_to_page(start);
1526 start = (start + PAGE_SIZE) & PAGE_MASK;
1532 return i ? : -EFAULT;
1534 #endif /* !CONFIG_MMU */
1537 * get_dump_page() - pin user page in memory while writing it to core dump
1538 * @addr: user address
1540 * Returns struct page pointer of user page pinned for dump,
1541 * to be freed afterwards by put_page().
1543 * Returns NULL on any kind of failure - a hole must then be inserted into
1544 * the corefile, to preserve alignment with its headers; and also returns
1545 * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
1546 * allowing a hole to be left in the corefile to save diskspace.
1548 * Called without mmap_lock (takes and releases the mmap_lock by itself).
1550 #ifdef CONFIG_ELF_CORE
1551 struct page *get_dump_page(unsigned long addr)
1553 struct mm_struct *mm = current->mm;
1558 if (mmap_read_lock_killable(mm))
1560 ret = __get_user_pages_locked(mm, addr, 1, &page, NULL, &locked,
1561 FOLL_FORCE | FOLL_DUMP | FOLL_GET);
1563 mmap_read_unlock(mm);
1564 return (ret == 1) ? page : NULL;
1566 #endif /* CONFIG_ELF_CORE */
1568 #if defined(CONFIG_FS_DAX) || defined (CONFIG_CMA)
1569 static bool check_dax_vmas(struct vm_area_struct **vmas, long nr_pages)
1572 struct vm_area_struct *vma_prev = NULL;
1574 for (i = 0; i < nr_pages; i++) {
1575 struct vm_area_struct *vma = vmas[i];
1577 if (vma == vma_prev)
1582 if (vma_is_fsdax(vma))
1589 static long check_and_migrate_cma_pages(struct mm_struct *mm,
1590 unsigned long start,
1591 unsigned long nr_pages,
1592 struct page **pages,
1593 struct vm_area_struct **vmas,
1594 unsigned int gup_flags)
1596 unsigned long i, isolation_error_count;
1598 LIST_HEAD(cma_page_list);
1599 long ret = nr_pages;
1600 struct page *prev_head, *head;
1601 struct migration_target_control mtc = {
1602 .nid = NUMA_NO_NODE,
1603 .gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_NOWARN,
1608 isolation_error_count = 0;
1610 for (i = 0; i < nr_pages; i++) {
1611 head = compound_head(pages[i]);
1612 if (head == prev_head)
1616 * If we get a page from the CMA zone, since we are going to
1617 * be pinning these entries, we might as well move them out
1618 * of the CMA zone if possible.
1620 if (is_migrate_cma_page(head)) {
1621 if (PageHuge(head)) {
1622 if (!isolate_huge_page(head, &cma_page_list))
1623 isolation_error_count++;
1625 if (!PageLRU(head) && drain_allow) {
1626 lru_add_drain_all();
1627 drain_allow = false;
1630 if (isolate_lru_page(head)) {
1631 isolation_error_count++;
1634 list_add_tail(&head->lru, &cma_page_list);
1635 mod_node_page_state(page_pgdat(head),
1637 page_is_file_lru(head),
1638 thp_nr_pages(head));
1644 * If list is empty, and no isolation errors, means that all pages are
1645 * in the correct zone.
1647 if (list_empty(&cma_page_list) && !isolation_error_count)
1650 if (!list_empty(&cma_page_list)) {
1652 * drop the above get_user_pages reference.
1654 if (gup_flags & FOLL_PIN)
1655 unpin_user_pages(pages, nr_pages);
1657 for (i = 0; i < nr_pages; i++)
1660 ret = migrate_pages(&cma_page_list, alloc_migration_target,
1661 NULL, (unsigned long)&mtc, MIGRATE_SYNC,
1664 if (!list_empty(&cma_page_list))
1665 putback_movable_pages(&cma_page_list);
1666 return ret > 0 ? -ENOMEM : ret;
1669 /* We unpinned pages before migration, pin them again */
1670 ret = __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1678 * check again because pages were unpinned, and we also might have
1679 * had isolation errors and need more pages to migrate.
1684 static long check_and_migrate_cma_pages(struct mm_struct *mm,
1685 unsigned long start,
1686 unsigned long nr_pages,
1687 struct page **pages,
1688 struct vm_area_struct **vmas,
1689 unsigned int gup_flags)
1693 #endif /* CONFIG_CMA */
1696 * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
1697 * allows us to process the FOLL_LONGTERM flag.
1699 static long __gup_longterm_locked(struct mm_struct *mm,
1700 unsigned long start,
1701 unsigned long nr_pages,
1702 struct page **pages,
1703 struct vm_area_struct **vmas,
1704 unsigned int gup_flags)
1706 struct vm_area_struct **vmas_tmp = vmas;
1707 unsigned long flags = 0;
1710 if (gup_flags & FOLL_LONGTERM) {
1715 vmas_tmp = kcalloc(nr_pages,
1716 sizeof(struct vm_area_struct *),
1721 flags = memalloc_nocma_save();
1724 rc = __get_user_pages_locked(mm, start, nr_pages, pages,
1725 vmas_tmp, NULL, gup_flags);
1727 if (gup_flags & FOLL_LONGTERM) {
1731 if (check_dax_vmas(vmas_tmp, rc)) {
1732 if (gup_flags & FOLL_PIN)
1733 unpin_user_pages(pages, rc);
1735 for (i = 0; i < rc; i++)
1741 rc = check_and_migrate_cma_pages(mm, start, rc, pages,
1742 vmas_tmp, gup_flags);
1744 memalloc_nocma_restore(flags);
1747 if (vmas_tmp != vmas)
1751 #else /* !CONFIG_FS_DAX && !CONFIG_CMA */
1752 static __always_inline long __gup_longterm_locked(struct mm_struct *mm,
1753 unsigned long start,
1754 unsigned long nr_pages,
1755 struct page **pages,
1756 struct vm_area_struct **vmas,
1759 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1762 #endif /* CONFIG_FS_DAX || CONFIG_CMA */
1764 static bool is_valid_gup_flags(unsigned int gup_flags)
1767 * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
1768 * never directly by the caller, so enforce that with an assertion:
1770 if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
1773 * FOLL_PIN is a prerequisite to FOLL_LONGTERM. Another way of saying
1774 * that is, FOLL_LONGTERM is a specific case, more restrictive case of
1777 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1784 static long __get_user_pages_remote(struct mm_struct *mm,
1785 unsigned long start, unsigned long nr_pages,
1786 unsigned int gup_flags, struct page **pages,
1787 struct vm_area_struct **vmas, int *locked)
1790 * Parts of FOLL_LONGTERM behavior are incompatible with
1791 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1792 * vmas. However, this only comes up if locked is set, and there are
1793 * callers that do request FOLL_LONGTERM, but do not set locked. So,
1794 * allow what we can.
1796 if (gup_flags & FOLL_LONGTERM) {
1797 if (WARN_ON_ONCE(locked))
1800 * This will check the vmas (even if our vmas arg is NULL)
1801 * and return -ENOTSUPP if DAX isn't allowed in this case:
1803 return __gup_longterm_locked(mm, start, nr_pages, pages,
1804 vmas, gup_flags | FOLL_TOUCH |
1808 return __get_user_pages_locked(mm, start, nr_pages, pages, vmas,
1810 gup_flags | FOLL_TOUCH | FOLL_REMOTE);
1814 * get_user_pages_remote() - pin user pages in memory
1815 * @mm: mm_struct of target mm
1816 * @start: starting user address
1817 * @nr_pages: number of pages from start to pin
1818 * @gup_flags: flags modifying lookup behaviour
1819 * @pages: array that receives pointers to the pages pinned.
1820 * Should be at least nr_pages long. Or NULL, if caller
1821 * only intends to ensure the pages are faulted in.
1822 * @vmas: array of pointers to vmas corresponding to each page.
1823 * Or NULL if the caller does not require them.
1824 * @locked: pointer to lock flag indicating whether lock is held and
1825 * subsequently whether VM_FAULT_RETRY functionality can be
1826 * utilised. Lock must initially be held.
1828 * Returns either number of pages pinned (which may be less than the
1829 * number requested), or an error. Details about the return value:
1831 * -- If nr_pages is 0, returns 0.
1832 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
1833 * -- If nr_pages is >0, and some pages were pinned, returns the number of
1834 * pages pinned. Again, this may be less than nr_pages.
1836 * The caller is responsible for releasing returned @pages, via put_page().
1838 * @vmas are valid only as long as mmap_lock is held.
1840 * Must be called with mmap_lock held for read or write.
1842 * get_user_pages_remote walks a process's page tables and takes a reference
1843 * to each struct page that each user address corresponds to at a given
1844 * instant. That is, it takes the page that would be accessed if a user
1845 * thread accesses the given user virtual address at that instant.
1847 * This does not guarantee that the page exists in the user mappings when
1848 * get_user_pages_remote returns, and there may even be a completely different
1849 * page there in some cases (eg. if mmapped pagecache has been invalidated
1850 * and subsequently re faulted). However it does guarantee that the page
1851 * won't be freed completely. And mostly callers simply care that the page
1852 * contains data that was valid *at some point in time*. Typically, an IO
1853 * or similar operation cannot guarantee anything stronger anyway because
1854 * locks can't be held over the syscall boundary.
1856 * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
1857 * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
1858 * be called after the page is finished with, and before put_page is called.
1860 * get_user_pages_remote is typically used for fewer-copy IO operations,
1861 * to get a handle on the memory by some means other than accesses
1862 * via the user virtual addresses. The pages may be submitted for
1863 * DMA to devices or accessed via their kernel linear mapping (via the
1864 * kmap APIs). Care should be taken to use the correct cache flushing APIs.
1866 * See also get_user_pages_fast, for performance critical applications.
1868 * get_user_pages_remote should be phased out in favor of
1869 * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
1870 * should use get_user_pages_remote because it cannot pass
1871 * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
1873 long get_user_pages_remote(struct mm_struct *mm,
1874 unsigned long start, unsigned long nr_pages,
1875 unsigned int gup_flags, struct page **pages,
1876 struct vm_area_struct **vmas, int *locked)
1878 if (!is_valid_gup_flags(gup_flags))
1881 return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
1882 pages, vmas, locked);
1884 EXPORT_SYMBOL(get_user_pages_remote);
1886 #else /* CONFIG_MMU */
1887 long get_user_pages_remote(struct mm_struct *mm,
1888 unsigned long start, unsigned long nr_pages,
1889 unsigned int gup_flags, struct page **pages,
1890 struct vm_area_struct **vmas, int *locked)
1895 static long __get_user_pages_remote(struct mm_struct *mm,
1896 unsigned long start, unsigned long nr_pages,
1897 unsigned int gup_flags, struct page **pages,
1898 struct vm_area_struct **vmas, int *locked)
1902 #endif /* !CONFIG_MMU */
1905 * get_user_pages() - pin user pages in memory
1906 * @start: starting user address
1907 * @nr_pages: number of pages from start to pin
1908 * @gup_flags: flags modifying lookup behaviour
1909 * @pages: array that receives pointers to the pages pinned.
1910 * Should be at least nr_pages long. Or NULL, if caller
1911 * only intends to ensure the pages are faulted in.
1912 * @vmas: array of pointers to vmas corresponding to each page.
1913 * Or NULL if the caller does not require them.
1915 * This is the same as get_user_pages_remote(), just with a less-flexible
1916 * calling convention where we assume that the mm being operated on belongs to
1917 * the current task, and doesn't allow passing of a locked parameter. We also
1918 * obviously don't pass FOLL_REMOTE in here.
1920 long get_user_pages(unsigned long start, unsigned long nr_pages,
1921 unsigned int gup_flags, struct page **pages,
1922 struct vm_area_struct **vmas)
1924 if (!is_valid_gup_flags(gup_flags))
1927 return __gup_longterm_locked(current->mm, start, nr_pages,
1928 pages, vmas, gup_flags | FOLL_TOUCH);
1930 EXPORT_SYMBOL(get_user_pages);
1933 * get_user_pages_locked() is suitable to replace the form:
1935 * mmap_read_lock(mm);
1937 * get_user_pages(mm, ..., pages, NULL);
1938 * mmap_read_unlock(mm);
1943 * mmap_read_lock(mm);
1945 * get_user_pages_locked(mm, ..., pages, &locked);
1947 * mmap_read_unlock(mm);
1949 * @start: starting user address
1950 * @nr_pages: number of pages from start to pin
1951 * @gup_flags: flags modifying lookup behaviour
1952 * @pages: array that receives pointers to the pages pinned.
1953 * Should be at least nr_pages long. Or NULL, if caller
1954 * only intends to ensure the pages are faulted in.
1955 * @locked: pointer to lock flag indicating whether lock is held and
1956 * subsequently whether VM_FAULT_RETRY functionality can be
1957 * utilised. Lock must initially be held.
1959 * We can leverage the VM_FAULT_RETRY functionality in the page fault
1960 * paths better by using either get_user_pages_locked() or
1961 * get_user_pages_unlocked().
1964 long get_user_pages_locked(unsigned long start, unsigned long nr_pages,
1965 unsigned int gup_flags, struct page **pages,
1969 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
1970 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1971 * vmas. As there are no users of this flag in this call we simply
1972 * disallow this option for now.
1974 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1977 * FOLL_PIN must only be set internally by the pin_user_pages*() APIs,
1978 * never directly by the caller, so enforce that:
1980 if (WARN_ON_ONCE(gup_flags & FOLL_PIN))
1983 return __get_user_pages_locked(current->mm, start, nr_pages,
1984 pages, NULL, locked,
1985 gup_flags | FOLL_TOUCH);
1987 EXPORT_SYMBOL(get_user_pages_locked);
1990 * get_user_pages_unlocked() is suitable to replace the form:
1992 * mmap_read_lock(mm);
1993 * get_user_pages(mm, ..., pages, NULL);
1994 * mmap_read_unlock(mm);
1998 * get_user_pages_unlocked(mm, ..., pages);
2000 * It is functionally equivalent to get_user_pages_fast so
2001 * get_user_pages_fast should be used instead if specific gup_flags
2002 * (e.g. FOLL_FORCE) are not required.
2004 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
2005 struct page **pages, unsigned int gup_flags)
2007 struct mm_struct *mm = current->mm;
2012 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
2013 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2014 * vmas. As there are no users of this flag in this call we simply
2015 * disallow this option for now.
2017 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
2021 ret = __get_user_pages_locked(mm, start, nr_pages, pages, NULL,
2022 &locked, gup_flags | FOLL_TOUCH);
2024 mmap_read_unlock(mm);
2027 EXPORT_SYMBOL(get_user_pages_unlocked);
2032 * get_user_pages_fast attempts to pin user pages by walking the page
2033 * tables directly and avoids taking locks. Thus the walker needs to be
2034 * protected from page table pages being freed from under it, and should
2035 * block any THP splits.
2037 * One way to achieve this is to have the walker disable interrupts, and
2038 * rely on IPIs from the TLB flushing code blocking before the page table
2039 * pages are freed. This is unsuitable for architectures that do not need
2040 * to broadcast an IPI when invalidating TLBs.
2042 * Another way to achieve this is to batch up page table containing pages
2043 * belonging to more than one mm_user, then rcu_sched a callback to free those
2044 * pages. Disabling interrupts will allow the fast_gup walker to both block
2045 * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
2046 * (which is a relatively rare event). The code below adopts this strategy.
2048 * Before activating this code, please be aware that the following assumptions
2049 * are currently made:
2051 * *) Either MMU_GATHER_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
2052 * free pages containing page tables or TLB flushing requires IPI broadcast.
2054 * *) ptes can be read atomically by the architecture.
2056 * *) access_ok is sufficient to validate userspace address ranges.
2058 * The last two assumptions can be relaxed by the addition of helper functions.
2060 * This code is based heavily on the PowerPC implementation by Nick Piggin.
2062 #ifdef CONFIG_HAVE_FAST_GUP
2063 #ifdef CONFIG_GUP_GET_PTE_LOW_HIGH
2066 * WARNING: only to be used in the get_user_pages_fast() implementation.
2068 * With get_user_pages_fast(), we walk down the pagetables without taking any
2069 * locks. For this we would like to load the pointers atomically, but sometimes
2070 * that is not possible (e.g. without expensive cmpxchg8b on x86_32 PAE). What
2071 * we do have is the guarantee that a PTE will only either go from not present
2072 * to present, or present to not present or both -- it will not switch to a
2073 * completely different present page without a TLB flush in between; something
2074 * that we are blocking by holding interrupts off.
2076 * Setting ptes from not present to present goes:
2078 * ptep->pte_high = h;
2080 * ptep->pte_low = l;
2082 * And present to not present goes:
2084 * ptep->pte_low = 0;
2086 * ptep->pte_high = 0;
2088 * We must ensure here that the load of pte_low sees 'l' IFF pte_high sees 'h'.
2089 * We load pte_high *after* loading pte_low, which ensures we don't see an older
2090 * value of pte_high. *Then* we recheck pte_low, which ensures that we haven't
2091 * picked up a changed pte high. We might have gotten rubbish values from
2092 * pte_low and pte_high, but we are guaranteed that pte_low will not have the
2093 * present bit set *unless* it is 'l'. Because get_user_pages_fast() only
2094 * operates on present ptes we're safe.
2096 static inline pte_t gup_get_pte(pte_t *ptep)
2101 pte.pte_low = ptep->pte_low;
2103 pte.pte_high = ptep->pte_high;
2105 } while (unlikely(pte.pte_low != ptep->pte_low));
2109 #else /* CONFIG_GUP_GET_PTE_LOW_HIGH */
2111 * We require that the PTE can be read atomically.
2113 static inline pte_t gup_get_pte(pte_t *ptep)
2115 return ptep_get(ptep);
2117 #endif /* CONFIG_GUP_GET_PTE_LOW_HIGH */
2119 static void __maybe_unused undo_dev_pagemap(int *nr, int nr_start,
2121 struct page **pages)
2123 while ((*nr) - nr_start) {
2124 struct page *page = pages[--(*nr)];
2126 ClearPageReferenced(page);
2127 if (flags & FOLL_PIN)
2128 unpin_user_page(page);
2134 #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
2135 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2136 unsigned int flags, struct page **pages, int *nr)
2138 struct dev_pagemap *pgmap = NULL;
2139 int nr_start = *nr, ret = 0;
2142 ptem = ptep = pte_offset_map(&pmd, addr);
2144 pte_t pte = gup_get_pte(ptep);
2145 struct page *head, *page;
2148 * Similar to the PMD case below, NUMA hinting must take slow
2149 * path using the pte_protnone check.
2151 if (pte_protnone(pte))
2154 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2157 if (pte_devmap(pte)) {
2158 if (unlikely(flags & FOLL_LONGTERM))
2161 pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
2162 if (unlikely(!pgmap)) {
2163 undo_dev_pagemap(nr, nr_start, flags, pages);
2166 } else if (pte_special(pte))
2169 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2170 page = pte_page(pte);
2172 head = try_grab_compound_head(page, 1, flags);
2176 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2177 put_compound_head(head, 1, flags);
2181 VM_BUG_ON_PAGE(compound_head(page) != head, page);
2184 * We need to make the page accessible if and only if we are
2185 * going to access its content (the FOLL_PIN case). Please
2186 * see Documentation/core-api/pin_user_pages.rst for
2189 if (flags & FOLL_PIN) {
2190 ret = arch_make_page_accessible(page);
2192 unpin_user_page(page);
2196 SetPageReferenced(page);
2200 } while (ptep++, addr += PAGE_SIZE, addr != end);
2206 put_dev_pagemap(pgmap);
2213 * If we can't determine whether or not a pte is special, then fail immediately
2214 * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
2217 * For a futex to be placed on a THP tail page, get_futex_key requires a
2218 * get_user_pages_fast_only implementation that can pin pages. Thus it's still
2219 * useful to have gup_huge_pmd even if we can't operate on ptes.
2221 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
2222 unsigned int flags, struct page **pages, int *nr)
2226 #endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
2228 #if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
2229 static int __gup_device_huge(unsigned long pfn, unsigned long addr,
2230 unsigned long end, unsigned int flags,
2231 struct page **pages, int *nr)
2234 struct dev_pagemap *pgmap = NULL;
2237 struct page *page = pfn_to_page(pfn);
2239 pgmap = get_dev_pagemap(pfn, pgmap);
2240 if (unlikely(!pgmap)) {
2241 undo_dev_pagemap(nr, nr_start, flags, pages);
2244 SetPageReferenced(page);
2246 if (unlikely(!try_grab_page(page, flags))) {
2247 undo_dev_pagemap(nr, nr_start, flags, pages);
2252 } while (addr += PAGE_SIZE, addr != end);
2255 put_dev_pagemap(pgmap);
2259 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2260 unsigned long end, unsigned int flags,
2261 struct page **pages, int *nr)
2263 unsigned long fault_pfn;
2266 fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2267 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2270 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2271 undo_dev_pagemap(nr, nr_start, flags, pages);
2277 static int __gup_device_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2278 unsigned long end, unsigned int flags,
2279 struct page **pages, int *nr)
2281 unsigned long fault_pfn;
2284 fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2285 if (!__gup_device_huge(fault_pfn, addr, end, flags, pages, nr))
2288 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2289 undo_dev_pagemap(nr, nr_start, flags, pages);
2295 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2296 unsigned long end, unsigned int flags,
2297 struct page **pages, int *nr)
2303 static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr,
2304 unsigned long end, unsigned int flags,
2305 struct page **pages, int *nr)
2312 static int record_subpages(struct page *page, unsigned long addr,
2313 unsigned long end, struct page **pages)
2317 for (nr = 0; addr != end; addr += PAGE_SIZE)
2318 pages[nr++] = page++;
2323 #ifdef CONFIG_ARCH_HAS_HUGEPD
2324 static unsigned long hugepte_addr_end(unsigned long addr, unsigned long end,
2327 unsigned long __boundary = (addr + sz) & ~(sz-1);
2328 return (__boundary - 1 < end - 1) ? __boundary : end;
2331 static int gup_hugepte(pte_t *ptep, unsigned long sz, unsigned long addr,
2332 unsigned long end, unsigned int flags,
2333 struct page **pages, int *nr)
2335 unsigned long pte_end;
2336 struct page *head, *page;
2340 pte_end = (addr + sz) & ~(sz-1);
2344 pte = huge_ptep_get(ptep);
2346 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2349 /* hugepages are never "special" */
2350 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2352 head = pte_page(pte);
2353 page = head + ((addr & (sz-1)) >> PAGE_SHIFT);
2354 refs = record_subpages(page, addr, end, pages + *nr);
2356 head = try_grab_compound_head(head, refs, flags);
2360 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2361 put_compound_head(head, refs, flags);
2366 SetPageReferenced(head);
2370 static int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2371 unsigned int pdshift, unsigned long end, unsigned int flags,
2372 struct page **pages, int *nr)
2375 unsigned long sz = 1UL << hugepd_shift(hugepd);
2378 ptep = hugepte_offset(hugepd, addr, pdshift);
2380 next = hugepte_addr_end(addr, end, sz);
2381 if (!gup_hugepte(ptep, sz, addr, end, flags, pages, nr))
2383 } while (ptep++, addr = next, addr != end);
2388 static inline int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2389 unsigned int pdshift, unsigned long end, unsigned int flags,
2390 struct page **pages, int *nr)
2394 #endif /* CONFIG_ARCH_HAS_HUGEPD */
2396 static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2397 unsigned long end, unsigned int flags,
2398 struct page **pages, int *nr)
2400 struct page *head, *page;
2403 if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
2406 if (pmd_devmap(orig)) {
2407 if (unlikely(flags & FOLL_LONGTERM))
2409 return __gup_device_huge_pmd(orig, pmdp, addr, end, flags,
2413 page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2414 refs = record_subpages(page, addr, end, pages + *nr);
2416 head = try_grab_compound_head(pmd_page(orig), refs, flags);
2420 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2421 put_compound_head(head, refs, flags);
2426 SetPageReferenced(head);
2430 static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2431 unsigned long end, unsigned int flags,
2432 struct page **pages, int *nr)
2434 struct page *head, *page;
2437 if (!pud_access_permitted(orig, flags & FOLL_WRITE))
2440 if (pud_devmap(orig)) {
2441 if (unlikely(flags & FOLL_LONGTERM))
2443 return __gup_device_huge_pud(orig, pudp, addr, end, flags,
2447 page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2448 refs = record_subpages(page, addr, end, pages + *nr);
2450 head = try_grab_compound_head(pud_page(orig), refs, flags);
2454 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2455 put_compound_head(head, refs, flags);
2460 SetPageReferenced(head);
2464 static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
2465 unsigned long end, unsigned int flags,
2466 struct page **pages, int *nr)
2469 struct page *head, *page;
2471 if (!pgd_access_permitted(orig, flags & FOLL_WRITE))
2474 BUILD_BUG_ON(pgd_devmap(orig));
2476 page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT);
2477 refs = record_subpages(page, addr, end, pages + *nr);
2479 head = try_grab_compound_head(pgd_page(orig), refs, flags);
2483 if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
2484 put_compound_head(head, refs, flags);
2489 SetPageReferenced(head);
2493 static int gup_pmd_range(pud_t *pudp, pud_t pud, unsigned long addr, unsigned long end,
2494 unsigned int flags, struct page **pages, int *nr)
2499 pmdp = pmd_offset_lockless(pudp, pud, addr);
2501 pmd_t pmd = READ_ONCE(*pmdp);
2503 next = pmd_addr_end(addr, end);
2504 if (!pmd_present(pmd))
2507 if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd) ||
2510 * NUMA hinting faults need to be handled in the GUP
2511 * slowpath for accounting purposes and so that they
2512 * can be serialised against THP migration.
2514 if (pmd_protnone(pmd))
2517 if (!gup_huge_pmd(pmd, pmdp, addr, next, flags,
2521 } else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
2523 * architecture have different format for hugetlbfs
2524 * pmd format and THP pmd format
2526 if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
2527 PMD_SHIFT, next, flags, pages, nr))
2529 } else if (!gup_pte_range(pmd, addr, next, flags, pages, nr))
2531 } while (pmdp++, addr = next, addr != end);
2536 static int gup_pud_range(p4d_t *p4dp, p4d_t p4d, unsigned long addr, unsigned long end,
2537 unsigned int flags, struct page **pages, int *nr)
2542 pudp = pud_offset_lockless(p4dp, p4d, addr);
2544 pud_t pud = READ_ONCE(*pudp);
2546 next = pud_addr_end(addr, end);
2547 if (unlikely(!pud_present(pud)))
2549 if (unlikely(pud_huge(pud))) {
2550 if (!gup_huge_pud(pud, pudp, addr, next, flags,
2553 } else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
2554 if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
2555 PUD_SHIFT, next, flags, pages, nr))
2557 } else if (!gup_pmd_range(pudp, pud, addr, next, flags, pages, nr))
2559 } while (pudp++, addr = next, addr != end);
2564 static int gup_p4d_range(pgd_t *pgdp, pgd_t pgd, unsigned long addr, unsigned long end,
2565 unsigned int flags, struct page **pages, int *nr)
2570 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
2572 p4d_t p4d = READ_ONCE(*p4dp);
2574 next = p4d_addr_end(addr, end);
2577 BUILD_BUG_ON(p4d_huge(p4d));
2578 if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
2579 if (!gup_huge_pd(__hugepd(p4d_val(p4d)), addr,
2580 P4D_SHIFT, next, flags, pages, nr))
2582 } else if (!gup_pud_range(p4dp, p4d, addr, next, flags, pages, nr))
2584 } while (p4dp++, addr = next, addr != end);
2589 static void gup_pgd_range(unsigned long addr, unsigned long end,
2590 unsigned int flags, struct page **pages, int *nr)
2595 pgdp = pgd_offset(current->mm, addr);
2597 pgd_t pgd = READ_ONCE(*pgdp);
2599 next = pgd_addr_end(addr, end);
2602 if (unlikely(pgd_huge(pgd))) {
2603 if (!gup_huge_pgd(pgd, pgdp, addr, next, flags,
2606 } else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
2607 if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
2608 PGDIR_SHIFT, next, flags, pages, nr))
2610 } else if (!gup_p4d_range(pgdp, pgd, addr, next, flags, pages, nr))
2612 } while (pgdp++, addr = next, addr != end);
2615 static inline void gup_pgd_range(unsigned long addr, unsigned long end,
2616 unsigned int flags, struct page **pages, int *nr)
2619 #endif /* CONFIG_HAVE_FAST_GUP */
2621 #ifndef gup_fast_permitted
2623 * Check if it's allowed to use get_user_pages_fast_only() for the range, or
2624 * we need to fall back to the slow version:
2626 static bool gup_fast_permitted(unsigned long start, unsigned long end)
2632 static int __gup_longterm_unlocked(unsigned long start, int nr_pages,
2633 unsigned int gup_flags, struct page **pages)
2638 * FIXME: FOLL_LONGTERM does not work with
2639 * get_user_pages_unlocked() (see comments in that function)
2641 if (gup_flags & FOLL_LONGTERM) {
2642 mmap_read_lock(current->mm);
2643 ret = __gup_longterm_locked(current->mm,
2645 pages, NULL, gup_flags);
2646 mmap_read_unlock(current->mm);
2648 ret = get_user_pages_unlocked(start, nr_pages,
2655 static unsigned long lockless_pages_from_mm(unsigned long start,
2657 unsigned int gup_flags,
2658 struct page **pages)
2660 unsigned long flags;
2664 if (!IS_ENABLED(CONFIG_HAVE_FAST_GUP) ||
2665 !gup_fast_permitted(start, end))
2668 if (gup_flags & FOLL_PIN) {
2669 seq = raw_read_seqcount(¤t->mm->write_protect_seq);
2675 * Disable interrupts. The nested form is used, in order to allow full,
2676 * general purpose use of this routine.
2678 * With interrupts disabled, we block page table pages from being freed
2679 * from under us. See struct mmu_table_batch comments in
2680 * include/asm-generic/tlb.h for more details.
2682 * We do not adopt an rcu_read_lock() here as we also want to block IPIs
2683 * that come from THPs splitting.
2685 local_irq_save(flags);
2686 gup_pgd_range(start, end, gup_flags, pages, &nr_pinned);
2687 local_irq_restore(flags);
2690 * When pinning pages for DMA there could be a concurrent write protect
2691 * from fork() via copy_page_range(), in this case always fail fast GUP.
2693 if (gup_flags & FOLL_PIN) {
2694 if (read_seqcount_retry(¤t->mm->write_protect_seq, seq)) {
2695 unpin_user_pages(pages, nr_pinned);
2702 static int internal_get_user_pages_fast(unsigned long start,
2703 unsigned long nr_pages,
2704 unsigned int gup_flags,
2705 struct page **pages)
2707 unsigned long len, end;
2708 unsigned long nr_pinned;
2711 if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM |
2712 FOLL_FORCE | FOLL_PIN | FOLL_GET |
2716 if (gup_flags & FOLL_PIN)
2717 atomic_set(¤t->mm->has_pinned, 1);
2719 if (!(gup_flags & FOLL_FAST_ONLY))
2720 might_lock_read(¤t->mm->mmap_lock);
2722 start = untagged_addr(start) & PAGE_MASK;
2723 len = nr_pages << PAGE_SHIFT;
2724 if (check_add_overflow(start, len, &end))
2726 if (unlikely(!access_ok((void __user *)start, len)))
2729 nr_pinned = lockless_pages_from_mm(start, end, gup_flags, pages);
2730 if (nr_pinned == nr_pages || gup_flags & FOLL_FAST_ONLY)
2733 /* Slow path: try to get the remaining pages with get_user_pages */
2734 start += nr_pinned << PAGE_SHIFT;
2736 ret = __gup_longterm_unlocked(start, nr_pages - nr_pinned, gup_flags,
2740 * The caller has to unpin the pages we already pinned so
2741 * returning -errno is not an option
2747 return ret + nr_pinned;
2751 * get_user_pages_fast_only() - pin user pages in memory
2752 * @start: starting user address
2753 * @nr_pages: number of pages from start to pin
2754 * @gup_flags: flags modifying pin behaviour
2755 * @pages: array that receives pointers to the pages pinned.
2756 * Should be at least nr_pages long.
2758 * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
2760 * Note a difference with get_user_pages_fast: this always returns the
2761 * number of pages pinned, 0 if no pages were pinned.
2763 * If the architecture does not support this function, simply return with no
2766 * Careful, careful! COW breaking can go either way, so a non-write
2767 * access can get ambiguous page results. If you call this function without
2768 * 'write' set, you'd better be sure that you're ok with that ambiguity.
2770 int get_user_pages_fast_only(unsigned long start, int nr_pages,
2771 unsigned int gup_flags, struct page **pages)
2775 * Internally (within mm/gup.c), gup fast variants must set FOLL_GET,
2776 * because gup fast is always a "pin with a +1 page refcount" request.
2778 * FOLL_FAST_ONLY is required in order to match the API description of
2779 * this routine: no fall back to regular ("slow") GUP.
2781 gup_flags |= FOLL_GET | FOLL_FAST_ONLY;
2783 nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
2787 * As specified in the API description above, this routine is not
2788 * allowed to return negative values. However, the common core
2789 * routine internal_get_user_pages_fast() *can* return -errno.
2790 * Therefore, correct for that here:
2797 EXPORT_SYMBOL_GPL(get_user_pages_fast_only);
2800 * get_user_pages_fast() - pin user pages in memory
2801 * @start: starting user address
2802 * @nr_pages: number of pages from start to pin
2803 * @gup_flags: flags modifying pin behaviour
2804 * @pages: array that receives pointers to the pages pinned.
2805 * Should be at least nr_pages long.
2807 * Attempt to pin user pages in memory without taking mm->mmap_lock.
2808 * If not successful, it will fall back to taking the lock and
2809 * calling get_user_pages().
2811 * Returns number of pages pinned. This may be fewer than the number requested.
2812 * If nr_pages is 0 or negative, returns 0. If no pages were pinned, returns
2815 int get_user_pages_fast(unsigned long start, int nr_pages,
2816 unsigned int gup_flags, struct page **pages)
2818 if (!is_valid_gup_flags(gup_flags))
2822 * The caller may or may not have explicitly set FOLL_GET; either way is
2823 * OK. However, internally (within mm/gup.c), gup fast variants must set
2824 * FOLL_GET, because gup fast is always a "pin with a +1 page refcount"
2827 gup_flags |= FOLL_GET;
2828 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
2830 EXPORT_SYMBOL_GPL(get_user_pages_fast);
2833 * pin_user_pages_fast() - pin user pages in memory without taking locks
2835 * @start: starting user address
2836 * @nr_pages: number of pages from start to pin
2837 * @gup_flags: flags modifying pin behaviour
2838 * @pages: array that receives pointers to the pages pinned.
2839 * Should be at least nr_pages long.
2841 * Nearly the same as get_user_pages_fast(), except that FOLL_PIN is set. See
2842 * get_user_pages_fast() for documentation on the function arguments, because
2843 * the arguments here are identical.
2845 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
2846 * see Documentation/core-api/pin_user_pages.rst for further details.
2848 int pin_user_pages_fast(unsigned long start, int nr_pages,
2849 unsigned int gup_flags, struct page **pages)
2851 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2852 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2855 gup_flags |= FOLL_PIN;
2856 return internal_get_user_pages_fast(start, nr_pages, gup_flags, pages);
2858 EXPORT_SYMBOL_GPL(pin_user_pages_fast);
2861 * This is the FOLL_PIN equivalent of get_user_pages_fast_only(). Behavior
2862 * is the same, except that this one sets FOLL_PIN instead of FOLL_GET.
2864 * The API rules are the same, too: no negative values may be returned.
2866 int pin_user_pages_fast_only(unsigned long start, int nr_pages,
2867 unsigned int gup_flags, struct page **pages)
2872 * FOLL_GET and FOLL_PIN are mutually exclusive. Note that the API
2873 * rules require returning 0, rather than -errno:
2875 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2878 * FOLL_FAST_ONLY is required in order to match the API description of
2879 * this routine: no fall back to regular ("slow") GUP.
2881 gup_flags |= (FOLL_PIN | FOLL_FAST_ONLY);
2882 nr_pinned = internal_get_user_pages_fast(start, nr_pages, gup_flags,
2885 * This routine is not allowed to return negative values. However,
2886 * internal_get_user_pages_fast() *can* return -errno. Therefore,
2887 * correct for that here:
2894 EXPORT_SYMBOL_GPL(pin_user_pages_fast_only);
2897 * pin_user_pages_remote() - pin pages of a remote process
2899 * @mm: mm_struct of target mm
2900 * @start: starting user address
2901 * @nr_pages: number of pages from start to pin
2902 * @gup_flags: flags modifying lookup behaviour
2903 * @pages: array that receives pointers to the pages pinned.
2904 * Should be at least nr_pages long. Or NULL, if caller
2905 * only intends to ensure the pages are faulted in.
2906 * @vmas: array of pointers to vmas corresponding to each page.
2907 * Or NULL if the caller does not require them.
2908 * @locked: pointer to lock flag indicating whether lock is held and
2909 * subsequently whether VM_FAULT_RETRY functionality can be
2910 * utilised. Lock must initially be held.
2912 * Nearly the same as get_user_pages_remote(), except that FOLL_PIN is set. See
2913 * get_user_pages_remote() for documentation on the function arguments, because
2914 * the arguments here are identical.
2916 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
2917 * see Documentation/core-api/pin_user_pages.rst for details.
2919 long pin_user_pages_remote(struct mm_struct *mm,
2920 unsigned long start, unsigned long nr_pages,
2921 unsigned int gup_flags, struct page **pages,
2922 struct vm_area_struct **vmas, int *locked)
2924 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2925 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2928 gup_flags |= FOLL_PIN;
2929 return __get_user_pages_remote(mm, start, nr_pages, gup_flags,
2930 pages, vmas, locked);
2932 EXPORT_SYMBOL(pin_user_pages_remote);
2935 * pin_user_pages() - pin user pages in memory for use by other devices
2937 * @start: starting user address
2938 * @nr_pages: number of pages from start to pin
2939 * @gup_flags: flags modifying lookup behaviour
2940 * @pages: array that receives pointers to the pages pinned.
2941 * Should be at least nr_pages long. Or NULL, if caller
2942 * only intends to ensure the pages are faulted in.
2943 * @vmas: array of pointers to vmas corresponding to each page.
2944 * Or NULL if the caller does not require them.
2946 * Nearly the same as get_user_pages(), except that FOLL_TOUCH is not set, and
2949 * FOLL_PIN means that the pages must be released via unpin_user_page(). Please
2950 * see Documentation/core-api/pin_user_pages.rst for details.
2952 long pin_user_pages(unsigned long start, unsigned long nr_pages,
2953 unsigned int gup_flags, struct page **pages,
2954 struct vm_area_struct **vmas)
2956 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2957 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2960 gup_flags |= FOLL_PIN;
2961 return __gup_longterm_locked(current->mm, start, nr_pages,
2962 pages, vmas, gup_flags);
2964 EXPORT_SYMBOL(pin_user_pages);
2967 * pin_user_pages_unlocked() is the FOLL_PIN variant of
2968 * get_user_pages_unlocked(). Behavior is the same, except that this one sets
2969 * FOLL_PIN and rejects FOLL_GET.
2971 long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
2972 struct page **pages, unsigned int gup_flags)
2974 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
2975 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
2978 gup_flags |= FOLL_PIN;
2979 return get_user_pages_unlocked(start, nr_pages, pages, gup_flags);
2981 EXPORT_SYMBOL(pin_user_pages_unlocked);
2984 * pin_user_pages_locked() is the FOLL_PIN variant of get_user_pages_locked().
2985 * Behavior is the same, except that this one sets FOLL_PIN and rejects
2988 long pin_user_pages_locked(unsigned long start, unsigned long nr_pages,
2989 unsigned int gup_flags, struct page **pages,
2993 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
2994 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
2995 * vmas. As there are no users of this flag in this call we simply
2996 * disallow this option for now.
2998 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
3001 /* FOLL_GET and FOLL_PIN are mutually exclusive. */
3002 if (WARN_ON_ONCE(gup_flags & FOLL_GET))
3005 gup_flags |= FOLL_PIN;
3006 return __get_user_pages_locked(current->mm, start, nr_pages,
3007 pages, NULL, locked,
3008 gup_flags | FOLL_TOUCH);
3010 EXPORT_SYMBOL(pin_user_pages_locked);