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