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