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