xref: /openbmc/linux/fs/userfaultfd.c (revision ae3473231e77a3f1909d48cd144cebe5e1d049b3)
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/hashtable.h>
16 #include <linux/sched.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 
30 static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
31 
32 enum userfaultfd_state {
33 	UFFD_STATE_WAIT_API,
34 	UFFD_STATE_RUNNING,
35 };
36 
37 /*
38  * Start with fault_pending_wqh and fault_wqh so they're more likely
39  * to be in the same cacheline.
40  */
41 struct userfaultfd_ctx {
42 	/* waitqueue head for the pending (i.e. not read) userfaults */
43 	wait_queue_head_t fault_pending_wqh;
44 	/* waitqueue head for the userfaults */
45 	wait_queue_head_t fault_wqh;
46 	/* waitqueue head for the pseudo fd to wakeup poll/read */
47 	wait_queue_head_t fd_wqh;
48 	/* a refile sequence protected by fault_pending_wqh lock */
49 	struct seqcount refile_seq;
50 	/* pseudo fd refcounting */
51 	atomic_t refcount;
52 	/* userfaultfd syscall flags */
53 	unsigned int flags;
54 	/* state machine */
55 	enum userfaultfd_state state;
56 	/* released */
57 	bool released;
58 	/* mm with one ore more vmas attached to this userfaultfd_ctx */
59 	struct mm_struct *mm;
60 };
61 
62 struct userfaultfd_wait_queue {
63 	struct uffd_msg msg;
64 	wait_queue_t wq;
65 	struct userfaultfd_ctx *ctx;
66 };
67 
68 struct userfaultfd_wake_range {
69 	unsigned long start;
70 	unsigned long len;
71 };
72 
73 static int userfaultfd_wake_function(wait_queue_t *wq, unsigned mode,
74 				     int wake_flags, void *key)
75 {
76 	struct userfaultfd_wake_range *range = key;
77 	int ret;
78 	struct userfaultfd_wait_queue *uwq;
79 	unsigned long start, len;
80 
81 	uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
82 	ret = 0;
83 	/* len == 0 means wake all */
84 	start = range->start;
85 	len = range->len;
86 	if (len && (start > uwq->msg.arg.pagefault.address ||
87 		    start + len <= uwq->msg.arg.pagefault.address))
88 		goto out;
89 	ret = wake_up_state(wq->private, mode);
90 	if (ret)
91 		/*
92 		 * Wake only once, autoremove behavior.
93 		 *
94 		 * After the effect of list_del_init is visible to the
95 		 * other CPUs, the waitqueue may disappear from under
96 		 * us, see the !list_empty_careful() in
97 		 * handle_userfault(). try_to_wake_up() has an
98 		 * implicit smp_mb__before_spinlock, and the
99 		 * wq->private is read before calling the extern
100 		 * function "wake_up_state" (which in turns calls
101 		 * try_to_wake_up). While the spin_lock;spin_unlock;
102 		 * wouldn't be enough, the smp_mb__before_spinlock is
103 		 * enough to avoid an explicit smp_mb() here.
104 		 */
105 		list_del_init(&wq->task_list);
106 out:
107 	return ret;
108 }
109 
110 /**
111  * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
112  * context.
113  * @ctx: [in] Pointer to the userfaultfd context.
114  *
115  * Returns: In case of success, returns not zero.
116  */
117 static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
118 {
119 	if (!atomic_inc_not_zero(&ctx->refcount))
120 		BUG();
121 }
122 
123 /**
124  * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
125  * context.
126  * @ctx: [in] Pointer to userfaultfd context.
127  *
128  * The userfaultfd context reference must have been previously acquired either
129  * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
130  */
131 static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
132 {
133 	if (atomic_dec_and_test(&ctx->refcount)) {
134 		VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
135 		VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
136 		VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
137 		VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
138 		VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
139 		VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
140 		mmdrop(ctx->mm);
141 		kmem_cache_free(userfaultfd_ctx_cachep, ctx);
142 	}
143 }
144 
145 static inline void msg_init(struct uffd_msg *msg)
146 {
147 	BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
148 	/*
149 	 * Must use memset to zero out the paddings or kernel data is
150 	 * leaked to userland.
151 	 */
152 	memset(msg, 0, sizeof(struct uffd_msg));
153 }
154 
155 static inline struct uffd_msg userfault_msg(unsigned long address,
156 					    unsigned int flags,
157 					    unsigned long reason)
158 {
159 	struct uffd_msg msg;
160 	msg_init(&msg);
161 	msg.event = UFFD_EVENT_PAGEFAULT;
162 	msg.arg.pagefault.address = address;
163 	if (flags & FAULT_FLAG_WRITE)
164 		/*
165 		 * If UFFD_FEATURE_PAGEFAULT_FLAG_WRITE was set in the
166 		 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WRITE
167 		 * was not set in a UFFD_EVENT_PAGEFAULT, it means it
168 		 * was a read fault, otherwise if set it means it's
169 		 * a write fault.
170 		 */
171 		msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
172 	if (reason & VM_UFFD_WP)
173 		/*
174 		 * If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
175 		 * uffdio_api.features and UFFD_PAGEFAULT_FLAG_WP was
176 		 * not set in a UFFD_EVENT_PAGEFAULT, it means it was
177 		 * a missing fault, otherwise if set it means it's a
178 		 * write protect fault.
179 		 */
180 		msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
181 	return msg;
182 }
183 
184 /*
185  * Verify the pagetables are still not ok after having reigstered into
186  * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
187  * userfault that has already been resolved, if userfaultfd_read and
188  * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
189  * threads.
190  */
191 static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
192 					 unsigned long address,
193 					 unsigned long flags,
194 					 unsigned long reason)
195 {
196 	struct mm_struct *mm = ctx->mm;
197 	pgd_t *pgd;
198 	pud_t *pud;
199 	pmd_t *pmd, _pmd;
200 	pte_t *pte;
201 	bool ret = true;
202 
203 	VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
204 
205 	pgd = pgd_offset(mm, address);
206 	if (!pgd_present(*pgd))
207 		goto out;
208 	pud = pud_offset(pgd, address);
209 	if (!pud_present(*pud))
210 		goto out;
211 	pmd = pmd_offset(pud, address);
212 	/*
213 	 * READ_ONCE must function as a barrier with narrower scope
214 	 * and it must be equivalent to:
215 	 *	_pmd = *pmd; barrier();
216 	 *
217 	 * This is to deal with the instability (as in
218 	 * pmd_trans_unstable) of the pmd.
219 	 */
220 	_pmd = READ_ONCE(*pmd);
221 	if (!pmd_present(_pmd))
222 		goto out;
223 
224 	ret = false;
225 	if (pmd_trans_huge(_pmd))
226 		goto out;
227 
228 	/*
229 	 * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
230 	 * and use the standard pte_offset_map() instead of parsing _pmd.
231 	 */
232 	pte = pte_offset_map(pmd, address);
233 	/*
234 	 * Lockless access: we're in a wait_event so it's ok if it
235 	 * changes under us.
236 	 */
237 	if (pte_none(*pte))
238 		ret = true;
239 	pte_unmap(pte);
240 
241 out:
242 	return ret;
243 }
244 
245 /*
246  * The locking rules involved in returning VM_FAULT_RETRY depending on
247  * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
248  * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
249  * recommendation in __lock_page_or_retry is not an understatement.
250  *
251  * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_sem must be released
252  * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
253  * not set.
254  *
255  * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
256  * set, VM_FAULT_RETRY can still be returned if and only if there are
257  * fatal_signal_pending()s, and the mmap_sem must be released before
258  * returning it.
259  */
260 int handle_userfault(struct vm_fault *vmf, unsigned long reason)
261 {
262 	struct mm_struct *mm = vmf->vma->vm_mm;
263 	struct userfaultfd_ctx *ctx;
264 	struct userfaultfd_wait_queue uwq;
265 	int ret;
266 	bool must_wait, return_to_userland;
267 
268 	BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
269 
270 	ret = VM_FAULT_SIGBUS;
271 	ctx = vmf->vma->vm_userfaultfd_ctx.ctx;
272 	if (!ctx)
273 		goto out;
274 
275 	BUG_ON(ctx->mm != mm);
276 
277 	VM_BUG_ON(reason & ~(VM_UFFD_MISSING|VM_UFFD_WP));
278 	VM_BUG_ON(!(reason & VM_UFFD_MISSING) ^ !!(reason & VM_UFFD_WP));
279 
280 	/*
281 	 * If it's already released don't get it. This avoids to loop
282 	 * in __get_user_pages if userfaultfd_release waits on the
283 	 * caller of handle_userfault to release the mmap_sem.
284 	 */
285 	if (unlikely(ACCESS_ONCE(ctx->released)))
286 		goto out;
287 
288 	/*
289 	 * We don't do userfault handling for the final child pid update.
290 	 */
291 	if (current->flags & PF_EXITING)
292 		goto out;
293 
294 	/*
295 	 * Check that we can return VM_FAULT_RETRY.
296 	 *
297 	 * NOTE: it should become possible to return VM_FAULT_RETRY
298 	 * even if FAULT_FLAG_TRIED is set without leading to gup()
299 	 * -EBUSY failures, if the userfaultfd is to be extended for
300 	 * VM_UFFD_WP tracking and we intend to arm the userfault
301 	 * without first stopping userland access to the memory. For
302 	 * VM_UFFD_MISSING userfaults this is enough for now.
303 	 */
304 	if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
305 		/*
306 		 * Validate the invariant that nowait must allow retry
307 		 * to be sure not to return SIGBUS erroneously on
308 		 * nowait invocations.
309 		 */
310 		BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
311 #ifdef CONFIG_DEBUG_VM
312 		if (printk_ratelimit()) {
313 			printk(KERN_WARNING
314 			       "FAULT_FLAG_ALLOW_RETRY missing %x\n",
315 			       vmf->flags);
316 			dump_stack();
317 		}
318 #endif
319 		goto out;
320 	}
321 
322 	/*
323 	 * Handle nowait, not much to do other than tell it to retry
324 	 * and wait.
325 	 */
326 	ret = VM_FAULT_RETRY;
327 	if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
328 		goto out;
329 
330 	/* take the reference before dropping the mmap_sem */
331 	userfaultfd_ctx_get(ctx);
332 
333 	init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
334 	uwq.wq.private = current;
335 	uwq.msg = userfault_msg(vmf->address, vmf->flags, reason);
336 	uwq.ctx = ctx;
337 
338 	return_to_userland =
339 		(vmf->flags & (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE)) ==
340 		(FAULT_FLAG_USER|FAULT_FLAG_KILLABLE);
341 
342 	spin_lock(&ctx->fault_pending_wqh.lock);
343 	/*
344 	 * After the __add_wait_queue the uwq is visible to userland
345 	 * through poll/read().
346 	 */
347 	__add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
348 	/*
349 	 * The smp_mb() after __set_current_state prevents the reads
350 	 * following the spin_unlock to happen before the list_add in
351 	 * __add_wait_queue.
352 	 */
353 	set_current_state(return_to_userland ? TASK_INTERRUPTIBLE :
354 			  TASK_KILLABLE);
355 	spin_unlock(&ctx->fault_pending_wqh.lock);
356 
357 	must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
358 					  reason);
359 	up_read(&mm->mmap_sem);
360 
361 	if (likely(must_wait && !ACCESS_ONCE(ctx->released) &&
362 		   (return_to_userland ? !signal_pending(current) :
363 		    !fatal_signal_pending(current)))) {
364 		wake_up_poll(&ctx->fd_wqh, POLLIN);
365 		schedule();
366 		ret |= VM_FAULT_MAJOR;
367 	}
368 
369 	__set_current_state(TASK_RUNNING);
370 
371 	if (return_to_userland) {
372 		if (signal_pending(current) &&
373 		    !fatal_signal_pending(current)) {
374 			/*
375 			 * If we got a SIGSTOP or SIGCONT and this is
376 			 * a normal userland page fault, just let
377 			 * userland return so the signal will be
378 			 * handled and gdb debugging works.  The page
379 			 * fault code immediately after we return from
380 			 * this function is going to release the
381 			 * mmap_sem and it's not depending on it
382 			 * (unlike gup would if we were not to return
383 			 * VM_FAULT_RETRY).
384 			 *
385 			 * If a fatal signal is pending we still take
386 			 * the streamlined VM_FAULT_RETRY failure path
387 			 * and there's no need to retake the mmap_sem
388 			 * in such case.
389 			 */
390 			down_read(&mm->mmap_sem);
391 			ret = 0;
392 		}
393 	}
394 
395 	/*
396 	 * Here we race with the list_del; list_add in
397 	 * userfaultfd_ctx_read(), however because we don't ever run
398 	 * list_del_init() to refile across the two lists, the prev
399 	 * and next pointers will never point to self. list_add also
400 	 * would never let any of the two pointers to point to
401 	 * self. So list_empty_careful won't risk to see both pointers
402 	 * pointing to self at any time during the list refile. The
403 	 * only case where list_del_init() is called is the full
404 	 * removal in the wake function and there we don't re-list_add
405 	 * and it's fine not to block on the spinlock. The uwq on this
406 	 * kernel stack can be released after the list_del_init.
407 	 */
408 	if (!list_empty_careful(&uwq.wq.task_list)) {
409 		spin_lock(&ctx->fault_pending_wqh.lock);
410 		/*
411 		 * No need of list_del_init(), the uwq on the stack
412 		 * will be freed shortly anyway.
413 		 */
414 		list_del(&uwq.wq.task_list);
415 		spin_unlock(&ctx->fault_pending_wqh.lock);
416 	}
417 
418 	/*
419 	 * ctx may go away after this if the userfault pseudo fd is
420 	 * already released.
421 	 */
422 	userfaultfd_ctx_put(ctx);
423 
424 out:
425 	return ret;
426 }
427 
428 static int userfaultfd_release(struct inode *inode, struct file *file)
429 {
430 	struct userfaultfd_ctx *ctx = file->private_data;
431 	struct mm_struct *mm = ctx->mm;
432 	struct vm_area_struct *vma, *prev;
433 	/* len == 0 means wake all */
434 	struct userfaultfd_wake_range range = { .len = 0, };
435 	unsigned long new_flags;
436 
437 	ACCESS_ONCE(ctx->released) = true;
438 
439 	if (!mmget_not_zero(mm))
440 		goto wakeup;
441 
442 	/*
443 	 * Flush page faults out of all CPUs. NOTE: all page faults
444 	 * must be retried without returning VM_FAULT_SIGBUS if
445 	 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
446 	 * changes while handle_userfault released the mmap_sem. So
447 	 * it's critical that released is set to true (above), before
448 	 * taking the mmap_sem for writing.
449 	 */
450 	down_write(&mm->mmap_sem);
451 	prev = NULL;
452 	for (vma = mm->mmap; vma; vma = vma->vm_next) {
453 		cond_resched();
454 		BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
455 		       !!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
456 		if (vma->vm_userfaultfd_ctx.ctx != ctx) {
457 			prev = vma;
458 			continue;
459 		}
460 		new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
461 		prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
462 				 new_flags, vma->anon_vma,
463 				 vma->vm_file, vma->vm_pgoff,
464 				 vma_policy(vma),
465 				 NULL_VM_UFFD_CTX);
466 		if (prev)
467 			vma = prev;
468 		else
469 			prev = vma;
470 		vma->vm_flags = new_flags;
471 		vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
472 	}
473 	up_write(&mm->mmap_sem);
474 	mmput(mm);
475 wakeup:
476 	/*
477 	 * After no new page faults can wait on this fault_*wqh, flush
478 	 * the last page faults that may have been already waiting on
479 	 * the fault_*wqh.
480 	 */
481 	spin_lock(&ctx->fault_pending_wqh.lock);
482 	__wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
483 	__wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, &range);
484 	spin_unlock(&ctx->fault_pending_wqh.lock);
485 
486 	wake_up_poll(&ctx->fd_wqh, POLLHUP);
487 	userfaultfd_ctx_put(ctx);
488 	return 0;
489 }
490 
491 /* fault_pending_wqh.lock must be hold by the caller */
492 static inline struct userfaultfd_wait_queue *find_userfault(
493 	struct userfaultfd_ctx *ctx)
494 {
495 	wait_queue_t *wq;
496 	struct userfaultfd_wait_queue *uwq;
497 
498 	VM_BUG_ON(!spin_is_locked(&ctx->fault_pending_wqh.lock));
499 
500 	uwq = NULL;
501 	if (!waitqueue_active(&ctx->fault_pending_wqh))
502 		goto out;
503 	/* walk in reverse to provide FIFO behavior to read userfaults */
504 	wq = list_last_entry(&ctx->fault_pending_wqh.task_list,
505 			     typeof(*wq), task_list);
506 	uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
507 out:
508 	return uwq;
509 }
510 
511 static unsigned int userfaultfd_poll(struct file *file, poll_table *wait)
512 {
513 	struct userfaultfd_ctx *ctx = file->private_data;
514 	unsigned int ret;
515 
516 	poll_wait(file, &ctx->fd_wqh, wait);
517 
518 	switch (ctx->state) {
519 	case UFFD_STATE_WAIT_API:
520 		return POLLERR;
521 	case UFFD_STATE_RUNNING:
522 		/*
523 		 * poll() never guarantees that read won't block.
524 		 * userfaults can be waken before they're read().
525 		 */
526 		if (unlikely(!(file->f_flags & O_NONBLOCK)))
527 			return POLLERR;
528 		/*
529 		 * lockless access to see if there are pending faults
530 		 * __pollwait last action is the add_wait_queue but
531 		 * the spin_unlock would allow the waitqueue_active to
532 		 * pass above the actual list_add inside
533 		 * add_wait_queue critical section. So use a full
534 		 * memory barrier to serialize the list_add write of
535 		 * add_wait_queue() with the waitqueue_active read
536 		 * below.
537 		 */
538 		ret = 0;
539 		smp_mb();
540 		if (waitqueue_active(&ctx->fault_pending_wqh))
541 			ret = POLLIN;
542 		return ret;
543 	default:
544 		BUG();
545 	}
546 }
547 
548 static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
549 				    struct uffd_msg *msg)
550 {
551 	ssize_t ret;
552 	DECLARE_WAITQUEUE(wait, current);
553 	struct userfaultfd_wait_queue *uwq;
554 
555 	/* always take the fd_wqh lock before the fault_pending_wqh lock */
556 	spin_lock(&ctx->fd_wqh.lock);
557 	__add_wait_queue(&ctx->fd_wqh, &wait);
558 	for (;;) {
559 		set_current_state(TASK_INTERRUPTIBLE);
560 		spin_lock(&ctx->fault_pending_wqh.lock);
561 		uwq = find_userfault(ctx);
562 		if (uwq) {
563 			/*
564 			 * Use a seqcount to repeat the lockless check
565 			 * in wake_userfault() to avoid missing
566 			 * wakeups because during the refile both
567 			 * waitqueue could become empty if this is the
568 			 * only userfault.
569 			 */
570 			write_seqcount_begin(&ctx->refile_seq);
571 
572 			/*
573 			 * The fault_pending_wqh.lock prevents the uwq
574 			 * to disappear from under us.
575 			 *
576 			 * Refile this userfault from
577 			 * fault_pending_wqh to fault_wqh, it's not
578 			 * pending anymore after we read it.
579 			 *
580 			 * Use list_del() by hand (as
581 			 * userfaultfd_wake_function also uses
582 			 * list_del_init() by hand) to be sure nobody
583 			 * changes __remove_wait_queue() to use
584 			 * list_del_init() in turn breaking the
585 			 * !list_empty_careful() check in
586 			 * handle_userfault(). The uwq->wq.task_list
587 			 * must never be empty at any time during the
588 			 * refile, or the waitqueue could disappear
589 			 * from under us. The "wait_queue_head_t"
590 			 * parameter of __remove_wait_queue() is unused
591 			 * anyway.
592 			 */
593 			list_del(&uwq->wq.task_list);
594 			__add_wait_queue(&ctx->fault_wqh, &uwq->wq);
595 
596 			write_seqcount_end(&ctx->refile_seq);
597 
598 			/* careful to always initialize msg if ret == 0 */
599 			*msg = uwq->msg;
600 			spin_unlock(&ctx->fault_pending_wqh.lock);
601 			ret = 0;
602 			break;
603 		}
604 		spin_unlock(&ctx->fault_pending_wqh.lock);
605 		if (signal_pending(current)) {
606 			ret = -ERESTARTSYS;
607 			break;
608 		}
609 		if (no_wait) {
610 			ret = -EAGAIN;
611 			break;
612 		}
613 		spin_unlock(&ctx->fd_wqh.lock);
614 		schedule();
615 		spin_lock(&ctx->fd_wqh.lock);
616 	}
617 	__remove_wait_queue(&ctx->fd_wqh, &wait);
618 	__set_current_state(TASK_RUNNING);
619 	spin_unlock(&ctx->fd_wqh.lock);
620 
621 	return ret;
622 }
623 
624 static ssize_t userfaultfd_read(struct file *file, char __user *buf,
625 				size_t count, loff_t *ppos)
626 {
627 	struct userfaultfd_ctx *ctx = file->private_data;
628 	ssize_t _ret, ret = 0;
629 	struct uffd_msg msg;
630 	int no_wait = file->f_flags & O_NONBLOCK;
631 
632 	if (ctx->state == UFFD_STATE_WAIT_API)
633 		return -EINVAL;
634 
635 	for (;;) {
636 		if (count < sizeof(msg))
637 			return ret ? ret : -EINVAL;
638 		_ret = userfaultfd_ctx_read(ctx, no_wait, &msg);
639 		if (_ret < 0)
640 			return ret ? ret : _ret;
641 		if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
642 			return ret ? ret : -EFAULT;
643 		ret += sizeof(msg);
644 		buf += sizeof(msg);
645 		count -= sizeof(msg);
646 		/*
647 		 * Allow to read more than one fault at time but only
648 		 * block if waiting for the very first one.
649 		 */
650 		no_wait = O_NONBLOCK;
651 	}
652 }
653 
654 static void __wake_userfault(struct userfaultfd_ctx *ctx,
655 			     struct userfaultfd_wake_range *range)
656 {
657 	unsigned long start, end;
658 
659 	start = range->start;
660 	end = range->start + range->len;
661 
662 	spin_lock(&ctx->fault_pending_wqh.lock);
663 	/* wake all in the range and autoremove */
664 	if (waitqueue_active(&ctx->fault_pending_wqh))
665 		__wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
666 				     range);
667 	if (waitqueue_active(&ctx->fault_wqh))
668 		__wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, range);
669 	spin_unlock(&ctx->fault_pending_wqh.lock);
670 }
671 
672 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
673 					   struct userfaultfd_wake_range *range)
674 {
675 	unsigned seq;
676 	bool need_wakeup;
677 
678 	/*
679 	 * To be sure waitqueue_active() is not reordered by the CPU
680 	 * before the pagetable update, use an explicit SMP memory
681 	 * barrier here. PT lock release or up_read(mmap_sem) still
682 	 * have release semantics that can allow the
683 	 * waitqueue_active() to be reordered before the pte update.
684 	 */
685 	smp_mb();
686 
687 	/*
688 	 * Use waitqueue_active because it's very frequent to
689 	 * change the address space atomically even if there are no
690 	 * userfaults yet. So we take the spinlock only when we're
691 	 * sure we've userfaults to wake.
692 	 */
693 	do {
694 		seq = read_seqcount_begin(&ctx->refile_seq);
695 		need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
696 			waitqueue_active(&ctx->fault_wqh);
697 		cond_resched();
698 	} while (read_seqcount_retry(&ctx->refile_seq, seq));
699 	if (need_wakeup)
700 		__wake_userfault(ctx, range);
701 }
702 
703 static __always_inline int validate_range(struct mm_struct *mm,
704 					  __u64 start, __u64 len)
705 {
706 	__u64 task_size = mm->task_size;
707 
708 	if (start & ~PAGE_MASK)
709 		return -EINVAL;
710 	if (len & ~PAGE_MASK)
711 		return -EINVAL;
712 	if (!len)
713 		return -EINVAL;
714 	if (start < mmap_min_addr)
715 		return -EINVAL;
716 	if (start >= task_size)
717 		return -EINVAL;
718 	if (len > task_size - start)
719 		return -EINVAL;
720 	return 0;
721 }
722 
723 static int userfaultfd_register(struct userfaultfd_ctx *ctx,
724 				unsigned long arg)
725 {
726 	struct mm_struct *mm = ctx->mm;
727 	struct vm_area_struct *vma, *prev, *cur;
728 	int ret;
729 	struct uffdio_register uffdio_register;
730 	struct uffdio_register __user *user_uffdio_register;
731 	unsigned long vm_flags, new_flags;
732 	bool found;
733 	unsigned long start, end, vma_end;
734 
735 	user_uffdio_register = (struct uffdio_register __user *) arg;
736 
737 	ret = -EFAULT;
738 	if (copy_from_user(&uffdio_register, user_uffdio_register,
739 			   sizeof(uffdio_register)-sizeof(__u64)))
740 		goto out;
741 
742 	ret = -EINVAL;
743 	if (!uffdio_register.mode)
744 		goto out;
745 	if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
746 				     UFFDIO_REGISTER_MODE_WP))
747 		goto out;
748 	vm_flags = 0;
749 	if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
750 		vm_flags |= VM_UFFD_MISSING;
751 	if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
752 		vm_flags |= VM_UFFD_WP;
753 		/*
754 		 * FIXME: remove the below error constraint by
755 		 * implementing the wprotect tracking mode.
756 		 */
757 		ret = -EINVAL;
758 		goto out;
759 	}
760 
761 	ret = validate_range(mm, uffdio_register.range.start,
762 			     uffdio_register.range.len);
763 	if (ret)
764 		goto out;
765 
766 	start = uffdio_register.range.start;
767 	end = start + uffdio_register.range.len;
768 
769 	ret = -ENOMEM;
770 	if (!mmget_not_zero(mm))
771 		goto out;
772 
773 	down_write(&mm->mmap_sem);
774 	vma = find_vma_prev(mm, start, &prev);
775 	if (!vma)
776 		goto out_unlock;
777 
778 	/* check that there's at least one vma in the range */
779 	ret = -EINVAL;
780 	if (vma->vm_start >= end)
781 		goto out_unlock;
782 
783 	/*
784 	 * Search for not compatible vmas.
785 	 *
786 	 * FIXME: this shall be relaxed later so that it doesn't fail
787 	 * on tmpfs backed vmas (in addition to the current allowance
788 	 * on anonymous vmas).
789 	 */
790 	found = false;
791 	for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
792 		cond_resched();
793 
794 		BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
795 		       !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
796 
797 		/* check not compatible vmas */
798 		ret = -EINVAL;
799 		if (cur->vm_ops)
800 			goto out_unlock;
801 
802 		/*
803 		 * Check that this vma isn't already owned by a
804 		 * different userfaultfd. We can't allow more than one
805 		 * userfaultfd to own a single vma simultaneously or we
806 		 * wouldn't know which one to deliver the userfaults to.
807 		 */
808 		ret = -EBUSY;
809 		if (cur->vm_userfaultfd_ctx.ctx &&
810 		    cur->vm_userfaultfd_ctx.ctx != ctx)
811 			goto out_unlock;
812 
813 		found = true;
814 	}
815 	BUG_ON(!found);
816 
817 	if (vma->vm_start < start)
818 		prev = vma;
819 
820 	ret = 0;
821 	do {
822 		cond_resched();
823 
824 		BUG_ON(vma->vm_ops);
825 		BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
826 		       vma->vm_userfaultfd_ctx.ctx != ctx);
827 
828 		/*
829 		 * Nothing to do: this vma is already registered into this
830 		 * userfaultfd and with the right tracking mode too.
831 		 */
832 		if (vma->vm_userfaultfd_ctx.ctx == ctx &&
833 		    (vma->vm_flags & vm_flags) == vm_flags)
834 			goto skip;
835 
836 		if (vma->vm_start > start)
837 			start = vma->vm_start;
838 		vma_end = min(end, vma->vm_end);
839 
840 		new_flags = (vma->vm_flags & ~vm_flags) | vm_flags;
841 		prev = vma_merge(mm, prev, start, vma_end, new_flags,
842 				 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
843 				 vma_policy(vma),
844 				 ((struct vm_userfaultfd_ctx){ ctx }));
845 		if (prev) {
846 			vma = prev;
847 			goto next;
848 		}
849 		if (vma->vm_start < start) {
850 			ret = split_vma(mm, vma, start, 1);
851 			if (ret)
852 				break;
853 		}
854 		if (vma->vm_end > end) {
855 			ret = split_vma(mm, vma, end, 0);
856 			if (ret)
857 				break;
858 		}
859 	next:
860 		/*
861 		 * In the vma_merge() successful mprotect-like case 8:
862 		 * the next vma was merged into the current one and
863 		 * the current one has not been updated yet.
864 		 */
865 		vma->vm_flags = new_flags;
866 		vma->vm_userfaultfd_ctx.ctx = ctx;
867 
868 	skip:
869 		prev = vma;
870 		start = vma->vm_end;
871 		vma = vma->vm_next;
872 	} while (vma && vma->vm_start < end);
873 out_unlock:
874 	up_write(&mm->mmap_sem);
875 	mmput(mm);
876 	if (!ret) {
877 		/*
878 		 * Now that we scanned all vmas we can already tell
879 		 * userland which ioctls methods are guaranteed to
880 		 * succeed on this range.
881 		 */
882 		if (put_user(UFFD_API_RANGE_IOCTLS,
883 			     &user_uffdio_register->ioctls))
884 			ret = -EFAULT;
885 	}
886 out:
887 	return ret;
888 }
889 
890 static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
891 				  unsigned long arg)
892 {
893 	struct mm_struct *mm = ctx->mm;
894 	struct vm_area_struct *vma, *prev, *cur;
895 	int ret;
896 	struct uffdio_range uffdio_unregister;
897 	unsigned long new_flags;
898 	bool found;
899 	unsigned long start, end, vma_end;
900 	const void __user *buf = (void __user *)arg;
901 
902 	ret = -EFAULT;
903 	if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
904 		goto out;
905 
906 	ret = validate_range(mm, uffdio_unregister.start,
907 			     uffdio_unregister.len);
908 	if (ret)
909 		goto out;
910 
911 	start = uffdio_unregister.start;
912 	end = start + uffdio_unregister.len;
913 
914 	ret = -ENOMEM;
915 	if (!mmget_not_zero(mm))
916 		goto out;
917 
918 	down_write(&mm->mmap_sem);
919 	vma = find_vma_prev(mm, start, &prev);
920 	if (!vma)
921 		goto out_unlock;
922 
923 	/* check that there's at least one vma in the range */
924 	ret = -EINVAL;
925 	if (vma->vm_start >= end)
926 		goto out_unlock;
927 
928 	/*
929 	 * Search for not compatible vmas.
930 	 *
931 	 * FIXME: this shall be relaxed later so that it doesn't fail
932 	 * on tmpfs backed vmas (in addition to the current allowance
933 	 * on anonymous vmas).
934 	 */
935 	found = false;
936 	ret = -EINVAL;
937 	for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
938 		cond_resched();
939 
940 		BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
941 		       !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
942 
943 		/*
944 		 * Check not compatible vmas, not strictly required
945 		 * here as not compatible vmas cannot have an
946 		 * userfaultfd_ctx registered on them, but this
947 		 * provides for more strict behavior to notice
948 		 * unregistration errors.
949 		 */
950 		if (cur->vm_ops)
951 			goto out_unlock;
952 
953 		found = true;
954 	}
955 	BUG_ON(!found);
956 
957 	if (vma->vm_start < start)
958 		prev = vma;
959 
960 	ret = 0;
961 	do {
962 		cond_resched();
963 
964 		BUG_ON(vma->vm_ops);
965 
966 		/*
967 		 * Nothing to do: this vma is already registered into this
968 		 * userfaultfd and with the right tracking mode too.
969 		 */
970 		if (!vma->vm_userfaultfd_ctx.ctx)
971 			goto skip;
972 
973 		if (vma->vm_start > start)
974 			start = vma->vm_start;
975 		vma_end = min(end, vma->vm_end);
976 
977 		new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
978 		prev = vma_merge(mm, prev, start, vma_end, new_flags,
979 				 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
980 				 vma_policy(vma),
981 				 NULL_VM_UFFD_CTX);
982 		if (prev) {
983 			vma = prev;
984 			goto next;
985 		}
986 		if (vma->vm_start < start) {
987 			ret = split_vma(mm, vma, start, 1);
988 			if (ret)
989 				break;
990 		}
991 		if (vma->vm_end > end) {
992 			ret = split_vma(mm, vma, end, 0);
993 			if (ret)
994 				break;
995 		}
996 	next:
997 		/*
998 		 * In the vma_merge() successful mprotect-like case 8:
999 		 * the next vma was merged into the current one and
1000 		 * the current one has not been updated yet.
1001 		 */
1002 		vma->vm_flags = new_flags;
1003 		vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
1004 
1005 	skip:
1006 		prev = vma;
1007 		start = vma->vm_end;
1008 		vma = vma->vm_next;
1009 	} while (vma && vma->vm_start < end);
1010 out_unlock:
1011 	up_write(&mm->mmap_sem);
1012 	mmput(mm);
1013 out:
1014 	return ret;
1015 }
1016 
1017 /*
1018  * userfaultfd_wake may be used in combination with the
1019  * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
1020  */
1021 static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
1022 			    unsigned long arg)
1023 {
1024 	int ret;
1025 	struct uffdio_range uffdio_wake;
1026 	struct userfaultfd_wake_range range;
1027 	const void __user *buf = (void __user *)arg;
1028 
1029 	ret = -EFAULT;
1030 	if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
1031 		goto out;
1032 
1033 	ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
1034 	if (ret)
1035 		goto out;
1036 
1037 	range.start = uffdio_wake.start;
1038 	range.len = uffdio_wake.len;
1039 
1040 	/*
1041 	 * len == 0 means wake all and we don't want to wake all here,
1042 	 * so check it again to be sure.
1043 	 */
1044 	VM_BUG_ON(!range.len);
1045 
1046 	wake_userfault(ctx, &range);
1047 	ret = 0;
1048 
1049 out:
1050 	return ret;
1051 }
1052 
1053 static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1054 			    unsigned long arg)
1055 {
1056 	__s64 ret;
1057 	struct uffdio_copy uffdio_copy;
1058 	struct uffdio_copy __user *user_uffdio_copy;
1059 	struct userfaultfd_wake_range range;
1060 
1061 	user_uffdio_copy = (struct uffdio_copy __user *) arg;
1062 
1063 	ret = -EFAULT;
1064 	if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1065 			   /* don't copy "copy" last field */
1066 			   sizeof(uffdio_copy)-sizeof(__s64)))
1067 		goto out;
1068 
1069 	ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1070 	if (ret)
1071 		goto out;
1072 	/*
1073 	 * double check for wraparound just in case. copy_from_user()
1074 	 * will later check uffdio_copy.src + uffdio_copy.len to fit
1075 	 * in the userland range.
1076 	 */
1077 	ret = -EINVAL;
1078 	if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1079 		goto out;
1080 	if (uffdio_copy.mode & ~UFFDIO_COPY_MODE_DONTWAKE)
1081 		goto out;
1082 	if (mmget_not_zero(ctx->mm)) {
1083 		ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
1084 				   uffdio_copy.len);
1085 		mmput(ctx->mm);
1086 	}
1087 	if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1088 		return -EFAULT;
1089 	if (ret < 0)
1090 		goto out;
1091 	BUG_ON(!ret);
1092 	/* len == 0 would wake all */
1093 	range.len = ret;
1094 	if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1095 		range.start = uffdio_copy.dst;
1096 		wake_userfault(ctx, &range);
1097 	}
1098 	ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1099 out:
1100 	return ret;
1101 }
1102 
1103 static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1104 				unsigned long arg)
1105 {
1106 	__s64 ret;
1107 	struct uffdio_zeropage uffdio_zeropage;
1108 	struct uffdio_zeropage __user *user_uffdio_zeropage;
1109 	struct userfaultfd_wake_range range;
1110 
1111 	user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1112 
1113 	ret = -EFAULT;
1114 	if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1115 			   /* don't copy "zeropage" last field */
1116 			   sizeof(uffdio_zeropage)-sizeof(__s64)))
1117 		goto out;
1118 
1119 	ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1120 			     uffdio_zeropage.range.len);
1121 	if (ret)
1122 		goto out;
1123 	ret = -EINVAL;
1124 	if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1125 		goto out;
1126 
1127 	if (mmget_not_zero(ctx->mm)) {
1128 		ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1129 				     uffdio_zeropage.range.len);
1130 		mmput(ctx->mm);
1131 	}
1132 	if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1133 		return -EFAULT;
1134 	if (ret < 0)
1135 		goto out;
1136 	/* len == 0 would wake all */
1137 	BUG_ON(!ret);
1138 	range.len = ret;
1139 	if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1140 		range.start = uffdio_zeropage.range.start;
1141 		wake_userfault(ctx, &range);
1142 	}
1143 	ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1144 out:
1145 	return ret;
1146 }
1147 
1148 /*
1149  * userland asks for a certain API version and we return which bits
1150  * and ioctl commands are implemented in this kernel for such API
1151  * version or -EINVAL if unknown.
1152  */
1153 static int userfaultfd_api(struct userfaultfd_ctx *ctx,
1154 			   unsigned long arg)
1155 {
1156 	struct uffdio_api uffdio_api;
1157 	void __user *buf = (void __user *)arg;
1158 	int ret;
1159 
1160 	ret = -EINVAL;
1161 	if (ctx->state != UFFD_STATE_WAIT_API)
1162 		goto out;
1163 	ret = -EFAULT;
1164 	if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
1165 		goto out;
1166 	if (uffdio_api.api != UFFD_API || uffdio_api.features) {
1167 		memset(&uffdio_api, 0, sizeof(uffdio_api));
1168 		if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1169 			goto out;
1170 		ret = -EINVAL;
1171 		goto out;
1172 	}
1173 	uffdio_api.features = UFFD_API_FEATURES;
1174 	uffdio_api.ioctls = UFFD_API_IOCTLS;
1175 	ret = -EFAULT;
1176 	if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
1177 		goto out;
1178 	ctx->state = UFFD_STATE_RUNNING;
1179 	ret = 0;
1180 out:
1181 	return ret;
1182 }
1183 
1184 static long userfaultfd_ioctl(struct file *file, unsigned cmd,
1185 			      unsigned long arg)
1186 {
1187 	int ret = -EINVAL;
1188 	struct userfaultfd_ctx *ctx = file->private_data;
1189 
1190 	if (cmd != UFFDIO_API && ctx->state == UFFD_STATE_WAIT_API)
1191 		return -EINVAL;
1192 
1193 	switch(cmd) {
1194 	case UFFDIO_API:
1195 		ret = userfaultfd_api(ctx, arg);
1196 		break;
1197 	case UFFDIO_REGISTER:
1198 		ret = userfaultfd_register(ctx, arg);
1199 		break;
1200 	case UFFDIO_UNREGISTER:
1201 		ret = userfaultfd_unregister(ctx, arg);
1202 		break;
1203 	case UFFDIO_WAKE:
1204 		ret = userfaultfd_wake(ctx, arg);
1205 		break;
1206 	case UFFDIO_COPY:
1207 		ret = userfaultfd_copy(ctx, arg);
1208 		break;
1209 	case UFFDIO_ZEROPAGE:
1210 		ret = userfaultfd_zeropage(ctx, arg);
1211 		break;
1212 	}
1213 	return ret;
1214 }
1215 
1216 #ifdef CONFIG_PROC_FS
1217 static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
1218 {
1219 	struct userfaultfd_ctx *ctx = f->private_data;
1220 	wait_queue_t *wq;
1221 	struct userfaultfd_wait_queue *uwq;
1222 	unsigned long pending = 0, total = 0;
1223 
1224 	spin_lock(&ctx->fault_pending_wqh.lock);
1225 	list_for_each_entry(wq, &ctx->fault_pending_wqh.task_list, task_list) {
1226 		uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1227 		pending++;
1228 		total++;
1229 	}
1230 	list_for_each_entry(wq, &ctx->fault_wqh.task_list, task_list) {
1231 		uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
1232 		total++;
1233 	}
1234 	spin_unlock(&ctx->fault_pending_wqh.lock);
1235 
1236 	/*
1237 	 * If more protocols will be added, there will be all shown
1238 	 * separated by a space. Like this:
1239 	 *	protocols: aa:... bb:...
1240 	 */
1241 	seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
1242 		   pending, total, UFFD_API, UFFD_API_FEATURES,
1243 		   UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
1244 }
1245 #endif
1246 
1247 static const struct file_operations userfaultfd_fops = {
1248 #ifdef CONFIG_PROC_FS
1249 	.show_fdinfo	= userfaultfd_show_fdinfo,
1250 #endif
1251 	.release	= userfaultfd_release,
1252 	.poll		= userfaultfd_poll,
1253 	.read		= userfaultfd_read,
1254 	.unlocked_ioctl = userfaultfd_ioctl,
1255 	.compat_ioctl	= userfaultfd_ioctl,
1256 	.llseek		= noop_llseek,
1257 };
1258 
1259 static void init_once_userfaultfd_ctx(void *mem)
1260 {
1261 	struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
1262 
1263 	init_waitqueue_head(&ctx->fault_pending_wqh);
1264 	init_waitqueue_head(&ctx->fault_wqh);
1265 	init_waitqueue_head(&ctx->fd_wqh);
1266 	seqcount_init(&ctx->refile_seq);
1267 }
1268 
1269 /**
1270  * userfaultfd_file_create - Creates an userfaultfd file pointer.
1271  * @flags: Flags for the userfaultfd file.
1272  *
1273  * This function creates an userfaultfd file pointer, w/out installing
1274  * it into the fd table. This is useful when the userfaultfd file is
1275  * used during the initialization of data structures that require
1276  * extra setup after the userfaultfd creation. So the userfaultfd
1277  * creation is split into the file pointer creation phase, and the
1278  * file descriptor installation phase.  In this way races with
1279  * userspace closing the newly installed file descriptor can be
1280  * avoided.  Returns an userfaultfd file pointer, or a proper error
1281  * pointer.
1282  */
1283 static struct file *userfaultfd_file_create(int flags)
1284 {
1285 	struct file *file;
1286 	struct userfaultfd_ctx *ctx;
1287 
1288 	BUG_ON(!current->mm);
1289 
1290 	/* Check the UFFD_* constants for consistency.  */
1291 	BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
1292 	BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
1293 
1294 	file = ERR_PTR(-EINVAL);
1295 	if (flags & ~UFFD_SHARED_FCNTL_FLAGS)
1296 		goto out;
1297 
1298 	file = ERR_PTR(-ENOMEM);
1299 	ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
1300 	if (!ctx)
1301 		goto out;
1302 
1303 	atomic_set(&ctx->refcount, 1);
1304 	ctx->flags = flags;
1305 	ctx->state = UFFD_STATE_WAIT_API;
1306 	ctx->released = false;
1307 	ctx->mm = current->mm;
1308 	/* prevent the mm struct to be freed */
1309 	atomic_inc(&ctx->mm->mm_count);
1310 
1311 	file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, ctx,
1312 				  O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS));
1313 	if (IS_ERR(file)) {
1314 		mmdrop(ctx->mm);
1315 		kmem_cache_free(userfaultfd_ctx_cachep, ctx);
1316 	}
1317 out:
1318 	return file;
1319 }
1320 
1321 SYSCALL_DEFINE1(userfaultfd, int, flags)
1322 {
1323 	int fd, error;
1324 	struct file *file;
1325 
1326 	error = get_unused_fd_flags(flags & UFFD_SHARED_FCNTL_FLAGS);
1327 	if (error < 0)
1328 		return error;
1329 	fd = error;
1330 
1331 	file = userfaultfd_file_create(flags);
1332 	if (IS_ERR(file)) {
1333 		error = PTR_ERR(file);
1334 		goto err_put_unused_fd;
1335 	}
1336 	fd_install(fd, file);
1337 
1338 	return fd;
1339 
1340 err_put_unused_fd:
1341 	put_unused_fd(fd);
1342 
1343 	return error;
1344 }
1345 
1346 static int __init userfaultfd_init(void)
1347 {
1348 	userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
1349 						sizeof(struct userfaultfd_ctx),
1350 						0,
1351 						SLAB_HWCACHE_ALIGN|SLAB_PANIC,
1352 						init_once_userfaultfd_ctx);
1353 	return 0;
1354 }
1355 __initcall(userfaultfd_init);
1356