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/pgtable.h>
23 #include <asm/tlbflush.h>
27 struct follow_page_context {
28 struct dev_pagemap *pgmap;
29 unsigned int page_mask;
33 * Return the compound head page with ref appropriately incremented,
34 * or NULL if that failed.
36 static inline struct page *try_get_compound_head(struct page *page, int refs)
38 struct page *head = compound_head(page);
40 if (WARN_ON_ONCE(page_ref_count(head) < 0))
42 if (unlikely(!page_cache_add_speculative(head, refs)))
48 * put_user_pages_dirty_lock() - release and optionally dirty gup-pinned pages
49 * @pages: array of pages to be maybe marked dirty, and definitely released.
50 * @npages: number of pages in the @pages array.
51 * @make_dirty: whether to mark the pages dirty
53 * "gup-pinned page" refers to a page that has had one of the get_user_pages()
54 * variants called on that page.
56 * For each page in the @pages array, make that page (or its head page, if a
57 * compound page) dirty, if @make_dirty is true, and if the page was previously
58 * listed as clean. In any case, releases all pages using put_user_page(),
59 * possibly via put_user_pages(), for the non-dirty case.
61 * Please see the put_user_page() documentation for details.
63 * set_page_dirty_lock() is used internally. If instead, set_page_dirty() is
64 * required, then the caller should a) verify that this is really correct,
65 * because _lock() is usually required, and b) hand code it:
66 * set_page_dirty_lock(), put_user_page().
69 void put_user_pages_dirty_lock(struct page **pages, unsigned long npages,
75 * TODO: this can be optimized for huge pages: if a series of pages is
76 * physically contiguous and part of the same compound page, then a
77 * single operation to the head page should suffice.
81 put_user_pages(pages, npages);
85 for (index = 0; index < npages; index++) {
86 struct page *page = compound_head(pages[index]);
88 * Checking PageDirty at this point may race with
89 * clear_page_dirty_for_io(), but that's OK. Two key
92 * 1) This code sees the page as already dirty, so it
93 * skips the call to set_page_dirty(). That could happen
94 * because clear_page_dirty_for_io() called
95 * page_mkclean(), followed by set_page_dirty().
96 * However, now the page is going to get written back,
97 * which meets the original intention of setting it
98 * dirty, so all is well: clear_page_dirty_for_io() goes
99 * on to call TestClearPageDirty(), and write the page
102 * 2) This code sees the page as clean, so it calls
103 * set_page_dirty(). The page stays dirty, despite being
104 * written back, so it gets written back again in the
105 * next writeback cycle. This is harmless.
107 if (!PageDirty(page))
108 set_page_dirty_lock(page);
112 EXPORT_SYMBOL(put_user_pages_dirty_lock);
115 * put_user_pages() - release an array of gup-pinned pages.
116 * @pages: array of pages to be marked dirty and released.
117 * @npages: number of pages in the @pages array.
119 * For each page in the @pages array, release the page using put_user_page().
121 * Please see the put_user_page() documentation for details.
123 void put_user_pages(struct page **pages, unsigned long npages)
128 * TODO: this can be optimized for huge pages: if a series of pages is
129 * physically contiguous and part of the same compound page, then a
130 * single operation to the head page should suffice.
132 for (index = 0; index < npages; index++)
133 put_user_page(pages[index]);
135 EXPORT_SYMBOL(put_user_pages);
138 static struct page *no_page_table(struct vm_area_struct *vma,
142 * When core dumping an enormous anonymous area that nobody
143 * has touched so far, we don't want to allocate unnecessary pages or
144 * page tables. Return error instead of NULL to skip handle_mm_fault,
145 * then get_dump_page() will return NULL to leave a hole in the dump.
146 * But we can only make this optimization where a hole would surely
147 * be zero-filled if handle_mm_fault() actually did handle it.
149 if ((flags & FOLL_DUMP) && (!vma->vm_ops || !vma->vm_ops->fault))
150 return ERR_PTR(-EFAULT);
154 static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
155 pte_t *pte, unsigned int flags)
157 /* No page to get reference */
158 if (flags & FOLL_GET)
161 if (flags & FOLL_TOUCH) {
164 if (flags & FOLL_WRITE)
165 entry = pte_mkdirty(entry);
166 entry = pte_mkyoung(entry);
168 if (!pte_same(*pte, entry)) {
169 set_pte_at(vma->vm_mm, address, pte, entry);
170 update_mmu_cache(vma, address, pte);
174 /* Proper page table entry exists, but no corresponding struct page */
179 * FOLL_FORCE can write to even unwritable pte's, but only
180 * after we've gone through a COW cycle and they are dirty.
182 static inline bool can_follow_write_pte(pte_t pte, unsigned int flags)
184 return pte_write(pte) ||
185 ((flags & FOLL_FORCE) && (flags & FOLL_COW) && pte_dirty(pte));
188 static struct page *follow_page_pte(struct vm_area_struct *vma,
189 unsigned long address, pmd_t *pmd, unsigned int flags,
190 struct dev_pagemap **pgmap)
192 struct mm_struct *mm = vma->vm_mm;
198 if (unlikely(pmd_bad(*pmd)))
199 return no_page_table(vma, flags);
201 ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
203 if (!pte_present(pte)) {
206 * KSM's break_ksm() relies upon recognizing a ksm page
207 * even while it is being migrated, so for that case we
208 * need migration_entry_wait().
210 if (likely(!(flags & FOLL_MIGRATION)))
214 entry = pte_to_swp_entry(pte);
215 if (!is_migration_entry(entry))
217 pte_unmap_unlock(ptep, ptl);
218 migration_entry_wait(mm, pmd, address);
221 if ((flags & FOLL_NUMA) && pte_protnone(pte))
223 if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
224 pte_unmap_unlock(ptep, ptl);
228 page = vm_normal_page(vma, address, pte);
229 if (!page && pte_devmap(pte) && (flags & FOLL_GET)) {
231 * Only return device mapping pages in the FOLL_GET case since
232 * they are only valid while holding the pgmap reference.
234 *pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
236 page = pte_page(pte);
239 } else if (unlikely(!page)) {
240 if (flags & FOLL_DUMP) {
241 /* Avoid special (like zero) pages in core dumps */
242 page = ERR_PTR(-EFAULT);
246 if (is_zero_pfn(pte_pfn(pte))) {
247 page = pte_page(pte);
251 ret = follow_pfn_pte(vma, address, ptep, flags);
257 if (flags & FOLL_SPLIT && PageTransCompound(page)) {
260 pte_unmap_unlock(ptep, ptl);
262 ret = split_huge_page(page);
270 if (flags & FOLL_GET) {
271 if (unlikely(!try_get_page(page))) {
272 page = ERR_PTR(-ENOMEM);
276 if (flags & FOLL_TOUCH) {
277 if ((flags & FOLL_WRITE) &&
278 !pte_dirty(pte) && !PageDirty(page))
279 set_page_dirty(page);
281 * pte_mkyoung() would be more correct here, but atomic care
282 * is needed to avoid losing the dirty bit: it is easier to use
283 * mark_page_accessed().
285 mark_page_accessed(page);
287 if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
288 /* Do not mlock pte-mapped THP */
289 if (PageTransCompound(page))
293 * The preliminary mapping check is mainly to avoid the
294 * pointless overhead of lock_page on the ZERO_PAGE
295 * which might bounce very badly if there is contention.
297 * If the page is already locked, we don't need to
298 * handle it now - vmscan will handle it later if and
299 * when it attempts to reclaim the page.
301 if (page->mapping && trylock_page(page)) {
302 lru_add_drain(); /* push cached pages to LRU */
304 * Because we lock page here, and migration is
305 * blocked by the pte's page reference, and we
306 * know the page is still mapped, we don't even
307 * need to check for file-cache page truncation.
309 mlock_vma_page(page);
314 pte_unmap_unlock(ptep, ptl);
317 pte_unmap_unlock(ptep, ptl);
320 return no_page_table(vma, flags);
323 static struct page *follow_pmd_mask(struct vm_area_struct *vma,
324 unsigned long address, pud_t *pudp,
326 struct follow_page_context *ctx)
331 struct mm_struct *mm = vma->vm_mm;
333 pmd = pmd_offset(pudp, address);
335 * The READ_ONCE() will stabilize the pmdval in a register or
336 * on the stack so that it will stop changing under the code.
338 pmdval = READ_ONCE(*pmd);
339 if (pmd_none(pmdval))
340 return no_page_table(vma, flags);
341 if (pmd_huge(pmdval) && is_vm_hugetlb_page(vma)) {
342 page = follow_huge_pmd(mm, address, pmd, flags);
345 return no_page_table(vma, flags);
347 if (is_hugepd(__hugepd(pmd_val(pmdval)))) {
348 page = follow_huge_pd(vma, address,
349 __hugepd(pmd_val(pmdval)), flags,
353 return no_page_table(vma, flags);
356 if (!pmd_present(pmdval)) {
357 if (likely(!(flags & FOLL_MIGRATION)))
358 return no_page_table(vma, flags);
359 VM_BUG_ON(thp_migration_supported() &&
360 !is_pmd_migration_entry(pmdval));
361 if (is_pmd_migration_entry(pmdval))
362 pmd_migration_entry_wait(mm, pmd);
363 pmdval = READ_ONCE(*pmd);
365 * MADV_DONTNEED may convert the pmd to null because
366 * mmap_sem is held in read mode
368 if (pmd_none(pmdval))
369 return no_page_table(vma, flags);
372 if (pmd_devmap(pmdval)) {
373 ptl = pmd_lock(mm, pmd);
374 page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
379 if (likely(!pmd_trans_huge(pmdval)))
380 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
382 if ((flags & FOLL_NUMA) && pmd_protnone(pmdval))
383 return no_page_table(vma, flags);
386 ptl = pmd_lock(mm, pmd);
387 if (unlikely(pmd_none(*pmd))) {
389 return no_page_table(vma, flags);
391 if (unlikely(!pmd_present(*pmd))) {
393 if (likely(!(flags & FOLL_MIGRATION)))
394 return no_page_table(vma, flags);
395 pmd_migration_entry_wait(mm, pmd);
398 if (unlikely(!pmd_trans_huge(*pmd))) {
400 return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
402 if (flags & (FOLL_SPLIT | FOLL_SPLIT_PMD)) {
404 page = pmd_page(*pmd);
405 if (is_huge_zero_page(page)) {
408 split_huge_pmd(vma, pmd, address);
409 if (pmd_trans_unstable(pmd))
411 } else if (flags & FOLL_SPLIT) {
412 if (unlikely(!try_get_page(page))) {
414 return ERR_PTR(-ENOMEM);
418 ret = split_huge_page(page);
422 return no_page_table(vma, flags);
423 } else { /* flags & FOLL_SPLIT_PMD */
425 split_huge_pmd(vma, pmd, address);
426 ret = pte_alloc(mm, pmd) ? -ENOMEM : 0;
429 return ret ? ERR_PTR(ret) :
430 follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
432 page = follow_trans_huge_pmd(vma, address, pmd, flags);
434 ctx->page_mask = HPAGE_PMD_NR - 1;
438 static struct page *follow_pud_mask(struct vm_area_struct *vma,
439 unsigned long address, p4d_t *p4dp,
441 struct follow_page_context *ctx)
446 struct mm_struct *mm = vma->vm_mm;
448 pud = pud_offset(p4dp, address);
450 return no_page_table(vma, flags);
451 if (pud_huge(*pud) && is_vm_hugetlb_page(vma)) {
452 page = follow_huge_pud(mm, address, pud, flags);
455 return no_page_table(vma, flags);
457 if (is_hugepd(__hugepd(pud_val(*pud)))) {
458 page = follow_huge_pd(vma, address,
459 __hugepd(pud_val(*pud)), flags,
463 return no_page_table(vma, flags);
465 if (pud_devmap(*pud)) {
466 ptl = pud_lock(mm, pud);
467 page = follow_devmap_pud(vma, address, pud, flags, &ctx->pgmap);
472 if (unlikely(pud_bad(*pud)))
473 return no_page_table(vma, flags);
475 return follow_pmd_mask(vma, address, pud, flags, ctx);
478 static struct page *follow_p4d_mask(struct vm_area_struct *vma,
479 unsigned long address, pgd_t *pgdp,
481 struct follow_page_context *ctx)
486 p4d = p4d_offset(pgdp, address);
488 return no_page_table(vma, flags);
489 BUILD_BUG_ON(p4d_huge(*p4d));
490 if (unlikely(p4d_bad(*p4d)))
491 return no_page_table(vma, flags);
493 if (is_hugepd(__hugepd(p4d_val(*p4d)))) {
494 page = follow_huge_pd(vma, address,
495 __hugepd(p4d_val(*p4d)), flags,
499 return no_page_table(vma, flags);
501 return follow_pud_mask(vma, address, p4d, flags, ctx);
505 * follow_page_mask - look up a page descriptor from a user-virtual address
506 * @vma: vm_area_struct mapping @address
507 * @address: virtual address to look up
508 * @flags: flags modifying lookup behaviour
509 * @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
510 * pointer to output page_mask
512 * @flags can have FOLL_ flags set, defined in <linux/mm.h>
514 * When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
515 * the device's dev_pagemap metadata to avoid repeating expensive lookups.
517 * On output, the @ctx->page_mask is set according to the size of the page.
519 * Return: the mapped (struct page *), %NULL if no mapping exists, or
520 * an error pointer if there is a mapping to something not represented
521 * by a page descriptor (see also vm_normal_page()).
523 static struct page *follow_page_mask(struct vm_area_struct *vma,
524 unsigned long address, unsigned int flags,
525 struct follow_page_context *ctx)
529 struct mm_struct *mm = vma->vm_mm;
533 /* make this handle hugepd */
534 page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
536 BUG_ON(flags & FOLL_GET);
540 pgd = pgd_offset(mm, address);
542 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
543 return no_page_table(vma, flags);
545 if (pgd_huge(*pgd)) {
546 page = follow_huge_pgd(mm, address, pgd, flags);
549 return no_page_table(vma, flags);
551 if (is_hugepd(__hugepd(pgd_val(*pgd)))) {
552 page = follow_huge_pd(vma, address,
553 __hugepd(pgd_val(*pgd)), flags,
557 return no_page_table(vma, flags);
560 return follow_p4d_mask(vma, address, pgd, flags, ctx);
563 struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
564 unsigned int foll_flags)
566 struct follow_page_context ctx = { NULL };
569 page = follow_page_mask(vma, address, foll_flags, &ctx);
571 put_dev_pagemap(ctx.pgmap);
575 static int get_gate_page(struct mm_struct *mm, unsigned long address,
576 unsigned int gup_flags, struct vm_area_struct **vma,
586 /* user gate pages are read-only */
587 if (gup_flags & FOLL_WRITE)
589 if (address > TASK_SIZE)
590 pgd = pgd_offset_k(address);
592 pgd = pgd_offset_gate(mm, address);
595 p4d = p4d_offset(pgd, address);
598 pud = pud_offset(p4d, address);
601 pmd = pmd_offset(pud, address);
602 if (!pmd_present(*pmd))
604 VM_BUG_ON(pmd_trans_huge(*pmd));
605 pte = pte_offset_map(pmd, address);
608 *vma = get_gate_vma(mm);
611 *page = vm_normal_page(*vma, address, *pte);
613 if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
615 *page = pte_page(*pte);
617 if (unlikely(!try_get_page(*page))) {
629 * mmap_sem must be held on entry. If @nonblocking != NULL and
630 * *@flags does not include FOLL_NOWAIT, the mmap_sem may be released.
631 * If it is, *@nonblocking will be set to 0 and -EBUSY returned.
633 static int faultin_page(struct task_struct *tsk, struct vm_area_struct *vma,
634 unsigned long address, unsigned int *flags, int *nonblocking)
636 unsigned int fault_flags = 0;
639 /* mlock all present pages, but do not fault in new pages */
640 if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)
642 if (*flags & FOLL_WRITE)
643 fault_flags |= FAULT_FLAG_WRITE;
644 if (*flags & FOLL_REMOTE)
645 fault_flags |= FAULT_FLAG_REMOTE;
647 fault_flags |= FAULT_FLAG_ALLOW_RETRY;
648 if (*flags & FOLL_NOWAIT)
649 fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
650 if (*flags & FOLL_TRIED) {
651 VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY);
652 fault_flags |= FAULT_FLAG_TRIED;
655 ret = handle_mm_fault(vma, address, fault_flags);
656 if (ret & VM_FAULT_ERROR) {
657 int err = vm_fault_to_errno(ret, *flags);
665 if (ret & VM_FAULT_MAJOR)
671 if (ret & VM_FAULT_RETRY) {
672 if (nonblocking && !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
678 * The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
679 * necessary, even if maybe_mkwrite decided not to set pte_write. We
680 * can thus safely do subsequent page lookups as if they were reads.
681 * But only do so when looping for pte_write is futile: in some cases
682 * userspace may also be wanting to write to the gotten user page,
683 * which a read fault here might prevent (a readonly page might get
684 * reCOWed by userspace write).
686 if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
691 static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
693 vm_flags_t vm_flags = vma->vm_flags;
694 int write = (gup_flags & FOLL_WRITE);
695 int foreign = (gup_flags & FOLL_REMOTE);
697 if (vm_flags & (VM_IO | VM_PFNMAP))
700 if (gup_flags & FOLL_ANON && !vma_is_anonymous(vma))
704 if (!(vm_flags & VM_WRITE)) {
705 if (!(gup_flags & FOLL_FORCE))
708 * We used to let the write,force case do COW in a
709 * VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
710 * set a breakpoint in a read-only mapping of an
711 * executable, without corrupting the file (yet only
712 * when that file had been opened for writing!).
713 * Anon pages in shared mappings are surprising: now
716 if (!is_cow_mapping(vm_flags))
719 } else if (!(vm_flags & VM_READ)) {
720 if (!(gup_flags & FOLL_FORCE))
723 * Is there actually any vma we can reach here which does not
724 * have VM_MAYREAD set?
726 if (!(vm_flags & VM_MAYREAD))
730 * gups are always data accesses, not instruction
731 * fetches, so execute=false here
733 if (!arch_vma_access_permitted(vma, write, false, foreign))
739 * __get_user_pages() - pin user pages in memory
740 * @tsk: task_struct of target task
741 * @mm: mm_struct of target mm
742 * @start: starting user address
743 * @nr_pages: number of pages from start to pin
744 * @gup_flags: flags modifying pin behaviour
745 * @pages: array that receives pointers to the pages pinned.
746 * Should be at least nr_pages long. Or NULL, if caller
747 * only intends to ensure the pages are faulted in.
748 * @vmas: array of pointers to vmas corresponding to each page.
749 * Or NULL if the caller does not require them.
750 * @nonblocking: whether waiting for disk IO or mmap_sem contention
752 * Returns either number of pages pinned (which may be less than the
753 * number requested), or an error. Details about the return value:
755 * -- If nr_pages is 0, returns 0.
756 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
757 * -- If nr_pages is >0, and some pages were pinned, returns the number of
758 * pages pinned. Again, this may be less than nr_pages.
760 * The caller is responsible for releasing returned @pages, via put_page().
762 * @vmas are valid only as long as mmap_sem is held.
764 * Must be called with mmap_sem held. It may be released. See below.
766 * __get_user_pages walks a process's page tables and takes a reference to
767 * each struct page that each user address corresponds to at a given
768 * instant. That is, it takes the page that would be accessed if a user
769 * thread accesses the given user virtual address at that instant.
771 * This does not guarantee that the page exists in the user mappings when
772 * __get_user_pages returns, and there may even be a completely different
773 * page there in some cases (eg. if mmapped pagecache has been invalidated
774 * and subsequently re faulted). However it does guarantee that the page
775 * won't be freed completely. And mostly callers simply care that the page
776 * contains data that was valid *at some point in time*. Typically, an IO
777 * or similar operation cannot guarantee anything stronger anyway because
778 * locks can't be held over the syscall boundary.
780 * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
781 * the page is written to, set_page_dirty (or set_page_dirty_lock, as
782 * appropriate) must be called after the page is finished with, and
783 * before put_page is called.
785 * If @nonblocking != NULL, __get_user_pages will not wait for disk IO
786 * or mmap_sem contention, and if waiting is needed to pin all pages,
787 * *@nonblocking will be set to 0. Further, if @gup_flags does not
788 * include FOLL_NOWAIT, the mmap_sem will be released via up_read() in
791 * A caller using such a combination of @nonblocking and @gup_flags
792 * must therefore hold the mmap_sem for reading only, and recognize
793 * when it's been released. Otherwise, it must be held for either
794 * reading or writing and will not be released.
796 * In most cases, get_user_pages or get_user_pages_fast should be used
797 * instead of __get_user_pages. __get_user_pages should be used only if
798 * you need some special @gup_flags.
800 static long __get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
801 unsigned long start, unsigned long nr_pages,
802 unsigned int gup_flags, struct page **pages,
803 struct vm_area_struct **vmas, int *nonblocking)
806 struct vm_area_struct *vma = NULL;
807 struct follow_page_context ctx = { NULL };
812 start = untagged_addr(start);
814 VM_BUG_ON(!!pages != !!(gup_flags & FOLL_GET));
817 * If FOLL_FORCE is set then do not force a full fault as the hinting
818 * fault information is unrelated to the reference behaviour of a task
819 * using the address space
821 if (!(gup_flags & FOLL_FORCE))
822 gup_flags |= FOLL_NUMA;
826 unsigned int foll_flags = gup_flags;
827 unsigned int page_increm;
829 /* first iteration or cross vma bound */
830 if (!vma || start >= vma->vm_end) {
831 vma = find_extend_vma(mm, start);
832 if (!vma && in_gate_area(mm, start)) {
833 ret = get_gate_page(mm, start & PAGE_MASK,
835 pages ? &pages[i] : NULL);
842 if (!vma || check_vma_flags(vma, gup_flags)) {
846 if (is_vm_hugetlb_page(vma)) {
847 i = follow_hugetlb_page(mm, vma, pages, vmas,
848 &start, &nr_pages, i,
849 gup_flags, nonblocking);
855 * If we have a pending SIGKILL, don't keep faulting pages and
856 * potentially allocating memory.
858 if (fatal_signal_pending(current)) {
864 page = follow_page_mask(vma, start, foll_flags, &ctx);
866 ret = faultin_page(tsk, vma, start, &foll_flags,
882 } else if (PTR_ERR(page) == -EEXIST) {
884 * Proper page table entry exists, but no corresponding
888 } else if (IS_ERR(page)) {
894 flush_anon_page(vma, page, start);
895 flush_dcache_page(page);
903 page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
904 if (page_increm > nr_pages)
905 page_increm = nr_pages;
907 start += page_increm * PAGE_SIZE;
908 nr_pages -= page_increm;
912 put_dev_pagemap(ctx.pgmap);
916 static bool vma_permits_fault(struct vm_area_struct *vma,
917 unsigned int fault_flags)
919 bool write = !!(fault_flags & FAULT_FLAG_WRITE);
920 bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
921 vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
923 if (!(vm_flags & vma->vm_flags))
927 * The architecture might have a hardware protection
928 * mechanism other than read/write that can deny access.
930 * gup always represents data access, not instruction
931 * fetches, so execute=false here:
933 if (!arch_vma_access_permitted(vma, write, false, foreign))
940 * fixup_user_fault() - manually resolve a user page fault
941 * @tsk: the task_struct to use for page fault accounting, or
942 * NULL if faults are not to be recorded.
943 * @mm: mm_struct of target mm
944 * @address: user address
945 * @fault_flags:flags to pass down to handle_mm_fault()
946 * @unlocked: did we unlock the mmap_sem while retrying, maybe NULL if caller
947 * does not allow retry
949 * This is meant to be called in the specific scenario where for locking reasons
950 * we try to access user memory in atomic context (within a pagefault_disable()
951 * section), this returns -EFAULT, and we want to resolve the user fault before
954 * Typically this is meant to be used by the futex code.
956 * The main difference with get_user_pages() is that this function will
957 * unconditionally call handle_mm_fault() which will in turn perform all the
958 * necessary SW fixup of the dirty and young bits in the PTE, while
959 * get_user_pages() only guarantees to update these in the struct page.
961 * This is important for some architectures where those bits also gate the
962 * access permission to the page because they are maintained in software. On
963 * such architectures, gup() will not be enough to make a subsequent access
966 * This function will not return with an unlocked mmap_sem. So it has not the
967 * same semantics wrt the @mm->mmap_sem as does filemap_fault().
969 int fixup_user_fault(struct task_struct *tsk, struct mm_struct *mm,
970 unsigned long address, unsigned int fault_flags,
973 struct vm_area_struct *vma;
974 vm_fault_t ret, major = 0;
976 address = untagged_addr(address);
979 fault_flags |= FAULT_FLAG_ALLOW_RETRY;
982 vma = find_extend_vma(mm, address);
983 if (!vma || address < vma->vm_start)
986 if (!vma_permits_fault(vma, fault_flags))
989 ret = handle_mm_fault(vma, address, fault_flags);
990 major |= ret & VM_FAULT_MAJOR;
991 if (ret & VM_FAULT_ERROR) {
992 int err = vm_fault_to_errno(ret, 0);
999 if (ret & VM_FAULT_RETRY) {
1000 down_read(&mm->mmap_sem);
1001 if (!(fault_flags & FAULT_FLAG_TRIED)) {
1003 fault_flags &= ~FAULT_FLAG_ALLOW_RETRY;
1004 fault_flags |= FAULT_FLAG_TRIED;
1017 EXPORT_SYMBOL_GPL(fixup_user_fault);
1019 static __always_inline long __get_user_pages_locked(struct task_struct *tsk,
1020 struct mm_struct *mm,
1021 unsigned long start,
1022 unsigned long nr_pages,
1023 struct page **pages,
1024 struct vm_area_struct **vmas,
1028 long ret, pages_done;
1032 /* if VM_FAULT_RETRY can be returned, vmas become invalid */
1034 /* check caller initialized locked */
1035 BUG_ON(*locked != 1);
1042 lock_dropped = false;
1044 ret = __get_user_pages(tsk, mm, start, nr_pages, flags, pages,
1047 /* VM_FAULT_RETRY couldn't trigger, bypass */
1050 /* VM_FAULT_RETRY cannot return errors */
1053 BUG_ON(ret >= nr_pages);
1064 * VM_FAULT_RETRY didn't trigger or it was a
1072 * VM_FAULT_RETRY triggered, so seek to the faulting offset.
1073 * For the prefault case (!pages) we only update counts.
1077 start += ret << PAGE_SHIFT;
1080 * Repeat on the address that fired VM_FAULT_RETRY
1081 * without FAULT_FLAG_ALLOW_RETRY but with
1085 lock_dropped = true;
1086 down_read(&mm->mmap_sem);
1087 ret = __get_user_pages(tsk, mm, start, 1, flags | FOLL_TRIED,
1103 if (lock_dropped && *locked) {
1105 * We must let the caller know we temporarily dropped the lock
1106 * and so the critical section protected by it was lost.
1108 up_read(&mm->mmap_sem);
1115 * get_user_pages_remote() - pin user pages in memory
1116 * @tsk: the task_struct to use for page fault accounting, or
1117 * NULL if faults are not to be recorded.
1118 * @mm: mm_struct of target mm
1119 * @start: starting user address
1120 * @nr_pages: number of pages from start to pin
1121 * @gup_flags: flags modifying lookup behaviour
1122 * @pages: array that receives pointers to the pages pinned.
1123 * Should be at least nr_pages long. Or NULL, if caller
1124 * only intends to ensure the pages are faulted in.
1125 * @vmas: array of pointers to vmas corresponding to each page.
1126 * Or NULL if the caller does not require them.
1127 * @locked: pointer to lock flag indicating whether lock is held and
1128 * subsequently whether VM_FAULT_RETRY functionality can be
1129 * utilised. Lock must initially be held.
1131 * Returns either number of pages pinned (which may be less than the
1132 * number requested), or an error. Details about the return value:
1134 * -- If nr_pages is 0, returns 0.
1135 * -- If nr_pages is >0, but no pages were pinned, returns -errno.
1136 * -- If nr_pages is >0, and some pages were pinned, returns the number of
1137 * pages pinned. Again, this may be less than nr_pages.
1139 * The caller is responsible for releasing returned @pages, via put_page().
1141 * @vmas are valid only as long as mmap_sem is held.
1143 * Must be called with mmap_sem held for read or write.
1145 * get_user_pages walks a process's page tables and takes a reference to
1146 * each struct page that each user address corresponds to at a given
1147 * instant. That is, it takes the page that would be accessed if a user
1148 * thread accesses the given user virtual address at that instant.
1150 * This does not guarantee that the page exists in the user mappings when
1151 * get_user_pages returns, and there may even be a completely different
1152 * page there in some cases (eg. if mmapped pagecache has been invalidated
1153 * and subsequently re faulted). However it does guarantee that the page
1154 * won't be freed completely. And mostly callers simply care that the page
1155 * contains data that was valid *at some point in time*. Typically, an IO
1156 * or similar operation cannot guarantee anything stronger anyway because
1157 * locks can't be held over the syscall boundary.
1159 * If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
1160 * is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
1161 * be called after the page is finished with, and before put_page is called.
1163 * get_user_pages is typically used for fewer-copy IO operations, to get a
1164 * handle on the memory by some means other than accesses via the user virtual
1165 * addresses. The pages may be submitted for DMA to devices or accessed via
1166 * their kernel linear mapping (via the kmap APIs). Care should be taken to
1167 * use the correct cache flushing APIs.
1169 * See also get_user_pages_fast, for performance critical applications.
1171 * get_user_pages should be phased out in favor of
1172 * get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
1173 * should use get_user_pages because it cannot pass
1174 * FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
1176 long get_user_pages_remote(struct task_struct *tsk, struct mm_struct *mm,
1177 unsigned long start, unsigned long nr_pages,
1178 unsigned int gup_flags, struct page **pages,
1179 struct vm_area_struct **vmas, int *locked)
1182 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
1183 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1184 * vmas. As there are no users of this flag in this call we simply
1185 * disallow this option for now.
1187 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1190 return __get_user_pages_locked(tsk, mm, start, nr_pages, pages, vmas,
1192 gup_flags | FOLL_TOUCH | FOLL_REMOTE);
1194 EXPORT_SYMBOL(get_user_pages_remote);
1197 * populate_vma_page_range() - populate a range of pages in the vma.
1199 * @start: start address
1203 * This takes care of mlocking the pages too if VM_LOCKED is set.
1205 * return 0 on success, negative error code on error.
1207 * vma->vm_mm->mmap_sem must be held.
1209 * If @nonblocking is NULL, it may be held for read or write and will
1212 * If @nonblocking is non-NULL, it must held for read only and may be
1213 * released. If it's released, *@nonblocking will be set to 0.
1215 long populate_vma_page_range(struct vm_area_struct *vma,
1216 unsigned long start, unsigned long end, int *nonblocking)
1218 struct mm_struct *mm = vma->vm_mm;
1219 unsigned long nr_pages = (end - start) / PAGE_SIZE;
1222 VM_BUG_ON(start & ~PAGE_MASK);
1223 VM_BUG_ON(end & ~PAGE_MASK);
1224 VM_BUG_ON_VMA(start < vma->vm_start, vma);
1225 VM_BUG_ON_VMA(end > vma->vm_end, vma);
1226 VM_BUG_ON_MM(!rwsem_is_locked(&mm->mmap_sem), mm);
1228 gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK;
1229 if (vma->vm_flags & VM_LOCKONFAULT)
1230 gup_flags &= ~FOLL_POPULATE;
1232 * We want to touch writable mappings with a write fault in order
1233 * to break COW, except for shared mappings because these don't COW
1234 * and we would not want to dirty them for nothing.
1236 if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
1237 gup_flags |= FOLL_WRITE;
1240 * We want mlock to succeed for regions that have any permissions
1241 * other than PROT_NONE.
1243 if (vma->vm_flags & (VM_READ | VM_WRITE | VM_EXEC))
1244 gup_flags |= FOLL_FORCE;
1247 * We made sure addr is within a VMA, so the following will
1248 * not result in a stack expansion that recurses back here.
1250 return __get_user_pages(current, mm, start, nr_pages, gup_flags,
1251 NULL, NULL, nonblocking);
1255 * __mm_populate - populate and/or mlock pages within a range of address space.
1257 * This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
1258 * flags. VMAs must be already marked with the desired vm_flags, and
1259 * mmap_sem must not be held.
1261 int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
1263 struct mm_struct *mm = current->mm;
1264 unsigned long end, nstart, nend;
1265 struct vm_area_struct *vma = NULL;
1271 for (nstart = start; nstart < end; nstart = nend) {
1273 * We want to fault in pages for [nstart; end) address range.
1274 * Find first corresponding VMA.
1278 down_read(&mm->mmap_sem);
1279 vma = find_vma(mm, nstart);
1280 } else if (nstart >= vma->vm_end)
1282 if (!vma || vma->vm_start >= end)
1285 * Set [nstart; nend) to intersection of desired address
1286 * range with the first VMA. Also, skip undesirable VMA types.
1288 nend = min(end, vma->vm_end);
1289 if (vma->vm_flags & (VM_IO | VM_PFNMAP))
1291 if (nstart < vma->vm_start)
1292 nstart = vma->vm_start;
1294 * Now fault in a range of pages. populate_vma_page_range()
1295 * double checks the vma flags, so that it won't mlock pages
1296 * if the vma was already munlocked.
1298 ret = populate_vma_page_range(vma, nstart, nend, &locked);
1300 if (ignore_errors) {
1302 continue; /* continue at next VMA */
1306 nend = nstart + ret * PAGE_SIZE;
1310 up_read(&mm->mmap_sem);
1311 return ret; /* 0 or negative error code */
1315 * get_dump_page() - pin user page in memory while writing it to core dump
1316 * @addr: user address
1318 * Returns struct page pointer of user page pinned for dump,
1319 * to be freed afterwards by put_page().
1321 * Returns NULL on any kind of failure - a hole must then be inserted into
1322 * the corefile, to preserve alignment with its headers; and also returns
1323 * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
1324 * allowing a hole to be left in the corefile to save diskspace.
1326 * Called without mmap_sem, but after all other threads have been killed.
1328 #ifdef CONFIG_ELF_CORE
1329 struct page *get_dump_page(unsigned long addr)
1331 struct vm_area_struct *vma;
1334 if (__get_user_pages(current, current->mm, addr, 1,
1335 FOLL_FORCE | FOLL_DUMP | FOLL_GET, &page, &vma,
1338 flush_cache_page(vma, addr, page_to_pfn(page));
1341 #endif /* CONFIG_ELF_CORE */
1342 #else /* CONFIG_MMU */
1343 static long __get_user_pages_locked(struct task_struct *tsk,
1344 struct mm_struct *mm, unsigned long start,
1345 unsigned long nr_pages, struct page **pages,
1346 struct vm_area_struct **vmas, int *locked,
1347 unsigned int foll_flags)
1349 struct vm_area_struct *vma;
1350 unsigned long vm_flags;
1353 /* calculate required read or write permissions.
1354 * If FOLL_FORCE is set, we only require the "MAY" flags.
1356 vm_flags = (foll_flags & FOLL_WRITE) ?
1357 (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
1358 vm_flags &= (foll_flags & FOLL_FORCE) ?
1359 (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
1361 for (i = 0; i < nr_pages; i++) {
1362 vma = find_vma(mm, start);
1364 goto finish_or_fault;
1366 /* protect what we can, including chardevs */
1367 if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
1368 !(vm_flags & vma->vm_flags))
1369 goto finish_or_fault;
1372 pages[i] = virt_to_page(start);
1378 start = (start + PAGE_SIZE) & PAGE_MASK;
1384 return i ? : -EFAULT;
1386 #endif /* !CONFIG_MMU */
1388 #if defined(CONFIG_FS_DAX) || defined (CONFIG_CMA)
1389 static bool check_dax_vmas(struct vm_area_struct **vmas, long nr_pages)
1392 struct vm_area_struct *vma_prev = NULL;
1394 for (i = 0; i < nr_pages; i++) {
1395 struct vm_area_struct *vma = vmas[i];
1397 if (vma == vma_prev)
1402 if (vma_is_fsdax(vma))
1409 static struct page *new_non_cma_page(struct page *page, unsigned long private)
1412 * We want to make sure we allocate the new page from the same node
1413 * as the source page.
1415 int nid = page_to_nid(page);
1417 * Trying to allocate a page for migration. Ignore allocation
1418 * failure warnings. We don't force __GFP_THISNODE here because
1419 * this node here is the node where we have CMA reservation and
1420 * in some case these nodes will have really less non movable
1421 * allocation memory.
1423 gfp_t gfp_mask = GFP_USER | __GFP_NOWARN;
1425 if (PageHighMem(page))
1426 gfp_mask |= __GFP_HIGHMEM;
1428 #ifdef CONFIG_HUGETLB_PAGE
1429 if (PageHuge(page)) {
1430 struct hstate *h = page_hstate(page);
1432 * We don't want to dequeue from the pool because pool pages will
1433 * mostly be from the CMA region.
1435 return alloc_migrate_huge_page(h, gfp_mask, nid, NULL);
1438 if (PageTransHuge(page)) {
1441 * ignore allocation failure warnings
1443 gfp_t thp_gfpmask = GFP_TRANSHUGE | __GFP_NOWARN;
1446 * Remove the movable mask so that we don't allocate from
1449 thp_gfpmask &= ~__GFP_MOVABLE;
1450 thp = __alloc_pages_node(nid, thp_gfpmask, HPAGE_PMD_ORDER);
1453 prep_transhuge_page(thp);
1457 return __alloc_pages_node(nid, gfp_mask, 0);
1460 static long check_and_migrate_cma_pages(struct task_struct *tsk,
1461 struct mm_struct *mm,
1462 unsigned long start,
1463 unsigned long nr_pages,
1464 struct page **pages,
1465 struct vm_area_struct **vmas,
1466 unsigned int gup_flags)
1470 bool drain_allow = true;
1471 bool migrate_allow = true;
1472 LIST_HEAD(cma_page_list);
1473 long ret = nr_pages;
1476 for (i = 0; i < nr_pages;) {
1478 struct page *head = compound_head(pages[i]);
1481 * gup may start from a tail page. Advance step by the left
1484 step = compound_nr(head) - (pages[i] - head);
1486 * If we get a page from the CMA zone, since we are going to
1487 * be pinning these entries, we might as well move them out
1488 * of the CMA zone if possible.
1490 if (is_migrate_cma_page(head)) {
1492 isolate_huge_page(head, &cma_page_list);
1494 if (!PageLRU(head) && drain_allow) {
1495 lru_add_drain_all();
1496 drain_allow = false;
1499 if (!isolate_lru_page(head)) {
1500 list_add_tail(&head->lru, &cma_page_list);
1501 mod_node_page_state(page_pgdat(head),
1503 page_is_file_cache(head),
1504 hpage_nr_pages(head));
1512 if (!list_empty(&cma_page_list)) {
1514 * drop the above get_user_pages reference.
1516 for (i = 0; i < nr_pages; i++)
1519 if (migrate_pages(&cma_page_list, new_non_cma_page,
1520 NULL, 0, MIGRATE_SYNC, MR_CONTIG_RANGE)) {
1522 * some of the pages failed migration. Do get_user_pages
1523 * without migration.
1525 migrate_allow = false;
1527 if (!list_empty(&cma_page_list))
1528 putback_movable_pages(&cma_page_list);
1531 * We did migrate all the pages, Try to get the page references
1532 * again migrating any new CMA pages which we failed to isolate
1535 ret = __get_user_pages_locked(tsk, mm, start, nr_pages,
1539 if ((ret > 0) && migrate_allow) {
1549 static long check_and_migrate_cma_pages(struct task_struct *tsk,
1550 struct mm_struct *mm,
1551 unsigned long start,
1552 unsigned long nr_pages,
1553 struct page **pages,
1554 struct vm_area_struct **vmas,
1555 unsigned int gup_flags)
1559 #endif /* CONFIG_CMA */
1562 * __gup_longterm_locked() is a wrapper for __get_user_pages_locked which
1563 * allows us to process the FOLL_LONGTERM flag.
1565 static long __gup_longterm_locked(struct task_struct *tsk,
1566 struct mm_struct *mm,
1567 unsigned long start,
1568 unsigned long nr_pages,
1569 struct page **pages,
1570 struct vm_area_struct **vmas,
1571 unsigned int gup_flags)
1573 struct vm_area_struct **vmas_tmp = vmas;
1574 unsigned long flags = 0;
1577 if (gup_flags & FOLL_LONGTERM) {
1582 vmas_tmp = kcalloc(nr_pages,
1583 sizeof(struct vm_area_struct *),
1588 flags = memalloc_nocma_save();
1591 rc = __get_user_pages_locked(tsk, mm, start, nr_pages, pages,
1592 vmas_tmp, NULL, gup_flags);
1594 if (gup_flags & FOLL_LONGTERM) {
1595 memalloc_nocma_restore(flags);
1599 if (check_dax_vmas(vmas_tmp, rc)) {
1600 for (i = 0; i < rc; i++)
1606 rc = check_and_migrate_cma_pages(tsk, mm, start, rc, pages,
1607 vmas_tmp, gup_flags);
1611 if (vmas_tmp != vmas)
1615 #else /* !CONFIG_FS_DAX && !CONFIG_CMA */
1616 static __always_inline long __gup_longterm_locked(struct task_struct *tsk,
1617 struct mm_struct *mm,
1618 unsigned long start,
1619 unsigned long nr_pages,
1620 struct page **pages,
1621 struct vm_area_struct **vmas,
1624 return __get_user_pages_locked(tsk, mm, start, nr_pages, pages, vmas,
1627 #endif /* CONFIG_FS_DAX || CONFIG_CMA */
1630 * This is the same as get_user_pages_remote(), just with a
1631 * less-flexible calling convention where we assume that the task
1632 * and mm being operated on are the current task's and don't allow
1633 * passing of a locked parameter. We also obviously don't pass
1634 * FOLL_REMOTE in here.
1636 long get_user_pages(unsigned long start, unsigned long nr_pages,
1637 unsigned int gup_flags, struct page **pages,
1638 struct vm_area_struct **vmas)
1640 return __gup_longterm_locked(current, current->mm, start, nr_pages,
1641 pages, vmas, gup_flags | FOLL_TOUCH);
1643 EXPORT_SYMBOL(get_user_pages);
1646 * We can leverage the VM_FAULT_RETRY functionality in the page fault
1647 * paths better by using either get_user_pages_locked() or
1648 * get_user_pages_unlocked().
1650 * get_user_pages_locked() is suitable to replace the form:
1652 * down_read(&mm->mmap_sem);
1654 * get_user_pages(tsk, mm, ..., pages, NULL);
1655 * up_read(&mm->mmap_sem);
1660 * down_read(&mm->mmap_sem);
1662 * get_user_pages_locked(tsk, mm, ..., pages, &locked);
1664 * up_read(&mm->mmap_sem);
1666 long get_user_pages_locked(unsigned long start, unsigned long nr_pages,
1667 unsigned int gup_flags, struct page **pages,
1671 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
1672 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1673 * vmas. As there are no users of this flag in this call we simply
1674 * disallow this option for now.
1676 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1679 return __get_user_pages_locked(current, current->mm, start, nr_pages,
1680 pages, NULL, locked,
1681 gup_flags | FOLL_TOUCH);
1683 EXPORT_SYMBOL(get_user_pages_locked);
1686 * get_user_pages_unlocked() is suitable to replace the form:
1688 * down_read(&mm->mmap_sem);
1689 * get_user_pages(tsk, mm, ..., pages, NULL);
1690 * up_read(&mm->mmap_sem);
1694 * get_user_pages_unlocked(tsk, mm, ..., pages);
1696 * It is functionally equivalent to get_user_pages_fast so
1697 * get_user_pages_fast should be used instead if specific gup_flags
1698 * (e.g. FOLL_FORCE) are not required.
1700 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
1701 struct page **pages, unsigned int gup_flags)
1703 struct mm_struct *mm = current->mm;
1708 * FIXME: Current FOLL_LONGTERM behavior is incompatible with
1709 * FAULT_FLAG_ALLOW_RETRY because of the FS DAX check requirement on
1710 * vmas. As there are no users of this flag in this call we simply
1711 * disallow this option for now.
1713 if (WARN_ON_ONCE(gup_flags & FOLL_LONGTERM))
1716 down_read(&mm->mmap_sem);
1717 ret = __get_user_pages_locked(current, mm, start, nr_pages, pages, NULL,
1718 &locked, gup_flags | FOLL_TOUCH);
1720 up_read(&mm->mmap_sem);
1723 EXPORT_SYMBOL(get_user_pages_unlocked);
1728 * get_user_pages_fast attempts to pin user pages by walking the page
1729 * tables directly and avoids taking locks. Thus the walker needs to be
1730 * protected from page table pages being freed from under it, and should
1731 * block any THP splits.
1733 * One way to achieve this is to have the walker disable interrupts, and
1734 * rely on IPIs from the TLB flushing code blocking before the page table
1735 * pages are freed. This is unsuitable for architectures that do not need
1736 * to broadcast an IPI when invalidating TLBs.
1738 * Another way to achieve this is to batch up page table containing pages
1739 * belonging to more than one mm_user, then rcu_sched a callback to free those
1740 * pages. Disabling interrupts will allow the fast_gup walker to both block
1741 * the rcu_sched callback, and an IPI that we broadcast for splitting THPs
1742 * (which is a relatively rare event). The code below adopts this strategy.
1744 * Before activating this code, please be aware that the following assumptions
1745 * are currently made:
1747 * *) Either HAVE_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
1748 * free pages containing page tables or TLB flushing requires IPI broadcast.
1750 * *) ptes can be read atomically by the architecture.
1752 * *) access_ok is sufficient to validate userspace address ranges.
1754 * The last two assumptions can be relaxed by the addition of helper functions.
1756 * This code is based heavily on the PowerPC implementation by Nick Piggin.
1758 #ifdef CONFIG_HAVE_FAST_GUP
1759 #ifdef CONFIG_GUP_GET_PTE_LOW_HIGH
1761 * WARNING: only to be used in the get_user_pages_fast() implementation.
1763 * With get_user_pages_fast(), we walk down the pagetables without taking any
1764 * locks. For this we would like to load the pointers atomically, but sometimes
1765 * that is not possible (e.g. without expensive cmpxchg8b on x86_32 PAE). What
1766 * we do have is the guarantee that a PTE will only either go from not present
1767 * to present, or present to not present or both -- it will not switch to a
1768 * completely different present page without a TLB flush in between; something
1769 * that we are blocking by holding interrupts off.
1771 * Setting ptes from not present to present goes:
1773 * ptep->pte_high = h;
1775 * ptep->pte_low = l;
1777 * And present to not present goes:
1779 * ptep->pte_low = 0;
1781 * ptep->pte_high = 0;
1783 * We must ensure here that the load of pte_low sees 'l' IFF pte_high sees 'h'.
1784 * We load pte_high *after* loading pte_low, which ensures we don't see an older
1785 * value of pte_high. *Then* we recheck pte_low, which ensures that we haven't
1786 * picked up a changed pte high. We might have gotten rubbish values from
1787 * pte_low and pte_high, but we are guaranteed that pte_low will not have the
1788 * present bit set *unless* it is 'l'. Because get_user_pages_fast() only
1789 * operates on present ptes we're safe.
1791 static inline pte_t gup_get_pte(pte_t *ptep)
1796 pte.pte_low = ptep->pte_low;
1798 pte.pte_high = ptep->pte_high;
1800 } while (unlikely(pte.pte_low != ptep->pte_low));
1804 #else /* CONFIG_GUP_GET_PTE_LOW_HIGH */
1806 * We require that the PTE can be read atomically.
1808 static inline pte_t gup_get_pte(pte_t *ptep)
1810 return READ_ONCE(*ptep);
1812 #endif /* CONFIG_GUP_GET_PTE_LOW_HIGH */
1814 static void __maybe_unused undo_dev_pagemap(int *nr, int nr_start,
1815 struct page **pages)
1817 while ((*nr) - nr_start) {
1818 struct page *page = pages[--(*nr)];
1820 ClearPageReferenced(page);
1825 #ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
1826 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
1827 unsigned int flags, struct page **pages, int *nr)
1829 struct dev_pagemap *pgmap = NULL;
1830 int nr_start = *nr, ret = 0;
1833 ptem = ptep = pte_offset_map(&pmd, addr);
1835 pte_t pte = gup_get_pte(ptep);
1836 struct page *head, *page;
1839 * Similar to the PMD case below, NUMA hinting must take slow
1840 * path using the pte_protnone check.
1842 if (pte_protnone(pte))
1845 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
1848 if (pte_devmap(pte)) {
1849 if (unlikely(flags & FOLL_LONGTERM))
1852 pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
1853 if (unlikely(!pgmap)) {
1854 undo_dev_pagemap(nr, nr_start, pages);
1857 } else if (pte_special(pte))
1860 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
1861 page = pte_page(pte);
1863 head = try_get_compound_head(page, 1);
1867 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
1872 VM_BUG_ON_PAGE(compound_head(page) != head, page);
1874 SetPageReferenced(page);
1878 } while (ptep++, addr += PAGE_SIZE, addr != end);
1884 put_dev_pagemap(pgmap);
1891 * If we can't determine whether or not a pte is special, then fail immediately
1892 * for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
1895 * For a futex to be placed on a THP tail page, get_futex_key requires a
1896 * __get_user_pages_fast implementation that can pin pages. Thus it's still
1897 * useful to have gup_huge_pmd even if we can't operate on ptes.
1899 static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
1900 unsigned int flags, struct page **pages, int *nr)
1904 #endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
1906 #if defined(CONFIG_ARCH_HAS_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
1907 static int __gup_device_huge(unsigned long pfn, unsigned long addr,
1908 unsigned long end, struct page **pages, int *nr)
1911 struct dev_pagemap *pgmap = NULL;
1914 struct page *page = pfn_to_page(pfn);
1916 pgmap = get_dev_pagemap(pfn, pgmap);
1917 if (unlikely(!pgmap)) {
1918 undo_dev_pagemap(nr, nr_start, pages);
1921 SetPageReferenced(page);
1926 } while (addr += PAGE_SIZE, addr != end);
1929 put_dev_pagemap(pgmap);
1933 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
1934 unsigned long end, struct page **pages, int *nr)
1936 unsigned long fault_pfn;
1939 fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
1940 if (!__gup_device_huge(fault_pfn, addr, end, pages, nr))
1943 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
1944 undo_dev_pagemap(nr, nr_start, pages);
1950 static int __gup_device_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
1951 unsigned long end, struct page **pages, int *nr)
1953 unsigned long fault_pfn;
1956 fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
1957 if (!__gup_device_huge(fault_pfn, addr, end, pages, nr))
1960 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
1961 undo_dev_pagemap(nr, nr_start, pages);
1967 static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
1968 unsigned long end, struct page **pages, int *nr)
1974 static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr,
1975 unsigned long end, struct page **pages, int *nr)
1982 static int record_subpages(struct page *page, unsigned long addr,
1983 unsigned long end, struct page **pages)
1987 for (nr = 0; addr != end; addr += PAGE_SIZE)
1988 pages[nr++] = page++;
1993 static void put_compound_head(struct page *page, int refs)
1995 VM_BUG_ON_PAGE(page_ref_count(page) < refs, page);
1997 * Calling put_page() for each ref is unnecessarily slow. Only the last
1998 * ref needs a put_page().
2001 page_ref_sub(page, refs - 1);
2005 #ifdef CONFIG_ARCH_HAS_HUGEPD
2006 static unsigned long hugepte_addr_end(unsigned long addr, unsigned long end,
2009 unsigned long __boundary = (addr + sz) & ~(sz-1);
2010 return (__boundary - 1 < end - 1) ? __boundary : end;
2013 static int gup_hugepte(pte_t *ptep, unsigned long sz, unsigned long addr,
2014 unsigned long end, unsigned int flags,
2015 struct page **pages, int *nr)
2017 unsigned long pte_end;
2018 struct page *head, *page;
2022 pte_end = (addr + sz) & ~(sz-1);
2026 pte = READ_ONCE(*ptep);
2028 if (!pte_access_permitted(pte, flags & FOLL_WRITE))
2031 /* hugepages are never "special" */
2032 VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
2034 head = pte_page(pte);
2035 page = head + ((addr & (sz-1)) >> PAGE_SHIFT);
2036 refs = record_subpages(page, addr, end, pages + *nr);
2038 head = try_get_compound_head(head, refs);
2042 if (unlikely(pte_val(pte) != pte_val(*ptep))) {
2043 put_compound_head(head, refs);
2048 SetPageReferenced(head);
2052 static int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2053 unsigned int pdshift, unsigned long end, unsigned int flags,
2054 struct page **pages, int *nr)
2057 unsigned long sz = 1UL << hugepd_shift(hugepd);
2060 ptep = hugepte_offset(hugepd, addr, pdshift);
2062 next = hugepte_addr_end(addr, end, sz);
2063 if (!gup_hugepte(ptep, sz, addr, end, flags, pages, nr))
2065 } while (ptep++, addr = next, addr != end);
2070 static inline int gup_huge_pd(hugepd_t hugepd, unsigned long addr,
2071 unsigned int pdshift, unsigned long end, unsigned int flags,
2072 struct page **pages, int *nr)
2076 #endif /* CONFIG_ARCH_HAS_HUGEPD */
2078 static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
2079 unsigned long end, unsigned int flags,
2080 struct page **pages, int *nr)
2082 struct page *head, *page;
2085 if (!pmd_access_permitted(orig, flags & FOLL_WRITE))
2088 if (pmd_devmap(orig)) {
2089 if (unlikely(flags & FOLL_LONGTERM))
2091 return __gup_device_huge_pmd(orig, pmdp, addr, end, pages, nr);
2094 page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
2095 refs = record_subpages(page, addr, end, pages + *nr);
2097 head = try_get_compound_head(pmd_page(orig), refs);
2101 if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
2102 put_compound_head(head, refs);
2107 SetPageReferenced(head);
2111 static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
2112 unsigned long end, unsigned int flags, struct page **pages, int *nr)
2114 struct page *head, *page;
2117 if (!pud_access_permitted(orig, flags & FOLL_WRITE))
2120 if (pud_devmap(orig)) {
2121 if (unlikely(flags & FOLL_LONGTERM))
2123 return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);
2126 page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
2127 refs = record_subpages(page, addr, end, pages + *nr);
2129 head = try_get_compound_head(pud_page(orig), refs);
2133 if (unlikely(pud_val(orig) != pud_val(*pudp))) {
2134 put_compound_head(head, refs);
2139 SetPageReferenced(head);
2143 static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
2144 unsigned long end, unsigned int flags,
2145 struct page **pages, int *nr)
2148 struct page *head, *page;
2150 if (!pgd_access_permitted(orig, flags & FOLL_WRITE))
2153 BUILD_BUG_ON(pgd_devmap(orig));
2155 page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT);
2156 refs = record_subpages(page, addr, end, pages + *nr);
2158 head = try_get_compound_head(pgd_page(orig), refs);
2162 if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
2163 put_compound_head(head, refs);
2168 SetPageReferenced(head);
2172 static int gup_pmd_range(pud_t pud, unsigned long addr, unsigned long end,
2173 unsigned int flags, struct page **pages, int *nr)
2178 pmdp = pmd_offset(&pud, addr);
2180 pmd_t pmd = READ_ONCE(*pmdp);
2182 next = pmd_addr_end(addr, end);
2183 if (!pmd_present(pmd))
2186 if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd) ||
2189 * NUMA hinting faults need to be handled in the GUP
2190 * slowpath for accounting purposes and so that they
2191 * can be serialised against THP migration.
2193 if (pmd_protnone(pmd))
2196 if (!gup_huge_pmd(pmd, pmdp, addr, next, flags,
2200 } else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
2202 * architecture have different format for hugetlbfs
2203 * pmd format and THP pmd format
2205 if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
2206 PMD_SHIFT, next, flags, pages, nr))
2208 } else if (!gup_pte_range(pmd, addr, next, flags, pages, nr))
2210 } while (pmdp++, addr = next, addr != end);
2215 static int gup_pud_range(p4d_t p4d, unsigned long addr, unsigned long end,
2216 unsigned int flags, struct page **pages, int *nr)
2221 pudp = pud_offset(&p4d, addr);
2223 pud_t pud = READ_ONCE(*pudp);
2225 next = pud_addr_end(addr, end);
2226 if (unlikely(!pud_present(pud)))
2228 if (unlikely(pud_huge(pud))) {
2229 if (!gup_huge_pud(pud, pudp, addr, next, flags,
2232 } else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
2233 if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
2234 PUD_SHIFT, next, flags, pages, nr))
2236 } else if (!gup_pmd_range(pud, addr, next, flags, pages, nr))
2238 } while (pudp++, addr = next, addr != end);
2243 static int gup_p4d_range(pgd_t pgd, unsigned long addr, unsigned long end,
2244 unsigned int flags, struct page **pages, int *nr)
2249 p4dp = p4d_offset(&pgd, addr);
2251 p4d_t p4d = READ_ONCE(*p4dp);
2253 next = p4d_addr_end(addr, end);
2256 BUILD_BUG_ON(p4d_huge(p4d));
2257 if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
2258 if (!gup_huge_pd(__hugepd(p4d_val(p4d)), addr,
2259 P4D_SHIFT, next, flags, pages, nr))
2261 } else if (!gup_pud_range(p4d, addr, next, flags, pages, nr))
2263 } while (p4dp++, addr = next, addr != end);
2268 static void gup_pgd_range(unsigned long addr, unsigned long end,
2269 unsigned int flags, struct page **pages, int *nr)
2274 pgdp = pgd_offset(current->mm, addr);
2276 pgd_t pgd = READ_ONCE(*pgdp);
2278 next = pgd_addr_end(addr, end);
2281 if (unlikely(pgd_huge(pgd))) {
2282 if (!gup_huge_pgd(pgd, pgdp, addr, next, flags,
2285 } else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
2286 if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
2287 PGDIR_SHIFT, next, flags, pages, nr))
2289 } else if (!gup_p4d_range(pgd, addr, next, flags, pages, nr))
2291 } while (pgdp++, addr = next, addr != end);
2294 static inline void gup_pgd_range(unsigned long addr, unsigned long end,
2295 unsigned int flags, struct page **pages, int *nr)
2298 #endif /* CONFIG_HAVE_FAST_GUP */
2300 #ifndef gup_fast_permitted
2302 * Check if it's allowed to use __get_user_pages_fast() for the range, or
2303 * we need to fall back to the slow version:
2305 static bool gup_fast_permitted(unsigned long start, unsigned long end)
2312 * Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
2314 * Note a difference with get_user_pages_fast: this always returns the
2315 * number of pages pinned, 0 if no pages were pinned.
2317 * If the architecture does not support this function, simply return with no
2320 int __get_user_pages_fast(unsigned long start, int nr_pages, int write,
2321 struct page **pages)
2323 unsigned long len, end;
2324 unsigned long flags;
2327 start = untagged_addr(start) & PAGE_MASK;
2328 len = (unsigned long) nr_pages << PAGE_SHIFT;
2333 if (unlikely(!access_ok((void __user *)start, len)))
2337 * Disable interrupts. We use the nested form as we can already have
2338 * interrupts disabled by get_futex_key.
2340 * With interrupts disabled, we block page table pages from being
2341 * freed from under us. See struct mmu_table_batch comments in
2342 * include/asm-generic/tlb.h for more details.
2344 * We do not adopt an rcu_read_lock(.) here as we also want to
2345 * block IPIs that come from THPs splitting.
2348 if (IS_ENABLED(CONFIG_HAVE_FAST_GUP) &&
2349 gup_fast_permitted(start, end)) {
2350 local_irq_save(flags);
2351 gup_pgd_range(start, end, write ? FOLL_WRITE : 0, pages, &nr);
2352 local_irq_restore(flags);
2357 EXPORT_SYMBOL_GPL(__get_user_pages_fast);
2359 static int __gup_longterm_unlocked(unsigned long start, int nr_pages,
2360 unsigned int gup_flags, struct page **pages)
2365 * FIXME: FOLL_LONGTERM does not work with
2366 * get_user_pages_unlocked() (see comments in that function)
2368 if (gup_flags & FOLL_LONGTERM) {
2369 down_read(¤t->mm->mmap_sem);
2370 ret = __gup_longterm_locked(current, current->mm,
2372 pages, NULL, gup_flags);
2373 up_read(¤t->mm->mmap_sem);
2375 ret = get_user_pages_unlocked(start, nr_pages,
2383 * get_user_pages_fast() - pin user pages in memory
2384 * @start: starting user address
2385 * @nr_pages: number of pages from start to pin
2386 * @gup_flags: flags modifying pin behaviour
2387 * @pages: array that receives pointers to the pages pinned.
2388 * Should be at least nr_pages long.
2390 * Attempt to pin user pages in memory without taking mm->mmap_sem.
2391 * If not successful, it will fall back to taking the lock and
2392 * calling get_user_pages().
2394 * Returns number of pages pinned. This may be fewer than the number
2395 * requested. If nr_pages is 0 or negative, returns 0. If no pages
2396 * were pinned, returns -errno.
2398 int get_user_pages_fast(unsigned long start, int nr_pages,
2399 unsigned int gup_flags, struct page **pages)
2401 unsigned long addr, len, end;
2402 int nr = 0, ret = 0;
2404 if (WARN_ON_ONCE(gup_flags & ~(FOLL_WRITE | FOLL_LONGTERM)))
2407 start = untagged_addr(start) & PAGE_MASK;
2409 len = (unsigned long) nr_pages << PAGE_SHIFT;
2414 if (unlikely(!access_ok((void __user *)start, len)))
2417 if (IS_ENABLED(CONFIG_HAVE_FAST_GUP) &&
2418 gup_fast_permitted(start, end)) {
2419 local_irq_disable();
2420 gup_pgd_range(addr, end, gup_flags, pages, &nr);
2425 if (nr < nr_pages) {
2426 /* Try to get the remaining pages with get_user_pages */
2427 start += nr << PAGE_SHIFT;
2430 ret = __gup_longterm_unlocked(start, nr_pages - nr,
2433 /* Have to be a bit careful with return values */
2444 EXPORT_SYMBOL_GPL(get_user_pages_fast);