xref: /linux/mm/userfaultfd.c (revision f4cdf7ca9a1fdcca413157df19753f388a5a224e)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  mm/userfaultfd.c
4  *
5  *  Copyright (C) 2007  Davide Libenzi <davidel@xmailserver.org>
6  *  Copyright (C) 2008-2009 Red Hat, Inc.
7  *  Copyright (C) 2015  Red Hat, Inc.
8  *
9  *  Some part derived from fs/eventfd.c (anon inode setup) and
10  *  mm/ksm.c (mm hashing).
11  */
12 
13 #include <linux/mm.h>
14 #include <linux/sched/signal.h>
15 #include <linux/pagemap.h>
16 #include <linux/rmap.h>
17 #include <linux/swap.h>
18 #include <linux/leafops.h>
19 #include <linux/userfaultfd_k.h>
20 #include <linux/mmu_notifier.h>
21 #include <linux/hugetlb.h>
22 #include <linux/list.h>
23 #include <linux/sched/mm.h>
24 #include <linux/mm_inline.h>
25 #include <linux/poll.h>
26 #include <linux/slab.h>
27 #include <linux/seq_file.h>
28 #include <linux/bug.h>
29 #include <linux/anon_inodes.h>
30 #include <linux/syscalls.h>
31 #include <linux/miscdevice.h>
32 #include <linux/uio.h>
33 #include <linux/file.h>
34 #include <linux/cleanup.h>
35 #include <asm/tlbflush.h>
36 #include <asm/tlb.h>
37 #include "internal.h"
38 #include "swap.h"
39 
40 struct mfill_state {
41 	struct userfaultfd_ctx *ctx;
42 	unsigned long src_start;
43 	unsigned long dst_start;
44 	unsigned long len;
45 	uffd_flags_t flags;
46 
47 	struct vm_area_struct *vma;
48 	unsigned long src_addr;
49 	unsigned long dst_addr;
50 	pmd_t *pmd;
51 };
52 
53 static bool anon_can_userfault(struct vm_area_struct *vma, vm_flags_t vm_flags)
54 {
55 	/* anonymous memory does not support MINOR mode */
56 	if (vm_flags & VM_UFFD_MINOR)
57 		return false;
58 	return true;
59 }
60 
61 static struct folio *anon_alloc_folio(struct vm_area_struct *vma,
62 				      unsigned long addr)
63 {
64 	struct folio *folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0, vma,
65 					      addr);
66 
67 	if (!folio)
68 		return NULL;
69 
70 	if (mem_cgroup_charge(folio, vma->vm_mm, GFP_KERNEL)) {
71 		folio_put(folio);
72 		return NULL;
73 	}
74 
75 	return folio;
76 }
77 
78 static const struct vm_uffd_ops anon_uffd_ops = {
79 	.can_userfault	= anon_can_userfault,
80 	.alloc_folio	= anon_alloc_folio,
81 };
82 
83 static const struct vm_uffd_ops *vma_uffd_ops(struct vm_area_struct *vma)
84 {
85 	if (vma_is_anonymous(vma))
86 		return &anon_uffd_ops;
87 	return vma->vm_ops->uffd_ops;
88 }
89 
90 static __always_inline
91 bool validate_dst_vma(struct vm_area_struct *dst_vma, unsigned long dst_end)
92 {
93 	/* Make sure that the dst range is fully within dst_vma. */
94 	if (dst_end > dst_vma->vm_end)
95 		return false;
96 
97 	/*
98 	 * Check the vma is registered in uffd, this is required to
99 	 * enforce the VM_MAYWRITE check done at uffd registration
100 	 * time.
101 	 */
102 	if (!dst_vma->vm_userfaultfd_ctx.ctx)
103 		return false;
104 
105 	return true;
106 }
107 
108 static __always_inline
109 struct vm_area_struct *find_vma_and_prepare_anon(struct mm_struct *mm,
110 						 unsigned long addr)
111 {
112 	struct vm_area_struct *vma;
113 
114 	mmap_assert_locked(mm);
115 	vma = vma_lookup(mm, addr);
116 	if (!vma)
117 		vma = ERR_PTR(-ENOENT);
118 	else if (!(vma->vm_flags & VM_SHARED) &&
119 		 unlikely(anon_vma_prepare(vma)))
120 		vma = ERR_PTR(-ENOMEM);
121 
122 	return vma;
123 }
124 
125 #ifdef CONFIG_PER_VMA_LOCK
126 /*
127  * uffd_lock_vma() - Lookup and lock vma corresponding to @address.
128  * @mm: mm to search vma in.
129  * @address: address that the vma should contain.
130  *
131  * Should be called without holding mmap_lock.
132  *
133  * Return: A locked vma containing @address, -ENOENT if no vma is found, or
134  * -ENOMEM if anon_vma couldn't be allocated.
135  */
136 static struct vm_area_struct *uffd_lock_vma(struct mm_struct *mm,
137 				       unsigned long address)
138 {
139 	struct vm_area_struct *vma;
140 
141 	vma = lock_vma_under_rcu(mm, address);
142 	if (vma) {
143 		/*
144 		 * We know we're going to need to use anon_vma, so check
145 		 * that early.
146 		 */
147 		if (!(vma->vm_flags & VM_SHARED) && unlikely(!vma->anon_vma))
148 			vma_end_read(vma);
149 		else
150 			return vma;
151 	}
152 
153 	mmap_read_lock(mm);
154 	vma = find_vma_and_prepare_anon(mm, address);
155 	if (!IS_ERR(vma)) {
156 		bool locked = vma_start_read_locked(vma);
157 
158 		if (!locked)
159 			vma = ERR_PTR(-EAGAIN);
160 	}
161 
162 	mmap_read_unlock(mm);
163 	return vma;
164 }
165 
166 static struct vm_area_struct *uffd_mfill_lock(struct mm_struct *dst_mm,
167 					      unsigned long dst_start,
168 					      unsigned long len)
169 {
170 	struct vm_area_struct *dst_vma;
171 
172 	dst_vma = uffd_lock_vma(dst_mm, dst_start);
173 	if (IS_ERR(dst_vma) || validate_dst_vma(dst_vma, dst_start + len))
174 		return dst_vma;
175 
176 	vma_end_read(dst_vma);
177 	return ERR_PTR(-ENOENT);
178 }
179 
180 static void uffd_mfill_unlock(struct vm_area_struct *vma)
181 {
182 	vma_end_read(vma);
183 }
184 
185 #else
186 
187 static struct vm_area_struct *uffd_mfill_lock(struct mm_struct *dst_mm,
188 					      unsigned long dst_start,
189 					      unsigned long len)
190 {
191 	struct vm_area_struct *dst_vma;
192 
193 	mmap_read_lock(dst_mm);
194 	dst_vma = find_vma_and_prepare_anon(dst_mm, dst_start);
195 	if (IS_ERR(dst_vma))
196 		goto out_unlock;
197 
198 	if (validate_dst_vma(dst_vma, dst_start + len))
199 		return dst_vma;
200 
201 	dst_vma = ERR_PTR(-ENOENT);
202 out_unlock:
203 	mmap_read_unlock(dst_mm);
204 	return dst_vma;
205 }
206 
207 static void uffd_mfill_unlock(struct vm_area_struct *vma)
208 {
209 	mmap_read_unlock(vma->vm_mm);
210 }
211 #endif
212 
213 static void mfill_put_vma(struct mfill_state *state)
214 {
215 	if (!state->vma)
216 		return;
217 
218 	up_read(&state->ctx->map_changing_lock);
219 	uffd_mfill_unlock(state->vma);
220 	state->vma = NULL;
221 }
222 
223 static int mfill_get_vma(struct mfill_state *state)
224 {
225 	struct userfaultfd_ctx *ctx = state->ctx;
226 	uffd_flags_t flags = state->flags;
227 	struct vm_area_struct *dst_vma;
228 	const struct vm_uffd_ops *ops;
229 	int err;
230 
231 	/*
232 	 * Make sure the vma is not shared, that the dst range is
233 	 * both valid and fully within a single existing vma.
234 	 */
235 	dst_vma = uffd_mfill_lock(ctx->mm, state->dst_start, state->len);
236 	if (IS_ERR(dst_vma))
237 		return PTR_ERR(dst_vma);
238 
239 	/*
240 	 * If memory mappings are changing because of non-cooperative
241 	 * operation (e.g. mremap) running in parallel, bail out and
242 	 * request the user to retry later
243 	 */
244 	down_read(&ctx->map_changing_lock);
245 	state->vma = dst_vma;
246 	err = -EAGAIN;
247 	if (atomic_read(&ctx->mmap_changing))
248 		goto out_unlock;
249 
250 	err = -EINVAL;
251 
252 	/*
253 	 * shmem_zero_setup is invoked in mmap for MAP_ANONYMOUS|MAP_SHARED but
254 	 * it will overwrite vm_ops, so vma_is_anonymous must return false.
255 	 */
256 	if (WARN_ON_ONCE(vma_is_anonymous(dst_vma) &&
257 	    dst_vma->vm_flags & VM_SHARED))
258 		goto out_unlock;
259 
260 	/*
261 	 * validate 'mode' now that we know the dst_vma: don't allow
262 	 * a wrprotect copy if the userfaultfd didn't register as WP.
263 	 */
264 	if ((flags & MFILL_ATOMIC_WP) && !(dst_vma->vm_flags & VM_UFFD_WP))
265 		goto out_unlock;
266 
267 	if (is_vm_hugetlb_page(dst_vma))
268 		return 0;
269 
270 	ops = vma_uffd_ops(dst_vma);
271 	if (!ops)
272 		goto out_unlock;
273 
274 	if (uffd_flags_mode_is(flags, MFILL_ATOMIC_CONTINUE) &&
275 	    !ops->get_folio_noalloc)
276 		goto out_unlock;
277 
278 	return 0;
279 
280 out_unlock:
281 	mfill_put_vma(state);
282 	return err;
283 }
284 
285 static pmd_t *mm_alloc_pmd(struct mm_struct *mm, unsigned long address)
286 {
287 	pgd_t *pgd;
288 	p4d_t *p4d;
289 	pud_t *pud;
290 
291 	pgd = pgd_offset(mm, address);
292 	p4d = p4d_alloc(mm, pgd, address);
293 	if (!p4d)
294 		return NULL;
295 	pud = pud_alloc(mm, p4d, address);
296 	if (!pud)
297 		return NULL;
298 	/*
299 	 * Note that we didn't run this because the pmd was
300 	 * missing, the *pmd may be already established and in
301 	 * turn it may also be a trans_huge_pmd.
302 	 */
303 	return pmd_alloc(mm, pud, address);
304 }
305 
306 static int mfill_establish_pmd(struct mfill_state *state)
307 {
308 	struct mm_struct *dst_mm = state->ctx->mm;
309 	pmd_t *dst_pmd, dst_pmdval;
310 
311 	dst_pmd = mm_alloc_pmd(dst_mm, state->dst_addr);
312 	if (unlikely(!dst_pmd))
313 		return -ENOMEM;
314 
315 	dst_pmdval = pmdp_get_lockless(dst_pmd);
316 	if (unlikely(pmd_none(dst_pmdval)) &&
317 	    unlikely(__pte_alloc(dst_mm, dst_pmd)))
318 		return -ENOMEM;
319 
320 	dst_pmdval = pmdp_get_lockless(dst_pmd);
321 	/*
322 	 * If the dst_pmd is THP don't override it and just be strict.
323 	 * (This includes the case where the PMD used to be THP and
324 	 * changed back to none after __pte_alloc().)
325 	 */
326 	if (unlikely(!pmd_present(dst_pmdval) || pmd_leaf(dst_pmdval)))
327 		return -EEXIST;
328 	if (unlikely(pmd_bad(dst_pmdval)))
329 		return -EFAULT;
330 
331 	state->pmd = dst_pmd;
332 	return 0;
333 }
334 
335 /* Check if dst_addr is outside of file's size. Must be called with ptl held. */
336 static bool mfill_file_over_size(struct vm_area_struct *dst_vma,
337 				 unsigned long dst_addr)
338 {
339 	struct inode *inode;
340 	pgoff_t offset, max_off;
341 
342 	if (!dst_vma->vm_file)
343 		return false;
344 
345 	inode = dst_vma->vm_file->f_inode;
346 	offset = linear_page_index(dst_vma, dst_addr);
347 	max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
348 	return offset >= max_off;
349 }
350 
351 /*
352  * Install PTEs, to map dst_addr (within dst_vma) to page.
353  *
354  * This function handles both MCOPY_ATOMIC_NORMAL and _CONTINUE for both shmem
355  * and anon, and for both shared and private VMAs.
356  */
357 static int mfill_atomic_install_pte(pmd_t *dst_pmd,
358 				    struct vm_area_struct *dst_vma,
359 				    unsigned long dst_addr, struct page *page,
360 				    uffd_flags_t flags)
361 {
362 	int ret;
363 	struct mm_struct *dst_mm = dst_vma->vm_mm;
364 	pte_t _dst_pte, *dst_pte;
365 	bool writable = dst_vma->vm_flags & VM_WRITE;
366 	bool vm_shared = dst_vma->vm_flags & VM_SHARED;
367 	spinlock_t *ptl;
368 	struct folio *folio = page_folio(page);
369 	bool page_in_cache = folio_mapping(folio);
370 	pte_t dst_ptep;
371 
372 	_dst_pte = mk_pte(page, dst_vma->vm_page_prot);
373 	_dst_pte = pte_mkdirty(_dst_pte);
374 	if (page_in_cache && !vm_shared)
375 		writable = false;
376 	if (writable)
377 		_dst_pte = pte_mkwrite(_dst_pte, dst_vma);
378 	if (flags & MFILL_ATOMIC_WP)
379 		_dst_pte = pte_mkuffd_wp(_dst_pte);
380 
381 	ret = -EAGAIN;
382 	dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
383 	if (!dst_pte)
384 		goto out;
385 
386 	if (mfill_file_over_size(dst_vma, dst_addr)) {
387 		ret = -EFAULT;
388 		goto out_unlock;
389 	}
390 
391 	ret = -EEXIST;
392 
393 	dst_ptep = ptep_get(dst_pte);
394 
395 	/*
396 	 * We are allowed to overwrite a UFFD pte marker: consider when both
397 	 * MISSING|WP registered, we firstly wr-protect a none pte which has no
398 	 * page cache page backing it, then access the page.
399 	 */
400 	if (!pte_none(dst_ptep) && !pte_is_uffd_marker(dst_ptep))
401 		goto out_unlock;
402 
403 	if (page_in_cache) {
404 		folio_add_file_rmap_pte(folio, page, dst_vma);
405 	} else {
406 		folio_add_new_anon_rmap(folio, dst_vma, dst_addr, RMAP_EXCLUSIVE);
407 		folio_add_lru_vma(folio, dst_vma);
408 	}
409 
410 	/*
411 	 * Must happen after rmap, as mm_counter() checks mapping (via
412 	 * PageAnon()), which is set by __page_set_anon_rmap().
413 	 */
414 	inc_mm_counter(dst_mm, mm_counter(folio));
415 
416 	set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
417 
418 	if (page_in_cache)
419 		folio_unlock(folio);
420 
421 	/* No need to invalidate - it was non-present before */
422 	update_mmu_cache(dst_vma, dst_addr, dst_pte);
423 	ret = 0;
424 out_unlock:
425 	pte_unmap_unlock(dst_pte, ptl);
426 out:
427 	return ret;
428 }
429 
430 static int mfill_copy_folio_locked(struct folio *folio, unsigned long src_addr)
431 {
432 	void *kaddr;
433 	int ret;
434 
435 	kaddr = kmap_local_folio(folio, 0);
436 	/*
437 	 * The read mmap_lock is held here.  Despite the
438 	 * mmap_lock being read recursive a deadlock is still
439 	 * possible if a writer has taken a lock.  For example:
440 	 *
441 	 * process A thread 1 takes read lock on own mmap_lock
442 	 * process A thread 2 calls mmap, blocks taking write lock
443 	 * process B thread 1 takes page fault, read lock on own mmap lock
444 	 * process B thread 2 calls mmap, blocks taking write lock
445 	 * process A thread 1 blocks taking read lock on process B
446 	 * process B thread 1 blocks taking read lock on process A
447 	 *
448 	 * Disable page faults to prevent potential deadlock
449 	 * and retry the copy outside the mmap_lock.
450 	 */
451 	pagefault_disable();
452 	ret = copy_from_user(kaddr, (const void __user *) src_addr,
453 			     PAGE_SIZE);
454 	pagefault_enable();
455 	kunmap_local(kaddr);
456 
457 	if (ret)
458 		return -EFAULT;
459 
460 	flush_dcache_folio(folio);
461 	return ret;
462 }
463 
464 #define MFILL_RETRY_STATE_VMA_FLAGS \
465 	append_vma_flags(__VMA_UFFD_FLAGS, VMA_SHARED_BIT)
466 
467 /*
468  * VMA state saved before dropping the locks in mfill_copy_folio_retry().
469  * Used to detect VMA replacement or incompatible changes after reacquiring the
470  * locks.
471  */
472 struct mfill_retry_state {
473 	const struct vm_uffd_ops *ops;
474 	struct file *file;
475 	vma_flags_t flags;
476 	pgoff_t pgoff;
477 };
478 
479 static void mfill_retry_state_save(struct mfill_retry_state *s,
480 				   struct vm_area_struct *vma)
481 {
482 	s->flags = vma_flags_and_mask(&vma->flags, MFILL_RETRY_STATE_VMA_FLAGS);
483 	s->ops = vma_uffd_ops(vma);
484 	s->pgoff = vma->vm_pgoff;
485 
486 	if (vma->vm_file)
487 		s->file = get_file(vma->vm_file);
488 }
489 
490 static bool mfill_retry_state_changed(struct mfill_retry_state *state,
491 				      struct vm_area_struct *vma)
492 {
493 	vma_flags_t flags = vma_flags_and_mask(&vma->flags,
494 					       MFILL_RETRY_STATE_VMA_FLAGS);
495 
496 	/* Have any UFFD flags (missing, WP, minor) changed? */
497 	if (!vma_flags_same_pair(&state->flags, &flags))
498 		return true;
499 
500 	/* VMA type or effective uffd_ops changed while the lock was dropped */
501 	if (state->ops != vma_uffd_ops(vma))
502 		return true;
503 
504 	/* VMA was anonymous before; changed only if it no longer is */
505 	if (!state->file)
506 		return !vma_is_anonymous(vma);
507 
508 	/* VMA was file backed, but file, inode or offset has changed */
509 	if (!vma->vm_file || vma->vm_file->f_inode != state->file->f_inode ||
510 	    state->file != vma->vm_file || vma->vm_pgoff != state->pgoff)
511 		return true;
512 
513 	return false;
514 }
515 
516 static void mfill_retry_state_put(struct mfill_retry_state *s)
517 {
518 	if (s->file)
519 		fput(s->file);
520 }
521 
522 DEFINE_FREE(retry_put, struct mfill_retry_state *,
523 	    if (_T) mfill_retry_state_put(_T));
524 
525 static int mfill_copy_folio_retry(struct mfill_state *mfill_state,
526 				  struct folio *folio)
527 {
528 	struct mfill_retry_state retry_state = { 0 };
529 	struct mfill_retry_state *for_free __free(retry_put) = &retry_state;
530 	unsigned long src_addr = mfill_state->src_addr;
531 	void *kaddr;
532 	int err;
533 
534 	mfill_retry_state_save(&retry_state, mfill_state->vma);
535 
536 	/* retry copying with mm_lock dropped */
537 	mfill_put_vma(mfill_state);
538 
539 	kaddr = kmap_local_folio(folio, 0);
540 	err = copy_from_user(kaddr, (const void __user *) src_addr, PAGE_SIZE);
541 	kunmap_local(kaddr);
542 	if (unlikely(err))
543 		return -EFAULT;
544 
545 	flush_dcache_folio(folio);
546 
547 	/* reget VMA and PMD, they could change underneath us */
548 	err = mfill_get_vma(mfill_state);
549 	if (err)
550 		return err;
551 
552 	if (mfill_retry_state_changed(&retry_state, mfill_state->vma))
553 		return -EAGAIN;
554 
555 	err = mfill_establish_pmd(mfill_state);
556 	if (err)
557 		return err;
558 
559 	return 0;
560 }
561 
562 static int __mfill_atomic_pte(struct mfill_state *state,
563 			      const struct vm_uffd_ops *ops)
564 {
565 	unsigned long dst_addr = state->dst_addr;
566 	unsigned long src_addr = state->src_addr;
567 	uffd_flags_t flags = state->flags;
568 	struct folio *folio;
569 	int ret;
570 
571 	if (!ops) {
572 		VM_WARN_ONCE(1, "UFFDIO_COPY for unsupported VMA");
573 		return -EOPNOTSUPP;
574 	}
575 
576 	folio = ops->alloc_folio(state->vma, state->dst_addr);
577 	if (!folio)
578 		return -ENOMEM;
579 
580 	if (uffd_flags_mode_is(flags, MFILL_ATOMIC_COPY)) {
581 		ret = mfill_copy_folio_locked(folio, src_addr);
582 		/*
583 		 * Fallback to copy_from_user outside mmap_lock.
584 		 * If retry is successful, mfill_copy_folio_locked() returns
585 		 * with locks retaken by mfill_get_vma().
586 		 * If there was an error, we must mfill_put_vma() anyway and it
587 		 * will take care of unlocking if needed.
588 		 */
589 		if (unlikely(ret)) {
590 			ret = mfill_copy_folio_retry(state, folio);
591 			if (ret)
592 				goto err_folio_put;
593 		}
594 	} else if (uffd_flags_mode_is(flags, MFILL_ATOMIC_ZEROPAGE)) {
595 		clear_user_highpage(&folio->page, state->dst_addr);
596 	} else {
597 		VM_WARN_ONCE(1, "Unknown UFFDIO operation, flags: %x", flags);
598 	}
599 
600 	/*
601 	 * The memory barrier inside __folio_mark_uptodate makes sure that
602 	 * preceding stores to the page contents become visible before
603 	 * the set_pte_at() write.
604 	 */
605 	__folio_mark_uptodate(folio);
606 
607 	if (ops->filemap_add) {
608 		ret = ops->filemap_add(folio, state->vma, state->dst_addr);
609 		if (ret)
610 			goto err_folio_put;
611 	}
612 
613 	ret = mfill_atomic_install_pte(state->pmd, state->vma, dst_addr,
614 				       &folio->page, flags);
615 	if (ret)
616 		goto err_filemap_remove;
617 
618 	return 0;
619 
620 err_filemap_remove:
621 	if (ops->filemap_remove)
622 		ops->filemap_remove(folio, state->vma);
623 err_folio_put:
624 	folio_put(folio);
625 	return ret;
626 }
627 
628 static int mfill_atomic_pte_copy(struct mfill_state *state)
629 {
630 	const struct vm_uffd_ops *ops = vma_uffd_ops(state->vma);
631 
632 	/*
633 	 * The normal page fault path for a MAP_PRIVATE mapping in a
634 	 * file-backed VMA will invoke the fault, fill the hole in the file and
635 	 * COW it right away. The result generates plain anonymous memory.
636 	 * So when we are asked to fill a hole in a MAP_PRIVATE mapping, we'll
637 	 * generate anonymous memory directly without actually filling the
638 	 * hole. For the MAP_PRIVATE case the robustness check only happens in
639 	 * the pagetable (to verify it's still none) and not in the page cache.
640 	 */
641 	if (!(state->vma->vm_flags & VM_SHARED))
642 		ops = &anon_uffd_ops;
643 
644 	return __mfill_atomic_pte(state, ops);
645 }
646 
647 static int mfill_atomic_pte_zeroed_folio(struct mfill_state *state)
648 {
649 	const struct vm_uffd_ops *ops = vma_uffd_ops(state->vma);
650 
651 	return __mfill_atomic_pte(state, ops);
652 }
653 
654 static int mfill_atomic_pte_zeropage(struct mfill_state *state)
655 {
656 	struct vm_area_struct *dst_vma = state->vma;
657 	unsigned long dst_addr = state->dst_addr;
658 	pmd_t *dst_pmd = state->pmd;
659 	pte_t _dst_pte, *dst_pte;
660 	spinlock_t *ptl;
661 	int ret;
662 
663 	if (mm_forbids_zeropage(dst_vma->vm_mm) ||
664 	    (dst_vma->vm_flags & VM_SHARED))
665 		return mfill_atomic_pte_zeroed_folio(state);
666 
667 	_dst_pte = pte_mkspecial(pfn_pte(zero_pfn(dst_addr),
668 					 dst_vma->vm_page_prot));
669 	ret = -EAGAIN;
670 	dst_pte = pte_offset_map_lock(dst_vma->vm_mm, dst_pmd, dst_addr, &ptl);
671 	if (!dst_pte)
672 		goto out;
673 	if (mfill_file_over_size(dst_vma, dst_addr)) {
674 		ret = -EFAULT;
675 		goto out_unlock;
676 	}
677 	ret = -EEXIST;
678 	if (!pte_none(ptep_get(dst_pte)))
679 		goto out_unlock;
680 	set_pte_at(dst_vma->vm_mm, dst_addr, dst_pte, _dst_pte);
681 	/* No need to invalidate - it was non-present before */
682 	update_mmu_cache(dst_vma, dst_addr, dst_pte);
683 	ret = 0;
684 out_unlock:
685 	pte_unmap_unlock(dst_pte, ptl);
686 out:
687 	return ret;
688 }
689 
690 /* Handles UFFDIO_CONTINUE for all shmem VMAs (shared or private). */
691 static int mfill_atomic_pte_continue(struct mfill_state *state)
692 {
693 	struct vm_area_struct *dst_vma = state->vma;
694 	const struct vm_uffd_ops *ops = vma_uffd_ops(dst_vma);
695 	unsigned long dst_addr = state->dst_addr;
696 	pgoff_t pgoff = linear_page_index(dst_vma, dst_addr);
697 	struct inode *inode = file_inode(dst_vma->vm_file);
698 	uffd_flags_t flags = state->flags;
699 	pmd_t *dst_pmd = state->pmd;
700 	struct folio *folio;
701 	struct page *page;
702 	int ret;
703 
704 	if (!ops) {
705 		VM_WARN_ONCE(1, "UFFDIO_CONTINUE for unsupported VMA");
706 		return -EOPNOTSUPP;
707 	}
708 
709 	folio = ops->get_folio_noalloc(inode, pgoff);
710 	/* Our caller expects us to return -EFAULT if we failed to find folio */
711 	if (IS_ERR_OR_NULL(folio))
712 		return -EFAULT;
713 
714 	page = folio_file_page(folio, pgoff);
715 	if (PageHWPoison(page)) {
716 		ret = -EIO;
717 		goto out_release;
718 	}
719 
720 	ret = mfill_atomic_install_pte(dst_pmd, dst_vma, dst_addr,
721 				       page, flags);
722 	if (ret)
723 		goto out_release;
724 
725 	return 0;
726 
727 out_release:
728 	folio_unlock(folio);
729 	folio_put(folio);
730 	return ret;
731 }
732 
733 /* Handles UFFDIO_POISON for all non-hugetlb VMAs. */
734 static int mfill_atomic_pte_poison(struct mfill_state *state)
735 {
736 	struct vm_area_struct *dst_vma = state->vma;
737 	struct mm_struct *dst_mm = dst_vma->vm_mm;
738 	unsigned long dst_addr = state->dst_addr;
739 	pmd_t *dst_pmd = state->pmd;
740 	pte_t _dst_pte, *dst_pte;
741 	spinlock_t *ptl;
742 	int ret;
743 
744 	_dst_pte = make_pte_marker(PTE_MARKER_POISONED);
745 	ret = -EAGAIN;
746 	dst_pte = pte_offset_map_lock(dst_mm, dst_pmd, dst_addr, &ptl);
747 	if (!dst_pte)
748 		goto out;
749 
750 	if (mfill_file_over_size(dst_vma, dst_addr)) {
751 		ret = -EFAULT;
752 		goto out_unlock;
753 	}
754 
755 	ret = -EEXIST;
756 	/* Refuse to overwrite any PTE, even a PTE marker (e.g. UFFD WP). */
757 	if (!pte_none(ptep_get(dst_pte)))
758 		goto out_unlock;
759 
760 	set_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte);
761 
762 	/* No need to invalidate - it was non-present before */
763 	update_mmu_cache(dst_vma, dst_addr, dst_pte);
764 	ret = 0;
765 out_unlock:
766 	pte_unmap_unlock(dst_pte, ptl);
767 out:
768 	return ret;
769 }
770 
771 #ifdef CONFIG_HUGETLB_PAGE
772 /*
773  * mfill_atomic processing for HUGETLB vmas.  Note that this routine is
774  * called with either vma-lock or mmap_lock held, it will release the lock
775  * before returning.
776  */
777 static __always_inline ssize_t mfill_atomic_hugetlb(
778 					      struct userfaultfd_ctx *ctx,
779 					      struct vm_area_struct *dst_vma,
780 					      unsigned long dst_start,
781 					      unsigned long src_start,
782 					      unsigned long len,
783 					      uffd_flags_t flags)
784 {
785 	struct mm_struct *dst_mm = dst_vma->vm_mm;
786 	ssize_t err;
787 	pte_t *dst_pte;
788 	unsigned long src_addr, dst_addr;
789 	long copied;
790 	struct folio *folio;
791 	unsigned long vma_hpagesize;
792 	pgoff_t idx;
793 	u32 hash;
794 	struct address_space *mapping;
795 
796 	/*
797 	 * There is no default zero huge page for all huge page sizes as
798 	 * supported by hugetlb.  A PMD_SIZE huge pages may exist as used
799 	 * by THP.  Since we can not reliably insert a zero page, this
800 	 * feature is not supported.
801 	 */
802 	if (uffd_flags_mode_is(flags, MFILL_ATOMIC_ZEROPAGE)) {
803 		up_read(&ctx->map_changing_lock);
804 		uffd_mfill_unlock(dst_vma);
805 		return -EINVAL;
806 	}
807 
808 	src_addr = src_start;
809 	dst_addr = dst_start;
810 	copied = 0;
811 	folio = NULL;
812 	vma_hpagesize = vma_kernel_pagesize(dst_vma);
813 
814 	/*
815 	 * Validate alignment based on huge page size
816 	 */
817 	err = -EINVAL;
818 	if (dst_start & (vma_hpagesize - 1) || len & (vma_hpagesize - 1))
819 		goto out_unlock;
820 
821 retry:
822 	/*
823 	 * On routine entry dst_vma is set.  If we had to drop mmap_lock and
824 	 * retry, dst_vma will be set to NULL and we must lookup again.
825 	 */
826 	if (!dst_vma) {
827 		dst_vma = uffd_mfill_lock(dst_mm, dst_start, len);
828 		if (IS_ERR(dst_vma)) {
829 			err = PTR_ERR(dst_vma);
830 			goto out;
831 		}
832 
833 		err = -ENOENT;
834 		if (!is_vm_hugetlb_page(dst_vma))
835 			goto out_unlock_vma;
836 
837 		err = -EINVAL;
838 		if (vma_hpagesize != vma_kernel_pagesize(dst_vma))
839 			goto out_unlock_vma;
840 
841 		/*
842 		 * If memory mappings are changing because of non-cooperative
843 		 * operation (e.g. mremap) running in parallel, bail out and
844 		 * request the user to retry later
845 		 */
846 		down_read(&ctx->map_changing_lock);
847 		err = -EAGAIN;
848 		if (atomic_read(&ctx->mmap_changing))
849 			goto out_unlock;
850 	}
851 
852 	while (src_addr < src_start + len) {
853 		VM_WARN_ON_ONCE(dst_addr >= dst_start + len);
854 
855 		/*
856 		 * Serialize via vma_lock and hugetlb_fault_mutex.
857 		 * vma_lock ensures the dst_pte remains valid even
858 		 * in the case of shared pmds.  fault mutex prevents
859 		 * races with other faulting threads.
860 		 */
861 		idx = hugetlb_linear_page_index(dst_vma, dst_addr);
862 		mapping = dst_vma->vm_file->f_mapping;
863 		hash = hugetlb_fault_mutex_hash(mapping, idx);
864 		mutex_lock(&hugetlb_fault_mutex_table[hash]);
865 		hugetlb_vma_lock_read(dst_vma);
866 
867 		err = -ENOMEM;
868 		dst_pte = huge_pte_alloc(dst_mm, dst_vma, dst_addr, vma_hpagesize);
869 		if (!dst_pte) {
870 			hugetlb_vma_unlock_read(dst_vma);
871 			mutex_unlock(&hugetlb_fault_mutex_table[hash]);
872 			goto out_unlock;
873 		}
874 
875 		if (!uffd_flags_mode_is(flags, MFILL_ATOMIC_CONTINUE)) {
876 			const pte_t ptep = huge_ptep_get(dst_mm, dst_addr, dst_pte);
877 
878 			if (!huge_pte_none(ptep) && !pte_is_uffd_marker(ptep)) {
879 				err = -EEXIST;
880 				hugetlb_vma_unlock_read(dst_vma);
881 				mutex_unlock(&hugetlb_fault_mutex_table[hash]);
882 				goto out_unlock;
883 			}
884 		}
885 
886 		err = hugetlb_mfill_atomic_pte(dst_pte, dst_vma, dst_addr,
887 					       src_addr, flags, &folio);
888 
889 		hugetlb_vma_unlock_read(dst_vma);
890 		mutex_unlock(&hugetlb_fault_mutex_table[hash]);
891 
892 		cond_resched();
893 
894 		if (unlikely(err == -ENOENT)) {
895 			up_read(&ctx->map_changing_lock);
896 			uffd_mfill_unlock(dst_vma);
897 			VM_WARN_ON_ONCE(!folio);
898 
899 			err = copy_folio_from_user(folio,
900 						   (const void __user *)src_addr, true);
901 			if (unlikely(err)) {
902 				err = -EFAULT;
903 				goto out;
904 			}
905 
906 			dst_vma = NULL;
907 			goto retry;
908 		} else
909 			VM_WARN_ON_ONCE(folio);
910 
911 		if (!err) {
912 			dst_addr += vma_hpagesize;
913 			src_addr += vma_hpagesize;
914 			copied += vma_hpagesize;
915 
916 			if (fatal_signal_pending(current))
917 				err = -EINTR;
918 		}
919 		if (err)
920 			break;
921 	}
922 
923 out_unlock:
924 	up_read(&ctx->map_changing_lock);
925 out_unlock_vma:
926 	uffd_mfill_unlock(dst_vma);
927 out:
928 	if (folio)
929 		folio_put(folio);
930 	VM_WARN_ON_ONCE(copied < 0);
931 	VM_WARN_ON_ONCE(err > 0);
932 	VM_WARN_ON_ONCE(!copied && !err);
933 	return copied ? copied : err;
934 }
935 #else /* !CONFIG_HUGETLB_PAGE */
936 /* fail at build time if gcc attempts to use this */
937 extern ssize_t mfill_atomic_hugetlb(struct userfaultfd_ctx *ctx,
938 				    struct vm_area_struct *dst_vma,
939 				    unsigned long dst_start,
940 				    unsigned long src_start,
941 				    unsigned long len,
942 				    uffd_flags_t flags);
943 #endif /* CONFIG_HUGETLB_PAGE */
944 
945 static __always_inline ssize_t mfill_atomic_pte(struct mfill_state *state)
946 {
947 	uffd_flags_t flags = state->flags;
948 
949 	if (uffd_flags_mode_is(flags, MFILL_ATOMIC_CONTINUE))
950 		return mfill_atomic_pte_continue(state);
951 	if (uffd_flags_mode_is(flags, MFILL_ATOMIC_POISON))
952 		return mfill_atomic_pte_poison(state);
953 	if (uffd_flags_mode_is(flags, MFILL_ATOMIC_COPY))
954 		return mfill_atomic_pte_copy(state);
955 	if (uffd_flags_mode_is(flags, MFILL_ATOMIC_ZEROPAGE))
956 		return mfill_atomic_pte_zeropage(state);
957 
958 	VM_WARN_ONCE(1, "Unknown UFFDIO operation, flags: %x", flags);
959 	return -EOPNOTSUPP;
960 }
961 
962 static __always_inline ssize_t mfill_atomic(struct userfaultfd_ctx *ctx,
963 					    unsigned long dst_start,
964 					    unsigned long src_start,
965 					    unsigned long len,
966 					    uffd_flags_t flags)
967 {
968 	struct mfill_state state = (struct mfill_state){
969 		.ctx = ctx,
970 		.dst_start = dst_start,
971 		.src_start = src_start,
972 		.flags = flags,
973 		.len = len,
974 		.src_addr = src_start,
975 		.dst_addr = dst_start,
976 	};
977 	long copied = 0;
978 	ssize_t err;
979 
980 	/*
981 	 * Sanitize the command parameters:
982 	 */
983 	VM_WARN_ON_ONCE(dst_start & ~PAGE_MASK);
984 	VM_WARN_ON_ONCE(len & ~PAGE_MASK);
985 
986 	/* Does the address range wrap, or is the span zero-sized? */
987 	VM_WARN_ON_ONCE(src_start + len <= src_start);
988 	VM_WARN_ON_ONCE(dst_start + len <= dst_start);
989 
990 	err = mfill_get_vma(&state);
991 	if (err)
992 		goto out;
993 
994 	/*
995 	 * If this is a HUGETLB vma, pass off to appropriate routine
996 	 */
997 	if (is_vm_hugetlb_page(state.vma))
998 		return  mfill_atomic_hugetlb(ctx, state.vma, dst_start,
999 					     src_start, len, flags);
1000 
1001 	while (state.src_addr < src_start + len) {
1002 		VM_WARN_ON_ONCE(state.dst_addr >= dst_start + len);
1003 
1004 		err = mfill_establish_pmd(&state);
1005 		if (err)
1006 			break;
1007 
1008 		/*
1009 		 * For shmem mappings, khugepaged is allowed to remove page
1010 		 * tables under us; pte_offset_map_lock() will deal with that.
1011 		 */
1012 
1013 		err = mfill_atomic_pte(&state);
1014 		cond_resched();
1015 
1016 		if (!err) {
1017 			state.dst_addr += PAGE_SIZE;
1018 			state.src_addr += PAGE_SIZE;
1019 			copied += PAGE_SIZE;
1020 
1021 			if (fatal_signal_pending(current))
1022 				err = -EINTR;
1023 		}
1024 		if (err)
1025 			break;
1026 	}
1027 
1028 	mfill_put_vma(&state);
1029 out:
1030 	VM_WARN_ON_ONCE(copied < 0);
1031 	VM_WARN_ON_ONCE(err > 0);
1032 	VM_WARN_ON_ONCE(!copied && !err);
1033 	return copied ? copied : err;
1034 }
1035 
1036 static ssize_t mfill_atomic_copy(struct userfaultfd_ctx *ctx, unsigned long dst_start,
1037 			  unsigned long src_start, unsigned long len,
1038 			  uffd_flags_t flags)
1039 {
1040 	return mfill_atomic(ctx, dst_start, src_start, len,
1041 			    uffd_flags_set_mode(flags, MFILL_ATOMIC_COPY));
1042 }
1043 
1044 static ssize_t mfill_atomic_zeropage(struct userfaultfd_ctx *ctx,
1045 			      unsigned long start,
1046 			      unsigned long len)
1047 {
1048 	return mfill_atomic(ctx, start, 0, len,
1049 			    uffd_flags_set_mode(0, MFILL_ATOMIC_ZEROPAGE));
1050 }
1051 
1052 static ssize_t mfill_atomic_continue(struct userfaultfd_ctx *ctx, unsigned long start,
1053 			      unsigned long len, uffd_flags_t flags)
1054 {
1055 
1056 	/*
1057 	 * A caller might reasonably assume that UFFDIO_CONTINUE contains an
1058 	 * smp_wmb() to ensure that any writes to the about-to-be-mapped page by
1059 	 * the thread doing the UFFDIO_CONTINUE are guaranteed to be visible to
1060 	 * subsequent loads from the page through the newly mapped address range.
1061 	 */
1062 	smp_wmb();
1063 
1064 	return mfill_atomic(ctx, start, 0, len,
1065 			    uffd_flags_set_mode(flags, MFILL_ATOMIC_CONTINUE));
1066 }
1067 
1068 static ssize_t mfill_atomic_poison(struct userfaultfd_ctx *ctx, unsigned long start,
1069 			    unsigned long len, uffd_flags_t flags)
1070 {
1071 	return mfill_atomic(ctx, start, 0, len,
1072 			    uffd_flags_set_mode(flags, MFILL_ATOMIC_POISON));
1073 }
1074 
1075 long uffd_wp_range(struct vm_area_struct *dst_vma,
1076 		   unsigned long start, unsigned long len, bool enable_wp)
1077 {
1078 	unsigned int mm_cp_flags;
1079 	struct mmu_gather tlb;
1080 	long ret;
1081 
1082 	VM_WARN_ONCE(start < dst_vma->vm_start || start + len > dst_vma->vm_end,
1083 			"The address range exceeds VMA boundary.\n");
1084 	if (enable_wp)
1085 		mm_cp_flags = MM_CP_UFFD_WP;
1086 	else
1087 		mm_cp_flags = MM_CP_UFFD_WP_RESOLVE;
1088 
1089 	/*
1090 	 * vma->vm_page_prot already reflects that uffd-wp is enabled for this
1091 	 * VMA (see userfaultfd_set_vm_flags()) and that all PTEs are supposed
1092 	 * to be write-protected as default whenever protection changes.
1093 	 * Try upgrading write permissions manually.
1094 	 */
1095 	if (!enable_wp && vma_wants_manual_pte_write_upgrade(dst_vma))
1096 		mm_cp_flags |= MM_CP_TRY_CHANGE_WRITABLE;
1097 	tlb_gather_mmu(&tlb, dst_vma->vm_mm);
1098 	ret = change_protection(&tlb, dst_vma, start, start + len, mm_cp_flags);
1099 	tlb_finish_mmu(&tlb);
1100 
1101 	return ret;
1102 }
1103 
1104 static int mwriteprotect_range(struct userfaultfd_ctx *ctx, unsigned long start,
1105 			unsigned long len, bool enable_wp)
1106 {
1107 	struct mm_struct *dst_mm = ctx->mm;
1108 	unsigned long end = start + len;
1109 	unsigned long _start, _end;
1110 	struct vm_area_struct *dst_vma;
1111 	unsigned long page_mask;
1112 	long err;
1113 	VMA_ITERATOR(vmi, dst_mm, start);
1114 
1115 	/*
1116 	 * Sanitize the command parameters:
1117 	 */
1118 	VM_WARN_ON_ONCE(start & ~PAGE_MASK);
1119 	VM_WARN_ON_ONCE(len & ~PAGE_MASK);
1120 
1121 	/* Does the address range wrap, or is the span zero-sized? */
1122 	VM_WARN_ON_ONCE(start + len <= start);
1123 
1124 	mmap_read_lock(dst_mm);
1125 
1126 	/*
1127 	 * If memory mappings are changing because of non-cooperative
1128 	 * operation (e.g. mremap) running in parallel, bail out and
1129 	 * request the user to retry later
1130 	 */
1131 	down_read(&ctx->map_changing_lock);
1132 	err = -EAGAIN;
1133 	if (atomic_read(&ctx->mmap_changing))
1134 		goto out_unlock;
1135 
1136 	err = -ENOENT;
1137 	for_each_vma_range(vmi, dst_vma, end) {
1138 
1139 		if (!userfaultfd_wp(dst_vma)) {
1140 			err = -ENOENT;
1141 			break;
1142 		}
1143 
1144 		if (is_vm_hugetlb_page(dst_vma)) {
1145 			err = -EINVAL;
1146 			page_mask = vma_kernel_pagesize(dst_vma) - 1;
1147 			if ((start & page_mask) || (len & page_mask))
1148 				break;
1149 		}
1150 
1151 		_start = max(dst_vma->vm_start, start);
1152 		_end = min(dst_vma->vm_end, end);
1153 
1154 		err = uffd_wp_range(dst_vma, _start, _end - _start, enable_wp);
1155 
1156 		/* Return 0 on success, <0 on failures */
1157 		if (err < 0)
1158 			break;
1159 		err = 0;
1160 	}
1161 out_unlock:
1162 	up_read(&ctx->map_changing_lock);
1163 	mmap_read_unlock(dst_mm);
1164 	return err;
1165 }
1166 
1167 
1168 void double_pt_lock(spinlock_t *ptl1,
1169 		    spinlock_t *ptl2)
1170 	__acquires(ptl1)
1171 	__acquires(ptl2)
1172 {
1173 	if (ptl1 > ptl2)
1174 		swap(ptl1, ptl2);
1175 	/* lock in virtual address order to avoid lock inversion */
1176 	spin_lock(ptl1);
1177 	if (ptl1 != ptl2)
1178 		spin_lock_nested(ptl2, SINGLE_DEPTH_NESTING);
1179 	else
1180 		__acquire(ptl2);
1181 }
1182 
1183 void double_pt_unlock(spinlock_t *ptl1,
1184 		      spinlock_t *ptl2)
1185 	__releases(ptl1)
1186 	__releases(ptl2)
1187 {
1188 	spin_unlock(ptl1);
1189 	if (ptl1 != ptl2)
1190 		spin_unlock(ptl2);
1191 	else
1192 		__release(ptl2);
1193 }
1194 
1195 static inline bool is_pte_pages_stable(pte_t *dst_pte, pte_t *src_pte,
1196 				       pte_t orig_dst_pte, pte_t orig_src_pte,
1197 				       pmd_t *dst_pmd, pmd_t dst_pmdval)
1198 {
1199 	return pte_same(ptep_get(src_pte), orig_src_pte) &&
1200 	       pte_same(ptep_get(dst_pte), orig_dst_pte) &&
1201 	       pmd_same(dst_pmdval, pmdp_get_lockless(dst_pmd));
1202 }
1203 
1204 /*
1205  * Checks if the two ptes and the corresponding folio are eligible for batched
1206  * move. If so, then returns pointer to the locked folio. Otherwise, returns NULL.
1207  *
1208  * NOTE: folio's reference is not required as the whole operation is within
1209  * PTL's critical section.
1210  */
1211 static struct folio *check_ptes_for_batched_move(struct vm_area_struct *src_vma,
1212 						 unsigned long src_addr,
1213 						 pte_t *src_pte, pte_t *dst_pte)
1214 {
1215 	pte_t orig_dst_pte, orig_src_pte;
1216 	struct folio *folio;
1217 
1218 	orig_dst_pte = ptep_get(dst_pte);
1219 	if (!pte_none(orig_dst_pte))
1220 		return NULL;
1221 
1222 	orig_src_pte = ptep_get(src_pte);
1223 	if (!pte_present(orig_src_pte) || is_zero_pfn(pte_pfn(orig_src_pte)))
1224 		return NULL;
1225 
1226 	folio = vm_normal_folio(src_vma, src_addr, orig_src_pte);
1227 	if (!folio || !folio_trylock(folio))
1228 		return NULL;
1229 	if (!PageAnonExclusive(&folio->page) || folio_test_large(folio)) {
1230 		folio_unlock(folio);
1231 		return NULL;
1232 	}
1233 	return folio;
1234 }
1235 
1236 /*
1237  * Moves src folios to dst in a batch as long as they are not large, and can
1238  * successfully take the lock via folio_trylock().
1239  */
1240 static long move_present_ptes(struct mm_struct *mm,
1241 			      struct vm_area_struct *dst_vma,
1242 			      struct vm_area_struct *src_vma,
1243 			      unsigned long dst_addr, unsigned long src_addr,
1244 			      pte_t *dst_pte, pte_t *src_pte,
1245 			      pte_t orig_dst_pte, pte_t orig_src_pte,
1246 			      pmd_t *dst_pmd, pmd_t dst_pmdval,
1247 			      spinlock_t *dst_ptl, spinlock_t *src_ptl,
1248 			      struct folio **first_src_folio, unsigned long len)
1249 {
1250 	int err = 0;
1251 	struct folio *src_folio = *first_src_folio;
1252 	unsigned long src_start = src_addr;
1253 	unsigned long src_end;
1254 
1255 	len = pmd_addr_end(dst_addr, dst_addr + len) - dst_addr;
1256 	src_end = pmd_addr_end(src_addr, src_addr + len);
1257 	flush_cache_range(src_vma, src_addr, src_end);
1258 	double_pt_lock(dst_ptl, src_ptl);
1259 
1260 	if (!is_pte_pages_stable(dst_pte, src_pte, orig_dst_pte, orig_src_pte,
1261 				 dst_pmd, dst_pmdval)) {
1262 		err = -EAGAIN;
1263 		goto out;
1264 	}
1265 	if (folio_test_large(src_folio) ||
1266 	    folio_maybe_dma_pinned(src_folio) ||
1267 	    !PageAnonExclusive(&src_folio->page)) {
1268 		err = -EBUSY;
1269 		goto out;
1270 	}
1271 	/* It's safe to drop the reference now as the page-table is holding one. */
1272 	folio_put(*first_src_folio);
1273 	*first_src_folio = NULL;
1274 	lazy_mmu_mode_enable();
1275 
1276 	while (true) {
1277 		orig_src_pte = ptep_get_and_clear(mm, src_addr, src_pte);
1278 		/* Folio got pinned from under us. Put it back and fail the move. */
1279 		if (folio_maybe_dma_pinned(src_folio)) {
1280 			set_pte_at(mm, src_addr, src_pte, orig_src_pte);
1281 			err = -EBUSY;
1282 			break;
1283 		}
1284 
1285 		folio_move_anon_rmap(src_folio, dst_vma);
1286 		src_folio->index = linear_page_index(dst_vma, dst_addr);
1287 
1288 		orig_dst_pte = folio_mk_pte(src_folio, dst_vma->vm_page_prot);
1289 		/* Set soft dirty bit so userspace can notice the pte was moved */
1290 		if (pgtable_supports_soft_dirty())
1291 			orig_dst_pte = pte_mksoft_dirty(orig_dst_pte);
1292 		if (pte_dirty(orig_src_pte))
1293 			orig_dst_pte = pte_mkdirty(orig_dst_pte);
1294 		orig_dst_pte = pte_mkwrite(orig_dst_pte, dst_vma);
1295 		set_pte_at(mm, dst_addr, dst_pte, orig_dst_pte);
1296 
1297 		src_addr += PAGE_SIZE;
1298 		if (src_addr == src_end)
1299 			break;
1300 		dst_addr += PAGE_SIZE;
1301 		dst_pte++;
1302 		src_pte++;
1303 
1304 		folio_unlock(src_folio);
1305 		src_folio = check_ptes_for_batched_move(src_vma, src_addr,
1306 							src_pte, dst_pte);
1307 		if (!src_folio)
1308 			break;
1309 	}
1310 
1311 	lazy_mmu_mode_disable();
1312 	if (src_addr > src_start)
1313 		flush_tlb_range(src_vma, src_start, src_addr);
1314 
1315 	if (src_folio)
1316 		folio_unlock(src_folio);
1317 out:
1318 	double_pt_unlock(dst_ptl, src_ptl);
1319 	return src_addr > src_start ? src_addr - src_start : err;
1320 }
1321 
1322 static int move_swap_pte(struct mm_struct *mm, struct vm_area_struct *dst_vma,
1323 			 unsigned long dst_addr, unsigned long src_addr,
1324 			 pte_t *dst_pte, pte_t *src_pte,
1325 			 pte_t orig_dst_pte, pte_t orig_src_pte,
1326 			 pmd_t *dst_pmd, pmd_t dst_pmdval,
1327 			 spinlock_t *dst_ptl, spinlock_t *src_ptl,
1328 			 struct folio *src_folio,
1329 			 struct swap_info_struct *si, swp_entry_t entry)
1330 {
1331 	/*
1332 	 * Check if the folio still belongs to the target swap entry after
1333 	 * acquiring the lock. Folio can be freed in the swap cache while
1334 	 * not locked.
1335 	 */
1336 	if (src_folio && unlikely(!folio_test_swapcache(src_folio) ||
1337 				  entry.val != src_folio->swap.val))
1338 		return -EAGAIN;
1339 
1340 	double_pt_lock(dst_ptl, src_ptl);
1341 
1342 	if (!is_pte_pages_stable(dst_pte, src_pte, orig_dst_pte, orig_src_pte,
1343 				 dst_pmd, dst_pmdval)) {
1344 		double_pt_unlock(dst_ptl, src_ptl);
1345 		return -EAGAIN;
1346 	}
1347 
1348 	/*
1349 	 * The src_folio resides in the swapcache, requiring an update to its
1350 	 * index and mapping to align with the dst_vma, where a swap-in may
1351 	 * occur and hit the swapcache after moving the PTE.
1352 	 */
1353 	if (src_folio) {
1354 		folio_move_anon_rmap(src_folio, dst_vma);
1355 		src_folio->index = linear_page_index(dst_vma, dst_addr);
1356 	} else {
1357 		/*
1358 		 * Check if the swap entry is cached after acquiring the src_pte
1359 		 * lock. Otherwise, we might miss a newly loaded swap cache folio.
1360 		 *
1361 		 * We are trying to catch newly added swap cache, the only possible case is
1362 		 * when a folio is swapped in and out again staying in swap cache, using the
1363 		 * same entry before the PTE check above. The PTL is acquired and released
1364 		 * twice, each time after updating the swap table. So holding
1365 		 * the PTL here ensures we see the updated value.
1366 		 */
1367 		if (swap_cache_has_folio(entry)) {
1368 			double_pt_unlock(dst_ptl, src_ptl);
1369 			return -EAGAIN;
1370 		}
1371 	}
1372 
1373 	orig_src_pte = ptep_get_and_clear(mm, src_addr, src_pte);
1374 	if (pgtable_supports_soft_dirty())
1375 		orig_src_pte = pte_swp_mksoft_dirty(orig_src_pte);
1376 	set_pte_at(mm, dst_addr, dst_pte, orig_src_pte);
1377 	double_pt_unlock(dst_ptl, src_ptl);
1378 
1379 	return PAGE_SIZE;
1380 }
1381 
1382 static int move_zeropage_pte(struct mm_struct *mm,
1383 			     struct vm_area_struct *dst_vma,
1384 			     struct vm_area_struct *src_vma,
1385 			     unsigned long dst_addr, unsigned long src_addr,
1386 			     pte_t *dst_pte, pte_t *src_pte,
1387 			     pte_t orig_dst_pte, pte_t orig_src_pte,
1388 			     pmd_t *dst_pmd, pmd_t dst_pmdval,
1389 			     spinlock_t *dst_ptl, spinlock_t *src_ptl)
1390 {
1391 	pte_t zero_pte;
1392 
1393 	double_pt_lock(dst_ptl, src_ptl);
1394 	if (!is_pte_pages_stable(dst_pte, src_pte, orig_dst_pte, orig_src_pte,
1395 				 dst_pmd, dst_pmdval)) {
1396 		double_pt_unlock(dst_ptl, src_ptl);
1397 		return -EAGAIN;
1398 	}
1399 
1400 	zero_pte = pte_mkspecial(pfn_pte(zero_pfn(dst_addr),
1401 					 dst_vma->vm_page_prot));
1402 	ptep_clear_flush(src_vma, src_addr, src_pte);
1403 	set_pte_at(mm, dst_addr, dst_pte, zero_pte);
1404 	double_pt_unlock(dst_ptl, src_ptl);
1405 
1406 	return PAGE_SIZE;
1407 }
1408 
1409 
1410 /*
1411  * The mmap_lock for reading is held by the caller. Just move the page(s)
1412  * from src_pmd to dst_pmd if possible, and return number of bytes moved.
1413  * On failure, an error code is returned.
1414  */
1415 static long move_pages_ptes(struct mm_struct *mm, pmd_t *dst_pmd, pmd_t *src_pmd,
1416 			    struct vm_area_struct *dst_vma,
1417 			    struct vm_area_struct *src_vma,
1418 			    unsigned long dst_addr, unsigned long src_addr,
1419 			    unsigned long len, __u64 mode)
1420 {
1421 	struct swap_info_struct *si = NULL;
1422 	pte_t orig_src_pte, orig_dst_pte;
1423 	pte_t src_folio_pte;
1424 	spinlock_t *src_ptl, *dst_ptl;
1425 	pte_t *src_pte = NULL;
1426 	pte_t *dst_pte = NULL;
1427 	pmd_t dummy_pmdval;
1428 	pmd_t dst_pmdval;
1429 	struct folio *src_folio = NULL;
1430 	struct mmu_notifier_range range;
1431 	long ret = 0;
1432 
1433 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
1434 				src_addr, src_addr + len);
1435 	mmu_notifier_invalidate_range_start(&range);
1436 retry:
1437 	/*
1438 	 * Use the maywrite version to indicate that dst_pte will be modified,
1439 	 * since dst_pte needs to be none, the subsequent pte_same() check
1440 	 * cannot prevent the dst_pte page from being freed concurrently, so we
1441 	 * also need to obtain dst_pmdval and recheck pmd_same() later.
1442 	 */
1443 	dst_pte = pte_offset_map_rw_nolock(mm, dst_pmd, dst_addr, &dst_pmdval,
1444 					   &dst_ptl);
1445 
1446 	/* Retry if a huge pmd materialized from under us */
1447 	if (unlikely(!dst_pte)) {
1448 		ret = -EAGAIN;
1449 		goto out;
1450 	}
1451 
1452 	/*
1453 	 * Unlike dst_pte, the subsequent pte_same() check can ensure the
1454 	 * stability of the src_pte page, so there is no need to get pmdval,
1455 	 * just pass a dummy variable to it.
1456 	 */
1457 	src_pte = pte_offset_map_rw_nolock(mm, src_pmd, src_addr, &dummy_pmdval,
1458 					   &src_ptl);
1459 
1460 	/*
1461 	 * We held the mmap_lock for reading so MADV_DONTNEED
1462 	 * can zap transparent huge pages under us, or the
1463 	 * transparent huge page fault can establish new
1464 	 * transparent huge pages under us.
1465 	 */
1466 	if (unlikely(!src_pte)) {
1467 		ret = -EAGAIN;
1468 		goto out;
1469 	}
1470 
1471 	/* Sanity checks before the operation */
1472 	if (pmd_none(*dst_pmd) || pmd_none(*src_pmd) ||
1473 	    pmd_trans_huge(*dst_pmd) || pmd_trans_huge(*src_pmd)) {
1474 		ret = -EINVAL;
1475 		goto out;
1476 	}
1477 
1478 	spin_lock(dst_ptl);
1479 	orig_dst_pte = ptep_get(dst_pte);
1480 	spin_unlock(dst_ptl);
1481 	if (!pte_none(orig_dst_pte)) {
1482 		ret = -EEXIST;
1483 		goto out;
1484 	}
1485 
1486 	spin_lock(src_ptl);
1487 	orig_src_pte = ptep_get(src_pte);
1488 	spin_unlock(src_ptl);
1489 	if (pte_none(orig_src_pte)) {
1490 		if (!(mode & UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES))
1491 			ret = -ENOENT;
1492 		else /* nothing to do to move a hole */
1493 			ret = PAGE_SIZE;
1494 		goto out;
1495 	}
1496 
1497 	/* If PTE changed after we locked the folio then start over */
1498 	if (src_folio && unlikely(!pte_same(src_folio_pte, orig_src_pte))) {
1499 		ret = -EAGAIN;
1500 		goto out;
1501 	}
1502 
1503 	if (pte_present(orig_src_pte)) {
1504 		if (is_zero_pfn(pte_pfn(orig_src_pte))) {
1505 			ret = move_zeropage_pte(mm, dst_vma, src_vma,
1506 					       dst_addr, src_addr, dst_pte, src_pte,
1507 					       orig_dst_pte, orig_src_pte,
1508 					       dst_pmd, dst_pmdval, dst_ptl, src_ptl);
1509 			goto out;
1510 		}
1511 
1512 		/*
1513 		 * Pin and lock source folio. Since we are in RCU read section,
1514 		 * we can't block, so on contention have to unmap the ptes,
1515 		 * obtain the lock and retry.
1516 		 */
1517 		if (!src_folio) {
1518 			struct folio *folio;
1519 			bool locked;
1520 
1521 			/*
1522 			 * Pin the page while holding the lock to be sure the
1523 			 * page isn't freed under us
1524 			 */
1525 			spin_lock(src_ptl);
1526 			if (!pte_same(orig_src_pte, ptep_get(src_pte))) {
1527 				spin_unlock(src_ptl);
1528 				ret = -EAGAIN;
1529 				goto out;
1530 			}
1531 
1532 			folio = vm_normal_folio(src_vma, src_addr, orig_src_pte);
1533 			if (!folio || !PageAnonExclusive(&folio->page)) {
1534 				spin_unlock(src_ptl);
1535 				ret = -EBUSY;
1536 				goto out;
1537 			}
1538 
1539 			locked = folio_trylock(folio);
1540 			/*
1541 			 * We avoid waiting for folio lock with a raised
1542 			 * refcount for large folios because extra refcounts
1543 			 * will result in split_folio() failing later and
1544 			 * retrying.  If multiple tasks are trying to move a
1545 			 * large folio we can end up livelocking.
1546 			 */
1547 			if (!locked && folio_test_large(folio)) {
1548 				spin_unlock(src_ptl);
1549 				ret = -EAGAIN;
1550 				goto out;
1551 			}
1552 
1553 			folio_get(folio);
1554 			src_folio = folio;
1555 			src_folio_pte = orig_src_pte;
1556 			spin_unlock(src_ptl);
1557 
1558 			if (!locked) {
1559 				pte_unmap(src_pte);
1560 				pte_unmap(dst_pte);
1561 				src_pte = dst_pte = NULL;
1562 				/* now we can block and wait */
1563 				folio_lock(src_folio);
1564 				goto retry;
1565 			}
1566 
1567 			if (WARN_ON_ONCE(!folio_test_anon(src_folio))) {
1568 				ret = -EBUSY;
1569 				goto out;
1570 			}
1571 		}
1572 
1573 		/* at this point we have src_folio locked */
1574 		if (folio_test_large(src_folio)) {
1575 			/* split_folio() can block */
1576 			pte_unmap(src_pte);
1577 			pte_unmap(dst_pte);
1578 			src_pte = dst_pte = NULL;
1579 			ret = split_folio(src_folio);
1580 			if (ret)
1581 				goto out;
1582 			/* have to reacquire the folio after it got split */
1583 			folio_unlock(src_folio);
1584 			folio_put(src_folio);
1585 			src_folio = NULL;
1586 			goto retry;
1587 		}
1588 
1589 		ret = move_present_ptes(mm, dst_vma, src_vma,
1590 					dst_addr, src_addr, dst_pte, src_pte,
1591 					orig_dst_pte, orig_src_pte, dst_pmd,
1592 					dst_pmdval, dst_ptl, src_ptl, &src_folio,
1593 					len);
1594 	} else { /* !pte_present() */
1595 		struct folio *folio = NULL;
1596 		const softleaf_t entry = softleaf_from_pte(orig_src_pte);
1597 
1598 		if (softleaf_is_migration(entry)) {
1599 			pte_unmap(src_pte);
1600 			pte_unmap(dst_pte);
1601 			src_pte = dst_pte = NULL;
1602 			migration_entry_wait(mm, src_pmd, src_addr);
1603 
1604 			ret = -EAGAIN;
1605 			goto out;
1606 		} else if (!softleaf_is_swap(entry)) {
1607 			ret = -EFAULT;
1608 			goto out;
1609 		}
1610 
1611 		if (!pte_swp_exclusive(orig_src_pte)) {
1612 			ret = -EBUSY;
1613 			goto out;
1614 		}
1615 
1616 		si = get_swap_device(entry);
1617 		if (unlikely(!si)) {
1618 			ret = -EAGAIN;
1619 			goto out;
1620 		}
1621 		/*
1622 		 * Verify the existence of the swapcache. If present, the folio's
1623 		 * index and mapping must be updated even when the PTE is a swap
1624 		 * entry. The anon_vma lock is not taken during this process since
1625 		 * the folio has already been unmapped, and the swap entry is
1626 		 * exclusive, preventing rmap walks.
1627 		 *
1628 		 * For large folios, return -EBUSY immediately, as split_folio()
1629 		 * also returns -EBUSY when attempting to split unmapped large
1630 		 * folios in the swapcache. This issue needs to be resolved
1631 		 * separately to allow proper handling.
1632 		 */
1633 		if (!src_folio)
1634 			folio = swap_cache_get_folio(entry);
1635 		if (folio) {
1636 			if (folio_test_large(folio)) {
1637 				ret = -EBUSY;
1638 				folio_put(folio);
1639 				goto out;
1640 			}
1641 			src_folio = folio;
1642 			src_folio_pte = orig_src_pte;
1643 			if (!folio_trylock(src_folio)) {
1644 				pte_unmap(src_pte);
1645 				pte_unmap(dst_pte);
1646 				src_pte = dst_pte = NULL;
1647 				put_swap_device(si);
1648 				si = NULL;
1649 				/* now we can block and wait */
1650 				folio_lock(src_folio);
1651 				goto retry;
1652 			}
1653 		}
1654 		ret = move_swap_pte(mm, dst_vma, dst_addr, src_addr, dst_pte, src_pte,
1655 				orig_dst_pte, orig_src_pte, dst_pmd, dst_pmdval,
1656 				dst_ptl, src_ptl, src_folio, si, entry);
1657 	}
1658 
1659 out:
1660 	if (src_folio) {
1661 		folio_unlock(src_folio);
1662 		folio_put(src_folio);
1663 	}
1664 	/*
1665 	 * Unmap in reverse order (LIFO) to maintain proper kmap_local
1666 	 * index ordering when CONFIG_HIGHPTE is enabled. We mapped dst_pte
1667 	 * first, then src_pte, so we must unmap src_pte first, then dst_pte.
1668 	 */
1669 	if (src_pte)
1670 		pte_unmap(src_pte);
1671 	if (dst_pte)
1672 		pte_unmap(dst_pte);
1673 	mmu_notifier_invalidate_range_end(&range);
1674 	if (si)
1675 		put_swap_device(si);
1676 
1677 	return ret;
1678 }
1679 
1680 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1681 static inline bool move_splits_huge_pmd(unsigned long dst_addr,
1682 					unsigned long src_addr,
1683 					unsigned long src_end)
1684 {
1685 	return (src_addr & ~HPAGE_PMD_MASK) || (dst_addr & ~HPAGE_PMD_MASK) ||
1686 		src_end - src_addr < HPAGE_PMD_SIZE;
1687 }
1688 #else
1689 static inline bool move_splits_huge_pmd(unsigned long dst_addr,
1690 					unsigned long src_addr,
1691 					unsigned long src_end)
1692 {
1693 	/* This is unreachable anyway, just to avoid warnings when HPAGE_PMD_SIZE==0 */
1694 	return false;
1695 }
1696 #endif
1697 
1698 static inline bool vma_move_compatible(struct vm_area_struct *vma)
1699 {
1700 	return !(vma->vm_flags & (VM_PFNMAP | VM_IO |  VM_HUGETLB |
1701 				  VM_MIXEDMAP | VM_SHADOW_STACK));
1702 }
1703 
1704 static int validate_move_areas(struct userfaultfd_ctx *ctx,
1705 			       struct vm_area_struct *src_vma,
1706 			       struct vm_area_struct *dst_vma)
1707 {
1708 	/* Only allow moving if both have the same access and protection */
1709 	if ((src_vma->vm_flags & VM_ACCESS_FLAGS) != (dst_vma->vm_flags & VM_ACCESS_FLAGS) ||
1710 	    pgprot_val(src_vma->vm_page_prot) != pgprot_val(dst_vma->vm_page_prot))
1711 		return -EINVAL;
1712 
1713 	/* Only allow moving if both are mlocked or both aren't */
1714 	if ((src_vma->vm_flags & VM_LOCKED) != (dst_vma->vm_flags & VM_LOCKED))
1715 		return -EINVAL;
1716 
1717 	/*
1718 	 * For now, we keep it simple and only move between writable VMAs.
1719 	 * Access flags are equal, therefore checking only the source is enough.
1720 	 */
1721 	if (!(src_vma->vm_flags & VM_WRITE))
1722 		return -EINVAL;
1723 
1724 	/* Check if vma flags indicate content which can be moved */
1725 	if (!vma_move_compatible(src_vma) || !vma_move_compatible(dst_vma))
1726 		return -EINVAL;
1727 
1728 	/* Ensure dst_vma is registered in uffd we are operating on */
1729 	if (!dst_vma->vm_userfaultfd_ctx.ctx ||
1730 	    dst_vma->vm_userfaultfd_ctx.ctx != ctx)
1731 		return -EINVAL;
1732 
1733 	/* Only allow moving across anonymous vmas */
1734 	if (!vma_is_anonymous(src_vma) || !vma_is_anonymous(dst_vma))
1735 		return -EINVAL;
1736 
1737 	return 0;
1738 }
1739 
1740 static __always_inline
1741 int find_vmas_mm_locked(struct mm_struct *mm,
1742 			unsigned long dst_start,
1743 			unsigned long src_start,
1744 			struct vm_area_struct **dst_vmap,
1745 			struct vm_area_struct **src_vmap)
1746 {
1747 	struct vm_area_struct *vma;
1748 
1749 	mmap_assert_locked(mm);
1750 	vma = find_vma_and_prepare_anon(mm, dst_start);
1751 	if (IS_ERR(vma))
1752 		return PTR_ERR(vma);
1753 
1754 	*dst_vmap = vma;
1755 	/* Skip finding src_vma if src_start is in dst_vma */
1756 	if (src_start >= vma->vm_start && src_start < vma->vm_end)
1757 		goto out_success;
1758 
1759 	vma = vma_lookup(mm, src_start);
1760 	if (!vma)
1761 		return -ENOENT;
1762 out_success:
1763 	*src_vmap = vma;
1764 	return 0;
1765 }
1766 
1767 #ifdef CONFIG_PER_VMA_LOCK
1768 static int uffd_move_lock(struct mm_struct *mm,
1769 			  unsigned long dst_start,
1770 			  unsigned long src_start,
1771 			  struct vm_area_struct **dst_vmap,
1772 			  struct vm_area_struct **src_vmap)
1773 {
1774 	struct vm_area_struct *vma;
1775 	int err;
1776 
1777 	vma = uffd_lock_vma(mm, dst_start);
1778 	if (IS_ERR(vma))
1779 		return PTR_ERR(vma);
1780 
1781 	*dst_vmap = vma;
1782 	/*
1783 	 * Skip finding src_vma if src_start is in dst_vma. This also ensures
1784 	 * that we don't lock the same vma twice.
1785 	 */
1786 	if (src_start >= vma->vm_start && src_start < vma->vm_end) {
1787 		*src_vmap = vma;
1788 		return 0;
1789 	}
1790 
1791 	/*
1792 	 * Using uffd_lock_vma() to get src_vma can lead to following deadlock:
1793 	 *
1794 	 * Thread1				Thread2
1795 	 * -------				-------
1796 	 * vma_start_read(dst_vma)
1797 	 *					mmap_write_lock(mm)
1798 	 *					vma_start_write(src_vma)
1799 	 * vma_start_read(src_vma)
1800 	 * mmap_read_lock(mm)
1801 	 *					vma_start_write(dst_vma)
1802 	 */
1803 	*src_vmap = lock_vma_under_rcu(mm, src_start);
1804 	if (likely(*src_vmap))
1805 		return 0;
1806 
1807 	/* Undo any locking and retry in mmap_lock critical section */
1808 	vma_end_read(*dst_vmap);
1809 
1810 	mmap_read_lock(mm);
1811 	err = find_vmas_mm_locked(mm, dst_start, src_start, dst_vmap, src_vmap);
1812 	if (err)
1813 		goto out;
1814 
1815 	if (!vma_start_read_locked(*dst_vmap)) {
1816 		err = -EAGAIN;
1817 		goto out;
1818 	}
1819 
1820 	/* Nothing further to do if both vmas are locked. */
1821 	if (*dst_vmap == *src_vmap)
1822 		goto out;
1823 
1824 	if (!vma_start_read_locked_nested(*src_vmap, SINGLE_DEPTH_NESTING)) {
1825 		/* Undo dst_vmap locking if src_vmap failed to lock */
1826 		vma_end_read(*dst_vmap);
1827 		err = -EAGAIN;
1828 	}
1829 out:
1830 	mmap_read_unlock(mm);
1831 	return err;
1832 }
1833 
1834 static void uffd_move_unlock(struct vm_area_struct *dst_vma,
1835 			     struct vm_area_struct *src_vma)
1836 {
1837 	vma_end_read(src_vma);
1838 	if (src_vma != dst_vma)
1839 		vma_end_read(dst_vma);
1840 }
1841 
1842 #else
1843 
1844 static int uffd_move_lock(struct mm_struct *mm,
1845 			  unsigned long dst_start,
1846 			  unsigned long src_start,
1847 			  struct vm_area_struct **dst_vmap,
1848 			  struct vm_area_struct **src_vmap)
1849 {
1850 	int err;
1851 
1852 	mmap_read_lock(mm);
1853 	err = find_vmas_mm_locked(mm, dst_start, src_start, dst_vmap, src_vmap);
1854 	if (err)
1855 		mmap_read_unlock(mm);
1856 	return err;
1857 }
1858 
1859 static void uffd_move_unlock(struct vm_area_struct *dst_vma,
1860 			     struct vm_area_struct *src_vma)
1861 {
1862 	mmap_assert_locked(src_vma->vm_mm);
1863 	mmap_read_unlock(dst_vma->vm_mm);
1864 }
1865 #endif
1866 
1867 /**
1868  * move_pages - move arbitrary anonymous pages of an existing vma
1869  * @ctx: pointer to the userfaultfd context
1870  * @dst_start: start of the destination virtual memory range
1871  * @src_start: start of the source virtual memory range
1872  * @len: length of the virtual memory range
1873  * @mode: flags from uffdio_move.mode
1874  *
1875  * It will either use the mmap_lock in read mode or per-vma locks
1876  *
1877  * move_pages() remaps arbitrary anonymous pages atomically in zero
1878  * copy. It only works on non shared anonymous pages because those can
1879  * be relocated without generating non linear anon_vmas in the rmap
1880  * code.
1881  *
1882  * It provides a zero copy mechanism to handle userspace page faults.
1883  * The source vma pages should have mapcount == 1, which can be
1884  * enforced by using madvise(MADV_DONTFORK) on src vma.
1885  *
1886  * The thread receiving the page during the userland page fault
1887  * will receive the faulting page in the source vma through the network,
1888  * storage or any other I/O device (MADV_DONTFORK in the source vma
1889  * avoids move_pages() to fail with -EBUSY if the process forks before
1890  * move_pages() is called), then it will call move_pages() to map the
1891  * page in the faulting address in the destination vma.
1892  *
1893  * This userfaultfd command works purely via pagetables, so it's the
1894  * most efficient way to move physical non shared anonymous pages
1895  * across different virtual addresses. Unlike mremap()/mmap()/munmap()
1896  * it does not create any new vmas. The mapping in the destination
1897  * address is atomic.
1898  *
1899  * It only works if the vma protection bits are identical from the
1900  * source and destination vma.
1901  *
1902  * It can remap non shared anonymous pages within the same vma too.
1903  *
1904  * If the source virtual memory range has any unmapped holes, or if
1905  * the destination virtual memory range is not a whole unmapped hole,
1906  * move_pages() will fail respectively with -ENOENT or -EEXIST. This
1907  * provides a very strict behavior to avoid any chance of memory
1908  * corruption going unnoticed if there are userland race conditions.
1909  * Only one thread should resolve the userland page fault at any given
1910  * time for any given faulting address. This means that if two threads
1911  * try to both call move_pages() on the same destination address at the
1912  * same time, the second thread will get an explicit error from this
1913  * command.
1914  *
1915  * The command retval will return "len" is successful. The command
1916  * however can be interrupted by fatal signals or errors. If
1917  * interrupted it will return the number of bytes successfully
1918  * remapped before the interruption if any, or the negative error if
1919  * none. It will never return zero. Either it will return an error or
1920  * an amount of bytes successfully moved. If the retval reports a
1921  * "short" remap, the move_pages() command should be repeated by
1922  * userland with src+retval, dst+reval, len-retval if it wants to know
1923  * about the error that interrupted it.
1924  *
1925  * The UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES flag can be specified to
1926  * prevent -ENOENT errors to materialize if there are holes in the
1927  * source virtual range that is being remapped. The holes will be
1928  * accounted as successfully remapped in the retval of the
1929  * command. This is mostly useful to remap hugepage naturally aligned
1930  * virtual regions without knowing if there are transparent hugepage
1931  * in the regions or not, but preventing the risk of having to split
1932  * the hugepmd during the remap.
1933  */
1934 static ssize_t move_pages(struct userfaultfd_ctx *ctx, unsigned long dst_start,
1935 		   unsigned long src_start, unsigned long len, __u64 mode)
1936 {
1937 	struct mm_struct *mm = ctx->mm;
1938 	struct vm_area_struct *src_vma, *dst_vma;
1939 	unsigned long src_addr, dst_addr, src_end;
1940 	pmd_t *src_pmd, *dst_pmd;
1941 	long err = -EINVAL;
1942 	ssize_t moved = 0;
1943 
1944 	/* Sanitize the command parameters. */
1945 	VM_WARN_ON_ONCE(src_start & ~PAGE_MASK);
1946 	VM_WARN_ON_ONCE(dst_start & ~PAGE_MASK);
1947 	VM_WARN_ON_ONCE(len & ~PAGE_MASK);
1948 
1949 	/* Does the address range wrap, or is the span zero-sized? */
1950 	VM_WARN_ON_ONCE(src_start + len < src_start);
1951 	VM_WARN_ON_ONCE(dst_start + len < dst_start);
1952 
1953 	err = uffd_move_lock(mm, dst_start, src_start, &dst_vma, &src_vma);
1954 	if (err)
1955 		goto out;
1956 
1957 	/* Re-check after taking map_changing_lock */
1958 	err = -EAGAIN;
1959 	down_read(&ctx->map_changing_lock);
1960 	if (likely(atomic_read(&ctx->mmap_changing)))
1961 		goto out_unlock;
1962 	/*
1963 	 * Make sure the vma is not shared, that the src and dst remap
1964 	 * ranges are both valid and fully within a single existing
1965 	 * vma.
1966 	 */
1967 	err = -EINVAL;
1968 	if (src_vma->vm_flags & VM_SHARED)
1969 		goto out_unlock;
1970 	if (src_start + len > src_vma->vm_end)
1971 		goto out_unlock;
1972 
1973 	if (dst_vma->vm_flags & VM_SHARED)
1974 		goto out_unlock;
1975 	if (dst_start + len > dst_vma->vm_end)
1976 		goto out_unlock;
1977 
1978 	err = validate_move_areas(ctx, src_vma, dst_vma);
1979 	if (err)
1980 		goto out_unlock;
1981 
1982 	for (src_addr = src_start, dst_addr = dst_start, src_end = src_start + len;
1983 	     src_addr < src_end;) {
1984 		spinlock_t *ptl;
1985 		pmd_t dst_pmdval;
1986 		unsigned long step_size;
1987 
1988 		/*
1989 		 * Below works because anonymous area would not have a
1990 		 * transparent huge PUD. If file-backed support is added,
1991 		 * that case would need to be handled here.
1992 		 */
1993 		src_pmd = mm_find_pmd(mm, src_addr);
1994 		if (unlikely(!src_pmd)) {
1995 			if (!(mode & UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES)) {
1996 				err = -ENOENT;
1997 				break;
1998 			}
1999 			src_pmd = mm_alloc_pmd(mm, src_addr);
2000 			if (unlikely(!src_pmd)) {
2001 				err = -ENOMEM;
2002 				break;
2003 			}
2004 		}
2005 		dst_pmd = mm_alloc_pmd(mm, dst_addr);
2006 		if (unlikely(!dst_pmd)) {
2007 			err = -ENOMEM;
2008 			break;
2009 		}
2010 
2011 		dst_pmdval = pmdp_get_lockless(dst_pmd);
2012 		/*
2013 		 * If the dst_pmd is mapped as THP don't override it and just
2014 		 * be strict. If dst_pmd changes into TPH after this check, the
2015 		 * move_pages_huge_pmd() will detect the change and retry
2016 		 * while move_pages_pte() will detect the change and fail.
2017 		 */
2018 		if (unlikely(pmd_trans_huge(dst_pmdval))) {
2019 			err = -EEXIST;
2020 			break;
2021 		}
2022 
2023 		ptl = pmd_trans_huge_lock(src_pmd, src_vma);
2024 		if (ptl) {
2025 			/* Check if we can move the pmd without splitting it. */
2026 			if (move_splits_huge_pmd(dst_addr, src_addr, src_start + len) ||
2027 			    !pmd_none(dst_pmdval)) {
2028 				/* Can be a migration entry */
2029 				if (pmd_present(*src_pmd)) {
2030 					struct folio *folio = pmd_folio(*src_pmd);
2031 
2032 					if (!is_huge_zero_folio(folio) &&
2033 					    !PageAnonExclusive(&folio->page)) {
2034 						spin_unlock(ptl);
2035 						err = -EBUSY;
2036 						break;
2037 					}
2038 				}
2039 
2040 				spin_unlock(ptl);
2041 				split_huge_pmd(src_vma, src_pmd, src_addr);
2042 				/* The folio will be split by move_pages_pte() */
2043 				continue;
2044 			}
2045 
2046 			err = move_pages_huge_pmd(mm, dst_pmd, src_pmd,
2047 						  dst_pmdval, dst_vma, src_vma,
2048 						  dst_addr, src_addr);
2049 			step_size = HPAGE_PMD_SIZE;
2050 		} else {
2051 			long ret;
2052 
2053 			if (pmd_none(*src_pmd)) {
2054 				if (!(mode & UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES)) {
2055 					err = -ENOENT;
2056 					break;
2057 				}
2058 				if (unlikely(__pte_alloc(mm, src_pmd))) {
2059 					err = -ENOMEM;
2060 					break;
2061 				}
2062 			}
2063 
2064 			if (unlikely(pte_alloc(mm, dst_pmd))) {
2065 				err = -ENOMEM;
2066 				break;
2067 			}
2068 
2069 			ret = move_pages_ptes(mm, dst_pmd, src_pmd,
2070 					      dst_vma, src_vma, dst_addr,
2071 					      src_addr, src_end - src_addr, mode);
2072 			if (ret < 0)
2073 				err = ret;
2074 			else
2075 				step_size = ret;
2076 		}
2077 
2078 		cond_resched();
2079 
2080 		if (fatal_signal_pending(current)) {
2081 			/* Do not override an error */
2082 			if (!err || err == -EAGAIN)
2083 				err = -EINTR;
2084 			break;
2085 		}
2086 
2087 		if (err) {
2088 			if (err == -EAGAIN)
2089 				continue;
2090 			break;
2091 		}
2092 
2093 		/* Proceed to the next page */
2094 		dst_addr += step_size;
2095 		src_addr += step_size;
2096 		moved += step_size;
2097 	}
2098 
2099 out_unlock:
2100 	up_read(&ctx->map_changing_lock);
2101 	uffd_move_unlock(dst_vma, src_vma);
2102 out:
2103 	VM_WARN_ON_ONCE(moved < 0);
2104 	VM_WARN_ON_ONCE(err > 0);
2105 	VM_WARN_ON_ONCE(!moved && !err);
2106 	return moved ? moved : err;
2107 }
2108 
2109 static bool vma_can_userfault(struct vm_area_struct *vma, vm_flags_t vm_flags,
2110 		       bool wp_async)
2111 {
2112 	const struct vm_uffd_ops *ops = vma_uffd_ops(vma);
2113 
2114 	if (vma->vm_flags & (VM_DROPPABLE | VM_SHADOW_STACK))
2115 		return false;
2116 
2117 	if (!is_vm_hugetlb_page(vma) && (vma->vm_flags & VM_SPECIAL))
2118 		return false;
2119 
2120 	vm_flags &= __VM_UFFD_FLAGS;
2121 
2122 	/*
2123 	 * If WP is the only mode enabled and context is wp async, allow any
2124 	 * memory type.
2125 	 */
2126 	if (wp_async && (vm_flags == VM_UFFD_WP))
2127 		return true;
2128 
2129 	/* For any other mode reject VMAs that don't implement vm_uffd_ops */
2130 	if (!ops)
2131 		return false;
2132 
2133 	/*
2134 	 * If user requested uffd-wp but not enabled pte markers for
2135 	 * uffd-wp, then only anonymous memory is supported
2136 	 */
2137 	if (!uffd_supports_wp_marker() && (vm_flags & VM_UFFD_WP) &&
2138 	    !vma_is_anonymous(vma))
2139 		return false;
2140 
2141 	return ops->can_userfault(vma, vm_flags);
2142 }
2143 
2144 static void userfaultfd_set_vm_flags(struct vm_area_struct *vma,
2145 				     vm_flags_t vm_flags)
2146 {
2147 	const bool uffd_wp_changed = (vma->vm_flags ^ vm_flags) & VM_UFFD_WP;
2148 
2149 	vm_flags_reset(vma, vm_flags);
2150 	/*
2151 	 * For shared mappings, we want to enable writenotify while
2152 	 * userfaultfd-wp is enabled (see vma_wants_writenotify()). We'll simply
2153 	 * recalculate vma->vm_page_prot whenever userfaultfd-wp changes.
2154 	 */
2155 	if ((vma->vm_flags & VM_SHARED) && uffd_wp_changed)
2156 		vma_set_page_prot(vma);
2157 }
2158 
2159 static void userfaultfd_set_ctx(struct vm_area_struct *vma,
2160 				struct userfaultfd_ctx *ctx,
2161 				vm_flags_t vm_flags)
2162 {
2163 	vma_start_write(vma);
2164 	vma->vm_userfaultfd_ctx = (struct vm_userfaultfd_ctx){ctx};
2165 	userfaultfd_set_vm_flags(vma,
2166 				 (vma->vm_flags & ~__VM_UFFD_FLAGS) | vm_flags);
2167 }
2168 
2169 static void userfaultfd_reset_ctx(struct vm_area_struct *vma)
2170 {
2171 	userfaultfd_set_ctx(vma, NULL, 0);
2172 }
2173 
2174 static struct vm_area_struct *userfaultfd_clear_vma(struct vma_iterator *vmi,
2175 					     struct vm_area_struct *prev,
2176 					     struct vm_area_struct *vma,
2177 					     unsigned long start,
2178 					     unsigned long end)
2179 {
2180 	struct vm_area_struct *ret;
2181 	bool give_up_on_oom = false;
2182 	vma_flags_t new_vma_flags = vma->flags;
2183 
2184 	vma_flags_clear_mask(&new_vma_flags, __VMA_UFFD_FLAGS);
2185 
2186 	/*
2187 	 * If we are modifying only and not splitting, just give up on the merge
2188 	 * if OOM prevents us from merging successfully.
2189 	 */
2190 	if (start == vma->vm_start && end == vma->vm_end)
2191 		give_up_on_oom = true;
2192 
2193 	/* Reset ptes for the whole vma range if wr-protected */
2194 	if (userfaultfd_wp(vma))
2195 		uffd_wp_range(vma, start, end - start, false);
2196 
2197 	ret = vma_modify_flags_uffd(vmi, prev, vma, start, end,
2198 				    &new_vma_flags, NULL_VM_UFFD_CTX,
2199 				    give_up_on_oom);
2200 
2201 	/*
2202 	 * In the vma_merge() successful mprotect-like case 8:
2203 	 * the next vma was merged into the current one and
2204 	 * the current one has not been updated yet.
2205 	 */
2206 	if (!IS_ERR(ret))
2207 		userfaultfd_reset_ctx(ret);
2208 
2209 	return ret;
2210 }
2211 
2212 /* Assumes mmap write lock taken, and mm_struct pinned. */
2213 static int userfaultfd_register_range(struct userfaultfd_ctx *ctx,
2214 			       struct vm_area_struct *vma,
2215 			       vm_flags_t vm_flags,
2216 			       unsigned long start, unsigned long end,
2217 			       bool wp_async)
2218 {
2219 	vma_flags_t vma_flags = legacy_to_vma_flags(vm_flags);
2220 	VMA_ITERATOR(vmi, ctx->mm, start);
2221 	struct vm_area_struct *prev = vma_prev(&vmi);
2222 	unsigned long vma_end;
2223 	vma_flags_t new_vma_flags;
2224 
2225 	if (vma->vm_start < start)
2226 		prev = vma;
2227 
2228 	for_each_vma_range(vmi, vma, end) {
2229 		cond_resched();
2230 
2231 		VM_WARN_ON_ONCE(!vma_can_userfault(vma, vm_flags, wp_async));
2232 		VM_WARN_ON_ONCE(vma->vm_userfaultfd_ctx.ctx &&
2233 				vma->vm_userfaultfd_ctx.ctx != ctx);
2234 		VM_WARN_ON_ONCE(!vma_test(vma, VMA_MAYWRITE_BIT));
2235 
2236 		/*
2237 		 * Nothing to do: this vma is already registered into this
2238 		 * userfaultfd and with the right tracking mode too.
2239 		 */
2240 		if (vma->vm_userfaultfd_ctx.ctx == ctx &&
2241 		    vma_test_all_mask(vma, vma_flags))
2242 			goto skip;
2243 
2244 		if (vma->vm_start > start)
2245 			start = vma->vm_start;
2246 		vma_end = min(end, vma->vm_end);
2247 
2248 		new_vma_flags = vma->flags;
2249 		vma_flags_clear_mask(&new_vma_flags, __VMA_UFFD_FLAGS);
2250 		vma_flags_set_mask(&new_vma_flags, vma_flags);
2251 
2252 		vma = vma_modify_flags_uffd(&vmi, prev, vma, start, vma_end,
2253 					    &new_vma_flags,
2254 					    (struct vm_userfaultfd_ctx){ctx},
2255 					    /* give_up_on_oom = */false);
2256 		if (IS_ERR(vma))
2257 			return PTR_ERR(vma);
2258 
2259 		/*
2260 		 * In the vma_merge() successful mprotect-like case 8:
2261 		 * the next vma was merged into the current one and
2262 		 * the current one has not been updated yet.
2263 		 */
2264 		userfaultfd_set_ctx(vma, ctx, vm_flags);
2265 
2266 		if (is_vm_hugetlb_page(vma) && uffd_disable_huge_pmd_share(vma))
2267 			hugetlb_unshare_all_pmds(vma);
2268 
2269 skip:
2270 		prev = vma;
2271 		start = vma->vm_end;
2272 	}
2273 
2274 	return 0;
2275 }
2276 
2277 static void userfaultfd_release_new(struct userfaultfd_ctx *ctx)
2278 {
2279 	struct mm_struct *mm = ctx->mm;
2280 	struct vm_area_struct *vma;
2281 	VMA_ITERATOR(vmi, mm, 0);
2282 
2283 	/* the various vma->vm_userfaultfd_ctx still points to it */
2284 	mmap_write_lock(mm);
2285 	for_each_vma(vmi, vma) {
2286 		if (vma->vm_userfaultfd_ctx.ctx == ctx)
2287 			userfaultfd_reset_ctx(vma);
2288 	}
2289 	mmap_write_unlock(mm);
2290 }
2291 
2292 static void userfaultfd_release_all(struct mm_struct *mm,
2293 			     struct userfaultfd_ctx *ctx)
2294 {
2295 	struct vm_area_struct *vma, *prev;
2296 	VMA_ITERATOR(vmi, mm, 0);
2297 
2298 	if (!mmget_not_zero(mm))
2299 		return;
2300 
2301 	/*
2302 	 * Flush page faults out of all CPUs. NOTE: all page faults
2303 	 * must be retried without returning VM_FAULT_SIGBUS if
2304 	 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
2305 	 * changes while handle_userfault released the mmap_lock. So
2306 	 * it's critical that released is set to true (above), before
2307 	 * taking the mmap_lock for writing.
2308 	 */
2309 	mmap_write_lock(mm);
2310 	prev = NULL;
2311 	for_each_vma(vmi, vma) {
2312 		cond_resched();
2313 		VM_WARN_ON_ONCE(!!vma->vm_userfaultfd_ctx.ctx ^
2314 				!!(vma->vm_flags & __VM_UFFD_FLAGS));
2315 		if (vma->vm_userfaultfd_ctx.ctx != ctx) {
2316 			prev = vma;
2317 			continue;
2318 		}
2319 
2320 		vma = userfaultfd_clear_vma(&vmi, prev, vma,
2321 					    vma->vm_start, vma->vm_end);
2322 		prev = vma;
2323 	}
2324 	mmap_write_unlock(mm);
2325 	mmput(mm);
2326 }
2327 
2328 static int sysctl_unprivileged_userfaultfd __read_mostly;
2329 
2330 #ifdef CONFIG_SYSCTL
2331 static const struct ctl_table vm_userfaultfd_table[] = {
2332 	{
2333 		.procname	= "unprivileged_userfaultfd",
2334 		.data		= &sysctl_unprivileged_userfaultfd,
2335 		.maxlen		= sizeof(sysctl_unprivileged_userfaultfd),
2336 		.mode		= 0644,
2337 		.proc_handler	= proc_dointvec_minmax,
2338 		.extra1		= SYSCTL_ZERO,
2339 		.extra2		= SYSCTL_ONE,
2340 	},
2341 };
2342 #endif
2343 
2344 static struct kmem_cache *userfaultfd_ctx_cachep __ro_after_init;
2345 
2346 struct userfaultfd_fork_ctx {
2347 	struct userfaultfd_ctx *orig;
2348 	struct userfaultfd_ctx *new;
2349 	struct list_head list;
2350 };
2351 
2352 struct userfaultfd_unmap_ctx {
2353 	struct userfaultfd_ctx *ctx;
2354 	unsigned long start;
2355 	unsigned long end;
2356 	struct list_head list;
2357 };
2358 
2359 struct userfaultfd_wait_queue {
2360 	struct uffd_msg msg;
2361 	wait_queue_entry_t wq;
2362 	struct userfaultfd_ctx *ctx;
2363 	bool waken;
2364 };
2365 
2366 struct userfaultfd_wake_range {
2367 	unsigned long start;
2368 	unsigned long len;
2369 };
2370 
2371 /* internal indication that UFFD_API ioctl was successfully executed */
2372 #define UFFD_FEATURE_INITIALIZED		(1u << 31)
2373 
2374 static bool userfaultfd_is_initialized(struct userfaultfd_ctx *ctx)
2375 {
2376 	return ctx->features & UFFD_FEATURE_INITIALIZED;
2377 }
2378 
2379 static bool userfaultfd_wp_async_ctx(struct userfaultfd_ctx *ctx)
2380 {
2381 	return ctx && (ctx->features & UFFD_FEATURE_WP_ASYNC);
2382 }
2383 
2384 /*
2385  * Whether WP_UNPOPULATED is enabled on the uffd context.  It is only
2386  * meaningful when userfaultfd_wp()==true on the vma and when it's
2387  * anonymous.
2388  */
2389 bool userfaultfd_wp_unpopulated(struct vm_area_struct *vma)
2390 {
2391 	struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
2392 
2393 	if (!ctx)
2394 		return false;
2395 
2396 	return ctx->features & UFFD_FEATURE_WP_UNPOPULATED;
2397 }
2398 
2399 static int userfaultfd_wake_function(wait_queue_entry_t *wq, unsigned mode,
2400 				     int wake_flags, void *key)
2401 {
2402 	struct userfaultfd_wake_range *range = key;
2403 	int ret;
2404 	struct userfaultfd_wait_queue *uwq;
2405 	unsigned long start, len;
2406 
2407 	uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
2408 	ret = 0;
2409 	/* len == 0 means wake all */
2410 	start = range->start;
2411 	len = range->len;
2412 	if (len && (start > uwq->msg.arg.pagefault.address ||
2413 		    start + len <= uwq->msg.arg.pagefault.address))
2414 		goto out;
2415 	WRITE_ONCE(uwq->waken, true);
2416 	/*
2417 	 * The Program-Order guarantees provided by the scheduler
2418 	 * ensure uwq->waken is visible before the task is woken.
2419 	 */
2420 	ret = wake_up_state(wq->private, mode);
2421 	if (ret) {
2422 		/*
2423 		 * Wake only once, autoremove behavior.
2424 		 *
2425 		 * After the effect of list_del_init is visible to the other
2426 		 * CPUs, the waitqueue may disappear from under us, see the
2427 		 * !list_empty_careful() in handle_userfault().
2428 		 *
2429 		 * try_to_wake_up() has an implicit smp_mb(), and the
2430 		 * wq->private is read before calling the extern function
2431 		 * "wake_up_state" (which in turns calls try_to_wake_up).
2432 		 */
2433 		list_del_init(&wq->entry);
2434 	}
2435 out:
2436 	return ret;
2437 }
2438 
2439 /**
2440  * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
2441  * context.
2442  * @ctx: [in] Pointer to the userfaultfd context.
2443  */
2444 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
2445 {
2446 	refcount_inc(&ctx->refcount);
2447 }
2448 
2449 /**
2450  * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
2451  * context.
2452  * @ctx: [in] Pointer to userfaultfd context.
2453  *
2454  * The userfaultfd context reference must have been previously acquired either
2455  * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
2456  */
2457 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
2458 {
2459 	if (refcount_dec_and_test(&ctx->refcount)) {
2460 		VM_WARN_ON_ONCE(spin_is_locked(&ctx->fault_pending_wqh.lock));
2461 		VM_WARN_ON_ONCE(waitqueue_active(&ctx->fault_pending_wqh));
2462 		VM_WARN_ON_ONCE(spin_is_locked(&ctx->fault_wqh.lock));
2463 		VM_WARN_ON_ONCE(waitqueue_active(&ctx->fault_wqh));
2464 		VM_WARN_ON_ONCE(spin_is_locked(&ctx->event_wqh.lock));
2465 		VM_WARN_ON_ONCE(waitqueue_active(&ctx->event_wqh));
2466 		VM_WARN_ON_ONCE(spin_is_locked(&ctx->fd_wqh.lock));
2467 		VM_WARN_ON_ONCE(waitqueue_active(&ctx->fd_wqh));
2468 		mmdrop(ctx->mm);
2469 		kmem_cache_free(userfaultfd_ctx_cachep, ctx);
2470 	}
2471 }
2472 
2473 static inline void msg_init(struct uffd_msg *msg)
2474 {
2475 	BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
2476 	/*
2477 	 * Must use memset to zero out the paddings or kernel data is
2478 	 * leaked to userland.
2479 	 */
2480 	memset(msg, 0, sizeof(struct uffd_msg));
2481 }
2482 
2483 static inline struct uffd_msg userfault_msg(unsigned long address,
2484 					    unsigned long real_address,
2485 					    unsigned int flags,
2486 					    unsigned long reason,
2487 					    unsigned int features)
2488 {
2489 	struct uffd_msg msg;
2490 
2491 	msg_init(&msg);
2492 	msg.event = UFFD_EVENT_PAGEFAULT;
2493 
2494 	msg.arg.pagefault.address = (features & UFFD_FEATURE_EXACT_ADDRESS) ?
2495 				    real_address : address;
2496 
2497 	/*
2498 	 * These flags indicate why the userfault occurred:
2499 	 * - UFFD_PAGEFAULT_FLAG_WP indicates a write protect fault.
2500 	 * - UFFD_PAGEFAULT_FLAG_MINOR indicates a minor fault.
2501 	 * - Neither of these flags being set indicates a MISSING fault.
2502 	 *
2503 	 * Separately, UFFD_PAGEFAULT_FLAG_WRITE indicates it was a write
2504 	 * fault. Otherwise, it was a read fault.
2505 	 */
2506 	if (flags & FAULT_FLAG_WRITE)
2507 		msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
2508 	if (reason & VM_UFFD_WP)
2509 		msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
2510 	if (reason & VM_UFFD_MINOR)
2511 		msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_MINOR;
2512 	if (features & UFFD_FEATURE_THREAD_ID)
2513 		msg.arg.pagefault.feat.ptid = task_pid_vnr(current);
2514 	return msg;
2515 }
2516 
2517 #ifdef CONFIG_HUGETLB_PAGE
2518 /*
2519  * Same functionality as userfaultfd_must_wait below with modifications for
2520  * hugepmd ranges.
2521  */
2522 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
2523 					      struct vm_fault *vmf,
2524 					      unsigned long reason)
2525 {
2526 	struct vm_area_struct *vma = vmf->vma;
2527 	pte_t *ptep, pte;
2528 
2529 	assert_fault_locked(vmf);
2530 
2531 	ptep = hugetlb_walk(vma, vmf->address, vma_mmu_pagesize(vma));
2532 	if (!ptep)
2533 		return true;
2534 
2535 	pte = huge_ptep_get(vma->vm_mm, vmf->address, ptep);
2536 
2537 	/*
2538 	 * Lockless access: we're in a wait_event so it's ok if it
2539 	 * changes under us.
2540 	 */
2541 
2542 	/* Entry is still missing, wait for userspace to resolve the fault. */
2543 	if (huge_pte_none(pte))
2544 		return true;
2545 	/* UFFD PTE markers require userspace to resolve the fault. */
2546 	if (pte_is_uffd_marker(pte))
2547 		return true;
2548 	/*
2549 	 * Concurrent migration may have replaced the present PTE with a
2550 	 * non-marker swap entry between fault delivery and this lockless
2551 	 * re-check. huge_pte_write() on a swap entry decodes random offset
2552 	 * bits, so gate it on pte_present(). The migration completion path
2553 	 * will re-deliver the fault if it still needs userspace.
2554 	 */
2555 	if (!pte_present(pte))
2556 		return false;
2557 	/*
2558 	 * If VMA has UFFD WP faults enabled and WP fault, wait for userspace to
2559 	 * resolve the fault.
2560 	 */
2561 	if (!huge_pte_write(pte) && (reason & VM_UFFD_WP))
2562 		return true;
2563 
2564 	return false;
2565 }
2566 #else
2567 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
2568 					      struct vm_fault *vmf,
2569 					      unsigned long reason)
2570 {
2571 	/* Should never get here. */
2572 	VM_WARN_ON_ONCE(1);
2573 	return false;
2574 }
2575 #endif /* CONFIG_HUGETLB_PAGE */
2576 
2577 /*
2578  * Verify the pagetables are still not ok after having registered into
2579  * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
2580  * userfault that has already been resolved, if userfaultfd_read_iter and
2581  * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
2582  * threads.
2583  */
2584 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
2585 					 struct vm_fault *vmf,
2586 					 unsigned long reason)
2587 {
2588 	struct mm_struct *mm = ctx->mm;
2589 	unsigned long address = vmf->address;
2590 	pgd_t *pgd;
2591 	p4d_t *p4d;
2592 	pud_t *pud;
2593 	pmd_t *pmd, _pmd;
2594 	pte_t *pte;
2595 	pte_t ptent;
2596 	bool ret;
2597 
2598 	assert_fault_locked(vmf);
2599 
2600 	pgd = pgd_offset(mm, address);
2601 	if (!pgd_present(*pgd))
2602 		return true;
2603 	p4d = p4d_offset(pgd, address);
2604 	if (!p4d_present(*p4d))
2605 		return true;
2606 	pud = pud_offset(p4d, address);
2607 	if (!pud_present(*pud))
2608 		return true;
2609 	pmd = pmd_offset(pud, address);
2610 again:
2611 	_pmd = pmdp_get_lockless(pmd);
2612 	if (pmd_none(_pmd))
2613 		return true;
2614 
2615 	/*
2616 	 * A race could arise which would result in a softleaf entry such as
2617 	 * migration entry unexpectedly being present in the PMD, so explicitly
2618 	 * check for this and bail out if so.
2619 	 */
2620 	if (!pmd_present(_pmd))
2621 		return false;
2622 
2623 	if (pmd_trans_huge(_pmd))
2624 		return !pmd_write(_pmd) && (reason & VM_UFFD_WP);
2625 
2626 	pte = pte_offset_map(pmd, address);
2627 	if (!pte)
2628 		goto again;
2629 
2630 	/*
2631 	 * Lockless access: we're in a wait_event so it's ok if it
2632 	 * changes under us.
2633 	 */
2634 	ptent = ptep_get(pte);
2635 
2636 	ret = true;
2637 	/* Entry is still missing, wait for userspace to resolve the fault. */
2638 	if (pte_none(ptent))
2639 		goto out;
2640 	/* UFFD PTE markers require userspace to resolve the fault. */
2641 	if (pte_is_uffd_marker(ptent))
2642 		goto out;
2643 	/*
2644 	 * Concurrent swap-out / migration may have replaced the present PTE
2645 	 * with a non-marker swap entry between fault delivery and this
2646 	 * lockless re-check. pte_write() on a swap entry decodes random
2647 	 * offset bits, so gate it on pte_present(). The page-in path will
2648 	 * re-deliver the fault if it still needs userspace.
2649 	 */
2650 	if (!pte_present(ptent)) {
2651 		ret = false;
2652 		goto out;
2653 	}
2654 	/*
2655 	 * If VMA has UFFD WP faults enabled and WP fault, wait for userspace to
2656 	 * resolve the fault.
2657 	 */
2658 	if (!pte_write(ptent) && (reason & VM_UFFD_WP))
2659 		goto out;
2660 
2661 	ret = false;
2662 out:
2663 	pte_unmap(pte);
2664 	return ret;
2665 }
2666 
2667 static inline unsigned int userfaultfd_get_blocking_state(unsigned int flags)
2668 {
2669 	if (flags & FAULT_FLAG_INTERRUPTIBLE)
2670 		return TASK_INTERRUPTIBLE;
2671 
2672 	if (flags & FAULT_FLAG_KILLABLE)
2673 		return TASK_KILLABLE;
2674 
2675 	return TASK_UNINTERRUPTIBLE;
2676 }
2677 
2678 /*
2679  * The locking rules involved in returning VM_FAULT_RETRY depending on
2680  * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
2681  * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
2682  * recommendation in __lock_page_or_retry is not an understatement.
2683  *
2684  * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_lock must be released
2685  * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
2686  * not set.
2687  *
2688  * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
2689  * set, VM_FAULT_RETRY can still be returned if and only if there are
2690  * fatal_signal_pending()s, and the mmap_lock must be released before
2691  * returning it.
2692  */
2693 vm_fault_t handle_userfault(struct vm_fault *vmf, unsigned long reason)
2694 {
2695 	struct vm_area_struct *vma = vmf->vma;
2696 	struct mm_struct *mm = vma->vm_mm;
2697 	struct userfaultfd_ctx *ctx;
2698 	struct userfaultfd_wait_queue uwq;
2699 	vm_fault_t ret = VM_FAULT_SIGBUS;
2700 	bool must_wait;
2701 	unsigned int blocking_state;
2702 
2703 	/*
2704 	 * We don't do userfault handling for the final child pid update
2705 	 * and when coredumping (faults triggered by get_dump_page()).
2706 	 */
2707 	if (current->flags & (PF_EXITING|PF_DUMPCORE))
2708 		goto out;
2709 
2710 	assert_fault_locked(vmf);
2711 
2712 	ctx = vma->vm_userfaultfd_ctx.ctx;
2713 	if (!ctx)
2714 		goto out;
2715 
2716 	VM_WARN_ON_ONCE(ctx->mm != mm);
2717 
2718 	/* Any unrecognized flag is a bug. */
2719 	VM_WARN_ON_ONCE(reason & ~__VM_UFFD_FLAGS);
2720 	/* 0 or > 1 flags set is a bug; we expect exactly 1. */
2721 	VM_WARN_ON_ONCE(!reason || (reason & (reason - 1)));
2722 
2723 	if (ctx->features & UFFD_FEATURE_SIGBUS)
2724 		goto out;
2725 	if (!(vmf->flags & FAULT_FLAG_USER) && (ctx->flags & UFFD_USER_MODE_ONLY))
2726 		goto out;
2727 
2728 	/*
2729 	 * Check that we can return VM_FAULT_RETRY.
2730 	 *
2731 	 * NOTE: it should become possible to return VM_FAULT_RETRY
2732 	 * even if FAULT_FLAG_TRIED is set without leading to gup()
2733 	 * -EBUSY failures, if the userfaultfd is to be extended for
2734 	 * VM_UFFD_WP tracking and we intend to arm the userfault
2735 	 * without first stopping userland access to the memory. For
2736 	 * VM_UFFD_MISSING userfaults this is enough for now.
2737 	 */
2738 	if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
2739 		/*
2740 		 * Validate the invariant that nowait must allow retry
2741 		 * to be sure not to return SIGBUS erroneously on
2742 		 * nowait invocations.
2743 		 */
2744 		VM_WARN_ON_ONCE(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
2745 #ifdef CONFIG_DEBUG_VM
2746 		if (printk_ratelimit()) {
2747 			pr_warn("FAULT_FLAG_ALLOW_RETRY missing %x\n",
2748 				vmf->flags);
2749 			dump_stack();
2750 		}
2751 #endif
2752 		goto out;
2753 	}
2754 
2755 	/*
2756 	 * Handle nowait, not much to do other than tell it to retry
2757 	 * and wait.
2758 	 */
2759 	ret = VM_FAULT_RETRY;
2760 	if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2761 		goto out;
2762 
2763 	if (unlikely(READ_ONCE(ctx->released))) {
2764 		/*
2765 		 * If a concurrent release is detected, do not return
2766 		 * VM_FAULT_SIGBUS or VM_FAULT_NOPAGE, but instead always
2767 		 * return VM_FAULT_RETRY with lock released proactively.
2768 		 *
2769 		 * If we were to return VM_FAULT_SIGBUS here, the non
2770 		 * cooperative manager would be instead forced to
2771 		 * always call UFFDIO_UNREGISTER before it can safely
2772 		 * close the uffd, to avoid involuntary SIGBUS triggered.
2773 		 *
2774 		 * If we were to return VM_FAULT_NOPAGE, it would work for
2775 		 * the fault path, in which the lock will be released
2776 		 * later.  However for GUP, faultin_page() does nothing
2777 		 * special on NOPAGE, so GUP would spin retrying without
2778 		 * releasing the mmap read lock, causing possible livelock.
2779 		 *
2780 		 * Here only VM_FAULT_RETRY would make sure the mmap lock
2781 		 * be released immediately, so that the thread concurrently
2782 		 * releasing the userfault would always make progress.
2783 		 */
2784 		release_fault_lock(vmf);
2785 		goto out;
2786 	}
2787 
2788 	/* take the reference before dropping the mmap_lock */
2789 	userfaultfd_ctx_get(ctx);
2790 
2791 	init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
2792 	uwq.wq.private = current;
2793 	uwq.msg = userfault_msg(vmf->address, vmf->real_address, vmf->flags,
2794 				reason, ctx->features);
2795 	uwq.ctx = ctx;
2796 	uwq.waken = false;
2797 
2798 	blocking_state = userfaultfd_get_blocking_state(vmf->flags);
2799 
2800 	/*
2801 	 * Take the vma lock now, in order to safely call
2802 	 * userfaultfd_huge_must_wait() later. Since acquiring the
2803 	 * (sleepable) vma lock can modify the current task state, that
2804 	 * must be before explicitly calling set_current_state().
2805 	 */
2806 	if (is_vm_hugetlb_page(vma))
2807 		hugetlb_vma_lock_read(vma);
2808 
2809 	spin_lock_irq(&ctx->fault_pending_wqh.lock);
2810 	/*
2811 	 * After the __add_wait_queue the uwq is visible to userland
2812 	 * through poll/read().
2813 	 */
2814 	__add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
2815 	/*
2816 	 * The smp_mb() after __set_current_state prevents the reads
2817 	 * following the spin_unlock to happen before the list_add in
2818 	 * __add_wait_queue.
2819 	 */
2820 	set_current_state(blocking_state);
2821 	spin_unlock_irq(&ctx->fault_pending_wqh.lock);
2822 
2823 	if (is_vm_hugetlb_page(vma)) {
2824 		must_wait = userfaultfd_huge_must_wait(ctx, vmf, reason);
2825 		hugetlb_vma_unlock_read(vma);
2826 	} else {
2827 		must_wait = userfaultfd_must_wait(ctx, vmf, reason);
2828 	}
2829 
2830 	release_fault_lock(vmf);
2831 
2832 	if (likely(must_wait && !READ_ONCE(ctx->released))) {
2833 		wake_up_poll(&ctx->fd_wqh, EPOLLIN);
2834 		schedule();
2835 	}
2836 
2837 	__set_current_state(TASK_RUNNING);
2838 
2839 	/*
2840 	 * Here we race with the list_del; list_add in
2841 	 * userfaultfd_ctx_read(), however because we don't ever run
2842 	 * list_del_init() to refile across the two lists, the prev
2843 	 * and next pointers will never point to self. list_add also
2844 	 * would never let any of the two pointers to point to
2845 	 * self. So list_empty_careful won't risk to see both pointers
2846 	 * pointing to self at any time during the list refile. The
2847 	 * only case where list_del_init() is called is the full
2848 	 * removal in the wake function and there we don't re-list_add
2849 	 * and it's fine not to block on the spinlock. The uwq on this
2850 	 * kernel stack can be released after the list_del_init.
2851 	 */
2852 	if (!list_empty_careful(&uwq.wq.entry)) {
2853 		spin_lock_irq(&ctx->fault_pending_wqh.lock);
2854 		/*
2855 		 * No need of list_del_init(), the uwq on the stack
2856 		 * will be freed shortly anyway.
2857 		 */
2858 		list_del(&uwq.wq.entry);
2859 		spin_unlock_irq(&ctx->fault_pending_wqh.lock);
2860 	}
2861 
2862 	/*
2863 	 * ctx may go away after this if the userfault pseudo fd is
2864 	 * already released.
2865 	 */
2866 	userfaultfd_ctx_put(ctx);
2867 
2868 out:
2869 	return ret;
2870 }
2871 
2872 static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
2873 					      struct userfaultfd_wait_queue *ewq)
2874 {
2875 	struct userfaultfd_ctx *release_new_ctx;
2876 
2877 	if (WARN_ON_ONCE(current->flags & PF_EXITING))
2878 		goto out;
2879 
2880 	ewq->ctx = ctx;
2881 	init_waitqueue_entry(&ewq->wq, current);
2882 	release_new_ctx = NULL;
2883 
2884 	spin_lock_irq(&ctx->event_wqh.lock);
2885 	/*
2886 	 * After the __add_wait_queue the uwq is visible to userland
2887 	 * through poll/read().
2888 	 */
2889 	__add_wait_queue(&ctx->event_wqh, &ewq->wq);
2890 	for (;;) {
2891 		set_current_state(TASK_KILLABLE);
2892 		if (ewq->msg.event == 0)
2893 			break;
2894 		if (READ_ONCE(ctx->released) ||
2895 		    fatal_signal_pending(current)) {
2896 			/*
2897 			 * &ewq->wq may be queued in fork_event, but
2898 			 * __remove_wait_queue ignores the head
2899 			 * parameter. It would be a problem if it
2900 			 * didn't.
2901 			 */
2902 			__remove_wait_queue(&ctx->event_wqh, &ewq->wq);
2903 			if (ewq->msg.event == UFFD_EVENT_FORK) {
2904 				struct userfaultfd_ctx *new;
2905 
2906 				new = (struct userfaultfd_ctx *)
2907 					(unsigned long)
2908 					ewq->msg.arg.reserved.reserved1;
2909 				release_new_ctx = new;
2910 			}
2911 			break;
2912 		}
2913 
2914 		spin_unlock_irq(&ctx->event_wqh.lock);
2915 
2916 		wake_up_poll(&ctx->fd_wqh, EPOLLIN);
2917 		schedule();
2918 
2919 		spin_lock_irq(&ctx->event_wqh.lock);
2920 	}
2921 	__set_current_state(TASK_RUNNING);
2922 	spin_unlock_irq(&ctx->event_wqh.lock);
2923 
2924 	if (release_new_ctx) {
2925 		userfaultfd_release_new(release_new_ctx);
2926 		userfaultfd_ctx_put(release_new_ctx);
2927 	}
2928 
2929 	/*
2930 	 * ctx may go away after this if the userfault pseudo fd is
2931 	 * already released.
2932 	 */
2933 out:
2934 	atomic_dec(&ctx->mmap_changing);
2935 	VM_WARN_ON_ONCE(atomic_read(&ctx->mmap_changing) < 0);
2936 	userfaultfd_ctx_put(ctx);
2937 }
2938 
2939 static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
2940 				       struct userfaultfd_wait_queue *ewq)
2941 {
2942 	ewq->msg.event = 0;
2943 	wake_up_locked(&ctx->event_wqh);
2944 	__remove_wait_queue(&ctx->event_wqh, &ewq->wq);
2945 }
2946 
2947 int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
2948 {
2949 	struct userfaultfd_ctx *ctx = NULL, *octx;
2950 	struct userfaultfd_fork_ctx *fctx;
2951 
2952 	octx = vma->vm_userfaultfd_ctx.ctx;
2953 	if (!octx)
2954 		return 0;
2955 
2956 	if (!(octx->features & UFFD_FEATURE_EVENT_FORK)) {
2957 		userfaultfd_reset_ctx(vma);
2958 		return 0;
2959 	}
2960 
2961 	list_for_each_entry(fctx, fcs, list)
2962 		if (fctx->orig == octx) {
2963 			ctx = fctx->new;
2964 			break;
2965 		}
2966 
2967 	if (!ctx) {
2968 		fctx = kmalloc_obj(*fctx);
2969 		if (!fctx)
2970 			return -ENOMEM;
2971 
2972 		ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
2973 		if (!ctx) {
2974 			kfree(fctx);
2975 			return -ENOMEM;
2976 		}
2977 
2978 		refcount_set(&ctx->refcount, 1);
2979 		ctx->flags = octx->flags;
2980 		ctx->features = octx->features;
2981 		ctx->released = false;
2982 		init_rwsem(&ctx->map_changing_lock);
2983 		atomic_set(&ctx->mmap_changing, 0);
2984 		ctx->mm = vma->vm_mm;
2985 		mmgrab(ctx->mm);
2986 
2987 		userfaultfd_ctx_get(octx);
2988 		down_write(&octx->map_changing_lock);
2989 		atomic_inc(&octx->mmap_changing);
2990 		up_write(&octx->map_changing_lock);
2991 		fctx->orig = octx;
2992 		fctx->new = ctx;
2993 		list_add_tail(&fctx->list, fcs);
2994 	}
2995 
2996 	vma->vm_userfaultfd_ctx.ctx = ctx;
2997 	return 0;
2998 }
2999 
3000 static void dup_fctx(struct userfaultfd_fork_ctx *fctx)
3001 {
3002 	struct userfaultfd_ctx *ctx = fctx->orig;
3003 	struct userfaultfd_wait_queue ewq;
3004 
3005 	msg_init(&ewq.msg);
3006 
3007 	ewq.msg.event = UFFD_EVENT_FORK;
3008 	ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
3009 
3010 	userfaultfd_event_wait_completion(ctx, &ewq);
3011 }
3012 
3013 void dup_userfaultfd_complete(struct list_head *fcs)
3014 {
3015 	struct userfaultfd_fork_ctx *fctx, *n;
3016 
3017 	list_for_each_entry_safe(fctx, n, fcs, list) {
3018 		dup_fctx(fctx);
3019 		list_del(&fctx->list);
3020 		kfree(fctx);
3021 	}
3022 }
3023 
3024 void dup_userfaultfd_fail(struct list_head *fcs)
3025 {
3026 	struct userfaultfd_fork_ctx *fctx, *n;
3027 
3028 	/*
3029 	 * An error has occurred on fork, we will tear memory down, but have
3030 	 * allocated memory for fctx's and raised reference counts for both the
3031 	 * original and child contexts (and on the mm for each as a result).
3032 	 *
3033 	 * These would ordinarily be taken care of by a user handling the event,
3034 	 * but we are no longer doing so, so manually clean up here.
3035 	 *
3036 	 * mm tear down will take care of cleaning up VMA contexts.
3037 	 */
3038 	list_for_each_entry_safe(fctx, n, fcs, list) {
3039 		struct userfaultfd_ctx *octx = fctx->orig;
3040 		struct userfaultfd_ctx *ctx = fctx->new;
3041 
3042 		atomic_dec(&octx->mmap_changing);
3043 		VM_WARN_ON_ONCE(atomic_read(&octx->mmap_changing) < 0);
3044 		userfaultfd_ctx_put(octx);
3045 		userfaultfd_ctx_put(ctx);
3046 
3047 		list_del(&fctx->list);
3048 		kfree(fctx);
3049 	}
3050 }
3051 
3052 void mremap_userfaultfd_prep(struct vm_area_struct *vma,
3053 			     struct vm_userfaultfd_ctx *vm_ctx)
3054 {
3055 	struct userfaultfd_ctx *ctx;
3056 
3057 	ctx = vma->vm_userfaultfd_ctx.ctx;
3058 
3059 	if (!ctx)
3060 		return;
3061 
3062 	if (ctx->features & UFFD_FEATURE_EVENT_REMAP) {
3063 		vm_ctx->ctx = ctx;
3064 		userfaultfd_ctx_get(ctx);
3065 		down_write(&ctx->map_changing_lock);
3066 		atomic_inc(&ctx->mmap_changing);
3067 		up_write(&ctx->map_changing_lock);
3068 	} else {
3069 		/* Drop uffd context if remap feature not enabled */
3070 		userfaultfd_reset_ctx(vma);
3071 	}
3072 }
3073 
3074 void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
3075 				 unsigned long from, unsigned long to,
3076 				 unsigned long len)
3077 {
3078 	struct userfaultfd_ctx *ctx = vm_ctx->ctx;
3079 	struct userfaultfd_wait_queue ewq;
3080 
3081 	if (!ctx)
3082 		return;
3083 
3084 	msg_init(&ewq.msg);
3085 
3086 	ewq.msg.event = UFFD_EVENT_REMAP;
3087 	ewq.msg.arg.remap.from = from;
3088 	ewq.msg.arg.remap.to = to;
3089 	ewq.msg.arg.remap.len = len;
3090 
3091 	userfaultfd_event_wait_completion(ctx, &ewq);
3092 }
3093 
3094 void mremap_userfaultfd_fail(struct vm_userfaultfd_ctx *vm_ctx)
3095 {
3096 	struct userfaultfd_ctx *ctx = vm_ctx->ctx;
3097 
3098 	if (!ctx)
3099 		return;
3100 
3101 	atomic_dec(&ctx->mmap_changing);
3102 	VM_WARN_ON_ONCE(atomic_read(&ctx->mmap_changing) < 0);
3103 	userfaultfd_ctx_put(ctx);
3104 }
3105 
3106 bool userfaultfd_remove(struct vm_area_struct *vma,
3107 			unsigned long start, unsigned long end)
3108 {
3109 	struct mm_struct *mm = vma->vm_mm;
3110 	struct userfaultfd_ctx *ctx;
3111 	struct userfaultfd_wait_queue ewq;
3112 
3113 	ctx = vma->vm_userfaultfd_ctx.ctx;
3114 	if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_REMOVE))
3115 		return true;
3116 
3117 	userfaultfd_ctx_get(ctx);
3118 	down_write(&ctx->map_changing_lock);
3119 	atomic_inc(&ctx->mmap_changing);
3120 	up_write(&ctx->map_changing_lock);
3121 	mmap_read_unlock(mm);
3122 
3123 	msg_init(&ewq.msg);
3124 
3125 	ewq.msg.event = UFFD_EVENT_REMOVE;
3126 	ewq.msg.arg.remove.start = start;
3127 	ewq.msg.arg.remove.end = end;
3128 
3129 	userfaultfd_event_wait_completion(ctx, &ewq);
3130 
3131 	return false;
3132 }
3133 
3134 static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
3135 			  unsigned long start, unsigned long end)
3136 {
3137 	struct userfaultfd_unmap_ctx *unmap_ctx;
3138 
3139 	list_for_each_entry(unmap_ctx, unmaps, list)
3140 		if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
3141 		    unmap_ctx->end == end)
3142 			return true;
3143 
3144 	return false;
3145 }
3146 
3147 int userfaultfd_unmap_prep(struct vm_area_struct *vma, unsigned long start,
3148 			   unsigned long end, struct list_head *unmaps)
3149 {
3150 	struct userfaultfd_unmap_ctx *unmap_ctx;
3151 	struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
3152 
3153 	if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_UNMAP) ||
3154 	    has_unmap_ctx(ctx, unmaps, start, end))
3155 		return 0;
3156 
3157 	unmap_ctx = kzalloc_obj(*unmap_ctx);
3158 	if (!unmap_ctx)
3159 		return -ENOMEM;
3160 
3161 	userfaultfd_ctx_get(ctx);
3162 	down_write(&ctx->map_changing_lock);
3163 	atomic_inc(&ctx->mmap_changing);
3164 	up_write(&ctx->map_changing_lock);
3165 	unmap_ctx->ctx = ctx;
3166 	unmap_ctx->start = start;
3167 	unmap_ctx->end = end;
3168 	list_add_tail(&unmap_ctx->list, unmaps);
3169 
3170 	return 0;
3171 }
3172 
3173 void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf)
3174 {
3175 	struct userfaultfd_unmap_ctx *ctx, *n;
3176 	struct userfaultfd_wait_queue ewq;
3177 
3178 	list_for_each_entry_safe(ctx, n, uf, list) {
3179 		msg_init(&ewq.msg);
3180 
3181 		ewq.msg.event = UFFD_EVENT_UNMAP;
3182 		ewq.msg.arg.remove.start = ctx->start;
3183 		ewq.msg.arg.remove.end = ctx->end;
3184 
3185 		userfaultfd_event_wait_completion(ctx->ctx, &ewq);
3186 
3187 		list_del(&ctx->list);
3188 		kfree(ctx);
3189 	}
3190 }
3191 
3192 static int userfaultfd_release(struct inode *inode, struct file *file)
3193 {
3194 	struct userfaultfd_ctx *ctx = file->private_data;
3195 	struct mm_struct *mm = ctx->mm;
3196 	/* len == 0 means wake all */
3197 	struct userfaultfd_wake_range range = { .len = 0, };
3198 
3199 	WRITE_ONCE(ctx->released, true);
3200 
3201 	userfaultfd_release_all(mm, ctx);
3202 
3203 	/*
3204 	 * After no new page faults can wait on this fault_*wqh, flush
3205 	 * the last page faults that may have been already waiting on
3206 	 * the fault_*wqh.
3207 	 */
3208 	spin_lock_irq(&ctx->fault_pending_wqh.lock);
3209 	__wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
3210 	__wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range);
3211 	spin_unlock_irq(&ctx->fault_pending_wqh.lock);
3212 
3213 	/* Flush pending events that may still wait on event_wqh */
3214 	wake_up_all(&ctx->event_wqh);
3215 
3216 	wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
3217 	userfaultfd_ctx_put(ctx);
3218 	return 0;
3219 }
3220 
3221 /* fault_pending_wqh.lock must be hold by the caller */
3222 static inline struct userfaultfd_wait_queue *find_userfault_in(
3223 		wait_queue_head_t *wqh)
3224 {
3225 	wait_queue_entry_t *wq;
3226 	struct userfaultfd_wait_queue *uwq;
3227 
3228 	lockdep_assert_held(&wqh->lock);
3229 
3230 	uwq = NULL;
3231 	if (!waitqueue_active(wqh))
3232 		goto out;
3233 	/* walk in reverse to provide FIFO behavior to read userfaults */
3234 	wq = list_last_entry(&wqh->head, typeof(*wq), entry);
3235 	uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
3236 out:
3237 	return uwq;
3238 }
3239 
3240 static inline struct userfaultfd_wait_queue *find_userfault(
3241 		struct userfaultfd_ctx *ctx)
3242 {
3243 	return find_userfault_in(&ctx->fault_pending_wqh);
3244 }
3245 
3246 static inline struct userfaultfd_wait_queue *find_userfault_evt(
3247 		struct userfaultfd_ctx *ctx)
3248 {
3249 	return find_userfault_in(&ctx->event_wqh);
3250 }
3251 
3252 static __poll_t userfaultfd_poll(struct file *file, poll_table *wait)
3253 {
3254 	struct userfaultfd_ctx *ctx = file->private_data;
3255 	__poll_t ret;
3256 
3257 	poll_wait(file, &ctx->fd_wqh, wait);
3258 
3259 	if (!userfaultfd_is_initialized(ctx))
3260 		return EPOLLERR;
3261 
3262 	/*
3263 	 * poll() never guarantees that read won't block.
3264 	 * userfaults can be waken before they're read().
3265 	 */
3266 	if (unlikely(!(file->f_flags & O_NONBLOCK)))
3267 		return EPOLLERR;
3268 	/*
3269 	 * lockless access to see if there are pending faults
3270 	 * __pollwait last action is the add_wait_queue but
3271 	 * the spin_unlock would allow the waitqueue_active to
3272 	 * pass above the actual list_add inside
3273 	 * add_wait_queue critical section. So use a full
3274 	 * memory barrier to serialize the list_add write of
3275 	 * add_wait_queue() with the waitqueue_active read
3276 	 * below.
3277 	 */
3278 	ret = 0;
3279 	smp_mb();
3280 	if (waitqueue_active(&ctx->fault_pending_wqh))
3281 		ret = EPOLLIN;
3282 	else if (waitqueue_active(&ctx->event_wqh))
3283 		ret = EPOLLIN;
3284 
3285 	return ret;
3286 }
3287 
3288 static const struct file_operations userfaultfd_fops;
3289 
3290 static int resolve_userfault_fork(struct userfaultfd_ctx *new,
3291 				  struct inode *inode,
3292 				  struct uffd_msg *msg)
3293 {
3294 	int fd;
3295 
3296 	fd = anon_inode_create_getfd("[userfaultfd]", &userfaultfd_fops, new,
3297 			O_RDONLY | (new->flags & UFFD_SHARED_FCNTL_FLAGS), inode);
3298 	if (fd < 0)
3299 		return fd;
3300 
3301 	msg->arg.reserved.reserved1 = 0;
3302 	msg->arg.fork.ufd = fd;
3303 	return 0;
3304 }
3305 
3306 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
3307 				    struct uffd_msg *msg, struct inode *inode)
3308 {
3309 	ssize_t ret;
3310 	DECLARE_WAITQUEUE(wait, current);
3311 	struct userfaultfd_wait_queue *uwq;
3312 	/*
3313 	 * Handling fork event requires sleeping operations, so
3314 	 * we drop the event_wqh lock, then do these ops, then
3315 	 * lock it back and wake up the waiter. While the lock is
3316 	 * dropped the ewq may go away so we keep track of it
3317 	 * carefully.
3318 	 */
3319 	LIST_HEAD(fork_event);
3320 	struct userfaultfd_ctx *fork_nctx = NULL;
3321 
3322 	/* always take the fd_wqh lock before the fault_pending_wqh lock */
3323 	spin_lock_irq(&ctx->fd_wqh.lock);
3324 	__add_wait_queue(&ctx->fd_wqh, &wait);
3325 	for (;;) {
3326 		set_current_state(TASK_INTERRUPTIBLE);
3327 		spin_lock(&ctx->fault_pending_wqh.lock);
3328 		uwq = find_userfault(ctx);
3329 		if (uwq) {
3330 			/*
3331 			 * Use a seqcount to repeat the lockless check
3332 			 * in wake_userfault() to avoid missing
3333 			 * wakeups because during the refile both
3334 			 * waitqueue could become empty if this is the
3335 			 * only userfault.
3336 			 */
3337 			write_seqcount_begin(&ctx->refile_seq);
3338 
3339 			/*
3340 			 * The fault_pending_wqh.lock prevents the uwq
3341 			 * to disappear from under us.
3342 			 *
3343 			 * Refile this userfault from
3344 			 * fault_pending_wqh to fault_wqh, it's not
3345 			 * pending anymore after we read it.
3346 			 *
3347 			 * Use list_del() by hand (as
3348 			 * userfaultfd_wake_function also uses
3349 			 * list_del_init() by hand) to be sure nobody
3350 			 * changes __remove_wait_queue() to use
3351 			 * list_del_init() in turn breaking the
3352 			 * !list_empty_careful() check in
3353 			 * handle_userfault(). The uwq->wq.head list
3354 			 * must never be empty at any time during the
3355 			 * refile, or the waitqueue could disappear
3356 			 * from under us. The "wait_queue_head_t"
3357 			 * parameter of __remove_wait_queue() is unused
3358 			 * anyway.
3359 			 */
3360 			list_del(&uwq->wq.entry);
3361 			add_wait_queue(&ctx->fault_wqh, &uwq->wq);
3362 
3363 			write_seqcount_end(&ctx->refile_seq);
3364 
3365 			/* careful to always initialize msg if ret == 0 */
3366 			*msg = uwq->msg;
3367 			spin_unlock(&ctx->fault_pending_wqh.lock);
3368 			ret = 0;
3369 			break;
3370 		}
3371 		spin_unlock(&ctx->fault_pending_wqh.lock);
3372 
3373 		spin_lock(&ctx->event_wqh.lock);
3374 		uwq = find_userfault_evt(ctx);
3375 		if (uwq) {
3376 			*msg = uwq->msg;
3377 
3378 			if (uwq->msg.event == UFFD_EVENT_FORK) {
3379 				fork_nctx = (struct userfaultfd_ctx *)
3380 					(unsigned long)
3381 					uwq->msg.arg.reserved.reserved1;
3382 				list_move(&uwq->wq.entry, &fork_event);
3383 				/*
3384 				 * fork_nctx can be freed as soon as
3385 				 * we drop the lock, unless we take a
3386 				 * reference on it.
3387 				 */
3388 				userfaultfd_ctx_get(fork_nctx);
3389 				spin_unlock(&ctx->event_wqh.lock);
3390 				ret = 0;
3391 				break;
3392 			}
3393 
3394 			userfaultfd_event_complete(ctx, uwq);
3395 			spin_unlock(&ctx->event_wqh.lock);
3396 			ret = 0;
3397 			break;
3398 		}
3399 		spin_unlock(&ctx->event_wqh.lock);
3400 
3401 		if (signal_pending(current)) {
3402 			ret = -ERESTARTSYS;
3403 			break;
3404 		}
3405 		if (no_wait) {
3406 			ret = -EAGAIN;
3407 			break;
3408 		}
3409 		spin_unlock_irq(&ctx->fd_wqh.lock);
3410 		schedule();
3411 		spin_lock_irq(&ctx->fd_wqh.lock);
3412 	}
3413 	__remove_wait_queue(&ctx->fd_wqh, &wait);
3414 	__set_current_state(TASK_RUNNING);
3415 	spin_unlock_irq(&ctx->fd_wqh.lock);
3416 
3417 	if (!ret && msg->event == UFFD_EVENT_FORK) {
3418 		ret = resolve_userfault_fork(fork_nctx, inode, msg);
3419 		spin_lock_irq(&ctx->event_wqh.lock);
3420 		if (!list_empty(&fork_event)) {
3421 			/*
3422 			 * The fork thread didn't abort, so we can
3423 			 * drop the temporary refcount.
3424 			 */
3425 			userfaultfd_ctx_put(fork_nctx);
3426 
3427 			uwq = list_first_entry(&fork_event,
3428 					       typeof(*uwq),
3429 					       wq.entry);
3430 			/*
3431 			 * If fork_event list wasn't empty and in turn
3432 			 * the event wasn't already released by fork
3433 			 * (the event is allocated on fork kernel
3434 			 * stack), put the event back to its place in
3435 			 * the event_wq. fork_event head will be freed
3436 			 * as soon as we return so the event cannot
3437 			 * stay queued there no matter the current
3438 			 * "ret" value.
3439 			 */
3440 			list_del(&uwq->wq.entry);
3441 			__add_wait_queue(&ctx->event_wqh, &uwq->wq);
3442 
3443 			/*
3444 			 * Leave the event in the waitqueue and report
3445 			 * error to userland if we failed to resolve
3446 			 * the userfault fork.
3447 			 */
3448 			if (likely(!ret))
3449 				userfaultfd_event_complete(ctx, uwq);
3450 		} else {
3451 			/*
3452 			 * Here the fork thread aborted and the
3453 			 * refcount from the fork thread on fork_nctx
3454 			 * has already been released. We still hold
3455 			 * the reference we took before releasing the
3456 			 * lock above. If resolve_userfault_fork
3457 			 * failed we've to drop it because the
3458 			 * fork_nctx has to be freed in such case. If
3459 			 * it succeeded we'll hold it because the new
3460 			 * uffd references it.
3461 			 */
3462 			if (ret)
3463 				userfaultfd_ctx_put(fork_nctx);
3464 		}
3465 		spin_unlock_irq(&ctx->event_wqh.lock);
3466 	}
3467 
3468 	return ret;
3469 }
3470 
3471 static ssize_t userfaultfd_read_iter(struct kiocb *iocb, struct iov_iter *to)
3472 {
3473 	struct file *file = iocb->ki_filp;
3474 	struct userfaultfd_ctx *ctx = file->private_data;
3475 	ssize_t _ret, ret = 0;
3476 	struct uffd_msg msg;
3477 	struct inode *inode = file_inode(file);
3478 	bool no_wait;
3479 
3480 	if (!userfaultfd_is_initialized(ctx))
3481 		return -EINVAL;
3482 
3483 	no_wait = file->f_flags & O_NONBLOCK || iocb->ki_flags & IOCB_NOWAIT;
3484 	for (;;) {
3485 		if (iov_iter_count(to) < sizeof(msg))
3486 			return ret ? ret : -EINVAL;
3487 		_ret = userfaultfd_ctx_read(ctx, no_wait, &msg, inode);
3488 		if (_ret < 0)
3489 			return ret ? ret : _ret;
3490 		_ret = !copy_to_iter_full(&msg, sizeof(msg), to);
3491 		if (_ret)
3492 			return ret ? ret : -EFAULT;
3493 		ret += sizeof(msg);
3494 		/*
3495 		 * Allow to read more than one fault at time but only
3496 		 * block if waiting for the very first one.
3497 		 */
3498 		no_wait = true;
3499 	}
3500 }
3501 
3502 static void __wake_userfault(struct userfaultfd_ctx *ctx,
3503 			     struct userfaultfd_wake_range *range)
3504 {
3505 	spin_lock_irq(&ctx->fault_pending_wqh.lock);
3506 	/* wake all in the range and autoremove */
3507 	if (waitqueue_active(&ctx->fault_pending_wqh))
3508 		__wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
3509 				     range);
3510 	if (waitqueue_active(&ctx->fault_wqh))
3511 		__wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, range);
3512 	spin_unlock_irq(&ctx->fault_pending_wqh.lock);
3513 }
3514 
3515 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
3516 					   struct userfaultfd_wake_range *range)
3517 {
3518 	unsigned seq;
3519 	bool need_wakeup;
3520 
3521 	/*
3522 	 * To be sure waitqueue_active() is not reordered by the CPU
3523 	 * before the pagetable update, use an explicit SMP memory
3524 	 * barrier here. PT lock release or mmap_read_unlock(mm) still
3525 	 * have release semantics that can allow the
3526 	 * waitqueue_active() to be reordered before the pte update.
3527 	 */
3528 	smp_mb();
3529 
3530 	/*
3531 	 * Use waitqueue_active because it's very frequent to
3532 	 * change the address space atomically even if there are no
3533 	 * userfaults yet. So we take the spinlock only when we're
3534 	 * sure we've userfaults to wake.
3535 	 */
3536 	do {
3537 		seq = read_seqcount_begin(&ctx->refile_seq);
3538 		need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
3539 			waitqueue_active(&ctx->fault_wqh);
3540 		cond_resched();
3541 	} while (read_seqcount_retry(&ctx->refile_seq, seq));
3542 	if (need_wakeup)
3543 		__wake_userfault(ctx, range);
3544 }
3545 
3546 static __always_inline int validate_unaligned_range(
3547 	struct mm_struct *mm, __u64 start, __u64 len)
3548 {
3549 	__u64 task_size = mm->task_size;
3550 
3551 	if (len & ~PAGE_MASK)
3552 		return -EINVAL;
3553 	if (!len)
3554 		return -EINVAL;
3555 	if (start >= task_size)
3556 		return -EINVAL;
3557 	if (len > task_size - start)
3558 		return -EINVAL;
3559 	if (start + len <= start)
3560 		return -EINVAL;
3561 	return 0;
3562 }
3563 
3564 static __always_inline int validate_range(struct mm_struct *mm,
3565 					  __u64 start, __u64 len)
3566 {
3567 	if (start & ~PAGE_MASK)
3568 		return -EINVAL;
3569 
3570 	return validate_unaligned_range(mm, start, len);
3571 }
3572 
3573 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
3574 				unsigned long arg)
3575 {
3576 	struct mm_struct *mm = ctx->mm;
3577 	struct vm_area_struct *vma, *cur;
3578 	int ret;
3579 	struct uffdio_register uffdio_register;
3580 	struct uffdio_register __user *user_uffdio_register;
3581 	vm_flags_t vm_flags;
3582 	bool found;
3583 	bool basic_ioctls;
3584 	unsigned long start, end;
3585 	struct vma_iterator vmi;
3586 	bool wp_async = userfaultfd_wp_async_ctx(ctx);
3587 
3588 	user_uffdio_register = (struct uffdio_register __user *) arg;
3589 
3590 	ret = -EFAULT;
3591 	if (copy_from_user(&uffdio_register, user_uffdio_register,
3592 			   sizeof(uffdio_register)-sizeof(__u64)))
3593 		goto out;
3594 
3595 	ret = -EINVAL;
3596 	if (!uffdio_register.mode)
3597 		goto out;
3598 	if (uffdio_register.mode & ~UFFD_API_REGISTER_MODES)
3599 		goto out;
3600 	vm_flags = 0;
3601 	if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
3602 		vm_flags |= VM_UFFD_MISSING;
3603 	if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
3604 		if (!pgtable_supports_uffd_wp())
3605 			goto out;
3606 
3607 		vm_flags |= VM_UFFD_WP;
3608 	}
3609 	if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR) {
3610 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
3611 		goto out;
3612 #endif
3613 		vm_flags |= VM_UFFD_MINOR;
3614 	}
3615 
3616 	ret = validate_range(mm, uffdio_register.range.start,
3617 			     uffdio_register.range.len);
3618 	if (ret)
3619 		goto out;
3620 
3621 	start = uffdio_register.range.start;
3622 	end = start + uffdio_register.range.len;
3623 
3624 	ret = -ENOMEM;
3625 	if (!mmget_not_zero(mm))
3626 		goto out;
3627 
3628 	ret = -EINVAL;
3629 	mmap_write_lock(mm);
3630 	vma_iter_init(&vmi, mm, start);
3631 	vma = vma_find(&vmi, end);
3632 	if (!vma)
3633 		goto out_unlock;
3634 
3635 	/*
3636 	 * If the first vma contains huge pages, make sure start address
3637 	 * is aligned to huge page size.
3638 	 */
3639 	if (is_vm_hugetlb_page(vma)) {
3640 		unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
3641 
3642 		if (start & (vma_hpagesize - 1))
3643 			goto out_unlock;
3644 	}
3645 
3646 	/*
3647 	 * Search for not compatible vmas.
3648 	 */
3649 	found = false;
3650 	basic_ioctls = false;
3651 	cur = vma;
3652 	do {
3653 		cond_resched();
3654 
3655 		VM_WARN_ON_ONCE(!!cur->vm_userfaultfd_ctx.ctx ^
3656 				!!(cur->vm_flags & __VM_UFFD_FLAGS));
3657 
3658 		/* check not compatible vmas */
3659 		ret = -EINVAL;
3660 		if (!vma_can_userfault(cur, vm_flags, wp_async))
3661 			goto out_unlock;
3662 
3663 		/*
3664 		 * UFFDIO_COPY will fill file holes even without
3665 		 * PROT_WRITE. This check enforces that if this is a
3666 		 * MAP_SHARED, the process has write permission to the backing
3667 		 * file. If VM_MAYWRITE is set it also enforces that on a
3668 		 * MAP_SHARED vma: there is no F_WRITE_SEAL and no further
3669 		 * F_WRITE_SEAL can be taken until the vma is destroyed.
3670 		 */
3671 		ret = -EPERM;
3672 		if (unlikely(!(cur->vm_flags & VM_MAYWRITE)))
3673 			goto out_unlock;
3674 
3675 		/*
3676 		 * If this vma contains ending address, and huge pages
3677 		 * check alignment.
3678 		 */
3679 		if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
3680 		    end > cur->vm_start) {
3681 			unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
3682 
3683 			ret = -EINVAL;
3684 
3685 			if (end & (vma_hpagesize - 1))
3686 				goto out_unlock;
3687 		}
3688 		if ((vm_flags & VM_UFFD_WP) && !(cur->vm_flags & VM_MAYWRITE))
3689 			goto out_unlock;
3690 
3691 		/*
3692 		 * Check that this vma isn't already owned by a
3693 		 * different userfaultfd. We can't allow more than one
3694 		 * userfaultfd to own a single vma simultaneously or we
3695 		 * wouldn't know which one to deliver the userfaults to.
3696 		 */
3697 		ret = -EBUSY;
3698 		if (cur->vm_userfaultfd_ctx.ctx &&
3699 		    cur->vm_userfaultfd_ctx.ctx != ctx)
3700 			goto out_unlock;
3701 
3702 		/*
3703 		 * Note vmas containing huge pages
3704 		 */
3705 		if (is_vm_hugetlb_page(cur))
3706 			basic_ioctls = true;
3707 
3708 		found = true;
3709 	} for_each_vma_range(vmi, cur, end);
3710 	VM_WARN_ON_ONCE(!found);
3711 
3712 	ret = userfaultfd_register_range(ctx, vma, vm_flags, start, end,
3713 					 wp_async);
3714 
3715 out_unlock:
3716 	mmap_write_unlock(mm);
3717 	mmput(mm);
3718 	if (!ret) {
3719 		__u64 ioctls_out;
3720 
3721 		ioctls_out = basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
3722 			UFFD_API_RANGE_IOCTLS;
3723 
3724 		/*
3725 		 * Declare the WP ioctl only if the WP mode is
3726 		 * specified and all checks passed with the range
3727 		 */
3728 		if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_WP))
3729 			ioctls_out &= ~((__u64)1 << _UFFDIO_WRITEPROTECT);
3730 
3731 		/* CONTINUE ioctl is only supported for MINOR ranges. */
3732 		if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR))
3733 			ioctls_out &= ~((__u64)1 << _UFFDIO_CONTINUE);
3734 
3735 		/*
3736 		 * Now that we scanned all vmas we can already tell
3737 		 * userland which ioctls methods are guaranteed to
3738 		 * succeed on this range.
3739 		 */
3740 		if (put_user(ioctls_out, &user_uffdio_register->ioctls))
3741 			ret = -EFAULT;
3742 	}
3743 out:
3744 	return ret;
3745 }
3746 
3747 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
3748 				  unsigned long arg)
3749 {
3750 	struct mm_struct *mm = ctx->mm;
3751 	struct vm_area_struct *vma, *prev, *cur;
3752 	int ret;
3753 	struct uffdio_range uffdio_unregister;
3754 	bool found;
3755 	unsigned long start, end, vma_end;
3756 	const void __user *buf = (void __user *)arg;
3757 	struct vma_iterator vmi;
3758 	bool wp_async = userfaultfd_wp_async_ctx(ctx);
3759 
3760 	ret = -EFAULT;
3761 	if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
3762 		goto out;
3763 
3764 	ret = validate_range(mm, uffdio_unregister.start,
3765 			     uffdio_unregister.len);
3766 	if (ret)
3767 		goto out;
3768 
3769 	start = uffdio_unregister.start;
3770 	end = start + uffdio_unregister.len;
3771 
3772 	ret = -ENOMEM;
3773 	if (!mmget_not_zero(mm))
3774 		goto out;
3775 
3776 	mmap_write_lock(mm);
3777 	ret = -EINVAL;
3778 	vma_iter_init(&vmi, mm, start);
3779 	vma = vma_find(&vmi, end);
3780 	if (!vma)
3781 		goto out_unlock;
3782 
3783 	/*
3784 	 * If the first vma contains huge pages, make sure start address
3785 	 * is aligned to huge page size.
3786 	 */
3787 	if (is_vm_hugetlb_page(vma)) {
3788 		unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
3789 
3790 		if (start & (vma_hpagesize - 1))
3791 			goto out_unlock;
3792 	}
3793 
3794 	/*
3795 	 * Search for not compatible vmas.
3796 	 */
3797 	found = false;
3798 	cur = vma;
3799 	do {
3800 		cond_resched();
3801 
3802 		VM_WARN_ON_ONCE(!!cur->vm_userfaultfd_ctx.ctx ^
3803 				!!(cur->vm_flags & __VM_UFFD_FLAGS));
3804 
3805 		/*
3806 		 * Prevent unregistering through a different userfaultfd than
3807 		 * the one used for registration.
3808 		 */
3809 		if (cur->vm_userfaultfd_ctx.ctx &&
3810 		    cur->vm_userfaultfd_ctx.ctx != ctx)
3811 			goto out_unlock;
3812 
3813 		/*
3814 		 * Check not compatible vmas, not strictly required
3815 		 * here as not compatible vmas cannot have an
3816 		 * userfaultfd_ctx registered on them, but this
3817 		 * provides for more strict behavior to notice
3818 		 * unregistration errors.
3819 		 */
3820 		if (!vma_can_userfault(cur, cur->vm_flags, wp_async))
3821 			goto out_unlock;
3822 
3823 		found = true;
3824 	} for_each_vma_range(vmi, cur, end);
3825 	VM_WARN_ON_ONCE(!found);
3826 
3827 	vma_iter_set(&vmi, start);
3828 	prev = vma_prev(&vmi);
3829 	if (vma->vm_start < start)
3830 		prev = vma;
3831 
3832 	ret = 0;
3833 	for_each_vma_range(vmi, vma, end) {
3834 		cond_resched();
3835 
3836 		/* VMA not registered with userfaultfd. */
3837 		if (!vma->vm_userfaultfd_ctx.ctx)
3838 			goto skip;
3839 
3840 		VM_WARN_ON_ONCE(vma->vm_userfaultfd_ctx.ctx != ctx);
3841 		VM_WARN_ON_ONCE(!vma_can_userfault(vma, vma->vm_flags, wp_async));
3842 		VM_WARN_ON_ONCE(!(vma->vm_flags & VM_MAYWRITE));
3843 
3844 		if (vma->vm_start > start)
3845 			start = vma->vm_start;
3846 		vma_end = min(end, vma->vm_end);
3847 
3848 		if (userfaultfd_missing(vma)) {
3849 			/*
3850 			 * Wake any concurrent pending userfault while
3851 			 * we unregister, so they will not hang
3852 			 * permanently and it avoids userland to call
3853 			 * UFFDIO_WAKE explicitly.
3854 			 */
3855 			struct userfaultfd_wake_range range;
3856 			range.start = start;
3857 			range.len = vma_end - start;
3858 			wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
3859 		}
3860 
3861 		vma = userfaultfd_clear_vma(&vmi, prev, vma,
3862 					    start, vma_end);
3863 		if (IS_ERR(vma)) {
3864 			ret = PTR_ERR(vma);
3865 			break;
3866 		}
3867 
3868 skip:
3869 		prev = vma;
3870 		start = vma->vm_end;
3871 	}
3872 
3873 out_unlock:
3874 	mmap_write_unlock(mm);
3875 	mmput(mm);
3876 out:
3877 	return ret;
3878 }
3879 
3880 /*
3881  * userfaultfd_wake may be used in combination with the
3882  * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
3883  */
3884 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
3885 			    unsigned long arg)
3886 {
3887 	int ret;
3888 	struct uffdio_range uffdio_wake;
3889 	struct userfaultfd_wake_range range;
3890 	const void __user *buf = (void __user *)arg;
3891 
3892 	ret = -EFAULT;
3893 	if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
3894 		goto out;
3895 
3896 	ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
3897 	if (ret)
3898 		goto out;
3899 
3900 	range.start = uffdio_wake.start;
3901 	range.len = uffdio_wake.len;
3902 
3903 	/*
3904 	 * len == 0 means wake all and we don't want to wake all here,
3905 	 * so check it again to be sure.
3906 	 */
3907 	VM_WARN_ON_ONCE(!range.len);
3908 
3909 	wake_userfault(ctx, &range);
3910 	ret = 0;
3911 
3912 out:
3913 	return ret;
3914 }
3915 
3916 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
3917 			    unsigned long arg)
3918 {
3919 	__s64 ret;
3920 	struct uffdio_copy uffdio_copy;
3921 	struct uffdio_copy __user *user_uffdio_copy;
3922 	struct userfaultfd_wake_range range;
3923 	uffd_flags_t flags = 0;
3924 
3925 	user_uffdio_copy = (struct uffdio_copy __user *) arg;
3926 
3927 	ret = -EAGAIN;
3928 	if (unlikely(atomic_read(&ctx->mmap_changing))) {
3929 		if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
3930 			return -EFAULT;
3931 		goto out;
3932 	}
3933 
3934 	ret = -EFAULT;
3935 	if (copy_from_user(&uffdio_copy, user_uffdio_copy,
3936 			   /* don't copy "copy" last field */
3937 			   sizeof(uffdio_copy)-sizeof(__s64)))
3938 		goto out;
3939 
3940 	ret = validate_unaligned_range(ctx->mm, uffdio_copy.src,
3941 				       uffdio_copy.len);
3942 	if (ret)
3943 		goto out;
3944 	ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
3945 	if (ret)
3946 		goto out;
3947 
3948 	ret = -EINVAL;
3949 	if (uffdio_copy.mode & ~(UFFDIO_COPY_MODE_DONTWAKE|UFFDIO_COPY_MODE_WP))
3950 		goto out;
3951 	if (uffdio_copy.mode & UFFDIO_COPY_MODE_WP)
3952 		flags |= MFILL_ATOMIC_WP;
3953 	if (mmget_not_zero(ctx->mm)) {
3954 		ret = mfill_atomic_copy(ctx, uffdio_copy.dst, uffdio_copy.src,
3955 					uffdio_copy.len, flags);
3956 		mmput(ctx->mm);
3957 	} else {
3958 		return -ESRCH;
3959 	}
3960 	if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
3961 		return -EFAULT;
3962 	if (ret < 0)
3963 		goto out;
3964 	VM_WARN_ON_ONCE(!ret);
3965 	/* len == 0 would wake all */
3966 	range.len = ret;
3967 	if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
3968 		range.start = uffdio_copy.dst;
3969 		wake_userfault(ctx, &range);
3970 	}
3971 	ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
3972 out:
3973 	return ret;
3974 }
3975 
3976 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
3977 				unsigned long arg)
3978 {
3979 	__s64 ret;
3980 	struct uffdio_zeropage uffdio_zeropage;
3981 	struct uffdio_zeropage __user *user_uffdio_zeropage;
3982 	struct userfaultfd_wake_range range;
3983 
3984 	user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
3985 
3986 	ret = -EAGAIN;
3987 	if (unlikely(atomic_read(&ctx->mmap_changing))) {
3988 		if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
3989 			return -EFAULT;
3990 		goto out;
3991 	}
3992 
3993 	ret = -EFAULT;
3994 	if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
3995 			   /* don't copy "zeropage" last field */
3996 			   sizeof(uffdio_zeropage)-sizeof(__s64)))
3997 		goto out;
3998 
3999 	ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
4000 			     uffdio_zeropage.range.len);
4001 	if (ret)
4002 		goto out;
4003 	ret = -EINVAL;
4004 	if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
4005 		goto out;
4006 
4007 	if (mmget_not_zero(ctx->mm)) {
4008 		ret = mfill_atomic_zeropage(ctx, uffdio_zeropage.range.start,
4009 					    uffdio_zeropage.range.len);
4010 		mmput(ctx->mm);
4011 	} else {
4012 		return -ESRCH;
4013 	}
4014 	if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
4015 		return -EFAULT;
4016 	if (ret < 0)
4017 		goto out;
4018 	/* len == 0 would wake all */
4019 	VM_WARN_ON_ONCE(!ret);
4020 	range.len = ret;
4021 	if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
4022 		range.start = uffdio_zeropage.range.start;
4023 		wake_userfault(ctx, &range);
4024 	}
4025 	ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
4026 out:
4027 	return ret;
4028 }
4029 
4030 static int userfaultfd_writeprotect(struct userfaultfd_ctx *ctx,
4031 				    unsigned long arg)
4032 {
4033 	int ret;
4034 	struct uffdio_writeprotect uffdio_wp;
4035 	struct uffdio_writeprotect __user *user_uffdio_wp;
4036 	struct userfaultfd_wake_range range;
4037 	bool mode_wp, mode_dontwake;
4038 
4039 	if (atomic_read(&ctx->mmap_changing))
4040 		return -EAGAIN;
4041 
4042 	user_uffdio_wp = (struct uffdio_writeprotect __user *) arg;
4043 
4044 	if (copy_from_user(&uffdio_wp, user_uffdio_wp,
4045 			   sizeof(struct uffdio_writeprotect)))
4046 		return -EFAULT;
4047 
4048 	ret = validate_range(ctx->mm, uffdio_wp.range.start,
4049 			     uffdio_wp.range.len);
4050 	if (ret)
4051 		return ret;
4052 
4053 	if (uffdio_wp.mode & ~(UFFDIO_WRITEPROTECT_MODE_DONTWAKE |
4054 			       UFFDIO_WRITEPROTECT_MODE_WP))
4055 		return -EINVAL;
4056 
4057 	mode_wp = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_WP;
4058 	mode_dontwake = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_DONTWAKE;
4059 
4060 	if (mode_wp && mode_dontwake)
4061 		return -EINVAL;
4062 
4063 	if (mmget_not_zero(ctx->mm)) {
4064 		ret = mwriteprotect_range(ctx, uffdio_wp.range.start,
4065 					  uffdio_wp.range.len, mode_wp);
4066 		mmput(ctx->mm);
4067 	} else {
4068 		return -ESRCH;
4069 	}
4070 
4071 	if (ret)
4072 		return ret;
4073 
4074 	if (!mode_wp && !mode_dontwake) {
4075 		range.start = uffdio_wp.range.start;
4076 		range.len = uffdio_wp.range.len;
4077 		wake_userfault(ctx, &range);
4078 	}
4079 	return ret;
4080 }
4081 
4082 static int userfaultfd_continue(struct userfaultfd_ctx *ctx, unsigned long arg)
4083 {
4084 	__s64 ret;
4085 	struct uffdio_continue uffdio_continue;
4086 	struct uffdio_continue __user *user_uffdio_continue;
4087 	struct userfaultfd_wake_range range;
4088 	uffd_flags_t flags = 0;
4089 
4090 	user_uffdio_continue = (struct uffdio_continue __user *)arg;
4091 
4092 	ret = -EAGAIN;
4093 	if (unlikely(atomic_read(&ctx->mmap_changing))) {
4094 		if (unlikely(put_user(ret, &user_uffdio_continue->mapped)))
4095 			return -EFAULT;
4096 		goto out;
4097 	}
4098 
4099 	ret = -EFAULT;
4100 	if (copy_from_user(&uffdio_continue, user_uffdio_continue,
4101 			   /* don't copy the output fields */
4102 			   sizeof(uffdio_continue) - (sizeof(__s64))))
4103 		goto out;
4104 
4105 	ret = validate_range(ctx->mm, uffdio_continue.range.start,
4106 			     uffdio_continue.range.len);
4107 	if (ret)
4108 		goto out;
4109 
4110 	ret = -EINVAL;
4111 	if (uffdio_continue.mode & ~(UFFDIO_CONTINUE_MODE_DONTWAKE |
4112 				     UFFDIO_CONTINUE_MODE_WP))
4113 		goto out;
4114 	if (uffdio_continue.mode & UFFDIO_CONTINUE_MODE_WP)
4115 		flags |= MFILL_ATOMIC_WP;
4116 
4117 	if (mmget_not_zero(ctx->mm)) {
4118 		ret = mfill_atomic_continue(ctx, uffdio_continue.range.start,
4119 					    uffdio_continue.range.len, flags);
4120 		mmput(ctx->mm);
4121 	} else {
4122 		return -ESRCH;
4123 	}
4124 
4125 	if (unlikely(put_user(ret, &user_uffdio_continue->mapped)))
4126 		return -EFAULT;
4127 	if (ret < 0)
4128 		goto out;
4129 
4130 	/* len == 0 would wake all */
4131 	VM_WARN_ON_ONCE(!ret);
4132 	range.len = ret;
4133 	if (!(uffdio_continue.mode & UFFDIO_CONTINUE_MODE_DONTWAKE)) {
4134 		range.start = uffdio_continue.range.start;
4135 		wake_userfault(ctx, &range);
4136 	}
4137 	ret = range.len == uffdio_continue.range.len ? 0 : -EAGAIN;
4138 
4139 out:
4140 	return ret;
4141 }
4142 
4143 static inline int userfaultfd_poison(struct userfaultfd_ctx *ctx, unsigned long arg)
4144 {
4145 	__s64 ret;
4146 	struct uffdio_poison uffdio_poison;
4147 	struct uffdio_poison __user *user_uffdio_poison;
4148 	struct userfaultfd_wake_range range;
4149 
4150 	user_uffdio_poison = (struct uffdio_poison __user *)arg;
4151 
4152 	ret = -EAGAIN;
4153 	if (unlikely(atomic_read(&ctx->mmap_changing))) {
4154 		if (unlikely(put_user(ret, &user_uffdio_poison->updated)))
4155 			return -EFAULT;
4156 		goto out;
4157 	}
4158 
4159 	ret = -EFAULT;
4160 	if (copy_from_user(&uffdio_poison, user_uffdio_poison,
4161 			   /* don't copy the output fields */
4162 			   sizeof(uffdio_poison) - (sizeof(__s64))))
4163 		goto out;
4164 
4165 	ret = validate_range(ctx->mm, uffdio_poison.range.start,
4166 			     uffdio_poison.range.len);
4167 	if (ret)
4168 		goto out;
4169 
4170 	ret = -EINVAL;
4171 	if (uffdio_poison.mode & ~UFFDIO_POISON_MODE_DONTWAKE)
4172 		goto out;
4173 
4174 	if (mmget_not_zero(ctx->mm)) {
4175 		ret = mfill_atomic_poison(ctx, uffdio_poison.range.start,
4176 					  uffdio_poison.range.len, 0);
4177 		mmput(ctx->mm);
4178 	} else {
4179 		return -ESRCH;
4180 	}
4181 
4182 	if (unlikely(put_user(ret, &user_uffdio_poison->updated)))
4183 		return -EFAULT;
4184 	if (ret < 0)
4185 		goto out;
4186 
4187 	/* len == 0 would wake all */
4188 	VM_WARN_ON_ONCE(!ret);
4189 	range.len = ret;
4190 	if (!(uffdio_poison.mode & UFFDIO_POISON_MODE_DONTWAKE)) {
4191 		range.start = uffdio_poison.range.start;
4192 		wake_userfault(ctx, &range);
4193 	}
4194 	ret = range.len == uffdio_poison.range.len ? 0 : -EAGAIN;
4195 
4196 out:
4197 	return ret;
4198 }
4199 
4200 bool userfaultfd_wp_async(struct vm_area_struct *vma)
4201 {
4202 	return userfaultfd_wp_async_ctx(vma->vm_userfaultfd_ctx.ctx);
4203 }
4204 
4205 static inline unsigned int uffd_ctx_features(__u64 user_features)
4206 {
4207 	/*
4208 	 * For the current set of features the bits just coincide. Set
4209 	 * UFFD_FEATURE_INITIALIZED to mark the features as enabled.
4210 	 */
4211 	return (unsigned int)user_features | UFFD_FEATURE_INITIALIZED;
4212 }
4213 
4214 static int userfaultfd_move(struct userfaultfd_ctx *ctx,
4215 			    unsigned long arg)
4216 {
4217 	__s64 ret;
4218 	struct uffdio_move uffdio_move;
4219 	struct uffdio_move __user *user_uffdio_move;
4220 	struct userfaultfd_wake_range range;
4221 	struct mm_struct *mm = ctx->mm;
4222 
4223 	user_uffdio_move = (struct uffdio_move __user *) arg;
4224 
4225 	ret = -EAGAIN;
4226 	if (unlikely(atomic_read(&ctx->mmap_changing))) {
4227 		if (unlikely(put_user(ret, &user_uffdio_move->move)))
4228 			return -EFAULT;
4229 		goto out;
4230 	}
4231 
4232 	if (copy_from_user(&uffdio_move, user_uffdio_move,
4233 			   /* don't copy "move" last field */
4234 			   sizeof(uffdio_move)-sizeof(__s64)))
4235 		return -EFAULT;
4236 
4237 	/* Do not allow cross-mm moves. */
4238 	if (mm != current->mm)
4239 		return -EINVAL;
4240 
4241 	ret = validate_range(mm, uffdio_move.dst, uffdio_move.len);
4242 	if (ret)
4243 		return ret;
4244 
4245 	ret = validate_range(mm, uffdio_move.src, uffdio_move.len);
4246 	if (ret)
4247 		return ret;
4248 
4249 	if (uffdio_move.mode & ~(UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES|
4250 				 UFFDIO_MOVE_MODE_DONTWAKE))
4251 		return -EINVAL;
4252 
4253 	if (mmget_not_zero(mm)) {
4254 		ret = move_pages(ctx, uffdio_move.dst, uffdio_move.src,
4255 				 uffdio_move.len, uffdio_move.mode);
4256 		mmput(mm);
4257 	} else {
4258 		return -ESRCH;
4259 	}
4260 
4261 	if (unlikely(put_user(ret, &user_uffdio_move->move)))
4262 		return -EFAULT;
4263 	if (ret < 0)
4264 		goto out;
4265 
4266 	/* len == 0 would wake all */
4267 	VM_WARN_ON(!ret);
4268 	range.len = ret;
4269 	if (!(uffdio_move.mode & UFFDIO_MOVE_MODE_DONTWAKE)) {
4270 		range.start = uffdio_move.dst;
4271 		wake_userfault(ctx, &range);
4272 	}
4273 	ret = range.len == uffdio_move.len ? 0 : -EAGAIN;
4274 
4275 out:
4276 	return ret;
4277 }
4278 
4279 /*
4280  * userland asks for a certain API version and we return which bits
4281  * and ioctl commands are implemented in this kernel for such API
4282  * version or -EINVAL if unknown.
4283  */
4284 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
4285 			   unsigned long arg)
4286 {
4287 	struct uffdio_api uffdio_api;
4288 	void __user *buf = (void __user *)arg;
4289 	unsigned int ctx_features;
4290 	int ret;
4291 	__u64 features;
4292 
4293 	ret = -EFAULT;
4294 	if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
4295 		goto out;
4296 	features = uffdio_api.features;
4297 	ret = -EINVAL;
4298 	if (uffdio_api.api != UFFD_API)
4299 		goto err_out;
4300 	ret = -EPERM;
4301 	if ((features & UFFD_FEATURE_EVENT_FORK) && !capable(CAP_SYS_PTRACE))
4302 		goto err_out;
4303 
4304 	/* WP_ASYNC relies on WP_UNPOPULATED, choose it unconditionally */
4305 	if (features & UFFD_FEATURE_WP_ASYNC)
4306 		features |= UFFD_FEATURE_WP_UNPOPULATED;
4307 
4308 	/* report all available features and ioctls to userland */
4309 	uffdio_api.features = UFFD_API_FEATURES;
4310 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
4311 	uffdio_api.features &=
4312 		~(UFFD_FEATURE_MINOR_HUGETLBFS | UFFD_FEATURE_MINOR_SHMEM);
4313 #endif
4314 	if (!pgtable_supports_uffd_wp())
4315 		uffdio_api.features &= ~UFFD_FEATURE_PAGEFAULT_FLAG_WP;
4316 
4317 	if (!uffd_supports_wp_marker()) {
4318 		uffdio_api.features &= ~UFFD_FEATURE_WP_HUGETLBFS_SHMEM;
4319 		uffdio_api.features &= ~UFFD_FEATURE_WP_UNPOPULATED;
4320 		uffdio_api.features &= ~UFFD_FEATURE_WP_ASYNC;
4321 	}
4322 
4323 	ret = -EINVAL;
4324 	if (features & ~uffdio_api.features)
4325 		goto err_out;
4326 
4327 	uffdio_api.ioctls = UFFD_API_IOCTLS;
4328 	ret = -EFAULT;
4329 	if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
4330 		goto out;
4331 
4332 	/* only enable the requested features for this uffd context */
4333 	ctx_features = uffd_ctx_features(features);
4334 	ret = -EINVAL;
4335 	if (cmpxchg(&ctx->features, 0, ctx_features) != 0)
4336 		goto err_out;
4337 
4338 	ret = 0;
4339 out:
4340 	return ret;
4341 err_out:
4342 	memset(&uffdio_api, 0, sizeof(uffdio_api));
4343 	if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
4344 		ret = -EFAULT;
4345 	goto out;
4346 }
4347 
4348 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
4349 			      unsigned long arg)
4350 {
4351 	int ret = -EINVAL;
4352 	struct userfaultfd_ctx *ctx = file->private_data;
4353 
4354 	if (cmd != UFFDIO_API && !userfaultfd_is_initialized(ctx))
4355 		return -EINVAL;
4356 
4357 	switch (cmd) {
4358 	case UFFDIO_API:
4359 		ret = userfaultfd_api(ctx, arg);
4360 		break;
4361 	case UFFDIO_REGISTER:
4362 		ret = userfaultfd_register(ctx, arg);
4363 		break;
4364 	case UFFDIO_UNREGISTER:
4365 		ret = userfaultfd_unregister(ctx, arg);
4366 		break;
4367 	case UFFDIO_WAKE:
4368 		ret = userfaultfd_wake(ctx, arg);
4369 		break;
4370 	case UFFDIO_COPY:
4371 		ret = userfaultfd_copy(ctx, arg);
4372 		break;
4373 	case UFFDIO_ZEROPAGE:
4374 		ret = userfaultfd_zeropage(ctx, arg);
4375 		break;
4376 	case UFFDIO_MOVE:
4377 		ret = userfaultfd_move(ctx, arg);
4378 		break;
4379 	case UFFDIO_WRITEPROTECT:
4380 		ret = userfaultfd_writeprotect(ctx, arg);
4381 		break;
4382 	case UFFDIO_CONTINUE:
4383 		ret = userfaultfd_continue(ctx, arg);
4384 		break;
4385 	case UFFDIO_POISON:
4386 		ret = userfaultfd_poison(ctx, arg);
4387 		break;
4388 	}
4389 	return ret;
4390 }
4391 
4392 #ifdef CONFIG_PROC_FS
4393 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
4394 {
4395 	struct userfaultfd_ctx *ctx = f->private_data;
4396 	wait_queue_entry_t *wq;
4397 	unsigned long pending = 0, total = 0;
4398 
4399 	spin_lock_irq(&ctx->fault_pending_wqh.lock);
4400 	list_for_each_entry(wq, &ctx->fault_pending_wqh.head, entry) {
4401 		pending++;
4402 		total++;
4403 	}
4404 	list_for_each_entry(wq, &ctx->fault_wqh.head, entry) {
4405 		total++;
4406 	}
4407 	spin_unlock_irq(&ctx->fault_pending_wqh.lock);
4408 
4409 	/*
4410 	 * If more protocols will be added, there will be all shown
4411 	 * separated by a space. Like this:
4412 	 *	protocols: aa:... bb:...
4413 	 */
4414 	seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
4415 		   pending, total, UFFD_API, ctx->features,
4416 		   UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
4417 }
4418 #endif
4419 
4420 static const struct file_operations userfaultfd_fops = {
4421 #ifdef CONFIG_PROC_FS
4422 	.show_fdinfo	= userfaultfd_show_fdinfo,
4423 #endif
4424 	.release	= userfaultfd_release,
4425 	.poll		= userfaultfd_poll,
4426 	.read_iter	= userfaultfd_read_iter,
4427 	.unlocked_ioctl = userfaultfd_ioctl,
4428 	.compat_ioctl	= compat_ptr_ioctl,
4429 	.llseek		= noop_llseek,
4430 };
4431 
4432 static void init_once_userfaultfd_ctx(void *mem)
4433 {
4434 	struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
4435 
4436 	init_waitqueue_head(&ctx->fault_pending_wqh);
4437 	init_waitqueue_head(&ctx->fault_wqh);
4438 	init_waitqueue_head(&ctx->event_wqh);
4439 	init_waitqueue_head(&ctx->fd_wqh);
4440 	seqcount_spinlock_init(&ctx->refile_seq, &ctx->fault_pending_wqh.lock);
4441 }
4442 
4443 static int new_userfaultfd(int flags)
4444 {
4445 	struct userfaultfd_ctx *ctx __free(kfree) = NULL;
4446 
4447 	VM_WARN_ON_ONCE(!current->mm);
4448 
4449 	/* Check the UFFD_* constants for consistency. */
4450 	BUILD_BUG_ON(UFFD_USER_MODE_ONLY & UFFD_SHARED_FCNTL_FLAGS);
4451 
4452 	if (flags & ~(UFFD_SHARED_FCNTL_FLAGS | UFFD_USER_MODE_ONLY))
4453 		return -EINVAL;
4454 
4455 	ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
4456 	if (!ctx)
4457 		return -ENOMEM;
4458 
4459 	refcount_set(&ctx->refcount, 1);
4460 	ctx->flags = flags;
4461 	ctx->features = 0;
4462 	ctx->released = false;
4463 	init_rwsem(&ctx->map_changing_lock);
4464 	atomic_set(&ctx->mmap_changing, 0);
4465 	ctx->mm = current->mm;
4466 
4467 	FD_PREPARE(fdf, flags & UFFD_SHARED_FCNTL_FLAGS,
4468 		   anon_inode_create_getfile("[userfaultfd]", &userfaultfd_fops, ctx,
4469 					     O_RDONLY | (flags & UFFD_SHARED_FCNTL_FLAGS),
4470 					     NULL));
4471 	if (fdf.err)
4472 		return fdf.err;
4473 
4474 	/* prevent the mm struct to be freed */
4475 	mmgrab(ctx->mm);
4476 	fd_prepare_file(fdf)->f_mode |= FMODE_NOWAIT;
4477 	retain_and_null_ptr(ctx);
4478 	return fd_publish(fdf);
4479 }
4480 
4481 static inline bool userfaultfd_syscall_allowed(int flags)
4482 {
4483 	/* Userspace-only page faults are always allowed */
4484 	if (flags & UFFD_USER_MODE_ONLY)
4485 		return true;
4486 
4487 	/*
4488 	 * The user is requesting a userfaultfd which can handle kernel faults.
4489 	 * Privileged users are always allowed to do this.
4490 	 */
4491 	if (capable(CAP_SYS_PTRACE))
4492 		return true;
4493 
4494 	/* Otherwise, access to kernel fault handling is sysctl controlled. */
4495 	return sysctl_unprivileged_userfaultfd;
4496 }
4497 
4498 SYSCALL_DEFINE1(userfaultfd, int, flags)
4499 {
4500 	if (!userfaultfd_syscall_allowed(flags))
4501 		return -EPERM;
4502 
4503 	return new_userfaultfd(flags);
4504 }
4505 
4506 static long userfaultfd_dev_ioctl(struct file *file, unsigned int cmd, unsigned long flags)
4507 {
4508 	if (cmd != USERFAULTFD_IOC_NEW)
4509 		return -EINVAL;
4510 
4511 	return new_userfaultfd(flags);
4512 }
4513 
4514 static const struct file_operations userfaultfd_dev_fops = {
4515 	.unlocked_ioctl = userfaultfd_dev_ioctl,
4516 	.compat_ioctl = userfaultfd_dev_ioctl,
4517 	.owner = THIS_MODULE,
4518 	.llseek = noop_llseek,
4519 };
4520 
4521 static struct miscdevice userfaultfd_misc = {
4522 	.minor = MISC_DYNAMIC_MINOR,
4523 	.name = "userfaultfd",
4524 	.fops = &userfaultfd_dev_fops
4525 };
4526 
4527 static int __init userfaultfd_init(void)
4528 {
4529 	int ret;
4530 
4531 	ret = misc_register(&userfaultfd_misc);
4532 	if (ret)
4533 		return ret;
4534 
4535 	userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
4536 						sizeof(struct userfaultfd_ctx),
4537 						0,
4538 						SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4539 						init_once_userfaultfd_ctx);
4540 #ifdef CONFIG_SYSCTL
4541 	register_sysctl_init("vm", vm_userfaultfd_table);
4542 #endif
4543 	return 0;
4544 }
4545 __initcall(userfaultfd_init);
4546