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