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