xref: /linux/fs/userfaultfd.c (revision 1a80ff0f8896750156f22dbf2d4591d79bb2a155)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  fs/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/list.h>
14 #include <linux/hashtable.h>
15 #include <linux/sched/signal.h>
16 #include <linux/sched/mm.h>
17 #include <linux/mm.h>
18 #include <linux/mm_inline.h>
19 #include <linux/mmu_notifier.h>
20 #include <linux/poll.h>
21 #include <linux/slab.h>
22 #include <linux/seq_file.h>
23 #include <linux/file.h>
24 #include <linux/bug.h>
25 #include <linux/anon_inodes.h>
26 #include <linux/syscalls.h>
27 #include <linux/userfaultfd_k.h>
28 #include <linux/mempolicy.h>
29 #include <linux/ioctl.h>
30 #include <linux/security.h>
31 #include <linux/hugetlb.h>
32 #include <linux/swapops.h>
33 #include <linux/miscdevice.h>
34 #include <linux/uio.h>
35 
36 static int sysctl_unprivileged_userfaultfd __read_mostly;
37 
38 #ifdef CONFIG_SYSCTL
39 static const struct ctl_table vm_userfaultfd_table[] = {
40 	{
41 		.procname	= "unprivileged_userfaultfd",
42 		.data		= &sysctl_unprivileged_userfaultfd,
43 		.maxlen		= sizeof(sysctl_unprivileged_userfaultfd),
44 		.mode		= 0644,
45 		.proc_handler	= proc_dointvec_minmax,
46 		.extra1		= SYSCTL_ZERO,
47 		.extra2		= SYSCTL_ONE,
48 	},
49 };
50 #endif
51 
52 static struct kmem_cache *userfaultfd_ctx_cachep __ro_after_init;
53 
54 struct userfaultfd_fork_ctx {
55 	struct userfaultfd_ctx *orig;
56 	struct userfaultfd_ctx *new;
57 	struct list_head list;
58 };
59 
60 struct userfaultfd_unmap_ctx {
61 	struct userfaultfd_ctx *ctx;
62 	unsigned long start;
63 	unsigned long end;
64 	struct list_head list;
65 };
66 
67 struct userfaultfd_wait_queue {
68 	struct uffd_msg msg;
69 	wait_queue_entry_t wq;
70 	struct userfaultfd_ctx *ctx;
71 	bool waken;
72 };
73 
74 struct userfaultfd_wake_range {
75 	unsigned long start;
76 	unsigned long len;
77 };
78 
79 /* internal indication that UFFD_API ioctl was successfully executed */
80 #define UFFD_FEATURE_INITIALIZED		(1u << 31)
81 
82 static bool userfaultfd_is_initialized(struct userfaultfd_ctx *ctx)
83 {
84 	return ctx->features & UFFD_FEATURE_INITIALIZED;
85 }
86 
87 static bool userfaultfd_wp_async_ctx(struct userfaultfd_ctx *ctx)
88 {
89 	return ctx && (ctx->features & UFFD_FEATURE_WP_ASYNC);
90 }
91 
92 /*
93  * Whether WP_UNPOPULATED is enabled on the uffd context.  It is only
94  * meaningful when userfaultfd_wp()==true on the vma and when it's
95  * anonymous.
96  */
97 bool userfaultfd_wp_unpopulated(struct vm_area_struct *vma)
98 {
99 	struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
100 
101 	if (!ctx)
102 		return false;
103 
104 	return ctx->features & UFFD_FEATURE_WP_UNPOPULATED;
105 }
106 
107 static int userfaultfd_wake_function(wait_queue_entry_t *wq, unsigned mode,
108 				     int wake_flags, void *key)
109 {
110 	struct userfaultfd_wake_range *range = key;
111 	int ret;
112 	struct userfaultfd_wait_queue *uwq;
113 	unsigned long start, len;
114 
115 	uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
116 	ret = 0;
117 	/* len == 0 means wake all */
118 	start = range->start;
119 	len = range->len;
120 	if (len && (start > uwq->msg.arg.pagefault.address ||
121 		    start + len <= uwq->msg.arg.pagefault.address))
122 		goto out;
123 	WRITE_ONCE(uwq->waken, true);
124 	/*
125 	 * The Program-Order guarantees provided by the scheduler
126 	 * ensure uwq->waken is visible before the task is woken.
127 	 */
128 	ret = wake_up_state(wq->private, mode);
129 	if (ret) {
130 		/*
131 		 * Wake only once, autoremove behavior.
132 		 *
133 		 * After the effect of list_del_init is visible to the other
134 		 * CPUs, the waitqueue may disappear from under us, see the
135 		 * !list_empty_careful() in handle_userfault().
136 		 *
137 		 * try_to_wake_up() has an implicit smp_mb(), and the
138 		 * wq->private is read before calling the extern function
139 		 * "wake_up_state" (which in turns calls try_to_wake_up).
140 		 */
141 		list_del_init(&wq->entry);
142 	}
143 out:
144 	return ret;
145 }
146 
147 /**
148  * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
149  * context.
150  * @ctx: [in] Pointer to the userfaultfd context.
151  */
152 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
153 {
154 	refcount_inc(&ctx->refcount);
155 }
156 
157 /**
158  * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
159  * context.
160  * @ctx: [in] Pointer to userfaultfd context.
161  *
162  * The userfaultfd context reference must have been previously acquired either
163  * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
164  */
165 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
166 {
167 	if (refcount_dec_and_test(&ctx->refcount)) {
168 		VM_WARN_ON_ONCE(spin_is_locked(&ctx->fault_pending_wqh.lock));
169 		VM_WARN_ON_ONCE(waitqueue_active(&ctx->fault_pending_wqh));
170 		VM_WARN_ON_ONCE(spin_is_locked(&ctx->fault_wqh.lock));
171 		VM_WARN_ON_ONCE(waitqueue_active(&ctx->fault_wqh));
172 		VM_WARN_ON_ONCE(spin_is_locked(&ctx->event_wqh.lock));
173 		VM_WARN_ON_ONCE(waitqueue_active(&ctx->event_wqh));
174 		VM_WARN_ON_ONCE(spin_is_locked(&ctx->fd_wqh.lock));
175 		VM_WARN_ON_ONCE(waitqueue_active(&ctx->fd_wqh));
176 		mmdrop(ctx->mm);
177 		kmem_cache_free(userfaultfd_ctx_cachep, ctx);
178 	}
179 }
180 
181 static inline void msg_init(struct uffd_msg *msg)
182 {
183 	BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
184 	/*
185 	 * Must use memset to zero out the paddings or kernel data is
186 	 * leaked to userland.
187 	 */
188 	memset(msg, 0, sizeof(struct uffd_msg));
189 }
190 
191 static inline struct uffd_msg userfault_msg(unsigned long address,
192 					    unsigned long real_address,
193 					    unsigned int flags,
194 					    unsigned long reason,
195 					    unsigned int features)
196 {
197 	struct uffd_msg msg;
198 
199 	msg_init(&msg);
200 	msg.event = UFFD_EVENT_PAGEFAULT;
201 
202 	msg.arg.pagefault.address = (features & UFFD_FEATURE_EXACT_ADDRESS) ?
203 				    real_address : address;
204 
205 	/*
206 	 * These flags indicate why the userfault occurred:
207 	 * - UFFD_PAGEFAULT_FLAG_WP indicates a write protect fault.
208 	 * - UFFD_PAGEFAULT_FLAG_MINOR indicates a minor fault.
209 	 * - Neither of these flags being set indicates a MISSING fault.
210 	 *
211 	 * Separately, UFFD_PAGEFAULT_FLAG_WRITE indicates it was a write
212 	 * fault. Otherwise, it was a read fault.
213 	 */
214 	if (flags & FAULT_FLAG_WRITE)
215 		msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
216 	if (reason & VM_UFFD_WP)
217 		msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
218 	if (reason & VM_UFFD_MINOR)
219 		msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_MINOR;
220 	if (features & UFFD_FEATURE_THREAD_ID)
221 		msg.arg.pagefault.feat.ptid = task_pid_vnr(current);
222 	return msg;
223 }
224 
225 #ifdef CONFIG_HUGETLB_PAGE
226 /*
227  * Same functionality as userfaultfd_must_wait below with modifications for
228  * hugepmd ranges.
229  */
230 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
231 					      struct vm_fault *vmf,
232 					      unsigned long reason)
233 {
234 	struct vm_area_struct *vma = vmf->vma;
235 	pte_t *ptep, pte;
236 	bool ret = true;
237 
238 	assert_fault_locked(vmf);
239 
240 	ptep = hugetlb_walk(vma, vmf->address, vma_mmu_pagesize(vma));
241 	if (!ptep)
242 		goto out;
243 
244 	ret = false;
245 	pte = huge_ptep_get(vma->vm_mm, vmf->address, ptep);
246 
247 	/*
248 	 * Lockless access: we're in a wait_event so it's ok if it
249 	 * changes under us.  PTE markers should be handled the same as none
250 	 * ptes here.
251 	 */
252 	if (huge_pte_none_mostly(pte))
253 		ret = true;
254 	if (!huge_pte_write(pte) && (reason & VM_UFFD_WP))
255 		ret = true;
256 out:
257 	return ret;
258 }
259 #else
260 static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
261 					      struct vm_fault *vmf,
262 					      unsigned long reason)
263 {
264 	return false;	/* should never get here */
265 }
266 #endif /* CONFIG_HUGETLB_PAGE */
267 
268 /*
269  * Verify the pagetables are still not ok after having reigstered into
270  * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
271  * userfault that has already been resolved, if userfaultfd_read_iter and
272  * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
273  * threads.
274  */
275 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
276 					 struct vm_fault *vmf,
277 					 unsigned long reason)
278 {
279 	struct mm_struct *mm = ctx->mm;
280 	unsigned long address = vmf->address;
281 	pgd_t *pgd;
282 	p4d_t *p4d;
283 	pud_t *pud;
284 	pmd_t *pmd, _pmd;
285 	pte_t *pte;
286 	pte_t ptent;
287 	bool ret = true;
288 
289 	assert_fault_locked(vmf);
290 
291 	pgd = pgd_offset(mm, address);
292 	if (!pgd_present(*pgd))
293 		goto out;
294 	p4d = p4d_offset(pgd, address);
295 	if (!p4d_present(*p4d))
296 		goto out;
297 	pud = pud_offset(p4d, address);
298 	if (!pud_present(*pud))
299 		goto out;
300 	pmd = pmd_offset(pud, address);
301 again:
302 	_pmd = pmdp_get_lockless(pmd);
303 	if (pmd_none(_pmd))
304 		goto out;
305 
306 	ret = false;
307 	if (!pmd_present(_pmd) || pmd_devmap(_pmd))
308 		goto out;
309 
310 	if (pmd_trans_huge(_pmd)) {
311 		if (!pmd_write(_pmd) && (reason & VM_UFFD_WP))
312 			ret = true;
313 		goto out;
314 	}
315 
316 	pte = pte_offset_map(pmd, address);
317 	if (!pte) {
318 		ret = true;
319 		goto again;
320 	}
321 	/*
322 	 * Lockless access: we're in a wait_event so it's ok if it
323 	 * changes under us.  PTE markers should be handled the same as none
324 	 * ptes here.
325 	 */
326 	ptent = ptep_get(pte);
327 	if (pte_none_mostly(ptent))
328 		ret = true;
329 	if (!pte_write(ptent) && (reason & VM_UFFD_WP))
330 		ret = true;
331 	pte_unmap(pte);
332 
333 out:
334 	return ret;
335 }
336 
337 static inline unsigned int userfaultfd_get_blocking_state(unsigned int flags)
338 {
339 	if (flags & FAULT_FLAG_INTERRUPTIBLE)
340 		return TASK_INTERRUPTIBLE;
341 
342 	if (flags & FAULT_FLAG_KILLABLE)
343 		return TASK_KILLABLE;
344 
345 	return TASK_UNINTERRUPTIBLE;
346 }
347 
348 /*
349  * The locking rules involved in returning VM_FAULT_RETRY depending on
350  * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
351  * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
352  * recommendation in __lock_page_or_retry is not an understatement.
353  *
354  * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_lock must be released
355  * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
356  * not set.
357  *
358  * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
359  * set, VM_FAULT_RETRY can still be returned if and only if there are
360  * fatal_signal_pending()s, and the mmap_lock must be released before
361  * returning it.
362  */
363 vm_fault_t handle_userfault(struct vm_fault *vmf, unsigned long reason)
364 {
365 	struct vm_area_struct *vma = vmf->vma;
366 	struct mm_struct *mm = vma->vm_mm;
367 	struct userfaultfd_ctx *ctx;
368 	struct userfaultfd_wait_queue uwq;
369 	vm_fault_t ret = VM_FAULT_SIGBUS;
370 	bool must_wait;
371 	unsigned int blocking_state;
372 
373 	/*
374 	 * We don't do userfault handling for the final child pid update
375 	 * and when coredumping (faults triggered by get_dump_page()).
376 	 */
377 	if (current->flags & (PF_EXITING|PF_DUMPCORE))
378 		goto out;
379 
380 	assert_fault_locked(vmf);
381 
382 	ctx = vma->vm_userfaultfd_ctx.ctx;
383 	if (!ctx)
384 		goto out;
385 
386 	VM_WARN_ON_ONCE(ctx->mm != mm);
387 
388 	/* Any unrecognized flag is a bug. */
389 	VM_WARN_ON_ONCE(reason & ~__VM_UFFD_FLAGS);
390 	/* 0 or > 1 flags set is a bug; we expect exactly 1. */
391 	VM_WARN_ON_ONCE(!reason || (reason & (reason - 1)));
392 
393 	if (ctx->features & UFFD_FEATURE_SIGBUS)
394 		goto out;
395 	if (!(vmf->flags & FAULT_FLAG_USER) && (ctx->flags & UFFD_USER_MODE_ONLY))
396 		goto out;
397 
398 	/*
399 	 * Check that we can return VM_FAULT_RETRY.
400 	 *
401 	 * NOTE: it should become possible to return VM_FAULT_RETRY
402 	 * even if FAULT_FLAG_TRIED is set without leading to gup()
403 	 * -EBUSY failures, if the userfaultfd is to be extended for
404 	 * VM_UFFD_WP tracking and we intend to arm the userfault
405 	 * without first stopping userland access to the memory. For
406 	 * VM_UFFD_MISSING userfaults this is enough for now.
407 	 */
408 	if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
409 		/*
410 		 * Validate the invariant that nowait must allow retry
411 		 * to be sure not to return SIGBUS erroneously on
412 		 * nowait invocations.
413 		 */
414 		VM_WARN_ON_ONCE(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
415 #ifdef CONFIG_DEBUG_VM
416 		if (printk_ratelimit()) {
417 			pr_warn("FAULT_FLAG_ALLOW_RETRY missing %x\n",
418 				vmf->flags);
419 			dump_stack();
420 		}
421 #endif
422 		goto out;
423 	}
424 
425 	/*
426 	 * Handle nowait, not much to do other than tell it to retry
427 	 * and wait.
428 	 */
429 	ret = VM_FAULT_RETRY;
430 	if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
431 		goto out;
432 
433 	if (unlikely(READ_ONCE(ctx->released))) {
434 		/*
435 		 * If a concurrent release is detected, do not return
436 		 * VM_FAULT_SIGBUS or VM_FAULT_NOPAGE, but instead always
437 		 * return VM_FAULT_RETRY with lock released proactively.
438 		 *
439 		 * If we were to return VM_FAULT_SIGBUS here, the non
440 		 * cooperative manager would be instead forced to
441 		 * always call UFFDIO_UNREGISTER before it can safely
442 		 * close the uffd, to avoid involuntary SIGBUS triggered.
443 		 *
444 		 * If we were to return VM_FAULT_NOPAGE, it would work for
445 		 * the fault path, in which the lock will be released
446 		 * later.  However for GUP, faultin_page() does nothing
447 		 * special on NOPAGE, so GUP would spin retrying without
448 		 * releasing the mmap read lock, causing possible livelock.
449 		 *
450 		 * Here only VM_FAULT_RETRY would make sure the mmap lock
451 		 * be released immediately, so that the thread concurrently
452 		 * releasing the userfault would always make progress.
453 		 */
454 		release_fault_lock(vmf);
455 		goto out;
456 	}
457 
458 	/* take the reference before dropping the mmap_lock */
459 	userfaultfd_ctx_get(ctx);
460 
461 	init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
462 	uwq.wq.private = current;
463 	uwq.msg = userfault_msg(vmf->address, vmf->real_address, vmf->flags,
464 				reason, ctx->features);
465 	uwq.ctx = ctx;
466 	uwq.waken = false;
467 
468 	blocking_state = userfaultfd_get_blocking_state(vmf->flags);
469 
470         /*
471          * Take the vma lock now, in order to safely call
472          * userfaultfd_huge_must_wait() later. Since acquiring the
473          * (sleepable) vma lock can modify the current task state, that
474          * must be before explicitly calling set_current_state().
475          */
476 	if (is_vm_hugetlb_page(vma))
477 		hugetlb_vma_lock_read(vma);
478 
479 	spin_lock_irq(&ctx->fault_pending_wqh.lock);
480 	/*
481 	 * After the __add_wait_queue the uwq is visible to userland
482 	 * through poll/read().
483 	 */
484 	__add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
485 	/*
486 	 * The smp_mb() after __set_current_state prevents the reads
487 	 * following the spin_unlock to happen before the list_add in
488 	 * __add_wait_queue.
489 	 */
490 	set_current_state(blocking_state);
491 	spin_unlock_irq(&ctx->fault_pending_wqh.lock);
492 
493 	if (!is_vm_hugetlb_page(vma))
494 		must_wait = userfaultfd_must_wait(ctx, vmf, reason);
495 	else
496 		must_wait = userfaultfd_huge_must_wait(ctx, vmf, reason);
497 	if (is_vm_hugetlb_page(vma))
498 		hugetlb_vma_unlock_read(vma);
499 	release_fault_lock(vmf);
500 
501 	if (likely(must_wait && !READ_ONCE(ctx->released))) {
502 		wake_up_poll(&ctx->fd_wqh, EPOLLIN);
503 		schedule();
504 	}
505 
506 	__set_current_state(TASK_RUNNING);
507 
508 	/*
509 	 * Here we race with the list_del; list_add in
510 	 * userfaultfd_ctx_read(), however because we don't ever run
511 	 * list_del_init() to refile across the two lists, the prev
512 	 * and next pointers will never point to self. list_add also
513 	 * would never let any of the two pointers to point to
514 	 * self. So list_empty_careful won't risk to see both pointers
515 	 * pointing to self at any time during the list refile. The
516 	 * only case where list_del_init() is called is the full
517 	 * removal in the wake function and there we don't re-list_add
518 	 * and it's fine not to block on the spinlock. The uwq on this
519 	 * kernel stack can be released after the list_del_init.
520 	 */
521 	if (!list_empty_careful(&uwq.wq.entry)) {
522 		spin_lock_irq(&ctx->fault_pending_wqh.lock);
523 		/*
524 		 * No need of list_del_init(), the uwq on the stack
525 		 * will be freed shortly anyway.
526 		 */
527 		list_del(&uwq.wq.entry);
528 		spin_unlock_irq(&ctx->fault_pending_wqh.lock);
529 	}
530 
531 	/*
532 	 * ctx may go away after this if the userfault pseudo fd is
533 	 * already released.
534 	 */
535 	userfaultfd_ctx_put(ctx);
536 
537 out:
538 	return ret;
539 }
540 
541 static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
542 					      struct userfaultfd_wait_queue *ewq)
543 {
544 	struct userfaultfd_ctx *release_new_ctx;
545 
546 	if (WARN_ON_ONCE(current->flags & PF_EXITING))
547 		goto out;
548 
549 	ewq->ctx = ctx;
550 	init_waitqueue_entry(&ewq->wq, current);
551 	release_new_ctx = NULL;
552 
553 	spin_lock_irq(&ctx->event_wqh.lock);
554 	/*
555 	 * After the __add_wait_queue the uwq is visible to userland
556 	 * through poll/read().
557 	 */
558 	__add_wait_queue(&ctx->event_wqh, &ewq->wq);
559 	for (;;) {
560 		set_current_state(TASK_KILLABLE);
561 		if (ewq->msg.event == 0)
562 			break;
563 		if (READ_ONCE(ctx->released) ||
564 		    fatal_signal_pending(current)) {
565 			/*
566 			 * &ewq->wq may be queued in fork_event, but
567 			 * __remove_wait_queue ignores the head
568 			 * parameter. It would be a problem if it
569 			 * didn't.
570 			 */
571 			__remove_wait_queue(&ctx->event_wqh, &ewq->wq);
572 			if (ewq->msg.event == UFFD_EVENT_FORK) {
573 				struct userfaultfd_ctx *new;
574 
575 				new = (struct userfaultfd_ctx *)
576 					(unsigned long)
577 					ewq->msg.arg.reserved.reserved1;
578 				release_new_ctx = new;
579 			}
580 			break;
581 		}
582 
583 		spin_unlock_irq(&ctx->event_wqh.lock);
584 
585 		wake_up_poll(&ctx->fd_wqh, EPOLLIN);
586 		schedule();
587 
588 		spin_lock_irq(&ctx->event_wqh.lock);
589 	}
590 	__set_current_state(TASK_RUNNING);
591 	spin_unlock_irq(&ctx->event_wqh.lock);
592 
593 	if (release_new_ctx) {
594 		userfaultfd_release_new(release_new_ctx);
595 		userfaultfd_ctx_put(release_new_ctx);
596 	}
597 
598 	/*
599 	 * ctx may go away after this if the userfault pseudo fd is
600 	 * already released.
601 	 */
602 out:
603 	atomic_dec(&ctx->mmap_changing);
604 	VM_WARN_ON_ONCE(atomic_read(&ctx->mmap_changing) < 0);
605 	userfaultfd_ctx_put(ctx);
606 }
607 
608 static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
609 				       struct userfaultfd_wait_queue *ewq)
610 {
611 	ewq->msg.event = 0;
612 	wake_up_locked(&ctx->event_wqh);
613 	__remove_wait_queue(&ctx->event_wqh, &ewq->wq);
614 }
615 
616 int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
617 {
618 	struct userfaultfd_ctx *ctx = NULL, *octx;
619 	struct userfaultfd_fork_ctx *fctx;
620 
621 	octx = vma->vm_userfaultfd_ctx.ctx;
622 	if (!octx)
623 		return 0;
624 
625 	if (!(octx->features & UFFD_FEATURE_EVENT_FORK)) {
626 		userfaultfd_reset_ctx(vma);
627 		return 0;
628 	}
629 
630 	list_for_each_entry(fctx, fcs, list)
631 		if (fctx->orig == octx) {
632 			ctx = fctx->new;
633 			break;
634 		}
635 
636 	if (!ctx) {
637 		fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
638 		if (!fctx)
639 			return -ENOMEM;
640 
641 		ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
642 		if (!ctx) {
643 			kfree(fctx);
644 			return -ENOMEM;
645 		}
646 
647 		refcount_set(&ctx->refcount, 1);
648 		ctx->flags = octx->flags;
649 		ctx->features = octx->features;
650 		ctx->released = false;
651 		init_rwsem(&ctx->map_changing_lock);
652 		atomic_set(&ctx->mmap_changing, 0);
653 		ctx->mm = vma->vm_mm;
654 		mmgrab(ctx->mm);
655 
656 		userfaultfd_ctx_get(octx);
657 		down_write(&octx->map_changing_lock);
658 		atomic_inc(&octx->mmap_changing);
659 		up_write(&octx->map_changing_lock);
660 		fctx->orig = octx;
661 		fctx->new = ctx;
662 		list_add_tail(&fctx->list, fcs);
663 	}
664 
665 	vma->vm_userfaultfd_ctx.ctx = ctx;
666 	return 0;
667 }
668 
669 static void dup_fctx(struct userfaultfd_fork_ctx *fctx)
670 {
671 	struct userfaultfd_ctx *ctx = fctx->orig;
672 	struct userfaultfd_wait_queue ewq;
673 
674 	msg_init(&ewq.msg);
675 
676 	ewq.msg.event = UFFD_EVENT_FORK;
677 	ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
678 
679 	userfaultfd_event_wait_completion(ctx, &ewq);
680 }
681 
682 void dup_userfaultfd_complete(struct list_head *fcs)
683 {
684 	struct userfaultfd_fork_ctx *fctx, *n;
685 
686 	list_for_each_entry_safe(fctx, n, fcs, list) {
687 		dup_fctx(fctx);
688 		list_del(&fctx->list);
689 		kfree(fctx);
690 	}
691 }
692 
693 void dup_userfaultfd_fail(struct list_head *fcs)
694 {
695 	struct userfaultfd_fork_ctx *fctx, *n;
696 
697 	/*
698 	 * An error has occurred on fork, we will tear memory down, but have
699 	 * allocated memory for fctx's and raised reference counts for both the
700 	 * original and child contexts (and on the mm for each as a result).
701 	 *
702 	 * These would ordinarily be taken care of by a user handling the event,
703 	 * but we are no longer doing so, so manually clean up here.
704 	 *
705 	 * mm tear down will take care of cleaning up VMA contexts.
706 	 */
707 	list_for_each_entry_safe(fctx, n, fcs, list) {
708 		struct userfaultfd_ctx *octx = fctx->orig;
709 		struct userfaultfd_ctx *ctx = fctx->new;
710 
711 		atomic_dec(&octx->mmap_changing);
712 		VM_WARN_ON_ONCE(atomic_read(&octx->mmap_changing) < 0);
713 		userfaultfd_ctx_put(octx);
714 		userfaultfd_ctx_put(ctx);
715 
716 		list_del(&fctx->list);
717 		kfree(fctx);
718 	}
719 }
720 
721 void mremap_userfaultfd_prep(struct vm_area_struct *vma,
722 			     struct vm_userfaultfd_ctx *vm_ctx)
723 {
724 	struct userfaultfd_ctx *ctx;
725 
726 	ctx = vma->vm_userfaultfd_ctx.ctx;
727 
728 	if (!ctx)
729 		return;
730 
731 	if (ctx->features & UFFD_FEATURE_EVENT_REMAP) {
732 		vm_ctx->ctx = ctx;
733 		userfaultfd_ctx_get(ctx);
734 		down_write(&ctx->map_changing_lock);
735 		atomic_inc(&ctx->mmap_changing);
736 		up_write(&ctx->map_changing_lock);
737 	} else {
738 		/* Drop uffd context if remap feature not enabled */
739 		userfaultfd_reset_ctx(vma);
740 	}
741 }
742 
743 void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
744 				 unsigned long from, unsigned long to,
745 				 unsigned long len)
746 {
747 	struct userfaultfd_ctx *ctx = vm_ctx->ctx;
748 	struct userfaultfd_wait_queue ewq;
749 
750 	if (!ctx)
751 		return;
752 
753 	if (to & ~PAGE_MASK) {
754 		userfaultfd_ctx_put(ctx);
755 		return;
756 	}
757 
758 	msg_init(&ewq.msg);
759 
760 	ewq.msg.event = UFFD_EVENT_REMAP;
761 	ewq.msg.arg.remap.from = from;
762 	ewq.msg.arg.remap.to = to;
763 	ewq.msg.arg.remap.len = len;
764 
765 	userfaultfd_event_wait_completion(ctx, &ewq);
766 }
767 
768 bool userfaultfd_remove(struct vm_area_struct *vma,
769 			unsigned long start, unsigned long end)
770 {
771 	struct mm_struct *mm = vma->vm_mm;
772 	struct userfaultfd_ctx *ctx;
773 	struct userfaultfd_wait_queue ewq;
774 
775 	ctx = vma->vm_userfaultfd_ctx.ctx;
776 	if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_REMOVE))
777 		return true;
778 
779 	userfaultfd_ctx_get(ctx);
780 	down_write(&ctx->map_changing_lock);
781 	atomic_inc(&ctx->mmap_changing);
782 	up_write(&ctx->map_changing_lock);
783 	mmap_read_unlock(mm);
784 
785 	msg_init(&ewq.msg);
786 
787 	ewq.msg.event = UFFD_EVENT_REMOVE;
788 	ewq.msg.arg.remove.start = start;
789 	ewq.msg.arg.remove.end = end;
790 
791 	userfaultfd_event_wait_completion(ctx, &ewq);
792 
793 	return false;
794 }
795 
796 static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
797 			  unsigned long start, unsigned long end)
798 {
799 	struct userfaultfd_unmap_ctx *unmap_ctx;
800 
801 	list_for_each_entry(unmap_ctx, unmaps, list)
802 		if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
803 		    unmap_ctx->end == end)
804 			return true;
805 
806 	return false;
807 }
808 
809 int userfaultfd_unmap_prep(struct vm_area_struct *vma, unsigned long start,
810 			   unsigned long end, struct list_head *unmaps)
811 {
812 	struct userfaultfd_unmap_ctx *unmap_ctx;
813 	struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
814 
815 	if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_UNMAP) ||
816 	    has_unmap_ctx(ctx, unmaps, start, end))
817 		return 0;
818 
819 	unmap_ctx = kzalloc(sizeof(*unmap_ctx), GFP_KERNEL);
820 	if (!unmap_ctx)
821 		return -ENOMEM;
822 
823 	userfaultfd_ctx_get(ctx);
824 	down_write(&ctx->map_changing_lock);
825 	atomic_inc(&ctx->mmap_changing);
826 	up_write(&ctx->map_changing_lock);
827 	unmap_ctx->ctx = ctx;
828 	unmap_ctx->start = start;
829 	unmap_ctx->end = end;
830 	list_add_tail(&unmap_ctx->list, unmaps);
831 
832 	return 0;
833 }
834 
835 void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf)
836 {
837 	struct userfaultfd_unmap_ctx *ctx, *n;
838 	struct userfaultfd_wait_queue ewq;
839 
840 	list_for_each_entry_safe(ctx, n, uf, list) {
841 		msg_init(&ewq.msg);
842 
843 		ewq.msg.event = UFFD_EVENT_UNMAP;
844 		ewq.msg.arg.remove.start = ctx->start;
845 		ewq.msg.arg.remove.end = ctx->end;
846 
847 		userfaultfd_event_wait_completion(ctx->ctx, &ewq);
848 
849 		list_del(&ctx->list);
850 		kfree(ctx);
851 	}
852 }
853 
854 static int userfaultfd_release(struct inode *inode, struct file *file)
855 {
856 	struct userfaultfd_ctx *ctx = file->private_data;
857 	struct mm_struct *mm = ctx->mm;
858 	/* len == 0 means wake all */
859 	struct userfaultfd_wake_range range = { .len = 0, };
860 
861 	WRITE_ONCE(ctx->released, true);
862 
863 	userfaultfd_release_all(mm, ctx);
864 
865 	/*
866 	 * After no new page faults can wait on this fault_*wqh, flush
867 	 * the last page faults that may have been already waiting on
868 	 * the fault_*wqh.
869 	 */
870 	spin_lock_irq(&ctx->fault_pending_wqh.lock);
871 	__wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
872 	__wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range);
873 	spin_unlock_irq(&ctx->fault_pending_wqh.lock);
874 
875 	/* Flush pending events that may still wait on event_wqh */
876 	wake_up_all(&ctx->event_wqh);
877 
878 	wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
879 	userfaultfd_ctx_put(ctx);
880 	return 0;
881 }
882 
883 /* fault_pending_wqh.lock must be hold by the caller */
884 static inline struct userfaultfd_wait_queue *find_userfault_in(
885 		wait_queue_head_t *wqh)
886 {
887 	wait_queue_entry_t *wq;
888 	struct userfaultfd_wait_queue *uwq;
889 
890 	lockdep_assert_held(&wqh->lock);
891 
892 	uwq = NULL;
893 	if (!waitqueue_active(wqh))
894 		goto out;
895 	/* walk in reverse to provide FIFO behavior to read userfaults */
896 	wq = list_last_entry(&wqh->head, typeof(*wq), entry);
897 	uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
898 out:
899 	return uwq;
900 }
901 
902 static inline struct userfaultfd_wait_queue *find_userfault(
903 		struct userfaultfd_ctx *ctx)
904 {
905 	return find_userfault_in(&ctx->fault_pending_wqh);
906 }
907 
908 static inline struct userfaultfd_wait_queue *find_userfault_evt(
909 		struct userfaultfd_ctx *ctx)
910 {
911 	return find_userfault_in(&ctx->event_wqh);
912 }
913 
914 static __poll_t userfaultfd_poll(struct file *file, poll_table *wait)
915 {
916 	struct userfaultfd_ctx *ctx = file->private_data;
917 	__poll_t ret;
918 
919 	poll_wait(file, &ctx->fd_wqh, wait);
920 
921 	if (!userfaultfd_is_initialized(ctx))
922 		return EPOLLERR;
923 
924 	/*
925 	 * poll() never guarantees that read won't block.
926 	 * userfaults can be waken before they're read().
927 	 */
928 	if (unlikely(!(file->f_flags & O_NONBLOCK)))
929 		return EPOLLERR;
930 	/*
931 	 * lockless access to see if there are pending faults
932 	 * __pollwait last action is the add_wait_queue but
933 	 * the spin_unlock would allow the waitqueue_active to
934 	 * pass above the actual list_add inside
935 	 * add_wait_queue critical section. So use a full
936 	 * memory barrier to serialize the list_add write of
937 	 * add_wait_queue() with the waitqueue_active read
938 	 * below.
939 	 */
940 	ret = 0;
941 	smp_mb();
942 	if (waitqueue_active(&ctx->fault_pending_wqh))
943 		ret = EPOLLIN;
944 	else if (waitqueue_active(&ctx->event_wqh))
945 		ret = EPOLLIN;
946 
947 	return ret;
948 }
949 
950 static const struct file_operations userfaultfd_fops;
951 
952 static int resolve_userfault_fork(struct userfaultfd_ctx *new,
953 				  struct inode *inode,
954 				  struct uffd_msg *msg)
955 {
956 	int fd;
957 
958 	fd = anon_inode_create_getfd("[userfaultfd]", &userfaultfd_fops, new,
959 			O_RDONLY | (new->flags & UFFD_SHARED_FCNTL_FLAGS), inode);
960 	if (fd < 0)
961 		return fd;
962 
963 	msg->arg.reserved.reserved1 = 0;
964 	msg->arg.fork.ufd = fd;
965 	return 0;
966 }
967 
968 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
969 				    struct uffd_msg *msg, struct inode *inode)
970 {
971 	ssize_t ret;
972 	DECLARE_WAITQUEUE(wait, current);
973 	struct userfaultfd_wait_queue *uwq;
974 	/*
975 	 * Handling fork event requires sleeping operations, so
976 	 * we drop the event_wqh lock, then do these ops, then
977 	 * lock it back and wake up the waiter. While the lock is
978 	 * dropped the ewq may go away so we keep track of it
979 	 * carefully.
980 	 */
981 	LIST_HEAD(fork_event);
982 	struct userfaultfd_ctx *fork_nctx = NULL;
983 
984 	/* always take the fd_wqh lock before the fault_pending_wqh lock */
985 	spin_lock_irq(&ctx->fd_wqh.lock);
986 	__add_wait_queue(&ctx->fd_wqh, &wait);
987 	for (;;) {
988 		set_current_state(TASK_INTERRUPTIBLE);
989 		spin_lock(&ctx->fault_pending_wqh.lock);
990 		uwq = find_userfault(ctx);
991 		if (uwq) {
992 			/*
993 			 * Use a seqcount to repeat the lockless check
994 			 * in wake_userfault() to avoid missing
995 			 * wakeups because during the refile both
996 			 * waitqueue could become empty if this is the
997 			 * only userfault.
998 			 */
999 			write_seqcount_begin(&ctx->refile_seq);
1000 
1001 			/*
1002 			 * The fault_pending_wqh.lock prevents the uwq
1003 			 * to disappear from under us.
1004 			 *
1005 			 * Refile this userfault from
1006 			 * fault_pending_wqh to fault_wqh, it's not
1007 			 * pending anymore after we read it.
1008 			 *
1009 			 * Use list_del() by hand (as
1010 			 * userfaultfd_wake_function also uses
1011 			 * list_del_init() by hand) to be sure nobody
1012 			 * changes __remove_wait_queue() to use
1013 			 * list_del_init() in turn breaking the
1014 			 * !list_empty_careful() check in
1015 			 * handle_userfault(). The uwq->wq.head list
1016 			 * must never be empty at any time during the
1017 			 * refile, or the waitqueue could disappear
1018 			 * from under us. The "wait_queue_head_t"
1019 			 * parameter of __remove_wait_queue() is unused
1020 			 * anyway.
1021 			 */
1022 			list_del(&uwq->wq.entry);
1023 			add_wait_queue(&ctx->fault_wqh, &uwq->wq);
1024 
1025 			write_seqcount_end(&ctx->refile_seq);
1026 
1027 			/* careful to always initialize msg if ret == 0 */
1028 			*msg = uwq->msg;
1029 			spin_unlock(&ctx->fault_pending_wqh.lock);
1030 			ret = 0;
1031 			break;
1032 		}
1033 		spin_unlock(&ctx->fault_pending_wqh.lock);
1034 
1035 		spin_lock(&ctx->event_wqh.lock);
1036 		uwq = find_userfault_evt(ctx);
1037 		if (uwq) {
1038 			*msg = uwq->msg;
1039 
1040 			if (uwq->msg.event == UFFD_EVENT_FORK) {
1041 				fork_nctx = (struct userfaultfd_ctx *)
1042 					(unsigned long)
1043 					uwq->msg.arg.reserved.reserved1;
1044 				list_move(&uwq->wq.entry, &fork_event);
1045 				/*
1046 				 * fork_nctx can be freed as soon as
1047 				 * we drop the lock, unless we take a
1048 				 * reference on it.
1049 				 */
1050 				userfaultfd_ctx_get(fork_nctx);
1051 				spin_unlock(&ctx->event_wqh.lock);
1052 				ret = 0;
1053 				break;
1054 			}
1055 
1056 			userfaultfd_event_complete(ctx, uwq);
1057 			spin_unlock(&ctx->event_wqh.lock);
1058 			ret = 0;
1059 			break;
1060 		}
1061 		spin_unlock(&ctx->event_wqh.lock);
1062 
1063 		if (signal_pending(current)) {
1064 			ret = -ERESTARTSYS;
1065 			break;
1066 		}
1067 		if (no_wait) {
1068 			ret = -EAGAIN;
1069 			break;
1070 		}
1071 		spin_unlock_irq(&ctx->fd_wqh.lock);
1072 		schedule();
1073 		spin_lock_irq(&ctx->fd_wqh.lock);
1074 	}
1075 	__remove_wait_queue(&ctx->fd_wqh, &wait);
1076 	__set_current_state(TASK_RUNNING);
1077 	spin_unlock_irq(&ctx->fd_wqh.lock);
1078 
1079 	if (!ret && msg->event == UFFD_EVENT_FORK) {
1080 		ret = resolve_userfault_fork(fork_nctx, inode, msg);
1081 		spin_lock_irq(&ctx->event_wqh.lock);
1082 		if (!list_empty(&fork_event)) {
1083 			/*
1084 			 * The fork thread didn't abort, so we can
1085 			 * drop the temporary refcount.
1086 			 */
1087 			userfaultfd_ctx_put(fork_nctx);
1088 
1089 			uwq = list_first_entry(&fork_event,
1090 					       typeof(*uwq),
1091 					       wq.entry);
1092 			/*
1093 			 * If fork_event list wasn't empty and in turn
1094 			 * the event wasn't already released by fork
1095 			 * (the event is allocated on fork kernel
1096 			 * stack), put the event back to its place in
1097 			 * the event_wq. fork_event head will be freed
1098 			 * as soon as we return so the event cannot
1099 			 * stay queued there no matter the current
1100 			 * "ret" value.
1101 			 */
1102 			list_del(&uwq->wq.entry);
1103 			__add_wait_queue(&ctx->event_wqh, &uwq->wq);
1104 
1105 			/*
1106 			 * Leave the event in the waitqueue and report
1107 			 * error to userland if we failed to resolve
1108 			 * the userfault fork.
1109 			 */
1110 			if (likely(!ret))
1111 				userfaultfd_event_complete(ctx, uwq);
1112 		} else {
1113 			/*
1114 			 * Here the fork thread aborted and the
1115 			 * refcount from the fork thread on fork_nctx
1116 			 * has already been released. We still hold
1117 			 * the reference we took before releasing the
1118 			 * lock above. If resolve_userfault_fork
1119 			 * failed we've to drop it because the
1120 			 * fork_nctx has to be freed in such case. If
1121 			 * it succeeded we'll hold it because the new
1122 			 * uffd references it.
1123 			 */
1124 			if (ret)
1125 				userfaultfd_ctx_put(fork_nctx);
1126 		}
1127 		spin_unlock_irq(&ctx->event_wqh.lock);
1128 	}
1129 
1130 	return ret;
1131 }
1132 
1133 static ssize_t userfaultfd_read_iter(struct kiocb *iocb, struct iov_iter *to)
1134 {
1135 	struct file *file = iocb->ki_filp;
1136 	struct userfaultfd_ctx *ctx = file->private_data;
1137 	ssize_t _ret, ret = 0;
1138 	struct uffd_msg msg;
1139 	struct inode *inode = file_inode(file);
1140 	bool no_wait;
1141 
1142 	if (!userfaultfd_is_initialized(ctx))
1143 		return -EINVAL;
1144 
1145 	no_wait = file->f_flags & O_NONBLOCK || iocb->ki_flags & IOCB_NOWAIT;
1146 	for (;;) {
1147 		if (iov_iter_count(to) < sizeof(msg))
1148 			return ret ? ret : -EINVAL;
1149 		_ret = userfaultfd_ctx_read(ctx, no_wait, &msg, inode);
1150 		if (_ret < 0)
1151 			return ret ? ret : _ret;
1152 		_ret = !copy_to_iter_full(&msg, sizeof(msg), to);
1153 		if (_ret)
1154 			return ret ? ret : -EFAULT;
1155 		ret += sizeof(msg);
1156 		/*
1157 		 * Allow to read more than one fault at time but only
1158 		 * block if waiting for the very first one.
1159 		 */
1160 		no_wait = true;
1161 	}
1162 }
1163 
1164 static void __wake_userfault(struct userfaultfd_ctx *ctx,
1165 			     struct userfaultfd_wake_range *range)
1166 {
1167 	spin_lock_irq(&ctx->fault_pending_wqh.lock);
1168 	/* wake all in the range and autoremove */
1169 	if (waitqueue_active(&ctx->fault_pending_wqh))
1170 		__wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
1171 				     range);
1172 	if (waitqueue_active(&ctx->fault_wqh))
1173 		__wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, range);
1174 	spin_unlock_irq(&ctx->fault_pending_wqh.lock);
1175 }
1176 
1177 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
1178 					   struct userfaultfd_wake_range *range)
1179 {
1180 	unsigned seq;
1181 	bool need_wakeup;
1182 
1183 	/*
1184 	 * To be sure waitqueue_active() is not reordered by the CPU
1185 	 * before the pagetable update, use an explicit SMP memory
1186 	 * barrier here. PT lock release or mmap_read_unlock(mm) still
1187 	 * have release semantics that can allow the
1188 	 * waitqueue_active() to be reordered before the pte update.
1189 	 */
1190 	smp_mb();
1191 
1192 	/*
1193 	 * Use waitqueue_active because it's very frequent to
1194 	 * change the address space atomically even if there are no
1195 	 * userfaults yet. So we take the spinlock only when we're
1196 	 * sure we've userfaults to wake.
1197 	 */
1198 	do {
1199 		seq = read_seqcount_begin(&ctx->refile_seq);
1200 		need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
1201 			waitqueue_active(&ctx->fault_wqh);
1202 		cond_resched();
1203 	} while (read_seqcount_retry(&ctx->refile_seq, seq));
1204 	if (need_wakeup)
1205 		__wake_userfault(ctx, range);
1206 }
1207 
1208 static __always_inline int validate_unaligned_range(
1209 	struct mm_struct *mm, __u64 start, __u64 len)
1210 {
1211 	__u64 task_size = mm->task_size;
1212 
1213 	if (len & ~PAGE_MASK)
1214 		return -EINVAL;
1215 	if (!len)
1216 		return -EINVAL;
1217 	if (start < mmap_min_addr)
1218 		return -EINVAL;
1219 	if (start >= task_size)
1220 		return -EINVAL;
1221 	if (len > task_size - start)
1222 		return -EINVAL;
1223 	if (start + len <= start)
1224 		return -EINVAL;
1225 	return 0;
1226 }
1227 
1228 static __always_inline int validate_range(struct mm_struct *mm,
1229 					  __u64 start, __u64 len)
1230 {
1231 	if (start & ~PAGE_MASK)
1232 		return -EINVAL;
1233 
1234 	return validate_unaligned_range(mm, start, len);
1235 }
1236 
1237 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
1238 				unsigned long arg)
1239 {
1240 	struct mm_struct *mm = ctx->mm;
1241 	struct vm_area_struct *vma, *cur;
1242 	int ret;
1243 	struct uffdio_register uffdio_register;
1244 	struct uffdio_register __user *user_uffdio_register;
1245 	unsigned long vm_flags;
1246 	bool found;
1247 	bool basic_ioctls;
1248 	unsigned long start, end;
1249 	struct vma_iterator vmi;
1250 	bool wp_async = userfaultfd_wp_async_ctx(ctx);
1251 
1252 	user_uffdio_register = (struct uffdio_register __user *) arg;
1253 
1254 	ret = -EFAULT;
1255 	if (copy_from_user(&uffdio_register, user_uffdio_register,
1256 			   sizeof(uffdio_register)-sizeof(__u64)))
1257 		goto out;
1258 
1259 	ret = -EINVAL;
1260 	if (!uffdio_register.mode)
1261 		goto out;
1262 	if (uffdio_register.mode & ~UFFD_API_REGISTER_MODES)
1263 		goto out;
1264 	vm_flags = 0;
1265 	if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
1266 		vm_flags |= VM_UFFD_MISSING;
1267 	if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
1268 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
1269 		goto out;
1270 #endif
1271 		vm_flags |= VM_UFFD_WP;
1272 	}
1273 	if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR) {
1274 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1275 		goto out;
1276 #endif
1277 		vm_flags |= VM_UFFD_MINOR;
1278 	}
1279 
1280 	ret = validate_range(mm, uffdio_register.range.start,
1281 			     uffdio_register.range.len);
1282 	if (ret)
1283 		goto out;
1284 
1285 	start = uffdio_register.range.start;
1286 	end = start + uffdio_register.range.len;
1287 
1288 	ret = -ENOMEM;
1289 	if (!mmget_not_zero(mm))
1290 		goto out;
1291 
1292 	ret = -EINVAL;
1293 	mmap_write_lock(mm);
1294 	vma_iter_init(&vmi, mm, start);
1295 	vma = vma_find(&vmi, end);
1296 	if (!vma)
1297 		goto out_unlock;
1298 
1299 	/*
1300 	 * If the first vma contains huge pages, make sure start address
1301 	 * is aligned to huge page size.
1302 	 */
1303 	if (is_vm_hugetlb_page(vma)) {
1304 		unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1305 
1306 		if (start & (vma_hpagesize - 1))
1307 			goto out_unlock;
1308 	}
1309 
1310 	/*
1311 	 * Search for not compatible vmas.
1312 	 */
1313 	found = false;
1314 	basic_ioctls = false;
1315 	cur = vma;
1316 	do {
1317 		cond_resched();
1318 
1319 		VM_WARN_ON_ONCE(!!cur->vm_userfaultfd_ctx.ctx ^
1320 				!!(cur->vm_flags & __VM_UFFD_FLAGS));
1321 
1322 		/* check not compatible vmas */
1323 		ret = -EINVAL;
1324 		if (!vma_can_userfault(cur, vm_flags, wp_async))
1325 			goto out_unlock;
1326 
1327 		/*
1328 		 * UFFDIO_COPY will fill file holes even without
1329 		 * PROT_WRITE. This check enforces that if this is a
1330 		 * MAP_SHARED, the process has write permission to the backing
1331 		 * file. If VM_MAYWRITE is set it also enforces that on a
1332 		 * MAP_SHARED vma: there is no F_WRITE_SEAL and no further
1333 		 * F_WRITE_SEAL can be taken until the vma is destroyed.
1334 		 */
1335 		ret = -EPERM;
1336 		if (unlikely(!(cur->vm_flags & VM_MAYWRITE)))
1337 			goto out_unlock;
1338 
1339 		/*
1340 		 * If this vma contains ending address, and huge pages
1341 		 * check alignment.
1342 		 */
1343 		if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
1344 		    end > cur->vm_start) {
1345 			unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
1346 
1347 			ret = -EINVAL;
1348 
1349 			if (end & (vma_hpagesize - 1))
1350 				goto out_unlock;
1351 		}
1352 		if ((vm_flags & VM_UFFD_WP) && !(cur->vm_flags & VM_MAYWRITE))
1353 			goto out_unlock;
1354 
1355 		/*
1356 		 * Check that this vma isn't already owned by a
1357 		 * different userfaultfd. We can't allow more than one
1358 		 * userfaultfd to own a single vma simultaneously or we
1359 		 * wouldn't know which one to deliver the userfaults to.
1360 		 */
1361 		ret = -EBUSY;
1362 		if (cur->vm_userfaultfd_ctx.ctx &&
1363 		    cur->vm_userfaultfd_ctx.ctx != ctx)
1364 			goto out_unlock;
1365 
1366 		/*
1367 		 * Note vmas containing huge pages
1368 		 */
1369 		if (is_vm_hugetlb_page(cur))
1370 			basic_ioctls = true;
1371 
1372 		found = true;
1373 	} for_each_vma_range(vmi, cur, end);
1374 	VM_WARN_ON_ONCE(!found);
1375 
1376 	ret = userfaultfd_register_range(ctx, vma, vm_flags, start, end,
1377 					 wp_async);
1378 
1379 out_unlock:
1380 	mmap_write_unlock(mm);
1381 	mmput(mm);
1382 	if (!ret) {
1383 		__u64 ioctls_out;
1384 
1385 		ioctls_out = basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
1386 		    UFFD_API_RANGE_IOCTLS;
1387 
1388 		/*
1389 		 * Declare the WP ioctl only if the WP mode is
1390 		 * specified and all checks passed with the range
1391 		 */
1392 		if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_WP))
1393 			ioctls_out &= ~((__u64)1 << _UFFDIO_WRITEPROTECT);
1394 
1395 		/* CONTINUE ioctl is only supported for MINOR ranges. */
1396 		if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR))
1397 			ioctls_out &= ~((__u64)1 << _UFFDIO_CONTINUE);
1398 
1399 		/*
1400 		 * Now that we scanned all vmas we can already tell
1401 		 * userland which ioctls methods are guaranteed to
1402 		 * succeed on this range.
1403 		 */
1404 		if (put_user(ioctls_out, &user_uffdio_register->ioctls))
1405 			ret = -EFAULT;
1406 	}
1407 out:
1408 	return ret;
1409 }
1410 
1411 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
1412 				  unsigned long arg)
1413 {
1414 	struct mm_struct *mm = ctx->mm;
1415 	struct vm_area_struct *vma, *prev, *cur;
1416 	int ret;
1417 	struct uffdio_range uffdio_unregister;
1418 	bool found;
1419 	unsigned long start, end, vma_end;
1420 	const void __user *buf = (void __user *)arg;
1421 	struct vma_iterator vmi;
1422 	bool wp_async = userfaultfd_wp_async_ctx(ctx);
1423 
1424 	ret = -EFAULT;
1425 	if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
1426 		goto out;
1427 
1428 	ret = validate_range(mm, uffdio_unregister.start,
1429 			     uffdio_unregister.len);
1430 	if (ret)
1431 		goto out;
1432 
1433 	start = uffdio_unregister.start;
1434 	end = start + uffdio_unregister.len;
1435 
1436 	ret = -ENOMEM;
1437 	if (!mmget_not_zero(mm))
1438 		goto out;
1439 
1440 	mmap_write_lock(mm);
1441 	ret = -EINVAL;
1442 	vma_iter_init(&vmi, mm, start);
1443 	vma = vma_find(&vmi, end);
1444 	if (!vma)
1445 		goto out_unlock;
1446 
1447 	/*
1448 	 * If the first vma contains huge pages, make sure start address
1449 	 * is aligned to huge page size.
1450 	 */
1451 	if (is_vm_hugetlb_page(vma)) {
1452 		unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1453 
1454 		if (start & (vma_hpagesize - 1))
1455 			goto out_unlock;
1456 	}
1457 
1458 	/*
1459 	 * Search for not compatible vmas.
1460 	 */
1461 	found = false;
1462 	cur = vma;
1463 	do {
1464 		cond_resched();
1465 
1466 		VM_WARN_ON_ONCE(!!cur->vm_userfaultfd_ctx.ctx ^
1467 				!!(cur->vm_flags & __VM_UFFD_FLAGS));
1468 
1469 		/*
1470 		 * Prevent unregistering through a different userfaultfd than
1471 		 * the one used for registration.
1472 		 */
1473 		if (cur->vm_userfaultfd_ctx.ctx &&
1474 		    cur->vm_userfaultfd_ctx.ctx != ctx)
1475 			goto out_unlock;
1476 
1477 		/*
1478 		 * Check not compatible vmas, not strictly required
1479 		 * here as not compatible vmas cannot have an
1480 		 * userfaultfd_ctx registered on them, but this
1481 		 * provides for more strict behavior to notice
1482 		 * unregistration errors.
1483 		 */
1484 		if (!vma_can_userfault(cur, cur->vm_flags, wp_async))
1485 			goto out_unlock;
1486 
1487 		found = true;
1488 	} for_each_vma_range(vmi, cur, end);
1489 	VM_WARN_ON_ONCE(!found);
1490 
1491 	vma_iter_set(&vmi, start);
1492 	prev = vma_prev(&vmi);
1493 	if (vma->vm_start < start)
1494 		prev = vma;
1495 
1496 	ret = 0;
1497 	for_each_vma_range(vmi, vma, end) {
1498 		cond_resched();
1499 
1500 		/* VMA not registered with userfaultfd. */
1501 		if (!vma->vm_userfaultfd_ctx.ctx)
1502 			goto skip;
1503 
1504 		VM_WARN_ON_ONCE(vma->vm_userfaultfd_ctx.ctx != ctx);
1505 		VM_WARN_ON_ONCE(!vma_can_userfault(vma, vma->vm_flags, wp_async));
1506 		VM_WARN_ON_ONCE(!(vma->vm_flags & VM_MAYWRITE));
1507 
1508 		if (vma->vm_start > start)
1509 			start = vma->vm_start;
1510 		vma_end = min(end, vma->vm_end);
1511 
1512 		if (userfaultfd_missing(vma)) {
1513 			/*
1514 			 * Wake any concurrent pending userfault while
1515 			 * we unregister, so they will not hang
1516 			 * permanently and it avoids userland to call
1517 			 * UFFDIO_WAKE explicitly.
1518 			 */
1519 			struct userfaultfd_wake_range range;
1520 			range.start = start;
1521 			range.len = vma_end - start;
1522 			wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
1523 		}
1524 
1525 		vma = userfaultfd_clear_vma(&vmi, prev, vma,
1526 					    start, vma_end);
1527 		if (IS_ERR(vma)) {
1528 			ret = PTR_ERR(vma);
1529 			break;
1530 		}
1531 
1532 	skip:
1533 		prev = vma;
1534 		start = vma->vm_end;
1535 	}
1536 
1537 out_unlock:
1538 	mmap_write_unlock(mm);
1539 	mmput(mm);
1540 out:
1541 	return ret;
1542 }
1543 
1544 /*
1545  * userfaultfd_wake may be used in combination with the
1546  * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1547  */
1548 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1549 			    unsigned long arg)
1550 {
1551 	int ret;
1552 	struct uffdio_range uffdio_wake;
1553 	struct userfaultfd_wake_range range;
1554 	const void __user *buf = (void __user *)arg;
1555 
1556 	ret = -EFAULT;
1557 	if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1558 		goto out;
1559 
1560 	ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1561 	if (ret)
1562 		goto out;
1563 
1564 	range.start = uffdio_wake.start;
1565 	range.len = uffdio_wake.len;
1566 
1567 	/*
1568 	 * len == 0 means wake all and we don't want to wake all here,
1569 	 * so check it again to be sure.
1570 	 */
1571 	VM_WARN_ON_ONCE(!range.len);
1572 
1573 	wake_userfault(ctx, &range);
1574 	ret = 0;
1575 
1576 out:
1577 	return ret;
1578 }
1579 
1580 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1581 			    unsigned long arg)
1582 {
1583 	__s64 ret;
1584 	struct uffdio_copy uffdio_copy;
1585 	struct uffdio_copy __user *user_uffdio_copy;
1586 	struct userfaultfd_wake_range range;
1587 	uffd_flags_t flags = 0;
1588 
1589 	user_uffdio_copy = (struct uffdio_copy __user *) arg;
1590 
1591 	ret = -EAGAIN;
1592 	if (unlikely(atomic_read(&ctx->mmap_changing))) {
1593 		if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1594 			return -EFAULT;
1595 		goto out;
1596 	}
1597 
1598 	ret = -EFAULT;
1599 	if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1600 			   /* don't copy "copy" last field */
1601 			   sizeof(uffdio_copy)-sizeof(__s64)))
1602 		goto out;
1603 
1604 	ret = validate_unaligned_range(ctx->mm, uffdio_copy.src,
1605 				       uffdio_copy.len);
1606 	if (ret)
1607 		goto out;
1608 	ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1609 	if (ret)
1610 		goto out;
1611 
1612 	ret = -EINVAL;
1613 	if (uffdio_copy.mode & ~(UFFDIO_COPY_MODE_DONTWAKE|UFFDIO_COPY_MODE_WP))
1614 		goto out;
1615 	if (uffdio_copy.mode & UFFDIO_COPY_MODE_WP)
1616 		flags |= MFILL_ATOMIC_WP;
1617 	if (mmget_not_zero(ctx->mm)) {
1618 		ret = mfill_atomic_copy(ctx, uffdio_copy.dst, uffdio_copy.src,
1619 					uffdio_copy.len, flags);
1620 		mmput(ctx->mm);
1621 	} else {
1622 		return -ESRCH;
1623 	}
1624 	if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1625 		return -EFAULT;
1626 	if (ret < 0)
1627 		goto out;
1628 	VM_WARN_ON_ONCE(!ret);
1629 	/* len == 0 would wake all */
1630 	range.len = ret;
1631 	if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1632 		range.start = uffdio_copy.dst;
1633 		wake_userfault(ctx, &range);
1634 	}
1635 	ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1636 out:
1637 	return ret;
1638 }
1639 
1640 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1641 				unsigned long arg)
1642 {
1643 	__s64 ret;
1644 	struct uffdio_zeropage uffdio_zeropage;
1645 	struct uffdio_zeropage __user *user_uffdio_zeropage;
1646 	struct userfaultfd_wake_range range;
1647 
1648 	user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1649 
1650 	ret = -EAGAIN;
1651 	if (unlikely(atomic_read(&ctx->mmap_changing))) {
1652 		if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1653 			return -EFAULT;
1654 		goto out;
1655 	}
1656 
1657 	ret = -EFAULT;
1658 	if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1659 			   /* don't copy "zeropage" last field */
1660 			   sizeof(uffdio_zeropage)-sizeof(__s64)))
1661 		goto out;
1662 
1663 	ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1664 			     uffdio_zeropage.range.len);
1665 	if (ret)
1666 		goto out;
1667 	ret = -EINVAL;
1668 	if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1669 		goto out;
1670 
1671 	if (mmget_not_zero(ctx->mm)) {
1672 		ret = mfill_atomic_zeropage(ctx, uffdio_zeropage.range.start,
1673 					   uffdio_zeropage.range.len);
1674 		mmput(ctx->mm);
1675 	} else {
1676 		return -ESRCH;
1677 	}
1678 	if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1679 		return -EFAULT;
1680 	if (ret < 0)
1681 		goto out;
1682 	/* len == 0 would wake all */
1683 	VM_WARN_ON_ONCE(!ret);
1684 	range.len = ret;
1685 	if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1686 		range.start = uffdio_zeropage.range.start;
1687 		wake_userfault(ctx, &range);
1688 	}
1689 	ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1690 out:
1691 	return ret;
1692 }
1693 
1694 static int userfaultfd_writeprotect(struct userfaultfd_ctx *ctx,
1695 				    unsigned long arg)
1696 {
1697 	int ret;
1698 	struct uffdio_writeprotect uffdio_wp;
1699 	struct uffdio_writeprotect __user *user_uffdio_wp;
1700 	struct userfaultfd_wake_range range;
1701 	bool mode_wp, mode_dontwake;
1702 
1703 	if (atomic_read(&ctx->mmap_changing))
1704 		return -EAGAIN;
1705 
1706 	user_uffdio_wp = (struct uffdio_writeprotect __user *) arg;
1707 
1708 	if (copy_from_user(&uffdio_wp, user_uffdio_wp,
1709 			   sizeof(struct uffdio_writeprotect)))
1710 		return -EFAULT;
1711 
1712 	ret = validate_range(ctx->mm, uffdio_wp.range.start,
1713 			     uffdio_wp.range.len);
1714 	if (ret)
1715 		return ret;
1716 
1717 	if (uffdio_wp.mode & ~(UFFDIO_WRITEPROTECT_MODE_DONTWAKE |
1718 			       UFFDIO_WRITEPROTECT_MODE_WP))
1719 		return -EINVAL;
1720 
1721 	mode_wp = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_WP;
1722 	mode_dontwake = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_DONTWAKE;
1723 
1724 	if (mode_wp && mode_dontwake)
1725 		return -EINVAL;
1726 
1727 	if (mmget_not_zero(ctx->mm)) {
1728 		ret = mwriteprotect_range(ctx, uffdio_wp.range.start,
1729 					  uffdio_wp.range.len, mode_wp);
1730 		mmput(ctx->mm);
1731 	} else {
1732 		return -ESRCH;
1733 	}
1734 
1735 	if (ret)
1736 		return ret;
1737 
1738 	if (!mode_wp && !mode_dontwake) {
1739 		range.start = uffdio_wp.range.start;
1740 		range.len = uffdio_wp.range.len;
1741 		wake_userfault(ctx, &range);
1742 	}
1743 	return ret;
1744 }
1745 
1746 static int userfaultfd_continue(struct userfaultfd_ctx *ctx, unsigned long arg)
1747 {
1748 	__s64 ret;
1749 	struct uffdio_continue uffdio_continue;
1750 	struct uffdio_continue __user *user_uffdio_continue;
1751 	struct userfaultfd_wake_range range;
1752 	uffd_flags_t flags = 0;
1753 
1754 	user_uffdio_continue = (struct uffdio_continue __user *)arg;
1755 
1756 	ret = -EAGAIN;
1757 	if (unlikely(atomic_read(&ctx->mmap_changing))) {
1758 		if (unlikely(put_user(ret, &user_uffdio_continue->mapped)))
1759 			return -EFAULT;
1760 		goto out;
1761 	}
1762 
1763 	ret = -EFAULT;
1764 	if (copy_from_user(&uffdio_continue, user_uffdio_continue,
1765 			   /* don't copy the output fields */
1766 			   sizeof(uffdio_continue) - (sizeof(__s64))))
1767 		goto out;
1768 
1769 	ret = validate_range(ctx->mm, uffdio_continue.range.start,
1770 			     uffdio_continue.range.len);
1771 	if (ret)
1772 		goto out;
1773 
1774 	ret = -EINVAL;
1775 	if (uffdio_continue.mode & ~(UFFDIO_CONTINUE_MODE_DONTWAKE |
1776 				     UFFDIO_CONTINUE_MODE_WP))
1777 		goto out;
1778 	if (uffdio_continue.mode & UFFDIO_CONTINUE_MODE_WP)
1779 		flags |= MFILL_ATOMIC_WP;
1780 
1781 	if (mmget_not_zero(ctx->mm)) {
1782 		ret = mfill_atomic_continue(ctx, uffdio_continue.range.start,
1783 					    uffdio_continue.range.len, flags);
1784 		mmput(ctx->mm);
1785 	} else {
1786 		return -ESRCH;
1787 	}
1788 
1789 	if (unlikely(put_user(ret, &user_uffdio_continue->mapped)))
1790 		return -EFAULT;
1791 	if (ret < 0)
1792 		goto out;
1793 
1794 	/* len == 0 would wake all */
1795 	VM_WARN_ON_ONCE(!ret);
1796 	range.len = ret;
1797 	if (!(uffdio_continue.mode & UFFDIO_CONTINUE_MODE_DONTWAKE)) {
1798 		range.start = uffdio_continue.range.start;
1799 		wake_userfault(ctx, &range);
1800 	}
1801 	ret = range.len == uffdio_continue.range.len ? 0 : -EAGAIN;
1802 
1803 out:
1804 	return ret;
1805 }
1806 
1807 static inline int userfaultfd_poison(struct userfaultfd_ctx *ctx, unsigned long arg)
1808 {
1809 	__s64 ret;
1810 	struct uffdio_poison uffdio_poison;
1811 	struct uffdio_poison __user *user_uffdio_poison;
1812 	struct userfaultfd_wake_range range;
1813 
1814 	user_uffdio_poison = (struct uffdio_poison __user *)arg;
1815 
1816 	ret = -EAGAIN;
1817 	if (unlikely(atomic_read(&ctx->mmap_changing))) {
1818 		if (unlikely(put_user(ret, &user_uffdio_poison->updated)))
1819 			return -EFAULT;
1820 		goto out;
1821 	}
1822 
1823 	ret = -EFAULT;
1824 	if (copy_from_user(&uffdio_poison, user_uffdio_poison,
1825 			   /* don't copy the output fields */
1826 			   sizeof(uffdio_poison) - (sizeof(__s64))))
1827 		goto out;
1828 
1829 	ret = validate_range(ctx->mm, uffdio_poison.range.start,
1830 			     uffdio_poison.range.len);
1831 	if (ret)
1832 		goto out;
1833 
1834 	ret = -EINVAL;
1835 	if (uffdio_poison.mode & ~UFFDIO_POISON_MODE_DONTWAKE)
1836 		goto out;
1837 
1838 	if (mmget_not_zero(ctx->mm)) {
1839 		ret = mfill_atomic_poison(ctx, uffdio_poison.range.start,
1840 					  uffdio_poison.range.len, 0);
1841 		mmput(ctx->mm);
1842 	} else {
1843 		return -ESRCH;
1844 	}
1845 
1846 	if (unlikely(put_user(ret, &user_uffdio_poison->updated)))
1847 		return -EFAULT;
1848 	if (ret < 0)
1849 		goto out;
1850 
1851 	/* len == 0 would wake all */
1852 	VM_WARN_ON_ONCE(!ret);
1853 	range.len = ret;
1854 	if (!(uffdio_poison.mode & UFFDIO_POISON_MODE_DONTWAKE)) {
1855 		range.start = uffdio_poison.range.start;
1856 		wake_userfault(ctx, &range);
1857 	}
1858 	ret = range.len == uffdio_poison.range.len ? 0 : -EAGAIN;
1859 
1860 out:
1861 	return ret;
1862 }
1863 
1864 bool userfaultfd_wp_async(struct vm_area_struct *vma)
1865 {
1866 	return userfaultfd_wp_async_ctx(vma->vm_userfaultfd_ctx.ctx);
1867 }
1868 
1869 static inline unsigned int uffd_ctx_features(__u64 user_features)
1870 {
1871 	/*
1872 	 * For the current set of features the bits just coincide. Set
1873 	 * UFFD_FEATURE_INITIALIZED to mark the features as enabled.
1874 	 */
1875 	return (unsigned int)user_features | UFFD_FEATURE_INITIALIZED;
1876 }
1877 
1878 static int userfaultfd_move(struct userfaultfd_ctx *ctx,
1879 			    unsigned long arg)
1880 {
1881 	__s64 ret;
1882 	struct uffdio_move uffdio_move;
1883 	struct uffdio_move __user *user_uffdio_move;
1884 	struct userfaultfd_wake_range range;
1885 	struct mm_struct *mm = ctx->mm;
1886 
1887 	user_uffdio_move = (struct uffdio_move __user *) arg;
1888 
1889 	ret = -EAGAIN;
1890 	if (unlikely(atomic_read(&ctx->mmap_changing))) {
1891 		if (unlikely(put_user(ret, &user_uffdio_move->move)))
1892 			return -EFAULT;
1893 		goto out;
1894 	}
1895 
1896 	if (copy_from_user(&uffdio_move, user_uffdio_move,
1897 			   /* don't copy "move" last field */
1898 			   sizeof(uffdio_move)-sizeof(__s64)))
1899 		return -EFAULT;
1900 
1901 	/* Do not allow cross-mm moves. */
1902 	if (mm != current->mm)
1903 		return -EINVAL;
1904 
1905 	ret = validate_range(mm, uffdio_move.dst, uffdio_move.len);
1906 	if (ret)
1907 		return ret;
1908 
1909 	ret = validate_range(mm, uffdio_move.src, uffdio_move.len);
1910 	if (ret)
1911 		return ret;
1912 
1913 	if (uffdio_move.mode & ~(UFFDIO_MOVE_MODE_ALLOW_SRC_HOLES|
1914 				  UFFDIO_MOVE_MODE_DONTWAKE))
1915 		return -EINVAL;
1916 
1917 	if (mmget_not_zero(mm)) {
1918 		ret = move_pages(ctx, uffdio_move.dst, uffdio_move.src,
1919 				 uffdio_move.len, uffdio_move.mode);
1920 		mmput(mm);
1921 	} else {
1922 		return -ESRCH;
1923 	}
1924 
1925 	if (unlikely(put_user(ret, &user_uffdio_move->move)))
1926 		return -EFAULT;
1927 	if (ret < 0)
1928 		goto out;
1929 
1930 	/* len == 0 would wake all */
1931 	VM_WARN_ON(!ret);
1932 	range.len = ret;
1933 	if (!(uffdio_move.mode & UFFDIO_MOVE_MODE_DONTWAKE)) {
1934 		range.start = uffdio_move.dst;
1935 		wake_userfault(ctx, &range);
1936 	}
1937 	ret = range.len == uffdio_move.len ? 0 : -EAGAIN;
1938 
1939 out:
1940 	return ret;
1941 }
1942 
1943 /*
1944  * userland asks for a certain API version and we return which bits
1945  * and ioctl commands are implemented in this kernel for such API
1946  * version or -EINVAL if unknown.
1947  */
1948 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1949 			   unsigned long arg)
1950 {
1951 	struct uffdio_api uffdio_api;
1952 	void __user *buf = (void __user *)arg;
1953 	unsigned int ctx_features;
1954 	int ret;
1955 	__u64 features;
1956 
1957 	ret = -EFAULT;
1958 	if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1959 		goto out;
1960 	features = uffdio_api.features;
1961 	ret = -EINVAL;
1962 	if (uffdio_api.api != UFFD_API)
1963 		goto err_out;
1964 	ret = -EPERM;
1965 	if ((features & UFFD_FEATURE_EVENT_FORK) && !capable(CAP_SYS_PTRACE))
1966 		goto err_out;
1967 
1968 	/* WP_ASYNC relies on WP_UNPOPULATED, choose it unconditionally */
1969 	if (features & UFFD_FEATURE_WP_ASYNC)
1970 		features |= UFFD_FEATURE_WP_UNPOPULATED;
1971 
1972 	/* report all available features and ioctls to userland */
1973 	uffdio_api.features = UFFD_API_FEATURES;
1974 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1975 	uffdio_api.features &=
1976 		~(UFFD_FEATURE_MINOR_HUGETLBFS | UFFD_FEATURE_MINOR_SHMEM);
1977 #endif
1978 #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
1979 	uffdio_api.features &= ~UFFD_FEATURE_PAGEFAULT_FLAG_WP;
1980 #endif
1981 #ifndef CONFIG_PTE_MARKER_UFFD_WP
1982 	uffdio_api.features &= ~UFFD_FEATURE_WP_HUGETLBFS_SHMEM;
1983 	uffdio_api.features &= ~UFFD_FEATURE_WP_UNPOPULATED;
1984 	uffdio_api.features &= ~UFFD_FEATURE_WP_ASYNC;
1985 #endif
1986 
1987 	ret = -EINVAL;
1988 	if (features & ~uffdio_api.features)
1989 		goto err_out;
1990 
1991 	uffdio_api.ioctls = UFFD_API_IOCTLS;
1992 	ret = -EFAULT;
1993 	if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1994 		goto out;
1995 
1996 	/* only enable the requested features for this uffd context */
1997 	ctx_features = uffd_ctx_features(features);
1998 	ret = -EINVAL;
1999 	if (cmpxchg(&ctx->features, 0, ctx_features) != 0)
2000 		goto err_out;
2001 
2002 	ret = 0;
2003 out:
2004 	return ret;
2005 err_out:
2006 	memset(&uffdio_api, 0, sizeof(uffdio_api));
2007 	if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
2008 		ret = -EFAULT;
2009 	goto out;
2010 }
2011 
2012 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
2013 			      unsigned long arg)
2014 {
2015 	int ret = -EINVAL;
2016 	struct userfaultfd_ctx *ctx = file->private_data;
2017 
2018 	if (cmd != UFFDIO_API && !userfaultfd_is_initialized(ctx))
2019 		return -EINVAL;
2020 
2021 	switch(cmd) {
2022 	case UFFDIO_API:
2023 		ret = userfaultfd_api(ctx, arg);
2024 		break;
2025 	case UFFDIO_REGISTER:
2026 		ret = userfaultfd_register(ctx, arg);
2027 		break;
2028 	case UFFDIO_UNREGISTER:
2029 		ret = userfaultfd_unregister(ctx, arg);
2030 		break;
2031 	case UFFDIO_WAKE:
2032 		ret = userfaultfd_wake(ctx, arg);
2033 		break;
2034 	case UFFDIO_COPY:
2035 		ret = userfaultfd_copy(ctx, arg);
2036 		break;
2037 	case UFFDIO_ZEROPAGE:
2038 		ret = userfaultfd_zeropage(ctx, arg);
2039 		break;
2040 	case UFFDIO_MOVE:
2041 		ret = userfaultfd_move(ctx, arg);
2042 		break;
2043 	case UFFDIO_WRITEPROTECT:
2044 		ret = userfaultfd_writeprotect(ctx, arg);
2045 		break;
2046 	case UFFDIO_CONTINUE:
2047 		ret = userfaultfd_continue(ctx, arg);
2048 		break;
2049 	case UFFDIO_POISON:
2050 		ret = userfaultfd_poison(ctx, arg);
2051 		break;
2052 	}
2053 	return ret;
2054 }
2055 
2056 #ifdef CONFIG_PROC_FS
2057 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
2058 {
2059 	struct userfaultfd_ctx *ctx = f->private_data;
2060 	wait_queue_entry_t *wq;
2061 	unsigned long pending = 0, total = 0;
2062 
2063 	spin_lock_irq(&ctx->fault_pending_wqh.lock);
2064 	list_for_each_entry(wq, &ctx->fault_pending_wqh.head, entry) {
2065 		pending++;
2066 		total++;
2067 	}
2068 	list_for_each_entry(wq, &ctx->fault_wqh.head, entry) {
2069 		total++;
2070 	}
2071 	spin_unlock_irq(&ctx->fault_pending_wqh.lock);
2072 
2073 	/*
2074 	 * If more protocols will be added, there will be all shown
2075 	 * separated by a space. Like this:
2076 	 *	protocols: aa:... bb:...
2077 	 */
2078 	seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
2079 		   pending, total, UFFD_API, ctx->features,
2080 		   UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
2081 }
2082 #endif
2083 
2084 static const struct file_operations userfaultfd_fops = {
2085 #ifdef CONFIG_PROC_FS
2086 	.show_fdinfo	= userfaultfd_show_fdinfo,
2087 #endif
2088 	.release	= userfaultfd_release,
2089 	.poll		= userfaultfd_poll,
2090 	.read_iter	= userfaultfd_read_iter,
2091 	.unlocked_ioctl = userfaultfd_ioctl,
2092 	.compat_ioctl	= compat_ptr_ioctl,
2093 	.llseek		= noop_llseek,
2094 };
2095 
2096 static void init_once_userfaultfd_ctx(void *mem)
2097 {
2098 	struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
2099 
2100 	init_waitqueue_head(&ctx->fault_pending_wqh);
2101 	init_waitqueue_head(&ctx->fault_wqh);
2102 	init_waitqueue_head(&ctx->event_wqh);
2103 	init_waitqueue_head(&ctx->fd_wqh);
2104 	seqcount_spinlock_init(&ctx->refile_seq, &ctx->fault_pending_wqh.lock);
2105 }
2106 
2107 static int new_userfaultfd(int flags)
2108 {
2109 	struct userfaultfd_ctx *ctx;
2110 	struct file *file;
2111 	int fd;
2112 
2113 	VM_WARN_ON_ONCE(!current->mm);
2114 
2115 	/* Check the UFFD_* constants for consistency.  */
2116 	BUILD_BUG_ON(UFFD_USER_MODE_ONLY & UFFD_SHARED_FCNTL_FLAGS);
2117 
2118 	if (flags & ~(UFFD_SHARED_FCNTL_FLAGS | UFFD_USER_MODE_ONLY))
2119 		return -EINVAL;
2120 
2121 	ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
2122 	if (!ctx)
2123 		return -ENOMEM;
2124 
2125 	refcount_set(&ctx->refcount, 1);
2126 	ctx->flags = flags;
2127 	ctx->features = 0;
2128 	ctx->released = false;
2129 	init_rwsem(&ctx->map_changing_lock);
2130 	atomic_set(&ctx->mmap_changing, 0);
2131 	ctx->mm = current->mm;
2132 
2133 	fd = get_unused_fd_flags(flags & UFFD_SHARED_FCNTL_FLAGS);
2134 	if (fd < 0)
2135 		goto err_out;
2136 
2137 	/* Create a new inode so that the LSM can block the creation.  */
2138 	file = anon_inode_create_getfile("[userfaultfd]", &userfaultfd_fops, ctx,
2139 			O_RDONLY | (flags & UFFD_SHARED_FCNTL_FLAGS), NULL);
2140 	if (IS_ERR(file)) {
2141 		put_unused_fd(fd);
2142 		fd = PTR_ERR(file);
2143 		goto err_out;
2144 	}
2145 	/* prevent the mm struct to be freed */
2146 	mmgrab(ctx->mm);
2147 	file->f_mode |= FMODE_NOWAIT;
2148 	fd_install(fd, file);
2149 	return fd;
2150 err_out:
2151 	kmem_cache_free(userfaultfd_ctx_cachep, ctx);
2152 	return fd;
2153 }
2154 
2155 static inline bool userfaultfd_syscall_allowed(int flags)
2156 {
2157 	/* Userspace-only page faults are always allowed */
2158 	if (flags & UFFD_USER_MODE_ONLY)
2159 		return true;
2160 
2161 	/*
2162 	 * The user is requesting a userfaultfd which can handle kernel faults.
2163 	 * Privileged users are always allowed to do this.
2164 	 */
2165 	if (capable(CAP_SYS_PTRACE))
2166 		return true;
2167 
2168 	/* Otherwise, access to kernel fault handling is sysctl controlled. */
2169 	return sysctl_unprivileged_userfaultfd;
2170 }
2171 
2172 SYSCALL_DEFINE1(userfaultfd, int, flags)
2173 {
2174 	if (!userfaultfd_syscall_allowed(flags))
2175 		return -EPERM;
2176 
2177 	return new_userfaultfd(flags);
2178 }
2179 
2180 static long userfaultfd_dev_ioctl(struct file *file, unsigned int cmd, unsigned long flags)
2181 {
2182 	if (cmd != USERFAULTFD_IOC_NEW)
2183 		return -EINVAL;
2184 
2185 	return new_userfaultfd(flags);
2186 }
2187 
2188 static const struct file_operations userfaultfd_dev_fops = {
2189 	.unlocked_ioctl = userfaultfd_dev_ioctl,
2190 	.compat_ioctl = userfaultfd_dev_ioctl,
2191 	.owner = THIS_MODULE,
2192 	.llseek = noop_llseek,
2193 };
2194 
2195 static struct miscdevice userfaultfd_misc = {
2196 	.minor = MISC_DYNAMIC_MINOR,
2197 	.name = "userfaultfd",
2198 	.fops = &userfaultfd_dev_fops
2199 };
2200 
2201 static int __init userfaultfd_init(void)
2202 {
2203 	int ret;
2204 
2205 	ret = misc_register(&userfaultfd_misc);
2206 	if (ret)
2207 		return ret;
2208 
2209 	userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
2210 						sizeof(struct userfaultfd_ctx),
2211 						0,
2212 						SLAB_HWCACHE_ALIGN|SLAB_PANIC,
2213 						init_once_userfaultfd_ctx);
2214 #ifdef CONFIG_SYSCTL
2215 	register_sysctl_init("vm", vm_userfaultfd_table);
2216 #endif
2217 	return 0;
2218 }
2219 __initcall(userfaultfd_init);
2220