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