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