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