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