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