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