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