• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  mm/userfaultfd.c
4  *
5  *  Copyright (C) 2015  Red Hat, Inc.
6  */
7 
8 #include <linux/mm.h>
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>
19 #include <asm/tlb.h>
20 #include "internal.h"
21 #include "swap.h"
22 
23 static __always_inline
validate_dst_vma(struct vm_area_struct * dst_vma,unsigned long dst_end)24 bool validate_dst_vma(struct vm_area_struct *dst_vma, unsigned long dst_end)
25 {
26 	/* Make sure that the dst range is fully within dst_vma. */
27 	if (dst_end > dst_vma->vm_end)
28 		return false;
29 
30 	/*
31 	 * Check the vma is registered in uffd, this is required to
32 	 * enforce the VM_MAYWRITE check done at uffd registration
33 	 * time.
34 	 */
35 	if (!dst_vma->vm_userfaultfd_ctx.ctx)
36 		return false;
37 
38 	return true;
39 }
40 
41 static __always_inline
find_vma_and_prepare_anon(struct mm_struct * mm,unsigned long addr)42 struct vm_area_struct *find_vma_and_prepare_anon(struct mm_struct *mm,
43 						 unsigned long addr)
44 {
45 	struct vm_area_struct *vma;
46 
47 	mmap_assert_locked(mm);
48 	vma = vma_lookup(mm, addr);
49 	if (!vma)
50 		vma = ERR_PTR(-ENOENT);
51 	else if (!(vma->vm_flags & VM_SHARED) &&
52 		 unlikely(anon_vma_prepare(vma)))
53 		vma = ERR_PTR(-ENOMEM);
54 
55 	return vma;
56 }
57 
58 #ifdef CONFIG_PER_VMA_LOCK
59 /*
60  * uffd_lock_vma() - Lookup and lock vma corresponding to @address.
61  * @mm: mm to search vma in.
62  * @address: address that the vma should contain.
63  *
64  * Should be called without holding mmap_lock.
65  *
66  * Return: A locked vma containing @address, -ENOENT if no vma is found, or
67  * -ENOMEM if anon_vma couldn't be allocated.
68  */
uffd_lock_vma(struct mm_struct * mm,unsigned long address)69 static struct vm_area_struct *uffd_lock_vma(struct mm_struct *mm,
70 				       unsigned long address)
71 {
72 	struct vm_area_struct *vma;
73 
74 	vma = lock_vma_under_rcu(mm, address);
75 	if (vma) {
76 		/*
77 		 * We know we're going to need to use anon_vma, so check
78 		 * that early.
79 		 */
80 		if (!(vma->vm_flags & VM_SHARED) && unlikely(!vma->anon_vma))
81 			vma_end_read(vma);
82 		else
83 			return vma;
84 	}
85 
86 	mmap_read_lock(mm);
87 	vma = find_vma_and_prepare_anon(mm, address);
88 	if (!IS_ERR(vma)) {
89 		bool locked = vma_start_read_locked(vma);
90 
91 		if (!locked)
92 			vma = ERR_PTR(-EAGAIN);
93 	}
94 
95 	mmap_read_unlock(mm);
96 	return vma;
97 }
98 
uffd_mfill_lock(struct mm_struct * dst_mm,unsigned long dst_start,unsigned long len)99 static struct vm_area_struct *uffd_mfill_lock(struct mm_struct *dst_mm,
100 					      unsigned long dst_start,
101 					      unsigned long len)
102 {
103 	struct vm_area_struct *dst_vma;
104 
105 	dst_vma = uffd_lock_vma(dst_mm, dst_start);
106 	if (IS_ERR(dst_vma) || validate_dst_vma(dst_vma, dst_start + len))
107 		return dst_vma;
108 
109 	vma_end_read(dst_vma);
110 	return ERR_PTR(-ENOENT);
111 }
112 
uffd_mfill_unlock(struct vm_area_struct * vma)113 static void uffd_mfill_unlock(struct vm_area_struct *vma)
114 {
115 	vma_end_read(vma);
116 }
117 
118 #else
119 
uffd_mfill_lock(struct mm_struct * dst_mm,unsigned long dst_start,unsigned long len)120 static struct vm_area_struct *uffd_mfill_lock(struct mm_struct *dst_mm,
121 					      unsigned long dst_start,
122 					      unsigned long len)
123 {
124 	struct vm_area_struct *dst_vma;
125 
126 	mmap_read_lock(dst_mm);
127 	dst_vma = find_vma_and_prepare_anon(dst_mm, dst_start);
128 	if (IS_ERR(dst_vma))
129 		goto out_unlock;
130 
131 	if (validate_dst_vma(dst_vma, dst_start + len))
132 		return dst_vma;
133 
134 	dst_vma = ERR_PTR(-ENOENT);
135 out_unlock:
136 	mmap_read_unlock(dst_mm);
137 	return dst_vma;
138 }
139 
uffd_mfill_unlock(struct vm_area_struct * vma)140 static void uffd_mfill_unlock(struct vm_area_struct *vma)
141 {
142 	mmap_read_unlock(vma->vm_mm);
143 }
144 #endif
145 
146 /* Check if dst_addr is outside of file's size. Must be called with ptl held. */
mfill_file_over_size(struct vm_area_struct * dst_vma,unsigned long dst_addr)147 static bool mfill_file_over_size(struct vm_area_struct *dst_vma,
148 				 unsigned long dst_addr)
149 {
150 	struct inode *inode;
151 	pgoff_t offset, max_off;
152 
153 	if (!dst_vma->vm_file)
154 		return false;
155 
156 	inode = dst_vma->vm_file->f_inode;
157 	offset = linear_page_index(dst_vma, dst_addr);
158 	max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
159 	return offset >= max_off;
160 }
161 
162 /*
163  * Install PTEs, to map dst_addr (within dst_vma) to page.
164  *
165  * This function handles both MCOPY_ATOMIC_NORMAL and _CONTINUE for both shmem
166  * and anon, and for both shared and private VMAs.
167  */
mfill_atomic_install_pte(pmd_t * dst_pmd,struct vm_area_struct * dst_vma,unsigned long dst_addr,struct page * page,bool newly_allocated,uffd_flags_t flags)168 int mfill_atomic_install_pte(pmd_t *dst_pmd,
169 			     struct vm_area_struct *dst_vma,
170 			     unsigned long dst_addr, struct page *page,
171 			     bool newly_allocated, uffd_flags_t flags)
172 {
173 	int ret;
174 	struct mm_struct *dst_mm = dst_vma->vm_mm;
175 	pte_t _dst_pte, *dst_pte;
176 	bool writable = dst_vma->vm_flags & VM_WRITE;
177 	bool vm_shared = dst_vma->vm_flags & VM_SHARED;
178 	spinlock_t *ptl;
179 	struct folio *folio = page_folio(page);
180 	bool page_in_cache = folio_mapping(folio);
181 
182 	_dst_pte = mk_pte(page, dst_vma->vm_page_prot);
183 	_dst_pte = pte_mkdirty(_dst_pte);
184 	if (page_in_cache && !vm_shared)
185 		writable = false;
186 	if (writable)
187 		_dst_pte = pte_mkwrite(_dst_pte, dst_vma);
188 	if (flags & MFILL_ATOMIC_WP)
189 		_dst_pte = pte_mkuffd_wp(_dst_pte);
190 
191 	ret = -EAGAIN;
192 	dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
193 	if (!dst_pte)
194 		goto out;
195 
196 	if (mfill_file_over_size(dst_vma, dst_addr)) {
197 		ret = -EFAULT;
198 		goto out_unlock;
199 	}
200 
201 	ret = -EEXIST;
202 	/*
203 	 * We allow to overwrite a pte marker: consider when both MISSING|WP
204 	 * registered, we firstly wr-protect a none pte which has no page cache
205 	 * page backing it, then access the page.
206 	 */
207 	if (!pte_none_mostly(ptep_get(dst_pte)))
208 		goto out_unlock;
209 
210 	if (page_in_cache) {
211 		/* Usually, cache pages are already added to LRU */
212 		if (newly_allocated)
213 			folio_add_lru(folio);
214 		folio_add_file_rmap_pte(folio, page, dst_vma);
215 	} else {
216 		folio_add_new_anon_rmap(folio, dst_vma, dst_addr, RMAP_EXCLUSIVE);
217 		folio_add_lru_vma(folio, dst_vma);
218 	}
219 
220 	/*
221 	 * Must happen after rmap, as mm_counter() checks mapping (via
222 	 * PageAnon()), which is set by __page_set_anon_rmap().
223 	 */
224 	inc_mm_counter(dst_mm, mm_counter(folio));
225 
226 	set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
227 
228 	/* No need to invalidate - it was non-present before */
229 	update_mmu_cache(dst_vma, dst_addr, dst_pte);
230 	ret = 0;
231 out_unlock:
232 	pte_unmap_unlock(dst_pte, ptl);
233 out:
234 	return ret;
235 }
236 
mfill_atomic_pte_copy(pmd_t * dst_pmd,struct vm_area_struct * dst_vma,unsigned long dst_addr,unsigned long src_addr,uffd_flags_t flags,struct folio ** foliop)237 static int mfill_atomic_pte_copy(pmd_t *dst_pmd,
238 				 struct vm_area_struct *dst_vma,
239 				 unsigned long dst_addr,
240 				 unsigned long src_addr,
241 				 uffd_flags_t flags,
242 				 struct folio **foliop)
243 {
244 	void *kaddr;
245 	int ret;
246 	struct folio *folio;
247 
248 	if (!*foliop) {
249 		ret = -ENOMEM;
250 		folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0, dst_vma,
251 					dst_addr, false);
252 		if (!folio)
253 			goto out;
254 
255 		kaddr = kmap_local_folio(folio, 0);
256 		/*
257 		 * The read mmap_lock is held here.  Despite the
258 		 * mmap_lock being read recursive a deadlock is still
259 		 * possible if a writer has taken a lock.  For example:
260 		 *
261 		 * process A thread 1 takes read lock on own mmap_lock
262 		 * process A thread 2 calls mmap, blocks taking write lock
263 		 * process B thread 1 takes page fault, read lock on own mmap lock
264 		 * process B thread 2 calls mmap, blocks taking write lock
265 		 * process A thread 1 blocks taking read lock on process B
266 		 * process B thread 1 blocks taking read lock on process A
267 		 *
268 		 * Disable page faults to prevent potential deadlock
269 		 * and retry the copy outside the mmap_lock.
270 		 */
271 		pagefault_disable();
272 		ret = copy_from_user(kaddr, (const void __user *) src_addr,
273 				     PAGE_SIZE);
274 		pagefault_enable();
275 		kunmap_local(kaddr);
276 
277 		/* fallback to copy_from_user outside mmap_lock */
278 		if (unlikely(ret)) {
279 			ret = -ENOENT;
280 			*foliop = folio;
281 			/* don't free the page */
282 			goto out;
283 		}
284 
285 		flush_dcache_folio(folio);
286 	} else {
287 		folio = *foliop;
288 		*foliop = NULL;
289 	}
290 
291 	/*
292 	 * The memory barrier inside __folio_mark_uptodate makes sure that
293 	 * preceding stores to the page contents become visible before
294 	 * the set_pte_at() write.
295 	 */
296 	__folio_mark_uptodate(folio);
297 
298 	ret = -ENOMEM;
299 	if (mem_cgroup_charge(folio, dst_vma->vm_mm, GFP_KERNEL))
300 		goto out_release;
301 
302 	ret = mfill_atomic_install_pte(dst_pmd, dst_vma, dst_addr,
303 				       &folio->page, true, flags);
304 	if (ret)
305 		goto out_release;
306 out:
307 	return ret;
308 out_release:
309 	folio_put(folio);
310 	goto out;
311 }
312 
mfill_atomic_pte_zeroed_folio(pmd_t * dst_pmd,struct vm_area_struct * dst_vma,unsigned long dst_addr)313 static int mfill_atomic_pte_zeroed_folio(pmd_t *dst_pmd,
314 					 struct vm_area_struct *dst_vma,
315 					 unsigned long dst_addr)
316 {
317 	struct folio *folio;
318 	int ret = -ENOMEM;
319 
320 	folio = vma_alloc_zeroed_movable_folio(dst_vma, dst_addr);
321 	if (!folio)
322 		return ret;
323 
324 	if (mem_cgroup_charge(folio, dst_vma->vm_mm, GFP_KERNEL))
325 		goto out_put;
326 
327 	/*
328 	 * The memory barrier inside __folio_mark_uptodate makes sure that
329 	 * zeroing out the folio become visible before mapping the page
330 	 * using set_pte_at(). See do_anonymous_page().
331 	 */
332 	__folio_mark_uptodate(folio);
333 
334 	ret = mfill_atomic_install_pte(dst_pmd, dst_vma, dst_addr,
335 				       &folio->page, true, 0);
336 	if (ret)
337 		goto out_put;
338 
339 	return 0;
340 out_put:
341 	folio_put(folio);
342 	return ret;
343 }
344 
mfill_atomic_pte_zeropage(pmd_t * dst_pmd,struct vm_area_struct * dst_vma,unsigned long dst_addr)345 static int mfill_atomic_pte_zeropage(pmd_t *dst_pmd,
346 				     struct vm_area_struct *dst_vma,
347 				     unsigned long dst_addr)
348 {
349 	pte_t _dst_pte, *dst_pte;
350 	spinlock_t *ptl;
351 	int ret;
352 
353 	if (mm_forbids_zeropage(dst_vma->vm_mm))
354 		return mfill_atomic_pte_zeroed_folio(dst_pmd, dst_vma, dst_addr);
355 
356 	_dst_pte = pte_mkspecial(pfn_pte(my_zero_pfn(dst_addr),
357 					 dst_vma->vm_page_prot));
358 	ret = -EAGAIN;
359 	dst_pte = pte_offset_map_lock(dst_vma->vm_mm, dst_pmd, dst_addr, &ptl);
360 	if (!dst_pte)
361 		goto out;
362 	if (mfill_file_over_size(dst_vma, dst_addr)) {
363 		ret = -EFAULT;
364 		goto out_unlock;
365 	}
366 	ret = -EEXIST;
367 	if (!pte_none(ptep_get(dst_pte)))
368 		goto out_unlock;
369 	set_pte_at(dst_vma->vm_mm, dst_addr, dst_pte, _dst_pte);
370 	/* No need to invalidate - it was non-present before */
371 	update_mmu_cache(dst_vma, dst_addr, dst_pte);
372 	ret = 0;
373 out_unlock:
374 	pte_unmap_unlock(dst_pte, ptl);
375 out:
376 	return ret;
377 }
378 
379 /* Handles UFFDIO_CONTINUE for all shmem VMAs (shared or private). */
mfill_atomic_pte_continue(pmd_t * dst_pmd,struct vm_area_struct * dst_vma,unsigned long dst_addr,uffd_flags_t flags)380 static int mfill_atomic_pte_continue(pmd_t *dst_pmd,
381 				     struct vm_area_struct *dst_vma,
382 				     unsigned long dst_addr,
383 				     uffd_flags_t flags)
384 {
385 	struct inode *inode = file_inode(dst_vma->vm_file);
386 	pgoff_t pgoff = linear_page_index(dst_vma, dst_addr);
387 	struct folio *folio;
388 	struct page *page;
389 	int ret;
390 
391 	ret = shmem_get_folio(inode, pgoff, 0, &folio, SGP_NOALLOC);
392 	/* Our caller expects us to return -EFAULT if we failed to find folio */
393 	if (ret == -ENOENT)
394 		ret = -EFAULT;
395 	if (ret)
396 		goto out;
397 	if (!folio) {
398 		ret = -EFAULT;
399 		goto out;
400 	}
401 
402 	page = folio_file_page(folio, pgoff);
403 	if (PageHWPoison(page)) {
404 		ret = -EIO;
405 		goto out_release;
406 	}
407 
408 	ret = mfill_atomic_install_pte(dst_pmd, dst_vma, dst_addr,
409 				       page, false, flags);
410 	if (ret)
411 		goto out_release;
412 
413 	folio_unlock(folio);
414 	ret = 0;
415 out:
416 	return ret;
417 out_release:
418 	folio_unlock(folio);
419 	folio_put(folio);
420 	goto out;
421 }
422 
423 /* Handles UFFDIO_POISON for all non-hugetlb VMAs. */
mfill_atomic_pte_poison(pmd_t * dst_pmd,struct vm_area_struct * dst_vma,unsigned long dst_addr,uffd_flags_t flags)424 static int mfill_atomic_pte_poison(pmd_t *dst_pmd,
425 				   struct vm_area_struct *dst_vma,
426 				   unsigned long dst_addr,
427 				   uffd_flags_t flags)
428 {
429 	int ret;
430 	struct mm_struct *dst_mm = dst_vma->vm_mm;
431 	pte_t _dst_pte, *dst_pte;
432 	spinlock_t *ptl;
433 
434 	_dst_pte = make_pte_marker(PTE_MARKER_POISONED);
435 	ret = -EAGAIN;
436 	dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
437 	if (!dst_pte)
438 		goto out;
439 
440 	if (mfill_file_over_size(dst_vma, dst_addr)) {
441 		ret = -EFAULT;
442 		goto out_unlock;
443 	}
444 
445 	ret = -EEXIST;
446 	/* Refuse to overwrite any PTE, even a PTE marker (e.g. UFFD WP). */
447 	if (!pte_none(ptep_get(dst_pte)))
448 		goto out_unlock;
449 
450 	set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
451 
452 	/* No need to invalidate - it was non-present before */
453 	update_mmu_cache(dst_vma, dst_addr, dst_pte);
454 	ret = 0;
455 out_unlock:
456 	pte_unmap_unlock(dst_pte, ptl);
457 out:
458 	return ret;
459 }
460 
mm_alloc_pmd(struct mm_struct * mm,unsigned long address)461 static pmd_t *mm_alloc_pmd(struct mm_struct *mm, unsigned long address)
462 {
463 	pgd_t *pgd;
464 	p4d_t *p4d;
465 	pud_t *pud;
466 
467 	pgd = pgd_offset(mm, address);
468 	p4d = p4d_alloc(mm, pgd, address);
469 	if (!p4d)
470 		return NULL;
471 	pud = pud_alloc(mm, p4d, address);
472 	if (!pud)
473 		return NULL;
474 	/*
475 	 * Note that we didn't run this because the pmd was
476 	 * missing, the *pmd may be already established and in
477 	 * turn it may also be a trans_huge_pmd.
478 	 */
479 	return pmd_alloc(mm, pud, address);
480 }
481 
482 #ifdef CONFIG_HUGETLB_PAGE
483 /*
484  * mfill_atomic processing for HUGETLB vmas.  Note that this routine is
485  * called with either vma-lock or mmap_lock held, it will release the lock
486  * before returning.
487  */
mfill_atomic_hugetlb(struct userfaultfd_ctx * ctx,struct vm_area_struct * dst_vma,unsigned long dst_start,unsigned long src_start,unsigned long len,uffd_flags_t flags)488 static __always_inline ssize_t mfill_atomic_hugetlb(
489 					      struct userfaultfd_ctx *ctx,
490 					      struct vm_area_struct *dst_vma,
491 					      unsigned long dst_start,
492 					      unsigned long src_start,
493 					      unsigned long len,
494 					      uffd_flags_t flags)
495 {
496 	struct mm_struct *dst_mm = dst_vma->vm_mm;
497 	ssize_t err;
498 	pte_t *dst_pte;
499 	unsigned long src_addr, dst_addr;
500 	long copied;
501 	struct folio *folio;
502 	unsigned long vma_hpagesize;
503 	pgoff_t idx;
504 	u32 hash;
505 	struct address_space *mapping;
506 
507 	/*
508 	 * There is no default zero huge page for all huge page sizes as
509 	 * supported by hugetlb.  A PMD_SIZE huge pages may exist as used
510 	 * by THP.  Since we can not reliably insert a zero page, this
511 	 * feature is not supported.
512 	 */
513 	if (uffd_flags_mode_is(flags, MFILL_ATOMIC_ZEROPAGE)) {
514 		up_read(&ctx->map_changing_lock);
515 		uffd_mfill_unlock(dst_vma);
516 		return -EINVAL;
517 	}
518 
519 	src_addr = src_start;
520 	dst_addr = dst_start;
521 	copied = 0;
522 	folio = NULL;
523 	vma_hpagesize = vma_kernel_pagesize(dst_vma);
524 
525 	/*
526 	 * Validate alignment based on huge page size
527 	 */
528 	err = -EINVAL;
529 	if (dst_start & (vma_hpagesize - 1) || len & (vma_hpagesize - 1))
530 		goto out_unlock;
531 
532 retry:
533 	/*
534 	 * On routine entry dst_vma is set.  If we had to drop mmap_lock and
535 	 * retry, dst_vma will be set to NULL and we must lookup again.
536 	 */
537 	if (!dst_vma) {
538 		dst_vma = uffd_mfill_lock(dst_mm, dst_start, len);
539 		if (IS_ERR(dst_vma)) {
540 			err = PTR_ERR(dst_vma);
541 			goto out;
542 		}
543 
544 		err = -ENOENT;
545 		if (!is_vm_hugetlb_page(dst_vma))
546 			goto out_unlock_vma;
547 
548 		err = -EINVAL;
549 		if (vma_hpagesize != vma_kernel_pagesize(dst_vma))
550 			goto out_unlock_vma;
551 
552 		/*
553 		 * If memory mappings are changing because of non-cooperative
554 		 * operation (e.g. mremap) running in parallel, bail out and
555 		 * request the user to retry later
556 		 */
557 		down_read(&ctx->map_changing_lock);
558 		err = -EAGAIN;
559 		if (atomic_read(&ctx->mmap_changing))
560 			goto out_unlock;
561 	}
562 
563 	while (src_addr < src_start + len) {
564 		BUG_ON(dst_addr >= dst_start + len);
565 
566 		/*
567 		 * Serialize via vma_lock and hugetlb_fault_mutex.
568 		 * vma_lock ensures the dst_pte remains valid even
569 		 * in the case of shared pmds.  fault mutex prevents
570 		 * races with other faulting threads.
571 		 */
572 		idx = linear_page_index(dst_vma, dst_addr);
573 		mapping = dst_vma->vm_file->f_mapping;
574 		hash = hugetlb_fault_mutex_hash(mapping, idx);
575 		mutex_lock(&hugetlb_fault_mutex_table[hash]);
576 		hugetlb_vma_lock_read(dst_vma);
577 
578 		err = -ENOMEM;
579 		dst_pte = huge_pte_alloc(dst_mm, dst_vma, dst_addr, vma_hpagesize);
580 		if (!dst_pte) {
581 			hugetlb_vma_unlock_read(dst_vma);
582 			mutex_unlock(&hugetlb_fault_mutex_table[hash]);
583 			goto out_unlock;
584 		}
585 
586 		if (!uffd_flags_mode_is(flags, MFILL_ATOMIC_CONTINUE) &&
587 		    !huge_pte_none_mostly(huge_ptep_get(dst_mm, dst_addr, dst_pte))) {
588 			err = -EEXIST;
589 			hugetlb_vma_unlock_read(dst_vma);
590 			mutex_unlock(&hugetlb_fault_mutex_table[hash]);
591 			goto out_unlock;
592 		}
593 
594 		err = hugetlb_mfill_atomic_pte(dst_pte, dst_vma, dst_addr,
595 					       src_addr, flags, &folio);
596 
597 		hugetlb_vma_unlock_read(dst_vma);
598 		mutex_unlock(&hugetlb_fault_mutex_table[hash]);
599 
600 		cond_resched();
601 
602 		if (unlikely(err == -ENOENT)) {
603 			up_read(&ctx->map_changing_lock);
604 			uffd_mfill_unlock(dst_vma);
605 			BUG_ON(!folio);
606 
607 			err = copy_folio_from_user(folio,
608 						   (const void __user *)src_addr, true);
609 			if (unlikely(err)) {
610 				err = -EFAULT;
611 				goto out;
612 			}
613 
614 			dst_vma = NULL;
615 			goto retry;
616 		} else
617 			BUG_ON(folio);
618 
619 		if (!err) {
620 			dst_addr += vma_hpagesize;
621 			src_addr += vma_hpagesize;
622 			copied += vma_hpagesize;
623 
624 			if (fatal_signal_pending(current))
625 				err = -EINTR;
626 		}
627 		if (err)
628 			break;
629 	}
630 
631 out_unlock:
632 	up_read(&ctx->map_changing_lock);
633 out_unlock_vma:
634 	uffd_mfill_unlock(dst_vma);
635 out:
636 	if (folio)
637 		folio_put(folio);
638 	BUG_ON(copied < 0);
639 	BUG_ON(err > 0);
640 	BUG_ON(!copied && !err);
641 	return copied ? copied : err;
642 }
643 #else /* !CONFIG_HUGETLB_PAGE */
644 /* fail at build time if gcc attempts to use this */
645 extern ssize_t mfill_atomic_hugetlb(struct userfaultfd_ctx *ctx,
646 				    struct vm_area_struct *dst_vma,
647 				    unsigned long dst_start,
648 				    unsigned long src_start,
649 				    unsigned long len,
650 				    uffd_flags_t flags);
651 #endif /* CONFIG_HUGETLB_PAGE */
652 
mfill_atomic_pte(pmd_t * dst_pmd,struct vm_area_struct * dst_vma,unsigned long dst_addr,unsigned long src_addr,uffd_flags_t flags,struct folio ** foliop)653 static __always_inline ssize_t mfill_atomic_pte(pmd_t *dst_pmd,
654 						struct vm_area_struct *dst_vma,
655 						unsigned long dst_addr,
656 						unsigned long src_addr,
657 						uffd_flags_t flags,
658 						struct folio **foliop)
659 {
660 	ssize_t err;
661 
662 	if (uffd_flags_mode_is(flags, MFILL_ATOMIC_CONTINUE)) {
663 		return mfill_atomic_pte_continue(dst_pmd, dst_vma,
664 						 dst_addr, flags);
665 	} else if (uffd_flags_mode_is(flags, MFILL_ATOMIC_POISON)) {
666 		return mfill_atomic_pte_poison(dst_pmd, dst_vma,
667 					       dst_addr, flags);
668 	}
669 
670 	/*
671 	 * The normal page fault path for a shmem will invoke the
672 	 * fault, fill the hole in the file and COW it right away. The
673 	 * result generates plain anonymous memory. So when we are
674 	 * asked to fill an hole in a MAP_PRIVATE shmem mapping, we'll
675 	 * generate anonymous memory directly without actually filling
676 	 * the hole. For the MAP_PRIVATE case the robustness check
677 	 * only happens in the pagetable (to verify it's still none)
678 	 * and not in the radix tree.
679 	 */
680 	if (!(dst_vma->vm_flags & VM_SHARED)) {
681 		if (uffd_flags_mode_is(flags, MFILL_ATOMIC_COPY))
682 			err = mfill_atomic_pte_copy(dst_pmd, dst_vma,
683 						    dst_addr, src_addr,
684 						    flags, foliop);
685 		else
686 			err = mfill_atomic_pte_zeropage(dst_pmd,
687 						 dst_vma, dst_addr);
688 	} else {
689 		err = shmem_mfill_atomic_pte(dst_pmd, dst_vma,
690 					     dst_addr, src_addr,
691 					     flags, foliop);
692 	}
693 
694 	return err;
695 }
696 
mfill_atomic(struct userfaultfd_ctx * ctx,unsigned long dst_start,unsigned long src_start,unsigned long len,uffd_flags_t flags)697 static __always_inline ssize_t mfill_atomic(struct userfaultfd_ctx *ctx,
698 					    unsigned long dst_start,
699 					    unsigned long src_start,
700 					    unsigned long len,
701 					    uffd_flags_t flags)
702 {
703 	struct mm_struct *dst_mm = ctx->mm;
704 	struct vm_area_struct *dst_vma;
705 	ssize_t err;
706 	pmd_t *dst_pmd;
707 	unsigned long src_addr, dst_addr;
708 	long copied;
709 	struct folio *folio;
710 
711 	/*
712 	 * Sanitize the command parameters:
713 	 */
714 	BUG_ON(dst_start & ~PAGE_MASK);
715 	BUG_ON(len & ~PAGE_MASK);
716 
717 	/* Does the address range wrap, or is the span zero-sized? */
718 	BUG_ON(src_start + len <= src_start);
719 	BUG_ON(dst_start + len <= dst_start);
720 
721 	src_addr = src_start;
722 	dst_addr = dst_start;
723 	copied = 0;
724 	folio = NULL;
725 retry:
726 	/*
727 	 * Make sure the vma is not shared, that the dst range is
728 	 * both valid and fully within a single existing vma.
729 	 */
730 	dst_vma = uffd_mfill_lock(dst_mm, dst_start, len);
731 	if (IS_ERR(dst_vma)) {
732 		err = PTR_ERR(dst_vma);
733 		goto out;
734 	}
735 
736 	/*
737 	 * If memory mappings are changing because of non-cooperative
738 	 * operation (e.g. mremap) running in parallel, bail out and
739 	 * request the user to retry later
740 	 */
741 	down_read(&ctx->map_changing_lock);
742 	err = -EAGAIN;
743 	if (atomic_read(&ctx->mmap_changing))
744 		goto out_unlock;
745 
746 	err = -EINVAL;
747 	/*
748 	 * shmem_zero_setup is invoked in mmap for MAP_ANONYMOUS|MAP_SHARED but
749 	 * it will overwrite vm_ops, so vma_is_anonymous must return false.
750 	 */
751 	if (WARN_ON_ONCE(vma_is_anonymous(dst_vma) &&
752 	    dst_vma->vm_flags & VM_SHARED))
753 		goto out_unlock;
754 
755 	/*
756 	 * validate 'mode' now that we know the dst_vma: don't allow
757 	 * a wrprotect copy if the userfaultfd didn't register as WP.
758 	 */
759 	if ((flags & MFILL_ATOMIC_WP) && !(dst_vma->vm_flags & VM_UFFD_WP))
760 		goto out_unlock;
761 
762 	/*
763 	 * If this is a HUGETLB vma, pass off to appropriate routine
764 	 */
765 	if (is_vm_hugetlb_page(dst_vma))
766 		return  mfill_atomic_hugetlb(ctx, dst_vma, dst_start,
767 					     src_start, len, flags);
768 
769 	if (!vma_is_anonymous(dst_vma) && !vma_is_shmem(dst_vma))
770 		goto out_unlock;
771 	if (!vma_is_shmem(dst_vma) &&
772 	    uffd_flags_mode_is(flags, MFILL_ATOMIC_CONTINUE))
773 		goto out_unlock;
774 
775 	while (src_addr < src_start + len) {
776 		pmd_t dst_pmdval;
777 
778 		BUG_ON(dst_addr >= dst_start + len);
779 
780 		dst_pmd = mm_alloc_pmd(dst_mm, dst_addr);
781 		if (unlikely(!dst_pmd)) {
782 			err = -ENOMEM;
783 			break;
784 		}
785 
786 		dst_pmdval = pmdp_get_lockless(dst_pmd);
787 		if (unlikely(pmd_none(dst_pmdval)) &&
788 		    unlikely(__pte_alloc(dst_mm, dst_pmd))) {
789 			err = -ENOMEM;
790 			break;
791 		}
792 		dst_pmdval = pmdp_get_lockless(dst_pmd);
793 		/*
794 		 * If the dst_pmd is THP don't override it and just be strict.
795 		 * (This includes the case where the PMD used to be THP and
796 		 * changed back to none after __pte_alloc().)
797 		 */
798 		if (unlikely(!pmd_present(dst_pmdval) || pmd_trans_huge(dst_pmdval) ||
799 			     pmd_devmap(dst_pmdval))) {
800 			err = -EEXIST;
801 			break;
802 		}
803 		if (unlikely(pmd_bad(dst_pmdval))) {
804 			err = -EFAULT;
805 			break;
806 		}
807 		/*
808 		 * For shmem mappings, khugepaged is allowed to remove page
809 		 * tables under us; pte_offset_map_lock() will deal with that.
810 		 */
811 
812 		err = mfill_atomic_pte(dst_pmd, dst_vma, dst_addr,
813 				       src_addr, flags, &folio);
814 		cond_resched();
815 
816 		if (unlikely(err == -ENOENT)) {
817 			void *kaddr;
818 
819 			up_read(&ctx->map_changing_lock);
820 			uffd_mfill_unlock(dst_vma);
821 			BUG_ON(!folio);
822 
823 			kaddr = kmap_local_folio(folio, 0);
824 			err = copy_from_user(kaddr,
825 					     (const void __user *) src_addr,
826 					     PAGE_SIZE);
827 			kunmap_local(kaddr);
828 			if (unlikely(err)) {
829 				err = -EFAULT;
830 				goto out;
831 			}
832 			flush_dcache_folio(folio);
833 			goto retry;
834 		} else
835 			BUG_ON(folio);
836 
837 		if (!err) {
838 			dst_addr += PAGE_SIZE;
839 			src_addr += PAGE_SIZE;
840 			copied += PAGE_SIZE;
841 
842 			if (fatal_signal_pending(current))
843 				err = -EINTR;
844 		}
845 		if (err)
846 			break;
847 	}
848 
849 out_unlock:
850 	up_read(&ctx->map_changing_lock);
851 	uffd_mfill_unlock(dst_vma);
852 out:
853 	if (folio)
854 		folio_put(folio);
855 	BUG_ON(copied < 0);
856 	BUG_ON(err > 0);
857 	BUG_ON(!copied && !err);
858 	return copied ? copied : err;
859 }
860 
mfill_atomic_copy(struct userfaultfd_ctx * ctx,unsigned long dst_start,unsigned long src_start,unsigned long len,uffd_flags_t flags)861 ssize_t mfill_atomic_copy(struct userfaultfd_ctx *ctx, unsigned long dst_start,
862 			  unsigned long src_start, unsigned long len,
863 			  uffd_flags_t flags)
864 {
865 	return mfill_atomic(ctx, dst_start, src_start, len,
866 			    uffd_flags_set_mode(flags, MFILL_ATOMIC_COPY));
867 }
868 
mfill_atomic_zeropage(struct userfaultfd_ctx * ctx,unsigned long start,unsigned long len)869 ssize_t mfill_atomic_zeropage(struct userfaultfd_ctx *ctx,
870 			      unsigned long start,
871 			      unsigned long len)
872 {
873 	return mfill_atomic(ctx, start, 0, len,
874 			    uffd_flags_set_mode(0, MFILL_ATOMIC_ZEROPAGE));
875 }
876 
mfill_atomic_continue(struct userfaultfd_ctx * ctx,unsigned long start,unsigned long len,uffd_flags_t flags)877 ssize_t mfill_atomic_continue(struct userfaultfd_ctx *ctx, unsigned long start,
878 			      unsigned long len, uffd_flags_t flags)
879 {
880 
881 	/*
882 	 * A caller might reasonably assume that UFFDIO_CONTINUE contains an
883 	 * smp_wmb() to ensure that any writes to the about-to-be-mapped page by
884 	 * the thread doing the UFFDIO_CONTINUE are guaranteed to be visible to
885 	 * subsequent loads from the page through the newly mapped address range.
886 	 */
887 	smp_wmb();
888 
889 	return mfill_atomic(ctx, start, 0, len,
890 			    uffd_flags_set_mode(flags, MFILL_ATOMIC_CONTINUE));
891 }
892 
mfill_atomic_poison(struct userfaultfd_ctx * ctx,unsigned long start,unsigned long len,uffd_flags_t flags)893 ssize_t mfill_atomic_poison(struct userfaultfd_ctx *ctx, unsigned long start,
894 			    unsigned long len, uffd_flags_t flags)
895 {
896 	return mfill_atomic(ctx, start, 0, len,
897 			    uffd_flags_set_mode(flags, MFILL_ATOMIC_POISON));
898 }
899 
uffd_wp_range(struct vm_area_struct * dst_vma,unsigned long start,unsigned long len,bool enable_wp)900 long uffd_wp_range(struct vm_area_struct *dst_vma,
901 		   unsigned long start, unsigned long len, bool enable_wp)
902 {
903 	unsigned int mm_cp_flags;
904 	struct mmu_gather tlb;
905 	long ret;
906 
907 	VM_WARN_ONCE(start < dst_vma->vm_start || start + len > dst_vma->vm_end,
908 			"The address range exceeds VMA boundary.\n");
909 	if (enable_wp)
910 		mm_cp_flags = MM_CP_UFFD_WP;
911 	else
912 		mm_cp_flags = MM_CP_UFFD_WP_RESOLVE;
913 
914 	/*
915 	 * vma->vm_page_prot already reflects that uffd-wp is enabled for this
916 	 * VMA (see userfaultfd_set_vm_flags()) and that all PTEs are supposed
917 	 * to be write-protected as default whenever protection changes.
918 	 * Try upgrading write permissions manually.
919 	 */
920 	if (!enable_wp && vma_wants_manual_pte_write_upgrade(dst_vma))
921 		mm_cp_flags |= MM_CP_TRY_CHANGE_WRITABLE;
922 	tlb_gather_mmu(&tlb, dst_vma->vm_mm);
923 	ret = change_protection(&tlb, dst_vma, start, start + len, mm_cp_flags);
924 	tlb_finish_mmu(&tlb);
925 
926 	return ret;
927 }
928 
mwriteprotect_range(struct userfaultfd_ctx * ctx,unsigned long start,unsigned long len,bool enable_wp)929 int mwriteprotect_range(struct userfaultfd_ctx *ctx, unsigned long start,
930 			unsigned long len, bool enable_wp)
931 {
932 	struct mm_struct *dst_mm = ctx->mm;
933 	unsigned long end = start + len;
934 	unsigned long _start, _end;
935 	struct vm_area_struct *dst_vma;
936 	unsigned long page_mask;
937 	long err;
938 	VMA_ITERATOR(vmi, dst_mm, start);
939 
940 	/*
941 	 * Sanitize the command parameters:
942 	 */
943 	BUG_ON(start & ~PAGE_MASK);
944 	BUG_ON(len & ~PAGE_MASK);
945 
946 	/* Does the address range wrap, or is the span zero-sized? */
947 	BUG_ON(start + len <= start);
948 
949 	mmap_read_lock(dst_mm);
950 
951 	/*
952 	 * If memory mappings are changing because of non-cooperative
953 	 * operation (e.g. mremap) running in parallel, bail out and
954 	 * request the user to retry later
955 	 */
956 	down_read(&ctx->map_changing_lock);
957 	err = -EAGAIN;
958 	if (atomic_read(&ctx->mmap_changing))
959 		goto out_unlock;
960 
961 	err = -ENOENT;
962 	for_each_vma_range(vmi, dst_vma, end) {
963 
964 		if (!userfaultfd_wp(dst_vma)) {
965 			err = -ENOENT;
966 			break;
967 		}
968 
969 		if (is_vm_hugetlb_page(dst_vma)) {
970 			err = -EINVAL;
971 			page_mask = vma_kernel_pagesize(dst_vma) - 1;
972 			if ((start & page_mask) || (len & page_mask))
973 				break;
974 		}
975 
976 		_start = max(dst_vma->vm_start, start);
977 		_end = min(dst_vma->vm_end, end);
978 
979 		err = uffd_wp_range(dst_vma, _start, _end - _start, enable_wp);
980 
981 		/* Return 0 on success, <0 on failures */
982 		if (err < 0)
983 			break;
984 		err = 0;
985 	}
986 out_unlock:
987 	up_read(&ctx->map_changing_lock);
988 	mmap_read_unlock(dst_mm);
989 	return err;
990 }
991 
992 
double_pt_lock(spinlock_t * ptl1,spinlock_t * ptl2)993 void double_pt_lock(spinlock_t *ptl1,
994 		    spinlock_t *ptl2)
995 	__acquires(ptl1)
996 	__acquires(ptl2)
997 {
998 	if (ptl1 > ptl2)
999 		swap(ptl1, ptl2);
1000 	/* lock in virtual address order to avoid lock inversion */
1001 	spin_lock(ptl1);
1002 	if (ptl1 != ptl2)
1003 		spin_lock_nested(ptl2, SINGLE_DEPTH_NESTING);
1004 	else
1005 		__acquire(ptl2);
1006 }
1007 
double_pt_unlock(spinlock_t * ptl1,spinlock_t * ptl2)1008 void double_pt_unlock(spinlock_t *ptl1,
1009 		      spinlock_t *ptl2)
1010 	__releases(ptl1)
1011 	__releases(ptl2)
1012 {
1013 	spin_unlock(ptl1);
1014 	if (ptl1 != ptl2)
1015 		spin_unlock(ptl2);
1016 	else
1017 		__release(ptl2);
1018 }
1019 
1020 
1021 /*
1022  * Checks if the two ptes and the corresponding folio are eligible for batched
1023  * move. If so, then returns pointer to the locked folio. Otherwise, returns NULL.
1024  *
1025  * NOTE: folio's reference is not required as the whole operation is within
1026  * PTL's critical section.
1027  */
check_ptes_for_batched_move(struct vm_area_struct * src_vma,unsigned long src_addr,pte_t * src_pte,pte_t * dst_pte,struct anon_vma * src_anon_vma)1028 static struct folio *check_ptes_for_batched_move(struct vm_area_struct *src_vma,
1029 						 unsigned long src_addr,
1030 						 pte_t *src_pte, pte_t *dst_pte,
1031 						 struct anon_vma *src_anon_vma)
1032 {
1033 	pte_t orig_dst_pte, orig_src_pte;
1034 	struct folio *folio;
1035 
1036 	orig_dst_pte = ptep_get(dst_pte);
1037 	if (!pte_none(orig_dst_pte))
1038 		return NULL;
1039 
1040 	orig_src_pte = ptep_get(src_pte);
1041 	if (!pte_present(orig_src_pte) || is_zero_pfn(pte_pfn(orig_src_pte)))
1042 		return NULL;
1043 
1044 	folio = vm_normal_folio(src_vma, src_addr, orig_src_pte);
1045 	if (!folio || !folio_trylock(folio))
1046 		return NULL;
1047 	if (!PageAnonExclusive(&folio->page) || folio_test_large(folio) ||
1048 	    folio_anon_vma(folio) != src_anon_vma) {
1049 		folio_unlock(folio);
1050 		return NULL;
1051 	}
1052 	return folio;
1053 }
1054 
1055 /*
1056  * Moves src folios to dst in a batch as long as they share the same
1057  * anon_vma as the first folio, are not large, and can successfully
1058  * take the lock via folio_trylock().
1059  */
move_present_ptes(struct mm_struct * mm,struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma,unsigned long dst_addr,unsigned long src_addr,pte_t * dst_pte,pte_t * src_pte,pte_t orig_dst_pte,pte_t orig_src_pte,spinlock_t * dst_ptl,spinlock_t * src_ptl,struct folio ** first_src_folio,unsigned long len,struct anon_vma * src_anon_vma)1060 static long move_present_ptes(struct mm_struct *mm,
1061 			      struct vm_area_struct *dst_vma,
1062 			      struct vm_area_struct *src_vma,
1063 			      unsigned long dst_addr, unsigned long src_addr,
1064 			      pte_t *dst_pte, pte_t *src_pte,
1065 			      pte_t orig_dst_pte, pte_t orig_src_pte,
1066 			      spinlock_t *dst_ptl, spinlock_t *src_ptl,
1067 			      struct folio **first_src_folio, unsigned long len,
1068 			      struct anon_vma *src_anon_vma)
1069 {
1070 	int err = 0;
1071 	struct folio *src_folio = *first_src_folio;
1072 	unsigned long src_start = src_addr;
1073 	unsigned long src_end;
1074 
1075 	len = pmd_addr_end(dst_addr, dst_addr + len) - dst_addr;
1076 	src_end = pmd_addr_end(src_addr, src_addr + len);
1077 	flush_cache_range(src_vma, src_addr, src_end);
1078 	double_pt_lock(dst_ptl, src_ptl);
1079 
1080 	if (!pte_same(ptep_get(src_pte), orig_src_pte) ||
1081 	    !pte_same(ptep_get(dst_pte), orig_dst_pte)) {
1082 		err = -EAGAIN;
1083 		goto out;
1084 	}
1085 	if (folio_test_large(src_folio) ||
1086 	    folio_maybe_dma_pinned(src_folio) ||
1087 	    !PageAnonExclusive(&src_folio->page)) {
1088 		err = -EBUSY;
1089 		goto out;
1090 	}
1091 	/* It's safe to drop the reference now as the page-table is holding one. */
1092 	folio_put(*first_src_folio);
1093 	*first_src_folio = NULL;
1094 	arch_enter_lazy_mmu_mode();
1095 
1096 	while (true) {
1097 		orig_src_pte = ptep_get_and_clear(mm, src_addr, src_pte);
1098 		/* Folio got pinned from under us. Put it back and fail the move. */
1099 		if (folio_maybe_dma_pinned(src_folio)) {
1100 			set_pte_at(mm, src_addr, src_pte, orig_src_pte);
1101 			err = -EBUSY;
1102 			break;
1103 		}
1104 
1105 		folio_move_anon_rmap(src_folio, dst_vma);
1106 		src_folio->index = linear_page_index(dst_vma, dst_addr);
1107 
1108 		orig_dst_pte = mk_pte(&src_folio->page, dst_vma->vm_page_prot);
1109 		/* Set soft dirty bit so userspace can notice the pte was moved */
1110 #ifdef CONFIG_MEM_SOFT_DIRTY
1111 		orig_dst_pte = pte_mksoft_dirty(orig_dst_pte);
1112 #endif
1113 		if (pte_dirty(orig_src_pte))
1114 			orig_dst_pte = pte_mkdirty(orig_dst_pte);
1115 		orig_dst_pte = pte_mkwrite(orig_dst_pte, dst_vma);
1116 		set_pte_at(mm, dst_addr, dst_pte, orig_dst_pte);
1117 
1118 		src_addr += PAGE_SIZE;
1119 		if (src_addr == src_end)
1120 			break;
1121 		dst_addr += PAGE_SIZE;
1122 		dst_pte++;
1123 		src_pte++;
1124 
1125 		folio_unlock(src_folio);
1126 		src_folio = check_ptes_for_batched_move(src_vma, src_addr, src_pte,
1127 							dst_pte, src_anon_vma);
1128 		if (!src_folio)
1129 			break;
1130 	}
1131 
1132 	arch_leave_lazy_mmu_mode();
1133 	if (src_addr > src_start)
1134 		flush_tlb_range(src_vma, src_start, src_addr);
1135 
1136 	if (src_folio)
1137 		folio_unlock(src_folio);
1138 out:
1139 	double_pt_unlock(dst_ptl, src_ptl);
1140 	return src_addr > src_start ? src_addr - src_start : err;
1141 }
1142 
move_swap_pte(struct mm_struct * mm,struct vm_area_struct * dst_vma,unsigned long dst_addr,unsigned long src_addr,pte_t * dst_pte,pte_t * src_pte,pte_t orig_dst_pte,pte_t orig_src_pte,spinlock_t * dst_ptl,spinlock_t * src_ptl,struct folio * src_folio,struct swap_info_struct * si,swp_entry_t entry)1143 static int move_swap_pte(struct mm_struct *mm, struct vm_area_struct *dst_vma,
1144 			 unsigned long dst_addr, unsigned long src_addr,
1145 			 pte_t *dst_pte, pte_t *src_pte,
1146 			 pte_t orig_dst_pte, pte_t orig_src_pte,
1147 			 spinlock_t *dst_ptl, spinlock_t *src_ptl,
1148 			 struct folio *src_folio,
1149 			 struct swap_info_struct *si, swp_entry_t entry)
1150 {
1151 	/*
1152 	 * Check if the folio still belongs to the target swap entry after
1153 	 * acquiring the lock. Folio can be freed in the swap cache while
1154 	 * not locked.
1155 	 */
1156 	if (src_folio && unlikely(!folio_test_swapcache(src_folio) ||
1157 				  entry.val != src_folio->swap.val))
1158 		return -EAGAIN;
1159 
1160 	double_pt_lock(dst_ptl, src_ptl);
1161 
1162 	if (!pte_same(ptep_get(src_pte), orig_src_pte) ||
1163 	    !pte_same(ptep_get(dst_pte), orig_dst_pte)) {
1164 		double_pt_unlock(dst_ptl, src_ptl);
1165 		return -EAGAIN;
1166 	}
1167 
1168 	/*
1169 	 * The src_folio resides in the swapcache, requiring an update to its
1170 	 * index and mapping to align with the dst_vma, where a swap-in may
1171 	 * occur and hit the swapcache after moving the PTE.
1172 	 */
1173 	if (src_folio) {
1174 		folio_move_anon_rmap(src_folio, dst_vma);
1175 		src_folio->index = linear_page_index(dst_vma, dst_addr);
1176 	} else {
1177 		/*
1178 		 * Check if the swap entry is cached after acquiring the src_pte
1179 		 * lock. Otherwise, we might miss a newly loaded swap cache folio.
1180 		 *
1181 		 * Check swap_map directly to minimize overhead, READ_ONCE is sufficient.
1182 		 * We are trying to catch newly added swap cache, the only possible case is
1183 		 * when a folio is swapped in and out again staying in swap cache, using the
1184 		 * same entry before the PTE check above. The PTL is acquired and released
1185 		 * twice, each time after updating the swap_map's flag. So holding
1186 		 * the PTL here ensures we see the updated value. False positive is possible,
1187 		 * e.g. SWP_SYNCHRONOUS_IO swapin may set the flag without touching the
1188 		 * cache, or during the tiny synchronization window between swap cache and
1189 		 * swap_map, but it will be gone very quickly, worst result is retry jitters.
1190 		 */
1191 		if (READ_ONCE(si->swap_map[swp_offset(entry)]) & SWAP_HAS_CACHE) {
1192 			double_pt_unlock(dst_ptl, src_ptl);
1193 			return -EAGAIN;
1194 		}
1195 	}
1196 
1197 	orig_src_pte = ptep_get_and_clear(mm, src_addr, src_pte);
1198 #ifdef CONFIG_MEM_SOFT_DIRTY
1199 	orig_src_pte = pte_swp_mksoft_dirty(orig_src_pte);
1200 #endif
1201 	set_pte_at(mm, dst_addr, dst_pte, orig_src_pte);
1202 	double_pt_unlock(dst_ptl, src_ptl);
1203 
1204 	return PAGE_SIZE;
1205 }
1206 
move_zeropage_pte(struct mm_struct * mm,struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma,unsigned long dst_addr,unsigned long src_addr,pte_t * dst_pte,pte_t * src_pte,pte_t orig_dst_pte,pte_t orig_src_pte,spinlock_t * dst_ptl,spinlock_t * src_ptl)1207 static int move_zeropage_pte(struct mm_struct *mm,
1208 			     struct vm_area_struct *dst_vma,
1209 			     struct vm_area_struct *src_vma,
1210 			     unsigned long dst_addr, unsigned long src_addr,
1211 			     pte_t *dst_pte, pte_t *src_pte,
1212 			     pte_t orig_dst_pte, pte_t orig_src_pte,
1213 			     spinlock_t *dst_ptl, spinlock_t *src_ptl)
1214 {
1215 	pte_t zero_pte;
1216 
1217 	double_pt_lock(dst_ptl, src_ptl);
1218 	if (!pte_same(ptep_get(src_pte), orig_src_pte) ||
1219 	    !pte_same(ptep_get(dst_pte), orig_dst_pte)) {
1220 		double_pt_unlock(dst_ptl, src_ptl);
1221 		return -EAGAIN;
1222 	}
1223 
1224 	zero_pte = pte_mkspecial(pfn_pte(my_zero_pfn(dst_addr),
1225 					 dst_vma->vm_page_prot));
1226 	ptep_clear_flush(src_vma, src_addr, src_pte);
1227 	set_pte_at(mm, dst_addr, dst_pte, zero_pte);
1228 	double_pt_unlock(dst_ptl, src_ptl);
1229 
1230 	return PAGE_SIZE;
1231 }
1232 
1233 
1234 /*
1235  * The mmap_lock for reading is held by the caller. Just move the page(s)
1236  * from src_pmd to dst_pmd if possible, and return number of bytes moved.
1237  * On failure, an error code is returned.
1238  */
move_pages_ptes(struct mm_struct * mm,pmd_t * dst_pmd,pmd_t * src_pmd,struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma,unsigned long dst_addr,unsigned long src_addr,unsigned long len,__u64 mode)1239 static long move_pages_ptes(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd,
1240 			    struct vm_area_struct *dst_vma,
1241 			    struct vm_area_struct *src_vma,
1242 			    unsigned long dst_addr, unsigned long src_addr,
1243 			    unsigned long len, __u64 mode)
1244 {
1245 	swp_entry_t entry;
1246 	struct swap_info_struct *si = NULL;
1247 	pte_t orig_src_pte, orig_dst_pte;
1248 	pte_t src_folio_pte;
1249 	spinlock_t *src_ptl, *dst_ptl;
1250 	pte_t *src_pte = NULL;
1251 	pte_t *dst_pte = NULL;
1252 	pmd_t dummy_pmdval;
1253 	struct folio *src_folio = NULL;
1254 	struct anon_vma *src_anon_vma = NULL;
1255 	struct mmu_notifier_range range;
1256 	long ret = 0;
1257 
1258 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
1259 				src_addr, src_addr + len);
1260 	mmu_notifier_invalidate_range_start(&range);
1261 retry:
1262 	/*
1263 	 * Use the maywrite version to indicate that dst_pte will be modified,
1264 	 * but since we will use pte_same() to detect the change of the pte
1265 	 * entry, there is no need to get pmdval, so just pass a dummy variable
1266 	 * to it.
1267 	 */
1268 	dst_pte = pte_offset_map_rw_nolock(mm, dst_pmd, dst_addr, &dummy_pmdval,
1269 					   &dst_ptl);
1270 
1271 	/* Retry if a huge pmd materialized from under us */
1272 	if (unlikely(!dst_pte)) {
1273 		ret = -EAGAIN;
1274 		goto out;
1275 	}
1276 
1277 	/* same as dst_pte */
1278 	src_pte = pte_offset_map_rw_nolock(mm, src_pmd, src_addr, &dummy_pmdval,
1279 					   &src_ptl);
1280 
1281 	/*
1282 	 * We held the mmap_lock for reading so MADV_DONTNEED
1283 	 * can zap transparent huge pages under us, or the
1284 	 * transparent huge page fault can establish new
1285 	 * transparent huge pages under us.
1286 	 */
1287 	if (unlikely(!src_pte)) {
1288 		ret = -EAGAIN;
1289 		goto out;
1290 	}
1291 
1292 	/* Sanity checks before the operation */
1293 	if (WARN_ON_ONCE(pmd_none(*dst_pmd)) ||	WARN_ON_ONCE(pmd_none(*src_pmd)) ||
1294 	    WARN_ON_ONCE(pmd_trans_huge(*dst_pmd)) || WARN_ON_ONCE(pmd_trans_huge(*src_pmd))) {
1295 		ret = -EINVAL;
1296 		goto out;
1297 	}
1298 
1299 	spin_lock(dst_ptl);
1300 	orig_dst_pte = ptep_get(dst_pte);
1301 	spin_unlock(dst_ptl);
1302 	if (!pte_none(orig_dst_pte)) {
1303 		ret = -EEXIST;
1304 		goto out;
1305 	}
1306 
1307 	spin_lock(src_ptl);
1308 	orig_src_pte = ptep_get(src_pte);
1309 	spin_unlock(src_ptl);
1310 	if (pte_none(orig_src_pte)) {
1311 		if (!(mode & UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES))
1312 			ret = -ENOENT;
1313 		else /* nothing to do to move a hole */
1314 			ret = PAGE_SIZE;
1315 		goto out;
1316 	}
1317 
1318 	/* If PTE changed after we locked the folio them start over */
1319 	if (src_folio && unlikely(!pte_same(src_folio_pte, orig_src_pte))) {
1320 		ret = -EAGAIN;
1321 		goto out;
1322 	}
1323 
1324 	if (pte_present(orig_src_pte)) {
1325 		if (is_zero_pfn(pte_pfn(orig_src_pte))) {
1326 			ret = move_zeropage_pte(mm, dst_vma, src_vma,
1327 					       dst_addr, src_addr, dst_pte, src_pte,
1328 					       orig_dst_pte, orig_src_pte,
1329 					       dst_ptl, src_ptl);
1330 			goto out;
1331 		}
1332 
1333 		/*
1334 		 * Pin and lock both source folio and anon_vma. Since we are in
1335 		 * RCU read section, we can't block, so on contention have to
1336 		 * unmap the ptes, obtain the lock and retry.
1337 		 */
1338 		if (!src_folio) {
1339 			struct folio *folio;
1340 			bool locked;
1341 
1342 			/*
1343 			 * Pin the page while holding the lock to be sure the
1344 			 * page isn't freed under us
1345 			 */
1346 			spin_lock(src_ptl);
1347 			if (!pte_same(orig_src_pte, ptep_get(src_pte))) {
1348 				spin_unlock(src_ptl);
1349 				ret = -EAGAIN;
1350 				goto out;
1351 			}
1352 
1353 			folio = vm_normal_folio(src_vma, src_addr, orig_src_pte);
1354 			if (!folio || !PageAnonExclusive(&folio->page)) {
1355 				spin_unlock(src_ptl);
1356 				ret = -EBUSY;
1357 				goto out;
1358 			}
1359 
1360 			locked = folio_trylock(folio);
1361 			/*
1362 			 * We avoid waiting for folio lock with a raised
1363 			 * refcount for large folios because extra refcounts
1364 			 * will result in split_folio() failing later and
1365 			 * retrying.  If multiple tasks are trying to move a
1366 			 * large folio we can end up livelocking.
1367 			 */
1368 			if (!locked && folio_test_large(folio)) {
1369 				spin_unlock(src_ptl);
1370 				ret = -EAGAIN;
1371 				goto out;
1372 			}
1373 
1374 			folio_get(folio);
1375 			src_folio = folio;
1376 			src_folio_pte = orig_src_pte;
1377 			spin_unlock(src_ptl);
1378 
1379 			if (!locked) {
1380 				pte_unmap(src_pte);
1381 				pte_unmap(dst_pte);
1382 				src_pte = dst_pte = NULL;
1383 				/* now we can block and wait */
1384 				folio_lock(src_folio);
1385 				goto retry;
1386 			}
1387 
1388 			if (WARN_ON_ONCE(!folio_test_anon(src_folio))) {
1389 				ret = -EBUSY;
1390 				goto out;
1391 			}
1392 		}
1393 
1394 		/* at this point we have src_folio locked */
1395 		if (folio_test_large(src_folio)) {
1396 			/* split_folio() can block */
1397 			pte_unmap(src_pte);
1398 			pte_unmap(dst_pte);
1399 			src_pte = dst_pte = NULL;
1400 			ret = split_folio(src_folio);
1401 			if (ret)
1402 				goto out;
1403 			/* have to reacquire the folio after it got split */
1404 			folio_unlock(src_folio);
1405 			folio_put(src_folio);
1406 			src_folio = NULL;
1407 			goto retry;
1408 		}
1409 
1410 		if (!src_anon_vma) {
1411 			/*
1412 			 * folio_referenced walks the anon_vma chain
1413 			 * without the folio lock. Serialize against it with
1414 			 * the anon_vma lock, the folio lock is not enough.
1415 			 */
1416 			src_anon_vma = folio_get_anon_vma(src_folio);
1417 			if (!src_anon_vma) {
1418 				/* page was unmapped from under us */
1419 				ret = -EAGAIN;
1420 				goto out;
1421 			}
1422 			if (!anon_vma_trylock_write(src_anon_vma)) {
1423 				pte_unmap(src_pte);
1424 				pte_unmap(dst_pte);
1425 				src_pte = dst_pte = NULL;
1426 				/* now we can block and wait */
1427 				anon_vma_lock_write(src_anon_vma);
1428 				goto retry;
1429 			}
1430 		}
1431 
1432 		ret = move_present_ptes(mm, dst_vma, src_vma,
1433 					dst_addr, src_addr, dst_pte, src_pte,
1434 					orig_dst_pte, orig_src_pte,
1435 					dst_ptl, src_ptl, &src_folio,
1436 					len, src_anon_vma);
1437 	} else {
1438 		struct folio *folio = NULL;
1439 
1440 		entry = pte_to_swp_entry(orig_src_pte);
1441 		if (non_swap_entry(entry)) {
1442 			if (is_migration_entry(entry)) {
1443 				pte_unmap(src_pte);
1444 				pte_unmap(dst_pte);
1445 				src_pte = dst_pte = NULL;
1446 				migration_entry_wait(mm, src_pmd, src_addr);
1447 				ret = -EAGAIN;
1448 			} else
1449 				ret = -EFAULT;
1450 			goto out;
1451 		}
1452 
1453 		if (!pte_swp_exclusive(orig_src_pte)) {
1454 			ret = -EBUSY;
1455 			goto out;
1456 		}
1457 
1458 		si = get_swap_device(entry);
1459 		if (unlikely(!si)) {
1460 			ret = -EAGAIN;
1461 			goto out;
1462 		}
1463 		/*
1464 		 * Verify the existence of the swapcache. If present, the folio's
1465 		 * index and mapping must be updated even when the PTE is a swap
1466 		 * entry. The anon_vma lock is not taken during this process since
1467 		 * the folio has already been unmapped, and the swap entry is
1468 		 * exclusive, preventing rmap walks.
1469 		 *
1470 		 * For large folios, return -EBUSY immediately, as split_folio()
1471 		 * also returns -EBUSY when attempting to split unmapped large
1472 		 * folios in the swapcache. This issue needs to be resolved
1473 		 * separately to allow proper handling.
1474 		 */
1475 		if (!src_folio)
1476 			folio = filemap_get_folio(swap_address_space(entry),
1477 					swap_cache_index(entry));
1478 		if (!IS_ERR_OR_NULL(folio)) {
1479 			if (folio_test_large(folio)) {
1480 				ret = -EBUSY;
1481 				folio_put(folio);
1482 				goto out;
1483 			}
1484 			src_folio = folio;
1485 			src_folio_pte = orig_src_pte;
1486 			if (!folio_trylock(src_folio)) {
1487 				pte_unmap(src_pte);
1488 				pte_unmap(dst_pte);
1489 				src_pte = dst_pte = NULL;
1490 				put_swap_device(si);
1491 				si = NULL;
1492 				/* now we can block and wait */
1493 				folio_lock(src_folio);
1494 				goto retry;
1495 			}
1496 		}
1497 		ret = move_swap_pte(mm, dst_vma, dst_addr, src_addr, dst_pte, src_pte,
1498 				orig_dst_pte, orig_src_pte,
1499 				dst_ptl, src_ptl, src_folio, si, entry);
1500 	}
1501 
1502 out:
1503 	if (src_anon_vma) {
1504 		anon_vma_unlock_write(src_anon_vma);
1505 		put_anon_vma(src_anon_vma);
1506 	}
1507 	if (src_folio) {
1508 		folio_unlock(src_folio);
1509 		folio_put(src_folio);
1510 	}
1511 	/*
1512 	 * Unmap in reverse order (LIFO) to maintain proper kmap_local
1513 	 * index ordering when CONFIG_HIGHPTE is enabled. We mapped dst_pte
1514 	 * first, then src_pte, so we must unmap src_pte first, then dst_pte.
1515 	 */
1516 	if (src_pte)
1517 		pte_unmap(src_pte);
1518 	if (dst_pte)
1519 		pte_unmap(dst_pte);
1520 	mmu_notifier_invalidate_range_end(&range);
1521 	if (si)
1522 		put_swap_device(si);
1523 
1524 	return ret;
1525 }
1526 
1527 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
move_splits_huge_pmd(unsigned long dst_addr,unsigned long src_addr,unsigned long src_end)1528 static inline bool move_splits_huge_pmd(unsigned long dst_addr,
1529 					unsigned long src_addr,
1530 					unsigned long src_end)
1531 {
1532 	return (src_addr & ~HPAGE_PMD_MASK) || (dst_addr & ~HPAGE_PMD_MASK) ||
1533 		src_end - src_addr < HPAGE_PMD_SIZE;
1534 }
1535 #else
move_splits_huge_pmd(unsigned long dst_addr,unsigned long src_addr,unsigned long src_end)1536 static inline bool move_splits_huge_pmd(unsigned long dst_addr,
1537 					unsigned long src_addr,
1538 					unsigned long src_end)
1539 {
1540 	/* This is unreachable anyway, just to avoid warnings when HPAGE_PMD_SIZE==0 */
1541 	return false;
1542 }
1543 #endif
1544 
vma_move_compatible(struct vm_area_struct * vma)1545 static inline bool vma_move_compatible(struct vm_area_struct *vma)
1546 {
1547 	return !(vma->vm_flags & (VM_PFNMAP | VM_IO |  VM_HUGETLB |
1548 				  VM_MIXEDMAP | VM_SHADOW_STACK));
1549 }
1550 
validate_move_areas(struct userfaultfd_ctx * ctx,struct vm_area_struct * src_vma,struct vm_area_struct * dst_vma)1551 static int validate_move_areas(struct userfaultfd_ctx *ctx,
1552 			       struct vm_area_struct *src_vma,
1553 			       struct vm_area_struct *dst_vma)
1554 {
1555 	/* Only allow moving if both have the same access and protection */
1556 	if ((src_vma->vm_flags & VM_ACCESS_FLAGS) != (dst_vma->vm_flags & VM_ACCESS_FLAGS) ||
1557 	    pgprot_val(src_vma->vm_page_prot) != pgprot_val(dst_vma->vm_page_prot))
1558 		return -EINVAL;
1559 
1560 	/* Only allow moving if both are mlocked or both aren't */
1561 	if ((src_vma->vm_flags & VM_LOCKED) != (dst_vma->vm_flags & VM_LOCKED))
1562 		return -EINVAL;
1563 
1564 	/*
1565 	 * For now, we keep it simple and only move between writable VMAs.
1566 	 * Access flags are equal, therefore cheching only the source is enough.
1567 	 */
1568 	if (!(src_vma->vm_flags & VM_WRITE))
1569 		return -EINVAL;
1570 
1571 	/* Check if vma flags indicate content which can be moved */
1572 	if (!vma_move_compatible(src_vma) || !vma_move_compatible(dst_vma))
1573 		return -EINVAL;
1574 
1575 	/* Ensure dst_vma is registered in uffd we are operating on */
1576 	if (!dst_vma->vm_userfaultfd_ctx.ctx ||
1577 	    dst_vma->vm_userfaultfd_ctx.ctx != ctx)
1578 		return -EINVAL;
1579 
1580 	/* Only allow moving across anonymous vmas */
1581 	if (!vma_is_anonymous(src_vma) || !vma_is_anonymous(dst_vma))
1582 		return -EINVAL;
1583 
1584 	return 0;
1585 }
1586 
1587 static __always_inline
find_vmas_mm_locked(struct mm_struct * mm,unsigned long dst_start,unsigned long src_start,struct vm_area_struct ** dst_vmap,struct vm_area_struct ** src_vmap)1588 int find_vmas_mm_locked(struct mm_struct *mm,
1589 			unsigned long dst_start,
1590 			unsigned long src_start,
1591 			struct vm_area_struct **dst_vmap,
1592 			struct vm_area_struct **src_vmap)
1593 {
1594 	struct vm_area_struct *vma;
1595 
1596 	mmap_assert_locked(mm);
1597 	vma = find_vma_and_prepare_anon(mm, dst_start);
1598 	if (IS_ERR(vma))
1599 		return PTR_ERR(vma);
1600 
1601 	*dst_vmap = vma;
1602 	/* Skip finding src_vma if src_start is in dst_vma */
1603 	if (src_start >= vma->vm_start && src_start < vma->vm_end)
1604 		goto out_success;
1605 
1606 	vma = vma_lookup(mm, src_start);
1607 	if (!vma)
1608 		return -ENOENT;
1609 out_success:
1610 	*src_vmap = vma;
1611 	return 0;
1612 }
1613 
1614 #ifdef CONFIG_PER_VMA_LOCK
uffd_move_lock(struct mm_struct * mm,unsigned long dst_start,unsigned long src_start,struct vm_area_struct ** dst_vmap,struct vm_area_struct ** src_vmap)1615 static int uffd_move_lock(struct mm_struct *mm,
1616 			  unsigned long dst_start,
1617 			  unsigned long src_start,
1618 			  struct vm_area_struct **dst_vmap,
1619 			  struct vm_area_struct **src_vmap)
1620 {
1621 	struct vm_area_struct *vma;
1622 	int err;
1623 
1624 	vma = uffd_lock_vma(mm, dst_start);
1625 	if (IS_ERR(vma))
1626 		return PTR_ERR(vma);
1627 
1628 	*dst_vmap = vma;
1629 	/*
1630 	 * Skip finding src_vma if src_start is in dst_vma. This also ensures
1631 	 * that we don't lock the same vma twice.
1632 	 */
1633 	if (src_start >= vma->vm_start && src_start < vma->vm_end) {
1634 		*src_vmap = vma;
1635 		return 0;
1636 	}
1637 
1638 	/*
1639 	 * Using uffd_lock_vma() to get src_vma can lead to following deadlock:
1640 	 *
1641 	 * Thread1				Thread2
1642 	 * -------				-------
1643 	 * vma_start_read(dst_vma)
1644 	 *					mmap_write_lock(mm)
1645 	 *					vma_start_write(src_vma)
1646 	 * vma_start_read(src_vma)
1647 	 * mmap_read_lock(mm)
1648 	 *					vma_start_write(dst_vma)
1649 	 */
1650 	*src_vmap = lock_vma_under_rcu(mm, src_start);
1651 	if (likely(*src_vmap))
1652 		return 0;
1653 
1654 	/* Undo any locking and retry in mmap_lock critical section */
1655 	vma_end_read(*dst_vmap);
1656 
1657 	mmap_read_lock(mm);
1658 	err = find_vmas_mm_locked(mm, dst_start, src_start, dst_vmap, src_vmap);
1659 	if (err)
1660 		goto out;
1661 
1662 	if (!vma_start_read_locked(*dst_vmap)) {
1663 		err = -EAGAIN;
1664 		goto out;
1665 	}
1666 
1667 	/* Nothing further to do if both vmas are locked. */
1668 	if (*dst_vmap == *src_vmap)
1669 		goto out;
1670 
1671 	if (!vma_start_read_locked_nested(*src_vmap, SINGLE_DEPTH_NESTING)) {
1672 		/* Undo dst_vmap locking if src_vmap failed to lock */
1673 		vma_end_read(*dst_vmap);
1674 		err = -EAGAIN;
1675 	}
1676 out:
1677 	mmap_read_unlock(mm);
1678 	return err;
1679 }
1680 
uffd_move_unlock(struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma)1681 static void uffd_move_unlock(struct vm_area_struct *dst_vma,
1682 			     struct vm_area_struct *src_vma)
1683 {
1684 	vma_end_read(src_vma);
1685 	if (src_vma != dst_vma)
1686 		vma_end_read(dst_vma);
1687 }
1688 
1689 #else
1690 
uffd_move_lock(struct mm_struct * mm,unsigned long dst_start,unsigned long src_start,struct vm_area_struct ** dst_vmap,struct vm_area_struct ** src_vmap)1691 static int uffd_move_lock(struct mm_struct *mm,
1692 			  unsigned long dst_start,
1693 			  unsigned long src_start,
1694 			  struct vm_area_struct **dst_vmap,
1695 			  struct vm_area_struct **src_vmap)
1696 {
1697 	int err;
1698 
1699 	mmap_read_lock(mm);
1700 	err = find_vmas_mm_locked(mm, dst_start, src_start, dst_vmap, src_vmap);
1701 	if (err)
1702 		mmap_read_unlock(mm);
1703 	return err;
1704 }
1705 
uffd_move_unlock(struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma)1706 static void uffd_move_unlock(struct vm_area_struct *dst_vma,
1707 			     struct vm_area_struct *src_vma)
1708 {
1709 	mmap_assert_locked(src_vma->vm_mm);
1710 	mmap_read_unlock(dst_vma->vm_mm);
1711 }
1712 #endif
1713 
1714 /**
1715  * move_pages - move arbitrary anonymous pages of an existing vma
1716  * @ctx: pointer to the userfaultfd context
1717  * @dst_start: start of the destination virtual memory range
1718  * @src_start: start of the source virtual memory range
1719  * @len: length of the virtual memory range
1720  * @mode: flags from uffdio_move.mode
1721  *
1722  * It will either use the mmap_lock in read mode or per-vma locks
1723  *
1724  * move_pages() remaps arbitrary anonymous pages atomically in zero
1725  * copy. It only works on non shared anonymous pages because those can
1726  * be relocated without generating non linear anon_vmas in the rmap
1727  * code.
1728  *
1729  * It provides a zero copy mechanism to handle userspace page faults.
1730  * The source vma pages should have mapcount == 1, which can be
1731  * enforced by using madvise(MADV_DONTFORK) on src vma.
1732  *
1733  * The thread receiving the page during the userland page fault
1734  * will receive the faulting page in the source vma through the network,
1735  * storage or any other I/O device (MADV_DONTFORK in the source vma
1736  * avoids move_pages() to fail with -EBUSY if the process forks before
1737  * move_pages() is called), then it will call move_pages() to map the
1738  * page in the faulting address in the destination vma.
1739  *
1740  * This userfaultfd command works purely via pagetables, so it's the
1741  * most efficient way to move physical non shared anonymous pages
1742  * across different virtual addresses. Unlike mremap()/mmap()/munmap()
1743  * it does not create any new vmas. The mapping in the destination
1744  * address is atomic.
1745  *
1746  * It only works if the vma protection bits are identical from the
1747  * source and destination vma.
1748  *
1749  * It can remap non shared anonymous pages within the same vma too.
1750  *
1751  * If the source virtual memory range has any unmapped holes, or if
1752  * the destination virtual memory range is not a whole unmapped hole,
1753  * move_pages() will fail respectively with -ENOENT or -EEXIST. This
1754  * provides a very strict behavior to avoid any chance of memory
1755  * corruption going unnoticed if there are userland race conditions.
1756  * Only one thread should resolve the userland page fault at any given
1757  * time for any given faulting address. This means that if two threads
1758  * try to both call move_pages() on the same destination address at the
1759  * same time, the second thread will get an explicit error from this
1760  * command.
1761  *
1762  * The command retval will return "len" is successful. The command
1763  * however can be interrupted by fatal signals or errors. If
1764  * interrupted it will return the number of bytes successfully
1765  * remapped before the interruption if any, or the negative error if
1766  * none. It will never return zero. Either it will return an error or
1767  * an amount of bytes successfully moved. If the retval reports a
1768  * "short" remap, the move_pages() command should be repeated by
1769  * userland with src+retval, dst+reval, len-retval if it wants to know
1770  * about the error that interrupted it.
1771  *
1772  * The UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES flag can be specified to
1773  * prevent -ENOENT errors to materialize if there are holes in the
1774  * source virtual range that is being remapped. The holes will be
1775  * accounted as successfully remapped in the retval of the
1776  * command. This is mostly useful to remap hugepage naturally aligned
1777  * virtual regions without knowing if there are transparent hugepage
1778  * in the regions or not, but preventing the risk of having to split
1779  * the hugepmd during the remap.
1780  *
1781  * If there's any rmap walk that is taking the anon_vma locks without
1782  * first obtaining the folio lock (the only current instance is
1783  * folio_referenced), they will have to verify if the folio->mapping
1784  * has changed after taking the anon_vma lock. If it changed they
1785  * should release the lock and retry obtaining a new anon_vma, because
1786  * it means the anon_vma was changed by move_pages() before the lock
1787  * could be obtained. This is the only additional complexity added to
1788  * the rmap code to provide this anonymous page remapping functionality.
1789  */
move_pages(struct userfaultfd_ctx * ctx,unsigned long dst_start,unsigned long src_start,unsigned long len,__u64 mode)1790 ssize_t move_pages(struct userfaultfd_ctx *ctx, unsigned long dst_start,
1791 		   unsigned long src_start, unsigned long len, __u64 mode)
1792 {
1793 	struct mm_struct *mm = ctx->mm;
1794 	struct vm_area_struct *src_vma, *dst_vma;
1795 	unsigned long src_addr, dst_addr, src_end;
1796 	pmd_t *src_pmd, *dst_pmd;
1797 	long err = -EINVAL;
1798 	ssize_t moved = 0;
1799 
1800 	/* Sanitize the command parameters. */
1801 	if (WARN_ON_ONCE(src_start & ~PAGE_MASK) ||
1802 	    WARN_ON_ONCE(dst_start & ~PAGE_MASK) ||
1803 	    WARN_ON_ONCE(len & ~PAGE_MASK))
1804 		goto out;
1805 
1806 	/* Does the address range wrap, or is the span zero-sized? */
1807 	if (WARN_ON_ONCE(src_start + len <= src_start) ||
1808 	    WARN_ON_ONCE(dst_start + len <= dst_start))
1809 		goto out;
1810 
1811 	err = uffd_move_lock(mm, dst_start, src_start, &dst_vma, &src_vma);
1812 	if (err)
1813 		goto out;
1814 
1815 	/* Re-check after taking map_changing_lock */
1816 	err = -EAGAIN;
1817 	down_read(&ctx->map_changing_lock);
1818 	if (likely(atomic_read(&ctx->mmap_changing)))
1819 		goto out_unlock;
1820 	/*
1821 	 * Make sure the vma is not shared, that the src and dst remap
1822 	 * ranges are both valid and fully within a single existing
1823 	 * vma.
1824 	 */
1825 	err = -EINVAL;
1826 	if (src_vma->vm_flags & VM_SHARED)
1827 		goto out_unlock;
1828 	if (src_start + len > src_vma->vm_end)
1829 		goto out_unlock;
1830 
1831 	if (dst_vma->vm_flags & VM_SHARED)
1832 		goto out_unlock;
1833 	if (dst_start + len > dst_vma->vm_end)
1834 		goto out_unlock;
1835 
1836 	err = validate_move_areas(ctx, src_vma, dst_vma);
1837 	if (err)
1838 		goto out_unlock;
1839 
1840 	for (src_addr = src_start, dst_addr = dst_start, src_end = src_start + len;
1841 	     src_addr < src_end;) {
1842 		spinlock_t *ptl;
1843 		pmd_t dst_pmdval;
1844 		unsigned long step_size;
1845 
1846 		/*
1847 		 * Below works because anonymous area would not have a
1848 		 * transparent huge PUD. If file-backed support is added,
1849 		 * that case would need to be handled here.
1850 		 */
1851 		src_pmd = mm_find_pmd(mm, src_addr);
1852 		if (unlikely(!src_pmd)) {
1853 			if (!(mode & UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES)) {
1854 				err = -ENOENT;
1855 				break;
1856 			}
1857 			src_pmd = mm_alloc_pmd(mm, src_addr);
1858 			if (unlikely(!src_pmd)) {
1859 				err = -ENOMEM;
1860 				break;
1861 			}
1862 		}
1863 		dst_pmd = mm_alloc_pmd(mm, dst_addr);
1864 		if (unlikely(!dst_pmd)) {
1865 			err = -ENOMEM;
1866 			break;
1867 		}
1868 
1869 		dst_pmdval = pmdp_get_lockless(dst_pmd);
1870 		/*
1871 		 * If the dst_pmd is mapped as THP don't override it and just
1872 		 * be strict. If dst_pmd changes into TPH after this check, the
1873 		 * move_pages_huge_pmd() will detect the change and retry
1874 		 * while move_pages_pte() will detect the change and fail.
1875 		 */
1876 		if (unlikely(pmd_trans_huge(dst_pmdval))) {
1877 			err = -EEXIST;
1878 			break;
1879 		}
1880 
1881 		ptl = pmd_trans_huge_lock(src_pmd, src_vma);
1882 		if (ptl) {
1883 			if (pmd_devmap(*src_pmd)) {
1884 				spin_unlock(ptl);
1885 				err = -ENOENT;
1886 				break;
1887 			}
1888 
1889 			/* Check if we can move the pmd without splitting it. */
1890 			if (move_splits_huge_pmd(dst_addr, src_addr, src_start + len) ||
1891 			    !pmd_none(dst_pmdval)) {
1892 				/* Can be a migration entry */
1893 				if (pmd_present(*src_pmd)) {
1894 					struct folio *folio = pmd_folio(*src_pmd);
1895 
1896 					if (!is_huge_zero_folio(folio) &&
1897 					    !PageAnonExclusive(&folio->page)) {
1898 						spin_unlock(ptl);
1899 						err = -EBUSY;
1900 						break;
1901 					}
1902 				}
1903 
1904 				spin_unlock(ptl);
1905 				split_huge_pmd(src_vma, src_pmd, src_addr);
1906 				/* The folio will be split by move_pages_pte() */
1907 				continue;
1908 			}
1909 
1910 			err = move_pages_huge_pmd(mm, dst_pmd, src_pmd,
1911 						  dst_pmdval, dst_vma, src_vma,
1912 						  dst_addr, src_addr);
1913 			step_size = HPAGE_PMD_SIZE;
1914 		} else {
1915 			long ret;
1916 
1917 			if (pmd_none(*src_pmd)) {
1918 				if (!(mode & UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES)) {
1919 					err = -ENOENT;
1920 					break;
1921 				}
1922 				if (unlikely(__pte_alloc(mm, src_pmd))) {
1923 					err = -ENOMEM;
1924 					break;
1925 				}
1926 			}
1927 
1928 			if (unlikely(pte_alloc(mm, dst_pmd))) {
1929 				err = -ENOMEM;
1930 				break;
1931 			}
1932 
1933 			ret = move_pages_ptes(mm, dst_pmd, src_pmd,
1934 					      dst_vma, src_vma, dst_addr,
1935 					      src_addr, src_end - src_addr, mode);
1936 			if (ret < 0)
1937 				err = ret;
1938 			else
1939 				step_size = ret;
1940 		}
1941 
1942 		cond_resched();
1943 
1944 		if (fatal_signal_pending(current)) {
1945 			/* Do not override an error */
1946 			if (!err || err == -EAGAIN)
1947 				err = -EINTR;
1948 			break;
1949 		}
1950 
1951 		if (err) {
1952 			if (err == -EAGAIN)
1953 				continue;
1954 			break;
1955 		}
1956 
1957 		/* Proceed to the next page */
1958 		dst_addr += step_size;
1959 		src_addr += step_size;
1960 		moved += step_size;
1961 	}
1962 
1963 out_unlock:
1964 	up_read(&ctx->map_changing_lock);
1965 	uffd_move_unlock(dst_vma, src_vma);
1966 out:
1967 	VM_WARN_ON(moved < 0);
1968 	VM_WARN_ON(err > 0);
1969 	VM_WARN_ON(!moved && !err);
1970 	return moved ? moved : err;
1971 }
1972 
userfaultfd_set_vm_flags(struct vm_area_struct * vma,vm_flags_t flags)1973 static void userfaultfd_set_vm_flags(struct vm_area_struct *vma,
1974 				     vm_flags_t flags)
1975 {
1976 	const bool uffd_wp_changed = (vma->vm_flags ^ flags) & VM_UFFD_WP;
1977 
1978 	vm_flags_reset(vma, flags);
1979 	/*
1980 	 * For shared mappings, we want to enable writenotify while
1981 	 * userfaultfd-wp is enabled (see vma_wants_writenotify()). We'll simply
1982 	 * recalculate vma->vm_page_prot whenever userfaultfd-wp changes.
1983 	 */
1984 	if ((vma->vm_flags & VM_SHARED) && uffd_wp_changed)
1985 		vma_set_page_prot(vma);
1986 }
1987 
userfaultfd_set_ctx(struct vm_area_struct * vma,struct userfaultfd_ctx * ctx,unsigned long flags)1988 static void userfaultfd_set_ctx(struct vm_area_struct *vma,
1989 				struct userfaultfd_ctx *ctx,
1990 				unsigned long flags)
1991 {
1992 	vma_start_write(vma);
1993 	vma->vm_userfaultfd_ctx = (struct vm_userfaultfd_ctx){ctx};
1994 	userfaultfd_set_vm_flags(vma,
1995 				 (vma->vm_flags & ~__VM_UFFD_FLAGS) | flags);
1996 }
1997 
userfaultfd_reset_ctx(struct vm_area_struct * vma)1998 void userfaultfd_reset_ctx(struct vm_area_struct *vma)
1999 {
2000 	userfaultfd_set_ctx(vma, NULL, 0);
2001 }
2002 
userfaultfd_clear_vma(struct vma_iterator * vmi,struct vm_area_struct * prev,struct vm_area_struct * vma,unsigned long start,unsigned long end)2003 struct vm_area_struct *userfaultfd_clear_vma(struct vma_iterator *vmi,
2004 					     struct vm_area_struct *prev,
2005 					     struct vm_area_struct *vma,
2006 					     unsigned long start,
2007 					     unsigned long end)
2008 {
2009 	struct vm_area_struct *ret;
2010 	bool give_up_on_oom = false;
2011 
2012 	/*
2013 	 * If we are modifying only and not splitting, just give up on the merge
2014 	 * if OOM prevents us from merging successfully.
2015 	 */
2016 	if (start == vma->vm_start && end == vma->vm_end)
2017 		give_up_on_oom = true;
2018 
2019 	/* Reset ptes for the whole vma range if wr-protected */
2020 	if (userfaultfd_wp(vma))
2021 		uffd_wp_range(vma, start, end - start, false);
2022 
2023 	ret = vma_modify_flags_uffd(vmi, prev, vma, start, end,
2024 				    vma->vm_flags & ~__VM_UFFD_FLAGS,
2025 				    NULL_VM_UFFD_CTX, give_up_on_oom);
2026 
2027 	/*
2028 	 * In the vma_merge() successful mprotect-like case 8:
2029 	 * the next vma was merged into the current one and
2030 	 * the current one has not been updated yet.
2031 	 */
2032 	if (!IS_ERR(ret))
2033 		userfaultfd_reset_ctx(ret);
2034 
2035 	return ret;
2036 }
2037 
2038 /* Assumes mmap write lock taken, and mm_struct pinned. */
userfaultfd_register_range(struct userfaultfd_ctx * ctx,struct vm_area_struct * vma,unsigned long vm_flags,unsigned long start,unsigned long end,bool wp_async)2039 int userfaultfd_register_range(struct userfaultfd_ctx *ctx,
2040 			       struct vm_area_struct *vma,
2041 			       unsigned long vm_flags,
2042 			       unsigned long start, unsigned long end,
2043 			       bool wp_async)
2044 {
2045 	VMA_ITERATOR(vmi, ctx->mm, start);
2046 	struct vm_area_struct *prev = vma_prev(&vmi);
2047 	unsigned long vma_end;
2048 	unsigned long new_flags;
2049 
2050 	if (vma->vm_start < start)
2051 		prev = vma;
2052 
2053 	for_each_vma_range(vmi, vma, end) {
2054 		cond_resched();
2055 
2056 		BUG_ON(!vma_can_userfault(vma, vm_flags, wp_async));
2057 		BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
2058 		       vma->vm_userfaultfd_ctx.ctx != ctx);
2059 		WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
2060 
2061 		/*
2062 		 * Nothing to do: this vma is already registered into this
2063 		 * userfaultfd and with the right tracking mode too.
2064 		 */
2065 		if (vma->vm_userfaultfd_ctx.ctx == ctx &&
2066 		    (vma->vm_flags & vm_flags) == vm_flags)
2067 			goto skip;
2068 
2069 		if (vma->vm_start > start)
2070 			start = vma->vm_start;
2071 		vma_end = min(end, vma->vm_end);
2072 
2073 		new_flags = (vma->vm_flags & ~__VM_UFFD_FLAGS) | vm_flags;
2074 		vma = vma_modify_flags_uffd(&vmi, prev, vma, start, vma_end,
2075 					    new_flags,
2076 					    (struct vm_userfaultfd_ctx){ctx},
2077 					    /* give_up_on_oom = */false);
2078 		if (IS_ERR(vma))
2079 			return PTR_ERR(vma);
2080 
2081 		/*
2082 		 * In the vma_merge() successful mprotect-like case 8:
2083 		 * the next vma was merged into the current one and
2084 		 * the current one has not been updated yet.
2085 		 */
2086 		userfaultfd_set_ctx(vma, ctx, vm_flags);
2087 
2088 		if (is_vm_hugetlb_page(vma) && uffd_disable_huge_pmd_share(vma))
2089 			hugetlb_unshare_all_pmds(vma);
2090 
2091 skip:
2092 		prev = vma;
2093 		start = vma->vm_end;
2094 	}
2095 
2096 	return 0;
2097 }
2098 
userfaultfd_release_new(struct userfaultfd_ctx * ctx)2099 void userfaultfd_release_new(struct userfaultfd_ctx *ctx)
2100 {
2101 	struct mm_struct *mm = ctx->mm;
2102 	struct vm_area_struct *vma;
2103 	VMA_ITERATOR(vmi, mm, 0);
2104 
2105 	/* the various vma->vm_userfaultfd_ctx still points to it */
2106 	mmap_write_lock(mm);
2107 	for_each_vma(vmi, vma) {
2108 		if (vma->vm_userfaultfd_ctx.ctx == ctx)
2109 			userfaultfd_reset_ctx(vma);
2110 	}
2111 	mmap_write_unlock(mm);
2112 }
2113 
userfaultfd_release_all(struct mm_struct * mm,struct userfaultfd_ctx * ctx)2114 void userfaultfd_release_all(struct mm_struct *mm,
2115 			     struct userfaultfd_ctx *ctx)
2116 {
2117 	struct vm_area_struct *vma, *prev;
2118 	VMA_ITERATOR(vmi, mm, 0);
2119 
2120 	if (!mmget_not_zero(mm))
2121 		return;
2122 
2123 	/*
2124 	 * Flush page faults out of all CPUs. NOTE: all page faults
2125 	 * must be retried without returning VM_FAULT_SIGBUS if
2126 	 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
2127 	 * changes while handle_userfault released the mmap_lock. So
2128 	 * it's critical that released is set to true (above), before
2129 	 * taking the mmap_lock for writing.
2130 	 */
2131 	mmap_write_lock(mm);
2132 	prev = NULL;
2133 	for_each_vma(vmi, vma) {
2134 		cond_resched();
2135 		BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
2136 		       !!(vma->vm_flags & __VM_UFFD_FLAGS));
2137 		if (vma->vm_userfaultfd_ctx.ctx != ctx) {
2138 			prev = vma;
2139 			continue;
2140 		}
2141 
2142 		vma = userfaultfd_clear_vma(&vmi, prev, vma,
2143 					    vma->vm_start, vma->vm_end);
2144 		prev = vma;
2145 	}
2146 	mmap_write_unlock(mm);
2147 	mmput(mm);
2148 }
2149