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