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