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