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