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