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