1 // SPDX-License-Identifier: GPL-2.0-only
5 * Copyright (C) 2015 Red Hat, Inc.
9 #include <linux/sched/signal.h>
10 #include <linux/pagemap.h>
11 #include <linux/rmap.h>
12 #include <linux/swap.h>
13 #include <linux/swapops.h>
14 #include <linux/userfaultfd_k.h>
15 #include <linux/mmu_notifier.h>
16 #include <linux/hugetlb.h>
17 #include <linux/shmem_fs.h>
18 #include <asm/tlbflush.h>
22 static __always_inline
23 bool validate_dst_vma(struct vm_area_struct *dst_vma, unsigned long dst_end)
25 /* Make sure that the dst range is fully within dst_vma. */
26 if (dst_end > dst_vma->vm_end)
30 * Check the vma is registered in uffd, this is required to
31 * enforce the VM_MAYWRITE check done at uffd registration
34 if (!dst_vma->vm_userfaultfd_ctx.ctx)
40 static __always_inline
41 struct vm_area_struct *find_vma_and_prepare_anon(struct mm_struct *mm,
44 struct vm_area_struct *vma;
46 mmap_assert_locked(mm);
47 vma = vma_lookup(mm, addr);
49 vma = ERR_PTR(-ENOENT);
50 else if (!(vma->vm_flags & VM_SHARED) &&
51 unlikely(anon_vma_prepare(vma)))
52 vma = ERR_PTR(-ENOMEM);
57 #ifdef CONFIG_PER_VMA_LOCK
59 * lock_vma() - Lookup and lock vma corresponding to @address.
60 * @mm: mm to search vma in.
61 * @address: address that the vma should contain.
63 * Should be called without holding mmap_lock. vma should be unlocked after use
66 * Return: A locked vma containing @address, -ENOENT if no vma is found, or
67 * -ENOMEM if anon_vma couldn't be allocated.
69 static struct vm_area_struct *lock_vma(struct mm_struct *mm,
70 unsigned long address)
72 struct vm_area_struct *vma;
74 vma = lock_vma_under_rcu(mm, address);
77 * lock_vma_under_rcu() only checks anon_vma for private
78 * anonymous mappings. But we need to ensure it is assigned in
79 * private file-backed vmas as well.
81 if (!(vma->vm_flags & VM_SHARED) && unlikely(!vma->anon_vma))
88 vma = find_vma_and_prepare_anon(mm, address);
91 * We cannot use vma_start_read() as it may fail due to
92 * false locked (see comment in vma_start_read()). We
93 * can avoid that by directly locking vm_lock under
94 * mmap_lock, which guarantees that nobody can lock the
95 * vma for write (vma_start_write()) under us.
97 down_read(&vma->vm_lock->lock);
100 mmap_read_unlock(mm);
104 static struct vm_area_struct *uffd_mfill_lock(struct mm_struct *dst_mm,
105 unsigned long dst_start,
108 struct vm_area_struct *dst_vma;
110 dst_vma = lock_vma(dst_mm, dst_start);
111 if (IS_ERR(dst_vma) || validate_dst_vma(dst_vma, dst_start + len))
114 vma_end_read(dst_vma);
115 return ERR_PTR(-ENOENT);
118 static void uffd_mfill_unlock(struct vm_area_struct *vma)
125 static struct vm_area_struct *uffd_mfill_lock(struct mm_struct *dst_mm,
126 unsigned long dst_start,
129 struct vm_area_struct *dst_vma;
131 mmap_read_lock(dst_mm);
132 dst_vma = find_vma_and_prepare_anon(dst_mm, dst_start);
136 if (validate_dst_vma(dst_vma, dst_start + len))
139 dst_vma = ERR_PTR(-ENOENT);
141 mmap_read_unlock(dst_mm);
145 static void uffd_mfill_unlock(struct vm_area_struct *vma)
147 mmap_read_unlock(vma->vm_mm);
151 /* Check if dst_addr is outside of file's size. Must be called with ptl held. */
152 static bool mfill_file_over_size(struct vm_area_struct *dst_vma,
153 unsigned long dst_addr)
156 pgoff_t offset, max_off;
158 if (!dst_vma->vm_file)
161 inode = dst_vma->vm_file->f_inode;
162 offset = linear_page_index(dst_vma, dst_addr);
163 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
164 return offset >= max_off;
168 * Install PTEs, to map dst_addr (within dst_vma) to page.
170 * This function handles both MCOPY_ATOMIC_NORMAL and _CONTINUE for both shmem
171 * and anon, and for both shared and private VMAs.
173 int mfill_atomic_install_pte(pmd_t *dst_pmd,
174 struct vm_area_struct *dst_vma,
175 unsigned long dst_addr, struct page *page,
176 bool newly_allocated, uffd_flags_t flags)
179 struct mm_struct *dst_mm = dst_vma->vm_mm;
180 pte_t _dst_pte, *dst_pte;
181 bool writable = dst_vma->vm_flags & VM_WRITE;
182 bool vm_shared = dst_vma->vm_flags & VM_SHARED;
183 bool page_in_cache = page_mapping(page);
187 _dst_pte = mk_pte(page, dst_vma->vm_page_prot);
188 _dst_pte = pte_mkdirty(_dst_pte);
189 if (page_in_cache && !vm_shared)
192 _dst_pte = pte_mkwrite(_dst_pte, dst_vma);
193 if (flags & MFILL_ATOMIC_WP)
194 _dst_pte = pte_mkuffd_wp(_dst_pte);
197 dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
201 if (mfill_file_over_size(dst_vma, dst_addr)) {
208 * We allow to overwrite a pte marker: consider when both MISSING|WP
209 * registered, we firstly wr-protect a none pte which has no page cache
210 * page backing it, then access the page.
212 if (!pte_none_mostly(ptep_get(dst_pte)))
215 folio = page_folio(page);
217 /* Usually, cache pages are already added to LRU */
219 folio_add_lru(folio);
220 folio_add_file_rmap_pte(folio, page, dst_vma);
222 folio_add_new_anon_rmap(folio, dst_vma, dst_addr);
223 folio_add_lru_vma(folio, dst_vma);
227 * Must happen after rmap, as mm_counter() checks mapping (via
228 * PageAnon()), which is set by __page_set_anon_rmap().
230 inc_mm_counter(dst_mm, mm_counter(folio));
232 set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
234 /* No need to invalidate - it was non-present before */
235 update_mmu_cache(dst_vma, dst_addr, dst_pte);
238 pte_unmap_unlock(dst_pte, ptl);
243 static int mfill_atomic_pte_copy(pmd_t *dst_pmd,
244 struct vm_area_struct *dst_vma,
245 unsigned long dst_addr,
246 unsigned long src_addr,
248 struct folio **foliop)
256 folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0, dst_vma,
261 kaddr = kmap_local_folio(folio, 0);
263 * The read mmap_lock is held here. Despite the
264 * mmap_lock being read recursive a deadlock is still
265 * possible if a writer has taken a lock. For example:
267 * process A thread 1 takes read lock on own mmap_lock
268 * process A thread 2 calls mmap, blocks taking write lock
269 * process B thread 1 takes page fault, read lock on own mmap lock
270 * process B thread 2 calls mmap, blocks taking write lock
271 * process A thread 1 blocks taking read lock on process B
272 * process B thread 1 blocks taking read lock on process A
274 * Disable page faults to prevent potential deadlock
275 * and retry the copy outside the mmap_lock.
278 ret = copy_from_user(kaddr, (const void __user *) src_addr,
283 /* fallback to copy_from_user outside mmap_lock */
287 /* don't free the page */
291 flush_dcache_folio(folio);
298 * The memory barrier inside __folio_mark_uptodate makes sure that
299 * preceding stores to the page contents become visible before
300 * the set_pte_at() write.
302 __folio_mark_uptodate(folio);
305 if (mem_cgroup_charge(folio, dst_vma->vm_mm, GFP_KERNEL))
308 ret = mfill_atomic_install_pte(dst_pmd, dst_vma, dst_addr,
309 &folio->page, true, flags);
319 static int mfill_atomic_pte_zeropage(pmd_t *dst_pmd,
320 struct vm_area_struct *dst_vma,
321 unsigned long dst_addr)
323 pte_t _dst_pte, *dst_pte;
327 _dst_pte = pte_mkspecial(pfn_pte(my_zero_pfn(dst_addr),
328 dst_vma->vm_page_prot));
330 dst_pte = pte_offset_map_lock(dst_vma->vm_mm, dst_pmd, dst_addr, &ptl);
333 if (mfill_file_over_size(dst_vma, dst_addr)) {
338 if (!pte_none(ptep_get(dst_pte)))
340 set_pte_at(dst_vma->vm_mm, dst_addr, dst_pte, _dst_pte);
341 /* No need to invalidate - it was non-present before */
342 update_mmu_cache(dst_vma, dst_addr, dst_pte);
345 pte_unmap_unlock(dst_pte, ptl);
350 /* Handles UFFDIO_CONTINUE for all shmem VMAs (shared or private). */
351 static int mfill_atomic_pte_continue(pmd_t *dst_pmd,
352 struct vm_area_struct *dst_vma,
353 unsigned long dst_addr,
356 struct inode *inode = file_inode(dst_vma->vm_file);
357 pgoff_t pgoff = linear_page_index(dst_vma, dst_addr);
362 ret = shmem_get_folio(inode, pgoff, &folio, SGP_NOALLOC);
363 /* Our caller expects us to return -EFAULT if we failed to find folio */
373 page = folio_file_page(folio, pgoff);
374 if (PageHWPoison(page)) {
379 ret = mfill_atomic_install_pte(dst_pmd, dst_vma, dst_addr,
394 /* Handles UFFDIO_POISON for all non-hugetlb VMAs. */
395 static int mfill_atomic_pte_poison(pmd_t *dst_pmd,
396 struct vm_area_struct *dst_vma,
397 unsigned long dst_addr,
401 struct mm_struct *dst_mm = dst_vma->vm_mm;
402 pte_t _dst_pte, *dst_pte;
405 _dst_pte = make_pte_marker(PTE_MARKER_POISONED);
407 dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
411 if (mfill_file_over_size(dst_vma, dst_addr)) {
417 /* Refuse to overwrite any PTE, even a PTE marker (e.g. UFFD WP). */
418 if (!pte_none(ptep_get(dst_pte)))
421 set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
423 /* No need to invalidate - it was non-present before */
424 update_mmu_cache(dst_vma, dst_addr, dst_pte);
427 pte_unmap_unlock(dst_pte, ptl);
432 static pmd_t *mm_alloc_pmd(struct mm_struct *mm, unsigned long address)
438 pgd = pgd_offset(mm, address);
439 p4d = p4d_alloc(mm, pgd, address);
442 pud = pud_alloc(mm, p4d, address);
446 * Note that we didn't run this because the pmd was
447 * missing, the *pmd may be already established and in
448 * turn it may also be a trans_huge_pmd.
450 return pmd_alloc(mm, pud, address);
453 #ifdef CONFIG_HUGETLB_PAGE
455 * mfill_atomic processing for HUGETLB vmas. Note that this routine is
456 * called with either vma-lock or mmap_lock held, it will release the lock
459 static __always_inline ssize_t mfill_atomic_hugetlb(
460 struct userfaultfd_ctx *ctx,
461 struct vm_area_struct *dst_vma,
462 unsigned long dst_start,
463 unsigned long src_start,
467 struct mm_struct *dst_mm = dst_vma->vm_mm;
470 unsigned long src_addr, dst_addr;
473 unsigned long vma_hpagesize;
476 struct address_space *mapping;
479 * There is no default zero huge page for all huge page sizes as
480 * supported by hugetlb. A PMD_SIZE huge pages may exist as used
481 * by THP. Since we can not reliably insert a zero page, this
482 * feature is not supported.
484 if (uffd_flags_mode_is(flags, MFILL_ATOMIC_ZEROPAGE)) {
485 up_read(&ctx->map_changing_lock);
486 uffd_mfill_unlock(dst_vma);
490 src_addr = src_start;
491 dst_addr = dst_start;
494 vma_hpagesize = vma_kernel_pagesize(dst_vma);
497 * Validate alignment based on huge page size
500 if (dst_start & (vma_hpagesize - 1) || len & (vma_hpagesize - 1))
505 * On routine entry dst_vma is set. If we had to drop mmap_lock and
506 * retry, dst_vma will be set to NULL and we must lookup again.
509 dst_vma = uffd_mfill_lock(dst_mm, dst_start, len);
510 if (IS_ERR(dst_vma)) {
511 err = PTR_ERR(dst_vma);
516 if (!is_vm_hugetlb_page(dst_vma))
520 if (vma_hpagesize != vma_kernel_pagesize(dst_vma))
524 * If memory mappings are changing because of non-cooperative
525 * operation (e.g. mremap) running in parallel, bail out and
526 * request the user to retry later
528 down_read(&ctx->map_changing_lock);
530 if (atomic_read(&ctx->mmap_changing))
534 while (src_addr < src_start + len) {
535 BUG_ON(dst_addr >= dst_start + len);
538 * Serialize via vma_lock and hugetlb_fault_mutex.
539 * vma_lock ensures the dst_pte remains valid even
540 * in the case of shared pmds. fault mutex prevents
541 * races with other faulting threads.
543 idx = linear_page_index(dst_vma, dst_addr);
544 mapping = dst_vma->vm_file->f_mapping;
545 hash = hugetlb_fault_mutex_hash(mapping, idx);
546 mutex_lock(&hugetlb_fault_mutex_table[hash]);
547 hugetlb_vma_lock_read(dst_vma);
550 dst_pte = huge_pte_alloc(dst_mm, dst_vma, dst_addr, vma_hpagesize);
552 hugetlb_vma_unlock_read(dst_vma);
553 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
557 if (!uffd_flags_mode_is(flags, MFILL_ATOMIC_CONTINUE) &&
558 !huge_pte_none_mostly(huge_ptep_get(dst_pte))) {
560 hugetlb_vma_unlock_read(dst_vma);
561 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
565 err = hugetlb_mfill_atomic_pte(dst_pte, dst_vma, dst_addr,
566 src_addr, flags, &folio);
568 hugetlb_vma_unlock_read(dst_vma);
569 mutex_unlock(&hugetlb_fault_mutex_table[hash]);
573 if (unlikely(err == -ENOENT)) {
574 up_read(&ctx->map_changing_lock);
575 uffd_mfill_unlock(dst_vma);
578 err = copy_folio_from_user(folio,
579 (const void __user *)src_addr, true);
591 dst_addr += vma_hpagesize;
592 src_addr += vma_hpagesize;
593 copied += vma_hpagesize;
595 if (fatal_signal_pending(current))
603 up_read(&ctx->map_changing_lock);
605 uffd_mfill_unlock(dst_vma);
611 BUG_ON(!copied && !err);
612 return copied ? copied : err;
614 #else /* !CONFIG_HUGETLB_PAGE */
615 /* fail at build time if gcc attempts to use this */
616 extern ssize_t mfill_atomic_hugetlb(struct userfaultfd_ctx *ctx,
617 struct vm_area_struct *dst_vma,
618 unsigned long dst_start,
619 unsigned long src_start,
622 #endif /* CONFIG_HUGETLB_PAGE */
624 static __always_inline ssize_t mfill_atomic_pte(pmd_t *dst_pmd,
625 struct vm_area_struct *dst_vma,
626 unsigned long dst_addr,
627 unsigned long src_addr,
629 struct folio **foliop)
633 if (uffd_flags_mode_is(flags, MFILL_ATOMIC_CONTINUE)) {
634 return mfill_atomic_pte_continue(dst_pmd, dst_vma,
636 } else if (uffd_flags_mode_is(flags, MFILL_ATOMIC_POISON)) {
637 return mfill_atomic_pte_poison(dst_pmd, dst_vma,
642 * The normal page fault path for a shmem will invoke the
643 * fault, fill the hole in the file and COW it right away. The
644 * result generates plain anonymous memory. So when we are
645 * asked to fill an hole in a MAP_PRIVATE shmem mapping, we'll
646 * generate anonymous memory directly without actually filling
647 * the hole. For the MAP_PRIVATE case the robustness check
648 * only happens in the pagetable (to verify it's still none)
649 * and not in the radix tree.
651 if (!(dst_vma->vm_flags & VM_SHARED)) {
652 if (uffd_flags_mode_is(flags, MFILL_ATOMIC_COPY))
653 err = mfill_atomic_pte_copy(dst_pmd, dst_vma,
657 err = mfill_atomic_pte_zeropage(dst_pmd,
660 err = shmem_mfill_atomic_pte(dst_pmd, dst_vma,
668 static __always_inline ssize_t mfill_atomic(struct userfaultfd_ctx *ctx,
669 unsigned long dst_start,
670 unsigned long src_start,
674 struct mm_struct *dst_mm = ctx->mm;
675 struct vm_area_struct *dst_vma;
678 unsigned long src_addr, dst_addr;
683 * Sanitize the command parameters:
685 BUG_ON(dst_start & ~PAGE_MASK);
686 BUG_ON(len & ~PAGE_MASK);
688 /* Does the address range wrap, or is the span zero-sized? */
689 BUG_ON(src_start + len <= src_start);
690 BUG_ON(dst_start + len <= dst_start);
692 src_addr = src_start;
693 dst_addr = dst_start;
698 * Make sure the vma is not shared, that the dst range is
699 * both valid and fully within a single existing vma.
701 dst_vma = uffd_mfill_lock(dst_mm, dst_start, len);
702 if (IS_ERR(dst_vma)) {
703 err = PTR_ERR(dst_vma);
708 * If memory mappings are changing because of non-cooperative
709 * operation (e.g. mremap) running in parallel, bail out and
710 * request the user to retry later
712 down_read(&ctx->map_changing_lock);
714 if (atomic_read(&ctx->mmap_changing))
719 * shmem_zero_setup is invoked in mmap for MAP_ANONYMOUS|MAP_SHARED but
720 * it will overwrite vm_ops, so vma_is_anonymous must return false.
722 if (WARN_ON_ONCE(vma_is_anonymous(dst_vma) &&
723 dst_vma->vm_flags & VM_SHARED))
727 * validate 'mode' now that we know the dst_vma: don't allow
728 * a wrprotect copy if the userfaultfd didn't register as WP.
730 if ((flags & MFILL_ATOMIC_WP) && !(dst_vma->vm_flags & VM_UFFD_WP))
734 * If this is a HUGETLB vma, pass off to appropriate routine
736 if (is_vm_hugetlb_page(dst_vma))
737 return mfill_atomic_hugetlb(ctx, dst_vma, dst_start,
738 src_start, len, flags);
740 if (!vma_is_anonymous(dst_vma) && !vma_is_shmem(dst_vma))
742 if (!vma_is_shmem(dst_vma) &&
743 uffd_flags_mode_is(flags, MFILL_ATOMIC_CONTINUE))
746 while (src_addr < src_start + len) {
749 BUG_ON(dst_addr >= dst_start + len);
751 dst_pmd = mm_alloc_pmd(dst_mm, dst_addr);
752 if (unlikely(!dst_pmd)) {
757 dst_pmdval = pmdp_get_lockless(dst_pmd);
759 * If the dst_pmd is mapped as THP don't
760 * override it and just be strict.
762 if (unlikely(pmd_trans_huge(dst_pmdval))) {
766 if (unlikely(pmd_none(dst_pmdval)) &&
767 unlikely(__pte_alloc(dst_mm, dst_pmd))) {
771 /* If an huge pmd materialized from under us fail */
772 if (unlikely(pmd_trans_huge(*dst_pmd))) {
777 BUG_ON(pmd_none(*dst_pmd));
778 BUG_ON(pmd_trans_huge(*dst_pmd));
780 err = mfill_atomic_pte(dst_pmd, dst_vma, dst_addr,
781 src_addr, flags, &folio);
784 if (unlikely(err == -ENOENT)) {
787 up_read(&ctx->map_changing_lock);
788 uffd_mfill_unlock(dst_vma);
791 kaddr = kmap_local_folio(folio, 0);
792 err = copy_from_user(kaddr,
793 (const void __user *) src_addr,
800 flush_dcache_folio(folio);
806 dst_addr += PAGE_SIZE;
807 src_addr += PAGE_SIZE;
810 if (fatal_signal_pending(current))
818 up_read(&ctx->map_changing_lock);
819 uffd_mfill_unlock(dst_vma);
825 BUG_ON(!copied && !err);
826 return copied ? copied : err;
829 ssize_t mfill_atomic_copy(struct userfaultfd_ctx *ctx, unsigned long dst_start,
830 unsigned long src_start, unsigned long len,
833 return mfill_atomic(ctx, dst_start, src_start, len,
834 uffd_flags_set_mode(flags, MFILL_ATOMIC_COPY));
837 ssize_t mfill_atomic_zeropage(struct userfaultfd_ctx *ctx,
841 return mfill_atomic(ctx, start, 0, len,
842 uffd_flags_set_mode(0, MFILL_ATOMIC_ZEROPAGE));
845 ssize_t mfill_atomic_continue(struct userfaultfd_ctx *ctx, unsigned long start,
846 unsigned long len, uffd_flags_t flags)
850 * A caller might reasonably assume that UFFDIO_CONTINUE contains an
851 * smp_wmb() to ensure that any writes to the about-to-be-mapped page by
852 * the thread doing the UFFDIO_CONTINUE are guaranteed to be visible to
853 * subsequent loads from the page through the newly mapped address range.
857 return mfill_atomic(ctx, start, 0, len,
858 uffd_flags_set_mode(flags, MFILL_ATOMIC_CONTINUE));
861 ssize_t mfill_atomic_poison(struct userfaultfd_ctx *ctx, unsigned long start,
862 unsigned long len, uffd_flags_t flags)
864 return mfill_atomic(ctx, start, 0, len,
865 uffd_flags_set_mode(flags, MFILL_ATOMIC_POISON));
868 long uffd_wp_range(struct vm_area_struct *dst_vma,
869 unsigned long start, unsigned long len, bool enable_wp)
871 unsigned int mm_cp_flags;
872 struct mmu_gather tlb;
875 VM_WARN_ONCE(start < dst_vma->vm_start || start + len > dst_vma->vm_end,
876 "The address range exceeds VMA boundary.\n");
878 mm_cp_flags = MM_CP_UFFD_WP;
880 mm_cp_flags = MM_CP_UFFD_WP_RESOLVE;
883 * vma->vm_page_prot already reflects that uffd-wp is enabled for this
884 * VMA (see userfaultfd_set_vm_flags()) and that all PTEs are supposed
885 * to be write-protected as default whenever protection changes.
886 * Try upgrading write permissions manually.
888 if (!enable_wp && vma_wants_manual_pte_write_upgrade(dst_vma))
889 mm_cp_flags |= MM_CP_TRY_CHANGE_WRITABLE;
890 tlb_gather_mmu(&tlb, dst_vma->vm_mm);
891 ret = change_protection(&tlb, dst_vma, start, start + len, mm_cp_flags);
892 tlb_finish_mmu(&tlb);
897 int mwriteprotect_range(struct userfaultfd_ctx *ctx, unsigned long start,
898 unsigned long len, bool enable_wp)
900 struct mm_struct *dst_mm = ctx->mm;
901 unsigned long end = start + len;
902 unsigned long _start, _end;
903 struct vm_area_struct *dst_vma;
904 unsigned long page_mask;
906 VMA_ITERATOR(vmi, dst_mm, start);
909 * Sanitize the command parameters:
911 BUG_ON(start & ~PAGE_MASK);
912 BUG_ON(len & ~PAGE_MASK);
914 /* Does the address range wrap, or is the span zero-sized? */
915 BUG_ON(start + len <= start);
917 mmap_read_lock(dst_mm);
920 * If memory mappings are changing because of non-cooperative
921 * operation (e.g. mremap) running in parallel, bail out and
922 * request the user to retry later
924 down_read(&ctx->map_changing_lock);
926 if (atomic_read(&ctx->mmap_changing))
930 for_each_vma_range(vmi, dst_vma, end) {
932 if (!userfaultfd_wp(dst_vma)) {
937 if (is_vm_hugetlb_page(dst_vma)) {
939 page_mask = vma_kernel_pagesize(dst_vma) - 1;
940 if ((start & page_mask) || (len & page_mask))
944 _start = max(dst_vma->vm_start, start);
945 _end = min(dst_vma->vm_end, end);
947 err = uffd_wp_range(dst_vma, _start, _end - _start, enable_wp);
949 /* Return 0 on success, <0 on failures */
955 up_read(&ctx->map_changing_lock);
956 mmap_read_unlock(dst_mm);
961 void double_pt_lock(spinlock_t *ptl1,
969 /* exchange ptl1 and ptl2 */
974 /* lock in virtual address order to avoid lock inversion */
977 spin_lock_nested(ptl2, SINGLE_DEPTH_NESTING);
982 void double_pt_unlock(spinlock_t *ptl1,
995 static int move_present_pte(struct mm_struct *mm,
996 struct vm_area_struct *dst_vma,
997 struct vm_area_struct *src_vma,
998 unsigned long dst_addr, unsigned long src_addr,
999 pte_t *dst_pte, pte_t *src_pte,
1000 pte_t orig_dst_pte, pte_t orig_src_pte,
1001 spinlock_t *dst_ptl, spinlock_t *src_ptl,
1002 struct folio *src_folio)
1006 double_pt_lock(dst_ptl, src_ptl);
1008 if (!pte_same(ptep_get(src_pte), orig_src_pte) ||
1009 !pte_same(ptep_get(dst_pte), orig_dst_pte)) {
1013 if (folio_test_large(src_folio) ||
1014 folio_maybe_dma_pinned(src_folio) ||
1015 !PageAnonExclusive(&src_folio->page)) {
1020 orig_src_pte = ptep_clear_flush(src_vma, src_addr, src_pte);
1021 /* Folio got pinned from under us. Put it back and fail the move. */
1022 if (folio_maybe_dma_pinned(src_folio)) {
1023 set_pte_at(mm, src_addr, src_pte, orig_src_pte);
1028 folio_move_anon_rmap(src_folio, dst_vma);
1029 WRITE_ONCE(src_folio->index, linear_page_index(dst_vma, dst_addr));
1031 orig_dst_pte = mk_pte(&src_folio->page, dst_vma->vm_page_prot);
1032 /* Follow mremap() behavior and treat the entry dirty after the move */
1033 orig_dst_pte = pte_mkwrite(pte_mkdirty(orig_dst_pte), dst_vma);
1035 set_pte_at(mm, dst_addr, dst_pte, orig_dst_pte);
1037 double_pt_unlock(dst_ptl, src_ptl);
1041 static int move_swap_pte(struct mm_struct *mm,
1042 unsigned long dst_addr, unsigned long src_addr,
1043 pte_t *dst_pte, pte_t *src_pte,
1044 pte_t orig_dst_pte, pte_t orig_src_pte,
1045 spinlock_t *dst_ptl, spinlock_t *src_ptl)
1047 if (!pte_swp_exclusive(orig_src_pte))
1050 double_pt_lock(dst_ptl, src_ptl);
1052 if (!pte_same(ptep_get(src_pte), orig_src_pte) ||
1053 !pte_same(ptep_get(dst_pte), orig_dst_pte)) {
1054 double_pt_unlock(dst_ptl, src_ptl);
1058 orig_src_pte = ptep_get_and_clear(mm, src_addr, src_pte);
1059 set_pte_at(mm, dst_addr, dst_pte, orig_src_pte);
1060 double_pt_unlock(dst_ptl, src_ptl);
1065 static int move_zeropage_pte(struct mm_struct *mm,
1066 struct vm_area_struct *dst_vma,
1067 struct vm_area_struct *src_vma,
1068 unsigned long dst_addr, unsigned long src_addr,
1069 pte_t *dst_pte, pte_t *src_pte,
1070 pte_t orig_dst_pte, pte_t orig_src_pte,
1071 spinlock_t *dst_ptl, spinlock_t *src_ptl)
1075 double_pt_lock(dst_ptl, src_ptl);
1076 if (!pte_same(ptep_get(src_pte), orig_src_pte) ||
1077 !pte_same(ptep_get(dst_pte), orig_dst_pte)) {
1078 double_pt_unlock(dst_ptl, src_ptl);
1082 zero_pte = pte_mkspecial(pfn_pte(my_zero_pfn(dst_addr),
1083 dst_vma->vm_page_prot));
1084 ptep_clear_flush(src_vma, src_addr, src_pte);
1085 set_pte_at(mm, dst_addr, dst_pte, zero_pte);
1086 double_pt_unlock(dst_ptl, src_ptl);
1093 * The mmap_lock for reading is held by the caller. Just move the page
1094 * from src_pmd to dst_pmd if possible, and return true if succeeded
1095 * in moving the page.
1097 static int move_pages_pte(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd,
1098 struct vm_area_struct *dst_vma,
1099 struct vm_area_struct *src_vma,
1100 unsigned long dst_addr, unsigned long src_addr,
1104 pte_t orig_src_pte, orig_dst_pte;
1105 pte_t src_folio_pte;
1106 spinlock_t *src_ptl, *dst_ptl;
1107 pte_t *src_pte = NULL;
1108 pte_t *dst_pte = NULL;
1110 struct folio *src_folio = NULL;
1111 struct anon_vma *src_anon_vma = NULL;
1112 struct mmu_notifier_range range;
1115 flush_cache_range(src_vma, src_addr, src_addr + PAGE_SIZE);
1116 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
1117 src_addr, src_addr + PAGE_SIZE);
1118 mmu_notifier_invalidate_range_start(&range);
1120 dst_pte = pte_offset_map_nolock(mm, dst_pmd, dst_addr, &dst_ptl);
1122 /* Retry if a huge pmd materialized from under us */
1123 if (unlikely(!dst_pte)) {
1128 src_pte = pte_offset_map_nolock(mm, src_pmd, src_addr, &src_ptl);
1131 * We held the mmap_lock for reading so MADV_DONTNEED
1132 * can zap transparent huge pages under us, or the
1133 * transparent huge page fault can establish new
1134 * transparent huge pages under us.
1136 if (unlikely(!src_pte)) {
1141 /* Sanity checks before the operation */
1142 if (WARN_ON_ONCE(pmd_none(*dst_pmd)) || WARN_ON_ONCE(pmd_none(*src_pmd)) ||
1143 WARN_ON_ONCE(pmd_trans_huge(*dst_pmd)) || WARN_ON_ONCE(pmd_trans_huge(*src_pmd))) {
1149 orig_dst_pte = ptep_get(dst_pte);
1150 spin_unlock(dst_ptl);
1151 if (!pte_none(orig_dst_pte)) {
1157 orig_src_pte = ptep_get(src_pte);
1158 spin_unlock(src_ptl);
1159 if (pte_none(orig_src_pte)) {
1160 if (!(mode & UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES))
1162 else /* nothing to do to move a hole */
1167 /* If PTE changed after we locked the folio them start over */
1168 if (src_folio && unlikely(!pte_same(src_folio_pte, orig_src_pte))) {
1173 if (pte_present(orig_src_pte)) {
1174 if (is_zero_pfn(pte_pfn(orig_src_pte))) {
1175 err = move_zeropage_pte(mm, dst_vma, src_vma,
1176 dst_addr, src_addr, dst_pte, src_pte,
1177 orig_dst_pte, orig_src_pte,
1183 * Pin and lock both source folio and anon_vma. Since we are in
1184 * RCU read section, we can't block, so on contention have to
1185 * unmap the ptes, obtain the lock and retry.
1188 struct folio *folio;
1191 * Pin the page while holding the lock to be sure the
1192 * page isn't freed under us
1195 if (!pte_same(orig_src_pte, ptep_get(src_pte))) {
1196 spin_unlock(src_ptl);
1201 folio = vm_normal_folio(src_vma, src_addr, orig_src_pte);
1202 if (!folio || !PageAnonExclusive(&folio->page)) {
1203 spin_unlock(src_ptl);
1210 src_folio_pte = orig_src_pte;
1211 spin_unlock(src_ptl);
1213 if (!folio_trylock(src_folio)) {
1214 pte_unmap(&orig_src_pte);
1215 pte_unmap(&orig_dst_pte);
1216 src_pte = dst_pte = NULL;
1217 /* now we can block and wait */
1218 folio_lock(src_folio);
1222 if (WARN_ON_ONCE(!folio_test_anon(src_folio))) {
1228 /* at this point we have src_folio locked */
1229 if (folio_test_large(src_folio)) {
1230 /* split_folio() can block */
1231 pte_unmap(&orig_src_pte);
1232 pte_unmap(&orig_dst_pte);
1233 src_pte = dst_pte = NULL;
1234 err = split_folio(src_folio);
1237 /* have to reacquire the folio after it got split */
1238 folio_unlock(src_folio);
1239 folio_put(src_folio);
1244 if (!src_anon_vma) {
1246 * folio_referenced walks the anon_vma chain
1247 * without the folio lock. Serialize against it with
1248 * the anon_vma lock, the folio lock is not enough.
1250 src_anon_vma = folio_get_anon_vma(src_folio);
1251 if (!src_anon_vma) {
1252 /* page was unmapped from under us */
1256 if (!anon_vma_trylock_write(src_anon_vma)) {
1257 pte_unmap(&orig_src_pte);
1258 pte_unmap(&orig_dst_pte);
1259 src_pte = dst_pte = NULL;
1260 /* now we can block and wait */
1261 anon_vma_lock_write(src_anon_vma);
1266 err = move_present_pte(mm, dst_vma, src_vma,
1267 dst_addr, src_addr, dst_pte, src_pte,
1268 orig_dst_pte, orig_src_pte,
1269 dst_ptl, src_ptl, src_folio);
1271 entry = pte_to_swp_entry(orig_src_pte);
1272 if (non_swap_entry(entry)) {
1273 if (is_migration_entry(entry)) {
1274 pte_unmap(&orig_src_pte);
1275 pte_unmap(&orig_dst_pte);
1276 src_pte = dst_pte = NULL;
1277 migration_entry_wait(mm, src_pmd, src_addr);
1284 err = move_swap_pte(mm, dst_addr, src_addr,
1286 orig_dst_pte, orig_src_pte,
1292 anon_vma_unlock_write(src_anon_vma);
1293 put_anon_vma(src_anon_vma);
1296 folio_unlock(src_folio);
1297 folio_put(src_folio);
1303 mmu_notifier_invalidate_range_end(&range);
1308 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1309 static inline bool move_splits_huge_pmd(unsigned long dst_addr,
1310 unsigned long src_addr,
1311 unsigned long src_end)
1313 return (src_addr & ~HPAGE_PMD_MASK) || (dst_addr & ~HPAGE_PMD_MASK) ||
1314 src_end - src_addr < HPAGE_PMD_SIZE;
1317 static inline bool move_splits_huge_pmd(unsigned long dst_addr,
1318 unsigned long src_addr,
1319 unsigned long src_end)
1321 /* This is unreachable anyway, just to avoid warnings when HPAGE_PMD_SIZE==0 */
1326 static inline bool vma_move_compatible(struct vm_area_struct *vma)
1328 return !(vma->vm_flags & (VM_PFNMAP | VM_IO | VM_HUGETLB |
1329 VM_MIXEDMAP | VM_SHADOW_STACK));
1332 static int validate_move_areas(struct userfaultfd_ctx *ctx,
1333 struct vm_area_struct *src_vma,
1334 struct vm_area_struct *dst_vma)
1336 /* Only allow moving if both have the same access and protection */
1337 if ((src_vma->vm_flags & VM_ACCESS_FLAGS) != (dst_vma->vm_flags & VM_ACCESS_FLAGS) ||
1338 pgprot_val(src_vma->vm_page_prot) != pgprot_val(dst_vma->vm_page_prot))
1341 /* Only allow moving if both are mlocked or both aren't */
1342 if ((src_vma->vm_flags & VM_LOCKED) != (dst_vma->vm_flags & VM_LOCKED))
1346 * For now, we keep it simple and only move between writable VMAs.
1347 * Access flags are equal, therefore cheching only the source is enough.
1349 if (!(src_vma->vm_flags & VM_WRITE))
1352 /* Check if vma flags indicate content which can be moved */
1353 if (!vma_move_compatible(src_vma) || !vma_move_compatible(dst_vma))
1356 /* Ensure dst_vma is registered in uffd we are operating on */
1357 if (!dst_vma->vm_userfaultfd_ctx.ctx ||
1358 dst_vma->vm_userfaultfd_ctx.ctx != ctx)
1361 /* Only allow moving across anonymous vmas */
1362 if (!vma_is_anonymous(src_vma) || !vma_is_anonymous(dst_vma))
1368 static __always_inline
1369 int find_vmas_mm_locked(struct mm_struct *mm,
1370 unsigned long dst_start,
1371 unsigned long src_start,
1372 struct vm_area_struct **dst_vmap,
1373 struct vm_area_struct **src_vmap)
1375 struct vm_area_struct *vma;
1377 mmap_assert_locked(mm);
1378 vma = find_vma_and_prepare_anon(mm, dst_start);
1380 return PTR_ERR(vma);
1383 /* Skip finding src_vma if src_start is in dst_vma */
1384 if (src_start >= vma->vm_start && src_start < vma->vm_end)
1387 vma = vma_lookup(mm, src_start);
1395 #ifdef CONFIG_PER_VMA_LOCK
1396 static int uffd_move_lock(struct mm_struct *mm,
1397 unsigned long dst_start,
1398 unsigned long src_start,
1399 struct vm_area_struct **dst_vmap,
1400 struct vm_area_struct **src_vmap)
1402 struct vm_area_struct *vma;
1405 vma = lock_vma(mm, dst_start);
1407 return PTR_ERR(vma);
1411 * Skip finding src_vma if src_start is in dst_vma. This also ensures
1412 * that we don't lock the same vma twice.
1414 if (src_start >= vma->vm_start && src_start < vma->vm_end) {
1420 * Using lock_vma() to get src_vma can lead to following deadlock:
1424 * vma_start_read(dst_vma)
1425 * mmap_write_lock(mm)
1426 * vma_start_write(src_vma)
1427 * vma_start_read(src_vma)
1428 * mmap_read_lock(mm)
1429 * vma_start_write(dst_vma)
1431 *src_vmap = lock_vma_under_rcu(mm, src_start);
1432 if (likely(*src_vmap))
1435 /* Undo any locking and retry in mmap_lock critical section */
1436 vma_end_read(*dst_vmap);
1439 err = find_vmas_mm_locked(mm, dst_start, src_start, dst_vmap, src_vmap);
1442 * See comment in lock_vma() as to why not using
1443 * vma_start_read() here.
1445 down_read(&(*dst_vmap)->vm_lock->lock);
1446 if (*dst_vmap != *src_vmap)
1447 down_read(&(*src_vmap)->vm_lock->lock);
1449 mmap_read_unlock(mm);
1453 static void uffd_move_unlock(struct vm_area_struct *dst_vma,
1454 struct vm_area_struct *src_vma)
1456 vma_end_read(src_vma);
1457 if (src_vma != dst_vma)
1458 vma_end_read(dst_vma);
1463 static int uffd_move_lock(struct mm_struct *mm,
1464 unsigned long dst_start,
1465 unsigned long src_start,
1466 struct vm_area_struct **dst_vmap,
1467 struct vm_area_struct **src_vmap)
1472 err = find_vmas_mm_locked(mm, dst_start, src_start, dst_vmap, src_vmap);
1474 mmap_read_unlock(mm);
1478 static void uffd_move_unlock(struct vm_area_struct *dst_vma,
1479 struct vm_area_struct *src_vma)
1481 mmap_assert_locked(src_vma->vm_mm);
1482 mmap_read_unlock(dst_vma->vm_mm);
1487 * move_pages - move arbitrary anonymous pages of an existing vma
1488 * @ctx: pointer to the userfaultfd context
1489 * @dst_start: start of the destination virtual memory range
1490 * @src_start: start of the source virtual memory range
1491 * @len: length of the virtual memory range
1492 * @mode: flags from uffdio_move.mode
1494 * It will either use the mmap_lock in read mode or per-vma locks
1496 * move_pages() remaps arbitrary anonymous pages atomically in zero
1497 * copy. It only works on non shared anonymous pages because those can
1498 * be relocated without generating non linear anon_vmas in the rmap
1501 * It provides a zero copy mechanism to handle userspace page faults.
1502 * The source vma pages should have mapcount == 1, which can be
1503 * enforced by using madvise(MADV_DONTFORK) on src vma.
1505 * The thread receiving the page during the userland page fault
1506 * will receive the faulting page in the source vma through the network,
1507 * storage or any other I/O device (MADV_DONTFORK in the source vma
1508 * avoids move_pages() to fail with -EBUSY if the process forks before
1509 * move_pages() is called), then it will call move_pages() to map the
1510 * page in the faulting address in the destination vma.
1512 * This userfaultfd command works purely via pagetables, so it's the
1513 * most efficient way to move physical non shared anonymous pages
1514 * across different virtual addresses. Unlike mremap()/mmap()/munmap()
1515 * it does not create any new vmas. The mapping in the destination
1516 * address is atomic.
1518 * It only works if the vma protection bits are identical from the
1519 * source and destination vma.
1521 * It can remap non shared anonymous pages within the same vma too.
1523 * If the source virtual memory range has any unmapped holes, or if
1524 * the destination virtual memory range is not a whole unmapped hole,
1525 * move_pages() will fail respectively with -ENOENT or -EEXIST. This
1526 * provides a very strict behavior to avoid any chance of memory
1527 * corruption going unnoticed if there are userland race conditions.
1528 * Only one thread should resolve the userland page fault at any given
1529 * time for any given faulting address. This means that if two threads
1530 * try to both call move_pages() on the same destination address at the
1531 * same time, the second thread will get an explicit error from this
1534 * The command retval will return "len" is successful. The command
1535 * however can be interrupted by fatal signals or errors. If
1536 * interrupted it will return the number of bytes successfully
1537 * remapped before the interruption if any, or the negative error if
1538 * none. It will never return zero. Either it will return an error or
1539 * an amount of bytes successfully moved. If the retval reports a
1540 * "short" remap, the move_pages() command should be repeated by
1541 * userland with src+retval, dst+reval, len-retval if it wants to know
1542 * about the error that interrupted it.
1544 * The UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES flag can be specified to
1545 * prevent -ENOENT errors to materialize if there are holes in the
1546 * source virtual range that is being remapped. The holes will be
1547 * accounted as successfully remapped in the retval of the
1548 * command. This is mostly useful to remap hugepage naturally aligned
1549 * virtual regions without knowing if there are transparent hugepage
1550 * in the regions or not, but preventing the risk of having to split
1551 * the hugepmd during the remap.
1553 * If there's any rmap walk that is taking the anon_vma locks without
1554 * first obtaining the folio lock (the only current instance is
1555 * folio_referenced), they will have to verify if the folio->mapping
1556 * has changed after taking the anon_vma lock. If it changed they
1557 * should release the lock and retry obtaining a new anon_vma, because
1558 * it means the anon_vma was changed by move_pages() before the lock
1559 * could be obtained. This is the only additional complexity added to
1560 * the rmap code to provide this anonymous page remapping functionality.
1562 ssize_t move_pages(struct userfaultfd_ctx *ctx, unsigned long dst_start,
1563 unsigned long src_start, unsigned long len, __u64 mode)
1565 struct mm_struct *mm = ctx->mm;
1566 struct vm_area_struct *src_vma, *dst_vma;
1567 unsigned long src_addr, dst_addr;
1568 pmd_t *src_pmd, *dst_pmd;
1572 /* Sanitize the command parameters. */
1573 if (WARN_ON_ONCE(src_start & ~PAGE_MASK) ||
1574 WARN_ON_ONCE(dst_start & ~PAGE_MASK) ||
1575 WARN_ON_ONCE(len & ~PAGE_MASK))
1578 /* Does the address range wrap, or is the span zero-sized? */
1579 if (WARN_ON_ONCE(src_start + len <= src_start) ||
1580 WARN_ON_ONCE(dst_start + len <= dst_start))
1583 err = uffd_move_lock(mm, dst_start, src_start, &dst_vma, &src_vma);
1587 /* Re-check after taking map_changing_lock */
1589 down_read(&ctx->map_changing_lock);
1590 if (likely(atomic_read(&ctx->mmap_changing)))
1593 * Make sure the vma is not shared, that the src and dst remap
1594 * ranges are both valid and fully within a single existing
1598 if (src_vma->vm_flags & VM_SHARED)
1600 if (src_start + len > src_vma->vm_end)
1603 if (dst_vma->vm_flags & VM_SHARED)
1605 if (dst_start + len > dst_vma->vm_end)
1608 err = validate_move_areas(ctx, src_vma, dst_vma);
1612 for (src_addr = src_start, dst_addr = dst_start;
1613 src_addr < src_start + len;) {
1616 unsigned long step_size;
1619 * Below works because anonymous area would not have a
1620 * transparent huge PUD. If file-backed support is added,
1621 * that case would need to be handled here.
1623 src_pmd = mm_find_pmd(mm, src_addr);
1624 if (unlikely(!src_pmd)) {
1625 if (!(mode & UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES)) {
1629 src_pmd = mm_alloc_pmd(mm, src_addr);
1630 if (unlikely(!src_pmd)) {
1635 dst_pmd = mm_alloc_pmd(mm, dst_addr);
1636 if (unlikely(!dst_pmd)) {
1641 dst_pmdval = pmdp_get_lockless(dst_pmd);
1643 * If the dst_pmd is mapped as THP don't override it and just
1644 * be strict. If dst_pmd changes into TPH after this check, the
1645 * move_pages_huge_pmd() will detect the change and retry
1646 * while move_pages_pte() will detect the change and fail.
1648 if (unlikely(pmd_trans_huge(dst_pmdval))) {
1653 ptl = pmd_trans_huge_lock(src_pmd, src_vma);
1655 if (pmd_devmap(*src_pmd)) {
1661 /* Check if we can move the pmd without splitting it. */
1662 if (move_splits_huge_pmd(dst_addr, src_addr, src_start + len) ||
1663 !pmd_none(dst_pmdval)) {
1664 struct folio *folio = pfn_folio(pmd_pfn(*src_pmd));
1666 if (!folio || (!is_huge_zero_page(&folio->page) &&
1667 !PageAnonExclusive(&folio->page))) {
1674 split_huge_pmd(src_vma, src_pmd, src_addr);
1675 /* The folio will be split by move_pages_pte() */
1679 err = move_pages_huge_pmd(mm, dst_pmd, src_pmd,
1680 dst_pmdval, dst_vma, src_vma,
1681 dst_addr, src_addr);
1682 step_size = HPAGE_PMD_SIZE;
1684 if (pmd_none(*src_pmd)) {
1685 if (!(mode & UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES)) {
1689 if (unlikely(__pte_alloc(mm, src_pmd))) {
1695 if (unlikely(pte_alloc(mm, dst_pmd))) {
1700 err = move_pages_pte(mm, dst_pmd, src_pmd,
1702 dst_addr, src_addr, mode);
1703 step_size = PAGE_SIZE;
1708 if (fatal_signal_pending(current)) {
1709 /* Do not override an error */
1710 if (!err || err == -EAGAIN)
1721 /* Proceed to the next page */
1722 dst_addr += step_size;
1723 src_addr += step_size;
1728 up_read(&ctx->map_changing_lock);
1729 uffd_move_unlock(dst_vma, src_vma);
1731 VM_WARN_ON(moved < 0);
1732 VM_WARN_ON(err > 0);
1733 VM_WARN_ON(!moved && !err);
1734 return moved ? moved : err;