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